示例#1
0
 public function create($filename)
 {
     $now = date('Y_m_d_H_i_s');
     $fileob = new \SplFileObject($this->path . $now . '_' . $filename . '.php', 'w');
     $classname = $this->getClassByFileName(str_replace('_table', '', $filename));
     $fileob->flock(LOCK_EX);
     $fileob->fwrite("<?php\nuse Lib\\Migration;\nclass {$classname} extends Migration\n{\n    public function up()\n    {\n    }\n    public function down()\n    {\n    }\n} \n?>");
     $fileob->flock(LOCK_UN);
     return true;
 }
示例#2
0
文件: Bot.php 项目: mpyw/hardbotter
 /**
  * コンストラクタ
  * 副作用が大量にあるので注意
  */
 public function __construct(ClientInterface $client, $filename = 'stamp.json', $span = 0, $mark_limit = 10000, $back_limit = 3600)
 {
     // ヘッダの送出
     if (!headers_sent()) {
         header('Content-Type: text/html; charset=UTF-8');
     }
     // エラー表示の設定
     error_reporting(-1);
     ini_set('log_errors', PHP_SAPI === 'cli');
     ini_set('display_errors', PHP_SAPI !== 'cli');
     // 重複起動防止
     $file = new \SplFileObject($filename, 'a+b');
     if (!$file->flock(LOCK_EX | LOCK_NB)) {
         throw new \RuntimeException('Failed to lock file.');
     }
     // JSONとして保存してあるデータを取得
     clearstatcache();
     $json = $file->getSize() > 0 ? json_decode($file->fread($file->getSize()), true) : [];
     // JSONに前回実行時刻が保存されていた時
     if (isset($json['prev'])) {
         // 十分に時間が空いたかどうかをチェック
         if (!static::expired($json['prev'], $span)) {
             throw new \RuntimeException('Execution span is not enough.');
         }
     }
     // JSONにマーク済みステータス一覧が記録されていたとき復元する
     if (isset($json['marked'])) {
         $this->marked = array_map('filter_var', (array) $json['marked']);
     }
     $this->client = $client;
     $this->file = $file;
     $this->prev = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('r');
     $this->mark_limit = $mark_limit;
     $this->back_limit = $back_limit;
 }
 public function __construct($rewriteRuleFile = false)
 {
     if (function_exists('apache_get_modules') && !in_array('mod_rewrite', apache_get_modules())) {
         throw new \Exception('mod_rewrite module must be activated');
     }
     $rewriteRuleFile = $rewriteRuleFile ? $rewriteRuleFile : PATH_ROOT . '.htaccess';
     $this->setRewriteRuleFile($rewriteRuleFile);
     $fileRule = new \SplFileObject($this->_rewriteRuleFile, 'r');
     if ($fileRule->flock(LOCK_EX)) {
         foreach ($fileRule as $line) {
             if (strpos($line, 'RewriteRule') !== false && strpos($line, '#') === false) {
                 $this->setRewriteRule($line);
             }
         }
         $fileRule->flock(LOCK_UN);
     }
 }
示例#4
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);
 }
示例#5
0
 public function __construct($params = array())
 {
     if (!extension_loaded('apcu') && !extension_loaded('apc')) {
         throw new \Exception('Apcu extension not loaded try change your PHP configuration');
     }
     parent::init($params);
     Logger::getInstance()->addGroup('cache' . $this->_name, 'Cache ' . $this->_name, true, true);
     //create dynamic key and add to prefix (it's for multi applications)
     if (!file_exists(PATH_CACHE . $this->_name)) {
         $key = rand();
         $file = new \SplFileObject(PATH_CACHE . 'ApcuKey' . $this->_name, 'w+');
         if ($file->flock(LOCK_EX)) {
             $file->fwrite($key);
             $file->flock(LOCK_UN);
         }
         $this->_prefix .= $key;
     } else {
         $this->_prefix .= file_get_contents(PATH_CACHE . $this->_name);
     }
 }
示例#6
0
 /**
  * Writes the record data from memory into the file store.
  *
  * @return void
  */
 public function save()
 {
     $tmpHandle = new \SplFileObject('php://temp', 'w+');
     $tmpData = '';
     $tmpHandle->fputcsv($this->model->columns());
     foreach ($this->all() as $record) {
         $tmpHandle->fputcsv($record->toArray());
         $record->exists = true;
     }
     $tmpHandle->rewind();
     while (!$tmpHandle->eof()) {
         $tmpData .= $tmpHandle->fgets();
     }
     $this->file->flock(\LOCK_EX | \LOCK_NB);
     $this->file->ftruncate(0);
     $this->file->rewind();
     $this->file->fwrite($tmpData);
     $this->file->flock(\LOCK_UN);
 }
