public function current()
 {
     $type = 'unkown';
     $isCovered = false;
     if (isset($this->lines[$this->position])) {
         $type = $this->lines[$this->position]['type'];
         $isCovered = $this->lines[$this->position]['isCovered'];
     }
     return array('type' => $type, 'isCovered' => $isCovered, 'content' => $this->file->fgets());
 }
Пример #2
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (parent::execute($input, $output)) {
         $this->loadOCConfig();
         $properties = array('string $id', 'string $template', 'array $children', 'array $data', 'string $output');
         // TODO: get all library classes as well, maybe extract from registry somehow...
         $searchLine = "abstract class Controller {";
         $pathToController = "engine/controller.php";
         $catalogModels = $this->getModels(\DIR_APPLICATION);
         $adminModels = $this->getModels(str_ireplace("catalog/", "admin/", \DIR_APPLICATION));
         $textToInsert = array_unique(array_merge($properties, $catalogModels, $adminModels));
         //get line number where start Controller description
         $fp = fopen(\DIR_SYSTEM . $pathToController, 'r');
         $lineNumber = $this->getLineOfFile($fp, $searchLine);
         fclose($fp);
         //regenerate Controller text with properties
         $file = new \SplFileObject(\DIR_SYSTEM . $pathToController);
         $file->seek($lineNumber);
         $tempFile = sprintf("<?php %s \t/**%s", PHP_EOL, PHP_EOL);
         foreach ($textToInsert as $val) {
             $tempFile .= sprintf("\t* @property %s%s", $val, PHP_EOL);
         }
         $tempFile .= sprintf("\t**/%s%s%s", PHP_EOL, $searchLine, PHP_EOL);
         while (!$file->eof()) {
             $tempFile .= $file->fgets();
         }
         //write Controller
         $fp = fopen(\DIR_SYSTEM . $pathToController, 'w');
         fwrite($fp, $tempFile);
         fclose($fp);
     }
 }
Пример #3
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $filename = $input->getArgument('filename');
     if (!file_exists($filename)) {
         throw new \Symfony\Component\HttpKernel\Exception\BadRequestHttpException("Le fichier {$filename} n'existe pas.");
     }
     // Indicateurs
     $i = 0;
     // Nombre de mots-clés importés
     $em = $this->getContainer()->get('doctrine')->getManager();
     $categorieRepository = $em->getRepository('ComptesBundle:Categorie');
     $file = new \SplFileObject($filename);
     while (!$file->eof()) {
         $line = $file->fgets();
         list($word, $categorieID) = explode(':', $line);
         $word = trim($word);
         $categorieID = (int) $categorieID;
         $categorie = $categorieRepository->find($categorieID);
         if ($categorie === null) {
             throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException("La catégorie n°{$categorieID} est inconnue.");
         }
         $keyword = new Keyword();
         $keyword->setWord($word);
         $keyword->setCategorie($categorie);
         // Indicateurs
         $i++;
         // Enregistrement
         $em->persist($keyword);
     }
     // Persistance des données
     $em->flush();
     // Indicateurs
     $output->writeln("<info>{$i} mots-clés importés</info>");
 }
Пример #4
0
 function fgets()
 {
     if (!$this->valid()) {
         return false;
     }
     return parent::fgets();
 }
Пример #5
0
 public function actionIndex($path = null, $fix = null)
 {
     if ($path === null) {
         $path = YII_PATH;
     }
     echo "Checking {$path} for files with BOM.\n";
     $checkFiles = CFileHelper::findFiles($path, array('exclude' => array('.gitignore')));
     $detected = false;
     foreach ($checkFiles as $file) {
         $fileObj = new SplFileObject($file);
         if (!$fileObj->eof() && false !== strpos($fileObj->fgets(), self::BOM)) {
             if (!$detected) {
                 echo "Detected BOM in:\n";
                 $detected = true;
             }
             echo $file . "\n";
             if ($fix) {
                 file_put_contents($file, substr(file_get_contents($file), 3));
             }
         }
     }
     if (!$detected) {
         echo "No files with BOM were detected.\n";
     } else {
         if ($fix) {
             echo "All files were fixed.\n";
         }
     }
 }
