/** * {@inheritdoc} */ public function read() { if ($this->file->valid()) { $this->file->seek($this->getContext()->getReadCount()); $line = rtrim($this->file->current(), PHP_EOL); $this->getContext()->incrementReadCount(); return json_decode($line, true); } return null; }
/** * File constructor. * @param $uri String File path or URL * @throws \ErrorException * @throws \Exception */ public function __construct($uri) { try { $this->messageFactory = new MessageFactory(); $file = new \SplFileObject($uri, 'rb'); while ($file->valid()) { $raw_time = $file->fread(8); if (!$raw_time) { break; } $header = new Header($file->fread(6)); if ($header->magic !== 0xfe) { throw new \ErrorException("Unexpected magic number ({$header->magic})"); } $payload = $file->fread($header->length); $raw_crc = $file->fread(2); $entry = new Entry($raw_time, $header, $payload, $raw_crc); $this->entries[] = $entry; $this->messages[] = $this->messageFactory->build($entry); } if (!$this->hasEntries()) { throw new \ErrorException('No entries found in file.'); } $this->startTime = $this->entries[0]->time; $this->endTime = end($this->entries)->time; } catch (\Exception $ex) { // echo $ex->getMessage() . ' ' . $ex->getFile() . ':' . $ex->getLine(); die; } }
public function valid() { $current = $this->current(); if ($this->names) { return count($current) == count($this->names); } return parent::valid(); }
/** * valid SplFileObjectでCSVフィルを読ませると最終行の空配列で返るのでそれの抑止 * * @return bool */ public function valid() { $parentValid = parent::valid(); $var = parent::current(); if ($var === array(null)) { return false; } return $parentValid; }
function generate($nb, $fixture = __DIR__ . '/fixtures/lorem.txt') { $lorems = new SplFileObject($fixture, 'a+'); $txt = ''; while ($nb > 0 && $lorems->valid()) { $txt .= $lorems->current(); $lorems->next(); $nb--; } return $txt; }
public function getData() { try { $file = new SplFileObject($this->tmp_name, 'rb'); $data = null; for ($file; $file->valid(); $file->next()) { $data .= $file->current(); } return $data; } catch (RuntimeException $e) { } return null; }
/** * Get raw image data from the SplFileObject. * * @return string * String representation of the raw image binary data */ public function getRaw() { if (!is_null($this->raw)) { return $this->raw; } // Save our current position $position = $this->object->ftell(); $this->object->rewind(); $raw = ''; while ($this->object->valid()) { $raw .= $this->object->fgets(); } // Go back to our original position $this->object->fseek($position); return $this->raw = $raw; }
/** * @param \SplFileObject $fileObject * * @return Statement */ protected function parseFileObject(\SplFileObject $fileObject) { $this->statement = $this->getStatementClass(); foreach ($fileObject as $line) { if ($fileObject->valid()) { switch ($this->getLineType($line)) { case self::LINE_TYPE_STATEMENT: $this->parseStatementLine($line); break; case self::LINE_TYPE_TRANSACTION: $transaction = $this->parseTransactionLine($line); $this->statement->addTransaction($transaction); break; } } } return $this->statement; }
/** * Move forward to next element */ public function next() { if (null === $this->_file) { $this->_openFile(); } if ($this->_file) { $this->_key = $this->_key + 1; while ($this->_file->valid()) { $this->_file->next(); $this->_filepos = $this->_file->ftell(); if ($this->_accept()) { $this->_valid = true; return; } } } $this->_valid = false; }
public function parseFile($logFile, &$startId, $finish = false) { if (!$logFile || !file_exists($logFile)) { return $this->setError('Log file error'); } try { $file = new SplFileObject($logFile); $file->seek(!$startId ? 0 : $startId - 1); $counter = 0; $items = array(); $item = null; while ($file->valid()) { $row = trim($file->current()); $file->next(); if (!$row) { continue; } $item = Mage::getModel('mpbackup/backup_progress_item')->parse($row, $item); $items[] = $item; $counter += $item->getLength(); if (!$finish && $counter > Mageplace_Backup_Helper_Const::BACKUP_PROCESS_REQUEST_PERIOD * Mageplace_Backup_Helper_Const::BACKUP_PROCESS_RESPONSE_SIZE) { break; } } $startId = $file->key(); } catch (Exception $e) { Mage::logException($e); return $this->setError($e->getMessage()); } if (empty($items)) { if ($finish) { return $this->setError('Log is empty (' . print_r($items, true) . ') and log process is finished'); } else { return $this->setData(self::TEXT, self::TEXT_TREE_POINT)->setError(print_r($items, true)); } } return $this->setData(self::ITEMS, $items); }
/** * Read a key from the cache * * @param string $key Identifier for the data * @return mixed The cached data, or false if the data doesn't exist, has * expired, or if there was an error fetching it */ public function read($key) { $key = $this->_key($key); if (!$this->_init || $this->_setKey($key) === false) { return false; } if ($this->_config['lock']) { $this->_File->flock(LOCK_SH); } $this->_File->rewind(); $time = time(); $cachetime = (int) $this->_File->current(); if ($cachetime !== false && ($cachetime < $time || $time + $this->_config['duration'] < $cachetime)) { if ($this->_config['lock']) { $this->_File->flock(LOCK_UN); } return false; } $data = ''; $this->_File->next(); while ($this->_File->valid()) { $data .= $this->_File->current(); $this->_File->next(); } if ($this->_config['lock']) { $this->_File->flock(LOCK_UN); } $data = trim($data); if ($data !== '' && !empty($this->_config['serialize'])) { if ($this->_config['isWindows']) { $data = str_replace('\\\\\\\\', '\\', $data); } $data = unserialize((string) $data); } return $data; }
public function __invoke($csvFilePath, $checkLines = 2) { $file = new \SplFileObject($csvFilePath); $delimiters = [',', '\\t', ';', '|', ':']; $results = array(); $i = 0; while ($file->valid() && $i <= $checkLines) { $line = $file->fgets(); foreach ($delimiters as $delimiter) { $regExp = '/[' . $delimiter . ']/'; $fields = preg_split($regExp, $line); if (count($fields) > 1) { if (!empty($results[$delimiter])) { $results[$delimiter]++; } else { $results[$delimiter] = 1; } } } $i++; } $results = array_keys($results, max($results)); return $results[0]; }
public function read($key) { if (!$this->is_init || $this->_openFile($key) === false) { return false; } if ($this->settings['lock']) { $this->file->flock(LOCK_SH); } $this->file->rewind(); $time = time(); $cachetime = intval($this->file->current()); //check for expiry if ($cachetime !== false && ($cachetime < $time || $time + $this->settings['cache_duration'] < $cachetime)) { if ($this->settings['lock']) { $this->file->flock(LOCK_UN); } return false; } $data = ''; $this->file->next(); while ($this->file->valid()) { $data .= $this->file->current(); $this->file->next(); } if ($this->settings['lock']) { $this->file->flock(LOCK_UN); } $data = trim($data); if ($data !== '' && !empty($this->settings['serialize'])) { if ($this->settings['is_windows']) { $data = str_replace('\\\\\\\\', '\\', $data); } $data = json_decode((string) $data, TRUE); } return $data; }
/** * {@inheritdoc} */ public function valid() { return $this->file->valid(); }
/** * (PHP 5 >= 5.0.0)<br/> * Checks if current position is valid * @link http://php.net/manual/en/iterator.valid.php * @return boolean The return value will be casted to boolean and then evaluated. * Returns true on success or false on failure. */ public function valid() { if (!is_null($this->line_end_position)) { $line = $this->key(); if ($line > $this->line_end_position) { return false; } } return parent::valid(); }
/** * @param SplFileObject $filesListObject * @param $p_add_dir * @param $p_remove_dir * * @return bool */ function _addList($filesListObject, $p_add_dir, $p_remove_dir) { $v_header = array(); if (!$this->_file) { $this->_addBackupProcessMessage('Invalid file descriptor', true); return false; } $filesListObject->seek((int) $this->getStepIndex()); while ($filesListObject->valid()) { $this->setStepIndex($filesListObject->key()); if ($this->timeIsUp()) { return true; } $filename = $filesListObject->current(); if (trim($filename) === '') { $filesListObject->next(); continue; } if ($filename == $this->_tarname) { $filesListObject->next(); continue; } if (!file_exists($filename) && !is_link($filename)) { $this->_addBackupProcessMessage('File "' . $filename . '" does not exist', Mageplace_Backup_Model_Backup::LOG_LEVEL_WARNING); $filesListObject->next(); continue; } if (!$this->_addFile($filename, $v_header, $p_add_dir, $p_remove_dir)) { return false; } if ($this->_timeIsUp) { return true; } $filesListObject->next(); } $this->setStepIndex(null); return true; }
/** * Implements Iterator::valid(). */ public function valid() { return (!$this->lineLimit || $this->linesRead < $this->lineLimit) && parent::valid() && parent::current(); }
function mcs_check_csv_delimiter($import, $checkLines = 1) { $file = new SplFileObject($import, 'r', true); $delimiters = array(',', '\\t', ';', '|', ':'); $results = array(); $i = 0; while ($file->valid() && $i <= $checkLines) { $line = $file->fgets(); foreach ($delimiters as $delimiter) { $regExp = '/[' . $delimiter . ']/'; $fields = preg_split($regExp, $line); if (count($fields) > 1) { if (!empty($results[$delimiter])) { $results[$delimiter]++; } else { $results[$delimiter] = 1; } } } unset($delimiter); $i++; } $results = array_keys($results, max($results)); return $results[0]; }
/** * @param int $offset * @param int $limit * @param string $term * @return array */ protected function paginateLinesSearch($offset, $limit, $term) { $returnLines = array(); $returnLinesCount = 0; $matchingLinesCount = -1; if ($offset === 0) { $offset = -1; } parent::rewind(); if (is_bool($term) || is_null($term)) { trigger_error(sprintf('%s::paginateLines - %s search input seen, which results in empty string when typecast. Please check input value.', get_class($this), gettype($term))); } if (is_scalar($term) || is_object($term) && method_exists($term, '__toString')) { $term = (string) $term; while (parent::valid() && $returnLinesCount < $limit) { if (($current = parent::current()) !== '' && stripos($current, $term) !== false && ++$matchingLinesCount > $offset) { $returnLines[] = $current; $returnLinesCount++; } parent::next(); } parent::rewind(); return $returnLines; } throw new \InvalidArgumentException(sprintf('%s::paginateLines - Search value expected to be castable to string, "%s" seen.', get_class($this), gettype($term))); }
/** Returns the type-hints of the parameters of a given function. @param $oFunction The function to scan. @return array(string) An associative array mapping parameters' names to their type-hint. */ public static function getParametersTypeHints(ReflectionFunctionAbstract $oFunction) { $bArg = true; $bFunctionName = false; $iLevel = 0; $bInPrototype = false; $sHint = null; $aHints = array(); $oFile = new SplFileObject($oFunction->getFileName()); $oFile->seek($oFunction->getStartLine() - 1); while ($oFile->valid()) { $aTokens = token_get_all('<?php ' . $oFile->current() . ' */'); $iCount = count($aTokens); for ($i = 0; $i < $iCount; ++$i) { if ($bInPrototype) { if (is_array($aTokens[$i]) && $bArg == true) { switch ($aTokens[$i][0]) { case T_STRING: case T_ARRAY: $sHint = $aTokens[$i][1]; break; case T_VARIABLE: if ($sHint !== null) { $aHints[substr($aTokens[$i][1], 1)] = $sHint; } $bArg = false; $sHint = null; } } elseif ($aTokens[$i] == '(') { ++$iLevel; } elseif ($aTokens[$i] == ')') { if (--$iLevel == 0) { break 2; } } elseif ($iLevel == 1 && $aTokens[$i] == ',') { $bArg = true; } } elseif (is_array($aTokens[$i])) { switch ($aTokens[$i][0]) { case T_FUNCTION: $bFunctionName = true; break; case T_STRING: if ($bFunctionName) { if ($aTokens[$i][1] == $oFunction->getName()) { $bInPrototype = true; } else { $bFunctioName = false; } } } } } $oFile->next(); } return $aHints; }
public function finishBackupProcess($errorCheck = false, $cancel = false) { $this->initBackupData(); if (is_string($errorCheck)) { $errorCheck = strip_tags(nl2br(trim($errorCheck))); $this->addBackupProcessMessage($errorCheck, true); $this->setBackupErrors($errorCheck); } $stayLocalFilesWhenError = $errorCheck && !$this->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_BACKUP_ERROR_DELETE_LOCAL); if (!$stayLocalFilesWhenError) { $bu_files_loc = $this->getMainBackupFiles(true); if (!$this->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_LOCAL_COPY) && !empty($bu_files_loc)) { foreach ($bu_files_loc as $delfile) { if (file_exists($delfile)) { $this->addBackupProcessMessage($this->_helper()->__('Deleting "%s" file from the server', basename($delfile)), self::LOG_LEVEL_INFO); if (!@unlink($delfile)) { $this->addBackupProcessMessage($this->_helper()->__('File "%s" is not deleted', basename($delfile)), self::LOG_LEVEL_WARNING); } } } } } if ($errorCheck || $cancel) { $this->deleteUnnecessaryFiles(); } if ($this->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_LOCAL_COPY) || $stayLocalFilesWhenError) { if ($backupFiles = $this->getBackupFiles()) { if (is_string($backupFiles)) { $backupFiles = explode(';', $backupFiles); } else { if (!is_array($backupFiles)) { $backupFiles = array(); } } } else { $backupFiles = array(); } $bu_files = $this->getBackupFileNames(); if (!empty($bu_files) && is_array($bu_files)) { $backupFiles = array_merge($backupFiles, $bu_files); } if ($stayLocalFilesWhenError) { $mergeFiles = array(); $filesForDelete = $this->getFilesForDelete(); if (!empty($filesForDelete) && is_array($filesForDelete)) { $filesForDelete = array_unique($filesForDelete); foreach ($filesForDelete as $fileForDelete) { if (file_exists($fileForDelete)) { $mergeFiles[] = basename($fileForDelete); } } } $backupFiles = array_merge($backupFiles, $mergeFiles); } $backupFiles = array_unique($backupFiles); $this->setBackupFiles(implode(';', $backupFiles)); } $cloud = $this->getCloudFiles(); if (is_array($cloud)) { $cloudFiles = !empty($cloud['files']) && is_array($cloud['files']) ? $cloud['files'] : array(); $cloudInfo = !empty($cloud['infos']) && is_array($cloud['infos']) ? $cloud['infos'] : array(); $this->setBackupCloudFiles(implode(';', $cloudFiles)); $this->setBackupAdditional(serialize($cloudInfo)); } if ($cancel) { $this->setBackupCloudFiles(''); $this->setBackupFiles(''); } $logLevel = $this->getLogLevel(); if ($logLevel != self::LOG_LEVEL_OFF) { $logFile = $this->getLogMessageFileName(); $this->setBackupLogFile($logFile ? basename($logFile) : ''); } if ($errorCheck) { if ($this->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_BACKUP_ERROR_DELETE_LOCAL)) { $this->setBackupFiles(''); } if ($this->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_BACKUP_ERROR_DELETE_CLOUD)) { $this->setBackupCloudFiles(''); } $this->addBackupProcessMessage($this->_helper()->__('Backup was finished with errors'), self::LOG_LEVEL_ERROR); $this->setStatusErrors(); } elseif ($cancel) { $this->addBackupProcessMessage($this->_helper()->__('Backup was canceled'), self::LOG_LEVEL_INFO); $this->setStatusCancelled(); } else { $warnings = false; if ($this->getSession()->getHasBackupWarnings()) { $warnings = true; } else { $file = new SplFileObject($this->getLogMessageFileName()); while ($file->valid()) { $row = trim($file->current()); $file->next(); if (!$row) { continue; } if (stripos($row, sprintf(self::MESSAGE_TYPE_TEMPLATE, self::LOG_LEVEL_WARNING))) { $warnings = true; break; } } } if ($warnings) { $this->addBackupProcessMessage($this->_helper()->__('Backup was saved with warnings'), self::LOG_LEVEL_WARNING); $this->setStatusWarnings(); } else { $this->addBackupProcessMessage($this->_helper()->__('Backup was successfully saved'), self::LOG_LEVEL_INFO); $this->setStatusFinished(); } } $this->setBackupFinishDate(Mage::getSingleton('core/date')->gmtDate()); $this->deleteTempFiles(); Mage::getModel('mpbackup/interceptor')->checkMethodCall($this, 'save'); $this->addBackupProcessMessage($this->_helper()->__('Backup process was finished'), self::LOG_LEVEL_INFO); if ($this->isCron()) { Mage::getModel('mpbackup/cron')->finishSchedule($this, $errorCheck); } $this->getSession()->unsLogMessageFileName(); $this->_temp->clearMessages(); $this->_helper()->resetBackupProcessMessage(); $this->_clearSession(); return $this; }
/** * DEBUG EXCERPT * * @param String $filePath - File Location * @param Int $line - Line Number * @param Int $contenxt - Number of lines above and below. */ public static function excerpt($filePath, $line, $context = 2) { $lines = array(); $errorLine = $line; if (is_readable($filePath)) { if ($line < 0 || $context < 0) { return false; } //Based on a 0 index; $line--; //Line Number Offset. $offset = $line - $context < 0 ? abs($line - $context - 1) : 1; if (class_exists("SplFileObject")) { $data = new SplFileObject($filePath); //We Can't Seek Into The Minus! if ($line - $context > 0) { $data->seek($line - $context); } for ($i = $line - $context; $i <= $line + $context; $i++) { if (!$data->valid()) { //No More Information break; } //Format Current Line + Add To Array $lines[$i + $offset] = str_replace(array("\r\n", "\n"), "", $data->current()); //Read Next Line $data->next(); } } else { //Old Fasion Way. Load The Whole File Into An Array. $data = @explode("\n", file_get_contents($filePath)); //Sanity Check if (empty($data) || !isset($data[$line])) { return false; } for ($i = $line - $context; $i <= $line + $context; $i++) { if (!isset($data[$i + $offset - 1])) { //No More Information break; } //Format Current Line + Add To Array $lines[$i + $offset] = str_replace(array("\r\n", "\n"), "", $data[$i + $offset - 1]); } } } //Return Array Of Line Items return Debug::formatCode($lines, $errorLine); }
<?php //line 2 //line 3 //line 4 //line 5 $s = new SplFileObject(__FILE__); $s->seek(13); echo $s->current(); $s->next(); echo $s->current(); var_dump($s->valid());
/** * Returns whether or not the current iteration is valid. * * @return bool */ public function valid() { // if a stopping point is set, stop and reset if ($this->stop && $this->key() > $this->stop) { return false; } return parent::valid(); }
/** * Renvoi les x derniere ligne du fichier de log * @param int $_maxLigne nombre de ligne voulu * @return string Ligne du fichier de log */ public static function get($_log = 'core', $_begin, $_nbLines) { self::chunk($_log); $page = array(); if (!file_exists($_log) || !is_file($_log)) { $path = self::getPathToLog($_log); if (!file_exists($path)) { return false; } } else { $path = $_log; } $log = new SplFileObject($path); if ($log) { $log->seek($_begin); //Seek to the begening of lines $linesRead = 0; while ($log->valid() && $linesRead != $_nbLines) { $line = $log->current(); //get current line if (count(explode("|", $line)) == 3) { array_unshift($page, array_map('trim', explode("|", $line))); } else { if (trim($line) != '') { $lineread = array(); $lineread[0] = ''; $lineread[1] = ''; $lineread[2] = $line; array_unshift($page, $lineread); } } $log->next(); //go to next line $linesRead++; } } return $page; }
function skillsoft_import_customreport($handle, $importfile, $trace = false, $prefix = ' ') { global $CFG, $DB; set_time_limit(0); $starttime = microtime(true); if ($trace) { mtrace($prefix . get_string('skillsoft_customreport_import_start', 'skillsoft')); } $file = new SplFileObject($importfile); $file->setFlags(SplFileObject::READ_CSV); $rowcounter = -1; $insertokay = true; $transaction = $DB->start_delegated_transaction(); do { $row = $file->fgetcsv(); if ($rowcounter == -1) { //This is the header row $headerrowarray = $row; } else { if ($row[0]) { $report_results = ConvertCSVRowToReportResults($headerrowarray, $row); $insertokay = skillsoft_insert_report_results($report_results); } if ($trace) { if ($rowcounter % 1000 == 0) { //Output message every 1000 entries mtrace($prefix . $prefix . get_string('skillsoft_customreport_import_rowcount', 'skillsoft', $rowcounter)); } } } $file->next(); $rowcounter++; } while ($file->valid() && $insertokay); $transaction->allow_commit(); if ($insertokay) { if ($trace) { mtrace($prefix . $prefix . get_string('skillsoft_customreport_import_totalrow', 'skillsoft', $rowcounter)); } unset($file); skillsoft_update_customreport_imported($handle); } else { if ($trace) { mtrace($prefix . $prefix . get_string('skillsoft_customreport_import_errorrow', 'skillsoft', $rowcounter)); } } $endtime = microtime(true); $duration = $endtime - $starttime; if ($trace) { mtrace($prefix . get_string('skillsoft_customreport_import_end', 'skillsoft') . ' (took ' . $duration . ' seconds)'); } return $insertokay; }
/** * Update the index */ function update() { global $conf; // using a lock to prevent the indexer from running multiple instances if ($this->lock() == false) { $this->error('unable to get lock, bailing'); exit(1); } // are we indexing a single namespace or all files? if ($this->namespace) { $dir = $conf['datadir'] . DS . str_replace(':', DS, $this->namespace); $idPrefix = $this->namespace . ':'; } else { $dir = $conf['datadir']; $idPrefix = ''; } // get a temp file name to store the list of files to index if (empty(self::$tempFileName)) { self::$tempFileName = sys_get_temp_dir() . '/EnhancedIndexer-' . microtime(true); if (file_exists(self::$tempFileName)) { self::$tempFileName .= 'b'; } $this->quietecho("Searching pages... "); // we aren't going to use $data, but the search function needs it $data = array(); search($data, $dir, 'EnhancedIndexerCLI::save_search_allpages', array('skipacl' => true)); $this->quietecho(self::$totalPagesToIndex . " pages found.\n"); } $cnt = 0; try { // we are using the SplFileObject so we can read one line without loading the whole file $this->temp_file = new SplFileObject(self::$tempFileName); // this flag tells the SplFileObject to remove the \n from the end of each line it reads $this->temp_file->setFlags(SplFileObject::DROP_NEW_LINE); for ($i = $this->startOffset; $i < self::$totalPagesToIndex; $i++) { // make sure the file handle is still open if (!$this->temp_file->valid()) { break; } // move to the next line and read the page id $this->temp_file->seek($i); $pageId = $this->temp_file->current(); // index this page, if not done already if ($this->index($idPrefix . $pageId, $i + 1, self::$totalPagesToIndex)) { $cnt++; $this->clean = false; } // used to exit cleanly if ctrl+c is detected if ($this->exit) { break; } // restart when memory usage exceeds 256M if (memory_get_usage() > ONE_MEGABYTE * 256) { $this->error('Memory almost full, resetting'); $this->restart($i + 1); } if ($this->maxRuns && $cnt >= $this->maxRuns) { $this->error('Max runs reached ' . $cnt . ', restarting'); $this->restart($i + 1); } } // release the temp file if (!empty($this->temp_file)) { $this->temp_file = null; unset($this->temp_file); } } catch (Exception $e) { $this->error("\n" . $e->getMessage()); } // remove the temp file if (is_file(self::$tempFileName)) { $this->quietecho("Removing temp file... "); unlink(self::$tempFileName); $this->quietecho("done\n"); } }
/** * Obtain test case tags * * @return Array */ function getTags() { if (empty($this->_tagsMap)) { $testCaseFileObj = new SplFileObject($this->_testCaseFile); $line = ""; $inTags = false; if ($testCaseFileObj->isReadable()) { while ($testCaseFileObj->valid() && $line != "#--- End tags\n") { $line = $testCaseFileObj->fgets(); if ($inTags && $line == "#--- End tags\n") { $inTags = false; } if ($inTags) { $this->_tagsMap[] = trim(str_replace("#", "", $line)); } if (!$inTags && $line == "#--- Start tags\n") { $inTags = true; } } } } return $this->_tagsMap; }
function clean_logstalgia($clean_number, $directory, $root_directory) { global $conf; $filename = $directory . "logstalgia.txt"; $file = new SplFileObject($filename); $line_0 = $file->current(); $line_last = ""; $i = 0; while ($file->valid() && $i < $conf['limit_logstalgia']) { $i++; if ($file->current() != "") { $line_last = $file->current(); } $file->next(); } if ($i = $conf['limit_logstalgia']) { $line_0_explode = explode('|', $line_0); $line_last_explode = explode('|', $line_last); exec("cp {$filename} {$root_directory}/backup/logstalgia-" . $line_0_explode[0] . "-" . $line_last_explode[0] . ".txt"); exec("chown " . $conf['user_logstalgia'] . " {$root_directory}/backup/logstalgia-" . $line_0_explode[0] . "-" . $line_last_explode[0] . ".txt"); $handle = fopen($filename, "w") or die("Can't create file"); fclose($handle); } }
/** * Renvoi les x derniere ligne du fichier de log * @param int $_maxLigne nombre de ligne voulu * @return string Ligne du fichier de log */ public static function get($_log = 'core', $_begin, $_nbLines) { $replace = array('>' => '>', ''' => ''); self::chunk($_log); $page = array(); if (!file_exists($_log) || !is_file($_log)) { $path = self::getPathToLog($_log); if (!file_exists($path)) { return false; } } else { $path = $_log; } $log = new SplFileObject($path); if ($log) { $log->seek($_begin); //Seek to the begening of lines $linesRead = 0; while ($log->valid() && $linesRead != $_nbLines) { $line = $log->current(); //get current line $explode = explode("|", $line); if (count($explode) == 3) { $explode[2] = secureXSS($explode[2]); array_unshift($page, array_map('trim', $explode)); } else { if (trim($line) != '') { $lineread = array(); $lineread[0] = ''; $lineread[1] = ''; $lineread[2] = str_replace(array_keys($replace), $replace, htmlspecialchars($line)); $lineread[2] = $line; array_unshift($page, $lineread); } } $log->next(); //go to next line $linesRead++; } } return $page; }