示例#7
0
文件: File.php 项目: kmfk/slowdb
 /**
  * Index the file by getting key/value positions within the file
  *
  * @return array
  */
 public function buildIndex()
 {
     $this->file->flock(LOCK_SH);
     $this->file->fseek(0);
     $indexes = [];
     while (!$this->file->eof()) {
         $position = $this->file->ftell();
         // Grab key and value lengths - if its the last (empty) line, break
         if (!($metadata = $this->getMetadata())) {
             break;
         }
         // Gets the key and adds the key and position to the index
         $indexes[$this->file->fread($metadata->klen)] = $position;
         //Skip over the value, to the next key/value pair
         $this->file->fseek($metadata->vlen, SEEK_CUR);
     }
     $this->file->flock(LOCK_UN);
     return $indexes;
 }
示例#8
0
 /**
  * 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;
 }
示例#9
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;
 }
示例#10
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;
 }
示例#11
0
 private function updateOrDelete($id, $data = null)
 {
     /* Thanks to https://www.daniweb.com/web-development/php/threads/102279/deleting-a-line-from-a-file#post1353582 */
     /*
      * Create a new SplFileObject representation of the file
      * Open it for reading and writing and place the pointer at the beginning of the file
      * @see fopen for additional modes
      */
     $file = new \SplFileObject($this->filename, 'a+');
     /*
      * Set a bitmask of the flags to apply - Only relates to reading from file
      * In this case SplFileObject::DROP_NEW_LINE to remove new line charachters
      * and SplFileObject::SKIP_EMPTY to remove empty lines
      */
     $file->setFlags(7);
     /*
      * Lock the file so no other user can interfere with reading and writing while we work with it
      */
     $file->flock(LOCK_EX);
     /*
      * Create a SplTempFileObject
      * 0 indicates not to use memory to store the temp file.
      * This is probably slower than using memory, but for a large file it will be much more effective
      * than loading the entire file into memory
      * @see http://www.php.net/manual/en/spltempfileobject.construct.php for more details
      */
     $temp = new \SplTempFileObject(0);
     /*
      * Lock the temp file just in case
      */
     $temp->flock(LOCK_EX);
     /*
      * Iterate over each line of the file only loading one line into memory at any point in time
      */
     foreach ($file as $key => $line) {
         if ($key != $id) {
             /*
              * If this line does NOT match out delete write it to the temp file
              * Append a line ending to it
              */
             $temp->fwrite($line . PHP_EOL);
         } else {
             if ($data !== null) {
                 $temp->fwrite($data . PHP_EOL);
             }
         }
     }
     /*
      * Truncate the existing file to 0
      */
     $file->ftruncate(0);
     /*
      * Write the temp file back to the existing file
      */
     foreach ($temp as $line) {
         /*
          * Iterate over temp file and put each line back into original file
          */
         $file->fwrite($line);
     }
     /*
      * Release the file locks
      */
     $temp->flock(LOCK_UN);
     $file->flock(LOCK_UN);
     return true;
 }
示例#12
0
 protected function _writeLogs()
 {
     if (!empty($this->_logs)) {
         $file = new \SplFileObject($this->_selectLogDir() . date('d') . '.' . self::$_logExt, 'a+');
         if ($file->flock(LOCK_EX)) {
             $file->fwrite($this->_logs);
             $file->flock(LOCK_UN);
         }
         $this->_logs = '';
     }
 }
示例#13
0
 /**
  * @return $this
  */
 public function RUnlock()
 {
     $this->_file->flock(LOCK_UN);
 }
示例#14
0
 /**
  * Compiles the javascript files for the passed shop template.
  *
  * @param $timestamp
  * @param Shop\Template $template
  * @param Shop\Shop $shop
  */
 public function compileJavascript($timestamp, Shop\Template $template, Shop\Shop $shop)
 {
     if ($shop->getMain()) {
         $shop = $shop->getMain();
     }
     $file = $this->pathResolver->getJsFilePath($shop, $timestamp);
     $file = new \SplFileObject($file, "a");
     if (!$file->flock(LOCK_EX)) {
         return;
     }
     $file->ftruncate(0);
     $settings = $this->service->getSystemConfiguration(AbstractQuery::HYDRATE_OBJECT);
     $javascriptFiles = $this->collectJavascriptFiles($template, $shop);
     $content = '';
     foreach ($javascriptFiles as $jsFile) {
         $content .= file_get_contents($jsFile) . "\n";
     }
     if ($settings->getCompressJs()) {
         $content = $this->jsCompressor->compress($content);
     }
     $file->fwrite($content);
     $file->flock(LOCK_UN);
     // release the lock
 }