Пример #6
0
function upload_hathdl()
{
    $file = new SplFileObject($_FILES['ehgfile']['tmp_name']);
    $gid = -1;
    $page = -1;
    $title = null;
    $tags = null;
    while (!$file->eof()) {
        $line = $file->fgets();
        $line = trim($line);
        $token = explode(' ', $line);
        if (strcmp($token[0], 'GID') == 0) {
            $gid = intval($token[1]);
        } else {
            if (strcmp($token[0], 'FILES') == 0) {
                $page = intval($token[1]);
            } else {
                if (strcmp($token[0], 'TITLE') == 0) {
                    $title = trim(preg_replace('TITLE', '', $line));
                } else {
                    if (strcmp($token[0], 'Tags:') == 0) {
                        $tags = trim(preg_replace('Tags:', '', $line));
                    }
                }
            }
        }
    }
    shell_exec('cp ' . $_FILES['ehgfile']['tmp_name'] . ' hentaiathome/hathdl/');
    $info['gid'] = $gid;
    $info['page'] = $page;
    $info['title'] = $title;
    $info['tags'] = $tags;
    return $info;
}
Пример #7
0
 public function __construct($filepath)
 {
     $file = new \SplFileObject($filepath);
     $this->path = $file->getFilename();
     while (!$file->eof()) {
         $this->content .= $file->fgets();
     }
 }
Пример #8
0
 /**
  * Gets a line from the given resource.
  *
  * @link http://php.net/manual/en/function.fgets.php
  *
  * @param int $length   If set the reading will end when the given length reached.
  *
  * @throws \YapepBase\Exception\File\Exception   In case the object does not have an opened file.
  *
  * @return string|bool   The line. Or FALSE if the pointer is at the end of the resource, or on error.
  */
 public function getLine($length = null)
 {
     $this->checkIfFileOpened();
     if ($this->checkIfPointerIsAtTheEnd()) {
         return false;
     }
     return $this->splFile->fgets();
 }
Пример #9
0
 /**
  * Load file content and decode the json
  */
 protected function loadJson()
 {
     $lines = '';
     while (!$this->file->eof()) {
         $lines .= $this->file->fgets();
     }
     $this->json = json_decode($lines);
 }
Пример #10
0
 /**
  * Loads the config from a json file
  *
  * @param $configFile
  *
  * @throws ConfigException
  */
 private function loadJsonFromFile($configFile)
 {
     $file = new \SplFileObject($configFile, 'r+');
     $json = $file->fgets();
     $this->config = json_decode($json);
     if (json_last_error() != JSON_ERROR_NONE) {
         throw new ConfigException("Problem reading json");
     }
 }
Пример #11
0
 /**
  * Free the used slots
  *
  * @param $sliced_report_definitions_count
  */
 private function freeUsedRequestCount($sliced_report_definitions_count)
 {
     $this->file_counter->flock(LOCK_EX);
     $this->file_counter->rewind();
     $used_request_count = (int) $this->file_counter->fgets();
     $new_used_request_count = $used_request_count - $sliced_report_definitions_count;
     $this->file_counter->ftruncate(0);
     $this->file_counter->fwrite($new_used_request_count);
     $this->file_counter->flock(LOCK_UN);
 }
Пример #12
0
 public static function SendNewOrderMessage($account, $orderId, $PriceSum)
 {
     $file = new SplFileObject(__ROOT__ . '/application/EmailService/EmailTemplates/order.txt');
     $message = '';
     while (!$file->eof()) {
         $message = $message . $file->fgets();
     }
     $message = str_replace('@AccountName', $account->account_name, $message);
     $message = str_replace('@OrderId', $orderId, $message);
     $message = str_replace('@Price', $PriceSum, $message);
     mail($account->email, 'Регистрация', $message, 'Content-type:text/html;');
 }
