function get_last_log_line($filename) { $line = false; $f = false; if (file_exists($filename)) { $f = @fopen($filename, 'r'); } if ($f === false) { return false; } else { $cursor = -1; fseek($f, $cursor, SEEK_END); $char = fgetc($f); /** * Trim trailing newline chars of the file */ while ($char === "\n" || $char === "\r") { fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } /** * Read until the start of file or first newline char */ while ($char !== false && $char !== "\n" && $char !== "\r") { /** * Prepend the new char */ $line = $char . $line; fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } } return $line; }
function executeSqlFile(&$installQ, $filename, $tablePrfx = "") { $fp = fopen($filename, "r"); # show error if file could not be opened if ($fp == false) { echo "Error reading file " . H($filename) . ".<br>\n"; return false; } else { $sqlStmt = ""; while (!feof($fp)) { $char = fgetc($fp); if ($char == ";") { //replace table prefix $sql = str_replace("%prfx%", $tablePrfx, $sqlStmt); echo "lara"; echo "process sql [" . $sqlStmt . "]<br>"; //test $result = $installQ->exec($sql); if ($installQ->errorOccurred()) { $installQ->close(); displayErrorPage($installQ); fclose($fp); return false; } $sqlStmt = ""; } else { $sqlStmt = $sqlStmt . $char; } } fclose($fp); return true; } }
function read_history($history_file, $history_pos, $repo_path) { $fp = fopen($history_file, "r") or die("Unable to open file!"); $pos = -2; // Skip final new line character (Set to -1 if not present) $lines = array(); $currentLine = ''; while (-1 !== fseek($fp, $pos, SEEK_END)) { $char = fgetc($fp); if (PHP_EOL == $char) { $lines[] = $currentLine; $currentLine = ''; } else { $currentLine = $char . $currentLine; } $pos--; } list($result, $build_id, $branch, $commit_id, $ci_pipeline_time) = split('[|]', $lines[$history_pos]); list($dummy, $result) = split('[:]', $result); $result = trim($result); list($dummy, $build_id) = split('[:]', $build_id); $build_id = trim($build_id); list($dummy, $branch) = split('[:]', $branch); $branch = trim($branch); list($dummy, $commit_id) = split('[:]', $commit_id); $commit_id = substr(trim($commit_id), -10); list($dummy, $ci_pipeline_time) = split('[:]', $ci_pipeline_time); $ci_pipeline_time = substr(trim($ci_pipeline_time), -10); $history = array("result" => $result, "build_id" => $build_id, "branch" => $branch, "commit_id" => $commit_id, "artifact_path" => "{$repo_path}/ci_fuel_opnfv/artifact/{$branch}/{$build_id}", "log" => "{$repo_path}/ci_fuel_opnfv/artifact/{$branch}/{$build_id}/ci.log", "iso" => "{$repo_path}/ci_fuel_opnfv/artifact/{$branch}/{$build_id}/opnfv-{$build_id}.iso", "ci_pipeline_time" => $ci_pipeline_time); return $history; }
function setDomainAddress($domain, $address, $server, $ttl = 86400) { $process = proc_open('/usr/bin/nsupdate', array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')), $pipes); if (is_resource($process)) { fwrite($pipes[0], "server {$server}\n"); fwrite($pipes[0], "update delete {$domain}.\n"); if ($address !== false) { fwrite($pipes[0], "update add {$domain}. {$ttl} IN A {$address}\n"); } fwrite($pipes[0], "\n"); fclose($pipes[0]); $result = true; if (fgetc($pipes[1]) !== false) { $result = false; } fclose($pipes[1]); if (fgetc($pipes[2]) !== false) { $result = false; } fclose($pipes[2]); proc_close($process); return $result; } return false; }
/** * YunoHost - Self-hosting for all * Copyright (C) 2012 Kload <*****@*****.**> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ function read_file($file, $lines = 20) { if (!($handle = fopen($file, "r"))) { return false; } $linecounter = $lines; $pos = -2; $beginning = false; $text = array(); while ($linecounter > 0) { $t = " "; while ($t != "\n") { if (fseek($handle, $pos, SEEK_END) == -1) { $beginning = true; break; } $t = fgetc($handle); $pos--; } $linecounter--; if ($beginning) { rewind($handle); } $text[$lines - $linecounter - 1] = fgets($handle); if ($beginning) { break; } } fclose($handle); return array_reverse($text); }
function conversion_progress($filepath) { $line = ''; $f = fopen($filepath, 'r'); $cursor = -1; fseek($f, $cursor, SEEK_END); $char = fgetc($f); /** * Trim trailing newline chars of the file */ while ($char === " ") { fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } /** * Read until the start of file or first newline char */ while ($char !== false && $char !== " ") { /** * Prepend the new char */ $line = $char . $line; fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } echo $line; preg_match_all('!\\d+!', $line, $matches); var_dump($matches); }
function tail($callback) { if ($fp = fopen($this->tailfile, "rb")) { fseek($fp, 0, SEEK_END); $fs = fstat($fp); $ino = $fs['ino']; while ($this->publish_count < $this->max_lines_before_quit || $this->max_lines_before_quit == 0) { do { do { $ino = $this->rotate($ino); if ($ino == FALSE) { return FALSE; } $c = fgetc($fp); $line .= $c; } while ($c != "\n" && $c != "\r" && $c); if ($c === FALSE) { sleep(1); } } while ($c != "\n" && $c != "\r"); $this->publish_count++; call_user_func($callback, $line); $line = ''; $c = ''; } fclose($fp); } else { echo "Can't open file\n"; } }
protected function read_file($file, $lines) { //global $fsize; try { $handle = fopen($file, "r"); $linecounter = $lines; $pos = -2; $beginning = false; $text = array(); while ($linecounter > 0) { $t = " "; while ($t != "\n") { if (fseek($handle, $pos, SEEK_END) == -1) { $beginning = true; break; } $t = fgetc($handle); $pos--; } $linecounter--; if ($beginning) { rewind($handle); } $text[$lines - $linecounter - 1] = fgets($handle); if ($beginning) { break; } } fclose($handle); return array_reverse($text); } catch (Exception $e) { return $e->getMessage(); } }
public function run($handle, $rolloverChar, $returnMatches = false) { $buffer = ''; $count = strlen($this->testString); $found = true; for ($i = 0; $i < $count; $i++) { $char = false; if ($rolloverChar !== '') { $char = $rolloverChar; $rolloverChar = ''; } else { $char = fgetc($handle); } if (substr($this->testString, $i, 1) !== $char) { $found = false; break; } } if ($found) { if ($returnMatches) { $buffer = $this->testString; } } return array('found' => $found, 'buffer' => $buffer, 'length' => $count, 'rolloverChar' => ''); }
/** * * This function has core logic to check Suduko board is valid or not. * This function validate number of rows should be 9 and number of coloum should be 9 * @author Pankaj Kumar */ private function checkSuokuPattern() { $file = fopen($this->_fileName, "r"); $noOfRows = 0; $noOfCols = 0; $colArr = array(); while ($c = fgetc($file)) { if (in_array($c, array("\n"))) { // To check new line $noOfRows++; $colArr[] = $noOfCols; // Store all numbers of columns $noOfCols = 0; } else { $noOfCols++; } } if ($noOfRows == 9 && count(array_unique($colArr)) == 1 && $colArr[0] == 9) { // Possible condition to check Suduko board is valid or not echo $this->_fileName . ': 1<br>'; } else { echo $this->_fileName . ': 0<br>'; } fclose($file); }
function queryData($message = null) { global $serialConnection; if (!empty($message)) { // Set blocking mode for writing stream_set_blocking($serialConnection, 1); fputs($serialConnection, $message . "\n"); } $timeout = time() + 10; $line = ''; // Set non blocking mode for reading stream_set_blocking($serialConnection, 0); do { // Try to read one character from the device $c = fgetc($serialConnection); // Wait for data to arrive if ($c === false) { continue 1; } $line .= $c; } while ($c != "\n" && time() < $timeout); $response = trim($line); if (!empty($message) && $response == $message) { // Original message echoed back, read again sleep(1); $response = queryData(); } // Drain the read queue if there is anything left while ($c !== false) { $c = fgets($serialConnection); } return $response; }
/** * This function returns the extension associated with the file based on the file's content. * * @access public * @return string the extension for the file */ public function getFileExtensionFromStream() { $ext = ''; $handle = fopen($this->uri, 'r'); if ($handle) { $buffer = ''; for ($i = 0; !feof($handle) && $i < 1024; $i++) { $buffer .= fgetc($handle); } $buffer = trim($buffer); if (static::isBMP($buffer)) { $ext = 'bmp'; } else { if (static::isGIF($buffer)) { $ext = 'gif'; } else { if (static::isJPEG($buffer)) { $ext = 'jpg'; } else { if (static::isPNG($buffer)) { $ext = 'png'; } } } } } @fclose($handle); return $ext; }
/** * @param string $filename * @return GridFile * @throws MflParserException */ protected function extractGridFile($filename) { $file = new GridFile($filename); $source = $file->getFileHandler(); $reader = self::getReaderForFile($file); if (null === $reader) { } $x = 1; $y = 1; try { while (($character = fgetc($source)) !== false) { if ($character === "\n") { $x++; $y = 1; } else { $y++; } $reader->readGridFileCharacter($file, $character); } } catch (Exception $e) { //echo $e->getTraceAsString(); throw new MflParserException($x, $y, $e->getMessage()); } finally { fclose($source); } if ($reader->handleDefinitionForce() && sizeof($file->getDefinitions()) !== sizeof($file->getLevels())) { throw new MflParserException($x, $y, sprintf("Number of definitions (%d) and levels (%d) doesn't match", sizeof($file->getDefinitions()), sizeof($file->getLevels()))); } return $file; }
function walktrough($startdir) { global $filesCount, $dirsCount, $linesCount, $signsCount, $allowedext; $startdir = preg_replace("!/\$!", '', $startdir); $startdir .= '/'; $dir = opendir($startdir); while ($file = readdir($dir)) { if ($file == '.' || $file == '..') { continue; } if (is_file($startdir . $file)) { $filesCount++; $ext = preg_replace("!.*\\.!", '', $file); if (in_array($ext, $allowedext)) { $file = fopen($startdir . $file, 'r'); while (fgets($file, 1000000)) { $linesCount++; } rewind($file); while (fgetc($file)) { $signsCount++; } fclose($file); } } else { $dirsCount++; walktrough($startdir . $file); } } closedir($dir); }
public function rewind() { $this->close(); $this->f = fopen($this->filename, 'r'); $this->index = 0; $this->current = fgetc($this->f); }
/** * Returns the next record in raw format. * * @return string Next record in raw format. */ private function readNextRecord() { if ($this->isEOF) { $this->isValidPosition = false; } $isInRecord = false; $recording = ''; $lastChar = null; while (false !== ($char = fgetc($this->handle))) { $isNewArrayStart = $char === '-' && ($lastChar === "\n" || $lastChar === null); $lastChar = $char; if ($isInRecord && $isNewArrayStart) { fseek($this->handle, -1, SEEK_CUR); break; } if (!$isInRecord && $isNewArrayStart) { $isInRecord = true; } if ($isInRecord) { $recording .= $char; } } if ($char == false) { $this->isEOF = true; } return $recording; }
function encrypt($key, $datFile, $encFile) { if (openssl_pkcs7_encrypt($datFile, $encFile, $key, array())) { echo "<b>Successfully encrypted: </b>"; $tempStr = file_get_contents($encFile); $strOri = "MIME-Version: 1.0\nContent-Disposition: attachment; filename=\"smime.p7m\"\nContent-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\"\nContent-Transfer-Encoding: base64\n\n"; $fp = fopen($encFile, "w"); fwrite($fp, str_replace($strOri, "", $tempStr)); fclose($fp); echo str_replace($strOri, "", $encFile) . "<br/><br/>"; echo "<b>Encrypted string again, with \"\\n\" replaced with <br> and \"\\r\" replaced with [CR]:</b><br>"; $fp = fopen($encFile, 'r'); while (false !== ($char = fgetc($fp))) { if ($char == "\n") { echo "<br>"; } else { if ($char == "\r") { echo "[CR]"; } } echo $char; } } else { echo "Cannot Encrypt <br/>"; } }
protected function _read() { switch (fgetc($this->socket)) { case '+': return trim(fgets($this->socket), "\r\n"); case ':': return (int) trim(fgets($this->socket), "\r\n"); case '$': $length = (int) trim(fgets($this->socket), "\r\n"); if ($length === -1) { return null; } $return = ""; while (strlen($return) < $length) { $return .= fread($this->socket, $length - strlen($return)); } fgets($this->socket); return $return; case '*': $length = (int) trim(fgets($this->socket), "\r\n"); $return = []; for ($i = 0; $i < $length; $i++) { $return[] = $this->_read(); } return $return; case '-': throw new CacheException(trim(fgets($this->socket), "\r\n")); } }
function tail_file($file, $lines) { $handle = fopen($file, "r"); if (!is_resource($handle)) { return ''; } $linecounter = $lines; $pos = -2; $beginning = false; $text = array(); while ($linecounter > 0) { $t = " "; while ($t != "\n") { if (fseek($handle, $pos, SEEK_END) == -1) { $beginning = true; break; } $t = fgetc($handle); $pos--; } $linecounter--; if ($beginning) { rewind($handle); } $text[$lines - $linecounter - 1] = fgets($handle); if ($beginning) { break; } } fclose($handle); return $text; }
public static function TellStatus($GID) { if (file_exists('/tmp/' . $GID . '.curl')) { $Line = null; $TFHandle = fopen('/tmp/' . $GID . '.curl', 'r'); $Cursor = -1; fseek($TFHandle, $Cursor, SEEK_END); $Char = fgetc($TFHandle); while ($Char === "\n" || $Char === "\r") { fseek($TFHandle, $Cursor--, SEEK_END); $Char = fgetc($TFHandle); } while ($Char !== false && $Char !== "\n" && $Char !== "\r") { $Line = $Char . $Line; fseek($TFHandle, $Cursor--, SEEK_END); $Char = fgetc($TFHandle); } $StatusArray = array('status' => 'waiting', 'completedLength' => 0, 'totalLength' => 0, 'downloadSpeed' => 0, 'PID' => 0, 'GID' => $GID); if (!is_null($Line)) { $Status = explode(';', $Line); if (count($Status) == 5) { $StatusArray['status'] = $Status[0]; $StatusArray['completedLength'] = $Status[1]; $StatusArray['totalLength'] = $Status[2]; $StatusArray['downloadSpeed'] = $Status[3]; $StatusArray['PID'] = $Status[4]; } } return array('result' => $StatusArray); } else { return array('error' => true); } }
public static function inputc($message = "") { gio::output("{$message}: "); $stdin = fopen("php://stdin", "r"); $ret = fgetc($stdin); return trim($ret); }
function getPassword($stars = false) { // Get current style $oldStyle = shell_exec('stty -g'); if ($stars === false) { shell_exec('stty -echo'); $password = rtrim(fgets(STDIN), "\n"); } else { shell_exec('stty -icanon -echo min 1 time 0'); $password = ''; while (true) { $char = fgetc(STDIN); if ($char === "\n") { break; } else { if (ord($char) === 127) { if (strlen($password) > 0) { fwrite(STDOUT, " "); $password = substr($password, 0, -1); } } else { fwrite(STDOUT, "*"); $password .= $char; } } } } // Reset old style shell_exec('stty ' . $oldStyle); // Return the password return $password; }
function standard_compare($f1, $f2) { do { $d1 = fgetc($f1); while ($d1 == " " || $d1 == "\n" || $d1 == "\r") { $d1 = fgetc($f1); } $d2 = fgetc($f2); while ($d2 == " " || $d2 == "\n" || $d2 == "\r") { $d2 = fgetc($f2); } if ($d1 === false) { break; } if ($d2 === false) { return 0.0; } if ($d1 != $d2) { return 0.0; } } while (true); if (!($d2 === false)) { while (!($d2 === false)) { $d2 = fgetc($f2); if ($d2 != " " && $d2 != "\n" && $d2 != "\r") { return 0.0; } } } return 1.0; }
public static function findStubLength($file, $pattern = self::PATTERN_OPEN) { if (!($fp = fopen($file, 'rb'))) { throw new RuntimeException(sprintf('The phar "%s" could not be opened for reading.', $file)); } $stub = null; $offset = 0; $combo = str_split($pattern); while (!feof($fp)) { if (fgetc($fp) === $combo[$offset]) { $offset++; if (!isset($combo[$offset])) { $stub = ftell($fp); break; } } else { $offset = 0; } } fclose($fp); if (null === $stub) { throw new InvalidArgumentException(sprintf('The pattern could not be found in "%s".', $file)); } return $stub; }
function read($length = 1) { if ($this->ready() == FALSE) { return ''; } return $length == 1 ? fgetc($this->handle) : fread($this->handle, $length); }
/** * Fetches the next item from the stream using defined behavior * * @param resource $stream_handle The stream handle that is being use in the current context * * @access public * * @return string A single character or null if FEOF */ public function next($stream_handle) { //If feof, end it if (feof($stream_handle)) { return null; } //Extract the character $c = ($c = fgetc($stream_handle)) === false ? null : $c; //If character is 195 (utf8 control character) if ($c !== null && ord($c) == 195) { $c .= fgetc($stream_handle); } //If character is 195 (utf8 control character) if ($c !== null && ord($c) == 239) { //Get the next two characters and seek back if not UTF8 bom $c2 = fgetc($stream_handle); $c3 = fgetc($stream_handle); if (ord($c2) == 187 && ord($c3) == 191) { //Ok, BOM skipped, read next char using defined next method (to support possible UTF-8 chars) $c = $this->next($stream_handle); } else { //Seek back 2 characters, it was not a UTF-8 BOM fseek($stream_handle, ftell($stream_handle) - 2); } } //Return it return $c; }
function freq_analyze($infile, $cereg = '[a-z ]') { //Make frequency fingerprint $debug = 100; $total = 0; $in = fopen($infile, 'r'); while (!feof($in)) { $c = strtolower(fgetc($in)); if (eregi($cereg, $c)) { if (!isset($data[$c])) { $data[$c] = 0; } $data[$c]++; $total++; } } fclose($in); //Compute percents foreach ($data as $c => $n) { $data[$c] = $n / $total * 100; $debug -= $data[$c]; } //echo("Debug: $debug\n"); //Debug return $data; }
/** * Returns the next record in raw format. * * @return string Next record in raw format. */ protected function readNextRecord() { $depth = 0; $isInRecord = false; $record = ''; while (false !== ($char = fgetc($this->handle))) { if ($char === '{') { ++$depth; } if ($char === '}') { --$depth; } if (!$isInRecord && $char === '{') { $isInRecord = true; } if ($isInRecord) { $record .= $char; } if ($isInRecord && $char === '}' && $depth == 0) { break; } } if ($char == false) { $this->isEOF = true; } return $record; }
public static function seekPKHeader($handle) { $pkHeader = false; $curr = fgetc($handle); do { $prev = $curr; $curr = fgetc($handle); $pk = $prev == "P" && $curr == "K"; if ($pk) { $b1 = fgetc($handle); $b2 = fgetc($handle); if ($b1 == "" && $b2 == "") { $pkHeader = self::ZIP_CENTRAL_FILE_HEADER; } else { if ($b1 == "" && $b2 == "") { $pkHeader = self::ZIP_LOCAL_FILE_HEADER; } else { if ($b1 == "" && $b2 == "") { $pkHeader = self::ZIP_END_OF_CENTRAL_DIRECTORY; } else { if ($b1 == "" && $b2 == "") { $pkHeader = self::ZIP_LOCAL_DATA_DESCRIPTOR; } else { fseek($handle, -2, SEEK_CUR); $pk = false; } } } } } } while (!$pk && !feof($handle)); fseek($handle, -4, SEEK_CUR); return $pkHeader; }
public static function DownloadFileFromWebWithStatusOutput($strUrl) { $objFile = fopen($strUrl, 'r'); $strMetaDataArray = stream_get_meta_data($objFile); $intContentLength = null; foreach ($strMetaDataArray['wrapper_data'] as $strHeader) { $strHeader = strtolower($strHeader); if (strpos($strHeader, 'content-length: ') === 0) { $intContentLength = intval(substr($strHeader, 16)); } } if (!$intContentLength) { return null; } print 'Downloading package (' . $intContentLength . ' bytes)...'; print "\r\n"; $strData = null; $strLinePrint = null; for ($intIndex = 0; $intIndex < $intContentLength; $intIndex++) { if ($intIndex % 1024 == 0) { print str_repeat(chr(8), strlen($strLinePrint)); $intPercent = floor($intIndex / $intContentLength * 100); $strLinePrint = sprintf('%s%% [%-50s] %s', $intPercent, str_repeat('=', floor($intPercent / 2)) . '>', $intIndex); print $strLinePrint; } $strData .= fgetc($objFile); } fclose($objFile); print str_repeat(chr(8) . ' ' . chr(8), strlen($strLinePrint)); print "Done.\r\n\r\n"; return $strData; }