示例#15
0
文件: hicurl.php 项目: clox/hicurl
 /**
  * Function that writes history to the uncompiled history-file.
  * History-files are "uncompiled" before Hicurl::compileHistory has been called on them, which generates a
  * history-file of cosed state.
  * In its uncompiled state its structure is as follows:
  *		(historyData without closing bracket and brace)+(tempHistoryData)+(sizeOfTempHistoryData)
  * historyData is the following json-object: {"pages":[]}
  * But in the uncompiled file it is without the closing bracket+brace as stated above. Each element in its
  * pages-array is the following:<pre>
  * {	"formData"://this is present if it was a POST-request, and will contain the sent form-data
  *		,"name"://a name-string for the page that will be shown in the history-viewer. Set via historyData>name
  *		,"parentIndex": int//may hold an pointing to an index of another page in the pages-array. This will then be
  *			shown in the tree-view of the history-viewer. This is set up with loadSingle>historyData>id/parentId
  *		,"customData": //contains what was passed to customData-parameter of the load method if anything
  *		,"exchanges": [//An array of request&response pairs. Usually this will only contain one
  *								//element but more will be added for each failed request
  *			{
  *				"error": false if no error, otherwise an explanation of the error
  *				"content": the content of the page sent from the server
  *				"headers": ...and the headers
  *			}
  *		...
  *		]
  * }
  * </pre>
  * @param SplFileObject $historyFileObject
  * @param string $data A undecoded page-object, explained in the description of this method.
  * @param array $settings
  * @param array $historyData*/
 private static function writeHistory($historyFileObject, $data, $settings, $historyData)
 {
     if (!isset($historyFileObject)) {
         $historyFileObject = new SplFileObject($settings['history'], 'c+');
     }
     $historyFileObject->flock(LOCK_EX);
     //check if the historyFile is empty. we don't have to check for file-existence because it will always
     //have been created by now byt simply creating the SplFileObject
     if (!$historyFileObject->fstat()['size']) {
         $dataPrefix = '{"pages":[';
         $historyFileTempData = ['numPages' => 0, 'idIndices' => []];
     } else {
         $dataPrefix = ',';
         $tempDataSize = Hicurl::seekHistoryFileTempData($historyFileObject);
         $historyFileTempData = json_decode($historyFileObject->fread($tempDataSize), true);
         $historyFileObject->fseek(-4 - $tempDataSize, SEEK_END);
     }
     if (isset($historyData['id'])) {
         $historyFileTempData['idIndices'][$historyData['id']] = $historyFileTempData['numPages'];
     }
     if (isset($historyData['parentId'])) {
         $data['parentIndex'] = $historyFileTempData['idIndices'][$historyData['parentId']];
     }
     ++$historyFileTempData['numPages'];
     $historyFileObject->fwrite($dataPrefix . json_encode($data));
     $tempDataSize = $historyFileObject->fwrite(json_encode($historyFileTempData));
     $historyFileObject->fwrite(pack('N', $tempDataSize));
     $historyFileObject->flock(LOCK_UN);
 }
示例#16
0
 public function write($key, $data, $forceReplace = false, $expire = self::EXPIRE_INFINITE, $type = self::TYPE_TIME)
 {
     if (!is_string($key)) {
         throw new \Exception('Key name must be a string');
     }
     if ($this->exist($key)) {
         //override
         if (!$forceReplace) {
             throw new \Exception('Write key : "' . $key . '" fail, already defined');
         }
         Logger::getInstance()->debug('Key : "' . $key . '" already exist, override', 'cache' . $this->_name);
         if ($this->isLocked($key)) {
             Logger::getInstance()->debug('Key : "' . $key . '" must be unlocked', 'cache' . $this->_name);
             return;
         }
     }
     //create file
     $file = new \SplFileObject($this->_path . $this->_prefix . $this->_prefixGroups . md5($key), 'w+');
     if ($file->flock(LOCK_EX)) {
         $file->fwrite(base64_encode(serialize(array($this->_calculExpire($expire, $type), $key, $data, $type))));
         $file->flock(LOCK_UN);
     }
     Logger::getInstance()->debug('Key : "' . $key . '" written', 'cache' . $this->_name);
 }