Пример #13
0
 /**
  * Clears a directory of cached files with the correct header.
  *
  * @return void
  */
 protected function _clearDirectory($path)
 {
     $dir = new DirectoryIterator($path);
     foreach ($dir as $file) {
         $fileInfo = new SplFileObject($file->getPathname());
         $line = $fileInfo->fgets();
         if (preg_match('#^/\\* asset_compress \\d+ \\*/$#', $line)) {
             $this->out('Deleting ' . $fileInfo->getPathname());
             unlink($fileInfo->getPathname());
         }
     }
 }
Пример #14
0
 /**
  * Imports given JSON file
  * @param string $filePath Path to a JSON file with data to import
  * @return array Array with import output - metadata, status, warnings and errors
  */
 public function importFile($filePath)
 {
     $this->tmpFile = new SplFileObject($filePath, "r");
     $curState = new JSONImportStateStart(array('meta' => array(), 'result' => array(), 'user_id' => $this->params['user_id']));
     $result = array('success' => false);
     $stepResult = false;
     while (!$this->tmpFile->eof()) {
         $curLine = trim($this->tmpFile->fgets());
         $stepResult = $curState->processLine($curLine);
         // Returns next state for processing
         if (!is_array($stepResult)) {
             $curState = $stepResult;
             // Returned array with results
         } else {
             $result = $stepResult;
             $result['success'] = true;
             break;
         }
     }
     return $result;
 }
Пример #15
0
 /**
  *
  * because \SplFileObject::fread() is not available before 5.5.11 anyway
  * 
  * returns the full content of a file, rewinds pointer in the beginning and leaves it at the end
  * but dont rely on this pointer behaviour
  * 
  * @param \SplFileObject $fileObject
  *
  * @return \SplString|string
  */
 public static function getContent(\SplFileObject $fileObject)
 {
     if (class_exists('SplString')) {
         $result = new \SplString();
     } else {
         $result = '';
     }
     $fileObject->rewind();
     while (!$fileObject->eof()) {
         $result .= $fileObject->fgets();
     }
     return $result;
 }
Пример #16
0
 /**
  * @param \Closure $callback
  */
 protected function parseFile(\Closure $callback)
 {
     while (!$this->file->eof()) {
         if (strlen($this->delim) == 1) {
             $data = $this->file->fgetcsv($this->delim, $this->enclosure);
         } else {
             $data = explode($this->delim, $this->file->fgets());
             $data = array_map(function ($row) {
                 return mb_convert_encoding(trim($row, $this->enclosure), "UTF-8", "Windows-1252,ISO-8859-15");
             }, $data);
             if ($this->debug) {
                 break;
             }
             /*
              $enclosure = $this->enclosure;
              array_walk($data, function(&$val) use ($enclosure) {
                 return trim($val, $enclosure);
             });
             */
         }
         $callback($data);
     }
 }
Пример #17
0
 /**
  * 获取文件列表
  *
  * @author          mrmsl <*****@*****.**>
  * @date            2012-07-17 12:46:02
  *
  * @param string $node 节点路径
  *
  * @return array 文件列表
  */
 private function _getFile($node)
 {
     $node = trim($node, '/');
     $this->_denyDirectory($node);
     $file_arr = array();
     $directory = PACKER_JS_PATH . $node . '/';
     $k = 0;
     if (is_dir($directory)) {
         $date_format = sys_config('sys_timezone_datetime_format');
         $d = dir($directory);
         while ($f = $d->read()) {
             if ($f == '.' || $f == '..' || substr($f, 0, 1) == '.') {
                 continue;
             }
             $filename = $directory . '/' . $f;
             if (is_dir($filename)) {
                 $file_arr[$k] = array('text' => $f, 'checked' => $f == 'pack' ? null : false, 'id' => $node . '/' . $f);
                 $file_arr[$k]['data'] = $this->_getFile($f);
                 $k++;
             } elseif (substr($f, -3) == '.js' && !in_array($f, array('app.js'))) {
                 $desc = '';
                 //js文件说明
                 $file = new SplFileObject($filename);
                 if (!strpos($filename, '.min.')) {
                     $file->fgets();
                     $desc = trim(str_replace('*', '', $file->fgets()));
                     //第二行为文件说明
                 }
                 $file_arr[] = array('text' => $f, 'id' => $node . '/' . $f, 'leaf' => true, 'checked' => $node == 'pack' ? null : false, 'filesize' => format_size($file->getSize()), 'filemtime' => new_date($date_format, $file->getMTime()), 'desc' => $desc);
             }
         }
         //end while
         $d->close();
     }
     //end if
     return $file_arr;
 }
Пример #18
0
 /**
  * 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;
 }
 /**
  * Clears a directory of cached files with the correct header.
  *
  * @return void
  */
 protected function _clearDirectory($path)
 {
     $dir = new DirectoryIterator($path);
     foreach ($dir as $file) {
         if (in_array($file->getFilename(), array('.', '..'))) {
             continue;
         }
         $fileInfo = new SplFileObject($file->getPathname());
         $line = $fileInfo->fgets();
         if (preg_match('#^/\\* asset_compress \\d+ \\*/$#', $line)) {
             $pathName = $fileInfo->getPathname();
             unset($fileInfo);
             $this->out('Deleting ' . $pathName);
             unlink($pathName);
         }
     }
 }
Пример #20
0
 /**
  * Extracts data from the file
  * @param  SplFileObject $fileObject  File object.
  * @throws                            Invalid data exception.
  * @return array                      Filtered data.
  */
 private function extractData($fileObject)
 {
     $data = array();
     while (!$fileObject->eof()) {
         $line = trim($fileObject->fgets());
         if (!empty($line)) {
             //2 or more white spaces in case of team name with a space
             $parts = preg_split('/\\s{2,}/', $line);
             if (count($parts) == 9) {
                 $data[] = $parts;
             } else {
                 throw new Exception('Invalid data');
             }
         }
     }
     return $data;
 }
Пример #21
0
 public function import()
 {
     if ('0' === $this->job['export_db']) {
         $this->job->log(__('Skipping database import', 'my-wp-backup'));
         return true;
     }
     global $wpdb;
     $file = new \SplFileObject(MyWPBackup::$info['root_dir'] . self::FILENAME, 'r');
     $query = '';
     if (false === $wpdb->query('START TRANSACTION')) {
         throw new \Exception('Unable to start database trasacction.');
     }
     try {
         while (!$file->eof()) {
             $line = trim($file->fgets());
             if ('' === $line || '--' === substr($line, 0, 2) || '/*' === substr($line, 0, 2)) {
                 continue;
             }
             $query .= $line;
             if (';' === substr($query, -1, 1) && !empty($query)) {
                 if (false === $wpdb->query($query)) {
                     error_log('failed executing ' . substr($query, 0, 50) . '...' . substr($query, -50));
                     error_log('last error was ' . $wpdb->last_error);
                     error_log('last query was ' . $wpdb->last_query);
                     throw new \Exception(sprintf(__('Failed to execute a mysql query. Please import the sql file manually.', 'my-wp-backup'), $line));
                 } else {
                     $query = '';
                 }
             }
         }
         if (false === $wpdb->query('COMMIT')) {
             throw new \Exception(__('Unable to commit database trasaction.', 'my-wp-backup'));
         }
         return true;
     } catch (\Exception $e) {
         $msg = $e->getMessage();
         if (false === $wpdb->query('ROLLBACK')) {
             $msg = sprintf(__('Unable to rollback database transaction. Additionaly: %s ', 'my-wp-backup'), $msg);
         }
         $this->job->log($msg, 'error');
         return false;
     }
 }
Пример #22
0
 public static function get()
 {
     $filename = __DIR__ . '/../Resources/data/user-agents.txt';
     /*return trim(
           shell_exec(
               sprintf(
                   'awk NR==$((${RANDOM} %% `wc -l < %s` + 1)) %s',
                   $filename,
                   $filename
               )
           )
       );*/
     $file = new \SplFileObject($filename);
     $lines = 0;
     foreach ($file as $line) {
         $lines++;
     }
     $file->seek(rand(1, $lines));
     return trim($file->fgets());
 }
Пример #23
0
 protected function buildForClass($className)
 {
     $r = new \ReflectionClass($className);
     $file = new \SplFileObject($r->getFileName());
     $classLineNumber = $r->getStartLine();
     $uses = array();
     for ($i = 0; $i < $classLineNumber; $i++) {
         $line = $file->fgets();
         if (preg_match('/^\\s*use\\s([a-zA-Z_][a-zA-Z0-9_\\\\]*)(\\sas\\s([a-zA-Z_][a-zA-Z0-9_]*))?/i', $line, $match)) {
             $usedClassName = $match[1];
             if (isset($match[3])) {
                 $classAlias = $match[3];
             } else {
                 $explodedClassName = explode('\\', $usedClassName);
                 $classAlias = $explodedClassName[count($explodedClassName) - 1];
             }
             $uses[$classAlias] = $usedClassName;
         }
     }
     $this->uses[$className] = $uses;
 }
Пример #24
0
 public function import()
 {
     if ('0' === $this->job['export_db']) {
         $this->job->log(__('Skipping database import', 'my-wp-backup'));
         return;
     }
     global $wpdb;
     $file = new \SplFileObject(MyWPBackup::$info['root_dir'] . self::FILENAME, 'r');
     $query = '';
     while (!$file->eof()) {
         $line = trim($file->fgets());
         if ('' === $line || '--' === substr($line, 0, 2)) {
             continue;
         }
         $query .= $line;
         if (';' === substr($query, -1)) {
             if (false === $wpdb->query($query)) {
                 $this->job->log(sprintf(__('Failed to execute query: %s', 'my-wp-backup'), $line), 'error');
             }
             $query = '';
         }
     }
 }
Пример #25
0
 private function LoadSourceLines(\ReflectionFunctionAbstract $Reflection)
 {
     if (!$Reflection->isUserDefined()) {
         throw new Functional\FunctionException('Cannot parse function: Function must be user defined');
     }
     $FileName = $Reflection->getFileName();
     if (!file_exists($FileName)) {
         throw new Functional\FunctionException('Cannot parse function: Function does not belong to a valid file (cannot be eval\'d code)');
     }
     $SourceLines = [];
     $File = new \SplFileObject($Reflection->getFileName());
     $StartLine = $Reflection->getStartLine() - 2;
     $File->seek($StartLine);
     $EndLine = $Reflection->getEndLine() - 2;
     while ($File->key() <= $EndLine) {
         $SourceLines[] = trim($File->fgets());
     }
     unset($File);
     $FirstLine =& $SourceLines[0];
     $FirstLine = substr($FirstLine, stripos($FirstLine, 'function'));
     $LastLine =& $SourceLines[count($SourceLines) - 1];
     $LastLine = substr($LastLine, 0, strrpos($LastLine, '}') + 1);
     return array_filter($SourceLines);
 }
 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];
 }
Пример #27
0
$stddirs = array();
$stddirs[] = $path;
$stddirs = vTranslate::getFolders($path, $stddirs);
// Convert EVERYTHINGWOOOOOT
foreach ($stddirs as $sourcedir) {
    vTranslate::log("Processing: " . $sourcedir . "\n", $log);
    $targetpath = str_replace($path, $temppath, $sourcedir);
    if (!is_dir($targetpath)) {
        mkdir($targetpath);
    }
    $files = vTranslate::getFiles($sourcedir);
    foreach ($files as $f) {
        $file = new SplFileObject($sourcedir . '/' . $f);
        $targetfile = new SplFileObject($targetpath . '/' . $f, 'w');
        while (!$file->eof()) {
            $line = $file->fgets();
            if (strpos($file->getFilename(), '.ini')) {
                if (strpos($line, '_') === 0) {
                    $line = substr($line, 1);
                }
            } elseif (strpos($file->getFilename(), '.php')) {
                $line = str_replace("JText::_('_", "JText::_('", $line);
            }
            $targetfile->fwrite($line);
        }
    }
}
// et voilà
vTranslate::log("All done." . "\n\n", $log);
class vTranslate
{
Пример #28
0
<?php

$fname = tempnam('/tmp', 'foobar');
file_put_contents($fname, 'herpderp');
$spl = new SplFileObject($fname, 'r');
$spl->fseek($spl->getSize() - 4);
var_dump($spl->fgets());
Пример #29
0
 /**
  * Generates a uuid.
  *
  * @return string
  */
 private function getJobFilename($queueName)
 {
     $path = $this->baseDirectory . '/bernard.meta';
     if (!is_file($path)) {
         touch($path);
     }
     $file = new \SplFileObject($path, 'r+');
     $file->flock(LOCK_EX);
     $meta = unserialize($file->fgets());
     $id = isset($meta[$queueName]) ? $meta[$queueName] : 0;
     $id++;
     $filename = sprintf('%d.job', $id);
     $meta[$queueName] = $id;
     $content = serialize($meta);
     $file->fseek(0);
     $file->fwrite($content, strlen($content));
     $file->flock(LOCK_UN);
     return $filename;
 }
Пример #30
0
 /**
  * @param string $name
  * @param array $configRaw
  * @param integer $limit
  */
 protected function callSync($name, $configRaw, $limit)
 {
     //normalize config
     $config = array('last' => isset($configRaw[$name . '_last']) ? $configRaw[$name . '_last'] : 0, 'rows' => isset($configRaw[$name . '_rows']) ? $configRaw[$name . '_rows'] : 0);
     $filePath = $this->iniConfiguration->getTempPath() . '/' . $name . '.data';
     if ($config['rows'] == 0) {
         //create new request
         $response = $this->getWrapper()->request('data', $name, array('lastDownload' => $config['last']));
         //analyze response
         switch ($this->getWrapper()->analyzeResponse($response)) {
             case 'url':
                 //continue to download
                 $this->getWrapper()->download($response->url, $filePath);
                 break;
             case 'suspend':
                 //suspend processing for time in response
                 return $this->suspend($response->until);
             default:
                 throw new Api\ApiException('Response from datadepo is unknow');
         }
     }
     //open file and read header
     $file = new \SplFileObject($filePath);
     $header = json_decode($file->fgets(), TRUE);
     //check number of lines in downloaded file
     if ($config['rows'] == 0) {
         $file->seek(PHP_INT_MAX);
         $linesTotal = $file->key() + 1;
         if ($header['numRecords'] != $linesTotal - 1) {
             throw new Api\ApiException('Incompleted file downloaded in ' . $name . ' synchronizer');
         }
         $file->rewind();
     }
     $processCount = $this->iniConfiguration->get('limits', 'processCount');
     $collector = $this->createCollector();
     $count = 0;
     //skip line
     $file->seek($config['rows'] + 1);
     while ((!$file->eof() || $file->current() !== FALSE) && $count < $limit) {
         //add line to front
         $line = $this->wrapLine($file->current());
         $collector->add($line);
         $count++;
         //process
         if ($count % $processCount === 0) {
             $this->processChunk($collector);
             $collector = $this->createCollector();
         }
         $file->next();
     }
     //sync rest
     if (count($collector) > 0) {
         $this->processChunk($collector);
     }
     //check num processed
     if ($count == $limit) {
         $this->dataStore->setConfig($name . '_rows', $config['rows'] + $count);
     } else {
         $this->dataStore->setConfig($name . '_rows', 0);
         $this->dataStore->setConfig($name . '_last', $header['generatedAt']);
     }
     return new Api\DataDepoResponse(Api\DataDepoResponse::CODE_OK, NULL, array('processed' => $count));
 }