function DeleteLyrics3() { // Initialize getID3 engine $getID3 = new getID3(); $ThisFileInfo = $getID3->analyze($this->filename); if (isset($ThisFileInfo['lyrics3']['tag_offset_start']) && isset($ThisFileInfo['lyrics3']['tag_offset_end'])) { if (is_readable($this->filename) && is_writable($this->filename) && is_file($this->filename) && ($fp = fopen($this->filename, 'a+b'))) { flock($fp, LOCK_EX); $oldignoreuserabort = ignore_user_abort(true); fseek($fp, $ThisFileInfo['lyrics3']['tag_offset_end'], SEEK_SET); $DataAfterLyrics3 = ''; if ($ThisFileInfo['filesize'] > $ThisFileInfo['lyrics3']['tag_offset_end']) { $DataAfterLyrics3 = fread($fp, $ThisFileInfo['filesize'] - $ThisFileInfo['lyrics3']['tag_offset_end']); } ftruncate($fp, $ThisFileInfo['lyrics3']['tag_offset_start']); if (!empty($DataAfterLyrics3)) { fseek($fp, $ThisFileInfo['lyrics3']['tag_offset_start'], SEEK_SET); fwrite($fp, $DataAfterLyrics3, strlen($DataAfterLyrics3)); } flock($fp, LOCK_UN); fclose($fp); ignore_user_abort($oldignoreuserabort); return true; } else { $this->errors[] = 'Cannot fopen(' . $this->filename . ', "a+b")'; return false; } } // no Lyrics3 present return true; }
public function writeToLog($text) { if (empty($text)) { return; } $logFile = $this->logFile; $logFileHistory = $this->logFileHistory; $oldAbortStatus = ignore_user_abort(true); if ($fp = @fopen($logFile, "ab")) { if (@flock($fp, LOCK_EX)) { $logSize = @filesize($logFile); $logSize = intval($logSize); if ($logSize > $this->maxLogSize) { $this->logFileHistory = $this->logFile . ".old." . time(); $logFileHistory = $this->logFileHistory; @copy($logFile, $logFileHistory); ftruncate($fp, 0); } @fwrite($fp, $text); @fflush($fp); @flock($fp, LOCK_UN); @fclose($fp); } } ignore_user_abort($oldAbortStatus); }
function SaveSession($session) { $name = $this->file['name']; if (!$this->opened_file) { if (!($this->opened_file = fopen($name, 'c+'))) { return $this->SetPHPError('could not open the token file ' . $name, $php_error_message); } } if (!flock($this->opened_file, LOCK_EX)) { return $this->SetPHPError('could not lock the token file ' . $name . ' for writing', $php_error_message); } if (fseek($this->opened_file, 0)) { return $this->SetPHPError('could not rewind the token file ' . $name . ' for writing', $php_error_message); } if (!ftruncate($this->opened_file, 0)) { return $this->SetPHPError('could not truncate the token file ' . $name . ' for writing', $php_error_message); } if (!fwrite($this->opened_file, json_encode($session))) { return $this->SetPHPError('could not write to the token file ' . $name, $php_error_message); } if (!fclose($this->opened_file)) { return $this->SetPHPError('could not close to the token file ' . $name, $php_error_message); } $this->opened_file = false; return true; }
/** * @inheritdoc */ public function lock($class, $waitTime = null) { if (isset($this->locked[$class])) { $this->locked[$class]['count']++; return true; } $lockName = $this->getLockName($class); $fp = fopen($lockName, 'w'); $locked = false; if (!$waitTime) { flock($fp, LOCK_EX); $locked = true; } else { while ($waitTime > 0) { if (flock($fp, LOCK_EX | LOCK_NB)) { $locked = true; break; } sleep(1); $waitTime -= 1; } } if (!$locked) { fclose($fp); return false; } ftruncate($fp, 0); fwrite($fp, 'Locked at: ' . microtime(true)); $this->locked[$class] = ['res' => $fp, 'count' => 1]; return true; }
private function renewCache() { $mask = empty($this->cacheRealPath) ? 'w+b' : 'r+b'; $resource = fopen($this->cachePath, $mask); $exchangeData = array(); if (!empty($resource)) { $wasLocked = false; for ($i = 1; $i <= 10; $i++) { $lock = flock($resource, LOCK_EX | LOCK_NB); if ($lock) { if ($wasLocked) { $exchangeData = json_decode(fread($resource, filesize($this->cacheRealPath)), true); } else { $newExchangeData = $this->getFromWeb(); if (!empty($newExchangeData)) { ftruncate($resource, 0); $jsonData = json_encode($newExchangeData); fwrite($resource, $jsonData); $exchangeData = $newExchangeData; fflush($resource); } } flock($resource, LOCK_UN); break; } else { $wasLocked = true; sleep(1); } } } fclose($resource); return $exchangeData; }
/** * Saves data to the cache. Anything that evaluates to FALSE, NULL, * '', 0 will not be saved. * * @param string $key An identifier for the data. * @param mixed $data The data to be saved. * @param integer $ttl Lifetime of the stored data. In seconds. * @returns boolean TRUE on success, FALSE otherwise. */ public static function set($key, $data = false, $ttl = 3600) { if (!$key) { self::$error = "Invalid key"; return false; } if (!$data) { self::$error = "Invalid data"; return false; } $key = self::makeFileKey($key); if (!is_integer($ttl)) { $ttl = (int) $ttl; } $store = array('data' => $data, 'ttl' => time() + $ttl); $status = false; try { $fh = fopen($key, "c"); if (flock($fh, LOCK_EX)) { ftruncate($fh, 0); fwrite($fh, json_encode($store)); flock($fh, LOCK_UN); $status = true; } fclose($fh); } catch (Exception $e) { self::$error = "Exception caught: " . $e->getMessage(); return false; } return $status; }
/** * Clear entries from chosen file. * * @param mixed $handle */ public function clear($handle) { if ($this->open($handle) && is_resource($this->_handles[$handle])) { @ftruncate($this->_handles[$handle], 0); } do_action('learn_press_log_clear', $handle); }
/** * Creates a new post by pushing it to the array * of blog posts stored in the local directory. * @param newPost - non-null string containing the new post JSON object. */ function CreatePost($newPost) { $postFileName = $this->postFilename; $fileExists = file_exists($postFileName); $postFile = $this->createBlogPostFileHandle($postFileName, $fileExists); $fileSize = filesize($postFileName); // Store some useful variables for blog post parsing. $contents; $blogPosts = []; // Check if file size is larger than 0 or not empty. if ($fileSize > 0) { // Read the existing blog post file and store in a string. $contents = fread($postFile, $fileSize); // TODO(Jess): Delete later - for debugging. // print($contents); // Parse the contents JSON string into an array. $blogPosts = json_decode($contents, true) ?: []; // print($blogPosts); // Clear the blog post file. ftruncate($postFile, 0); // Update the pointer back to the beginning of the file. fseek($postFile, 0); } // Push the new blog post to the array of blog posts. array_push($blogPosts, $newPost); // Encode and store back into a JSON string. $postJSONString = json_encode($blogPosts); // Update the post file to the new JSON string. fwrite($postFile, $postJSONString); fclose($postFile); // TODO(Jess): Delete later - for debugging. print $postJSONString; }
function write_cache_file($file, $content) { // Open $handle = @fopen($file, 'r+b'); // @ - file may not exist if (!$handle) { $handle = fopen($file, 'wb'); if (!$handle) { return false; } } // Lock flock($handle, LOCK_EX); ftruncate($handle, 0); // Write if (fwrite($handle, $content) === false) { // Unlock and close flock($handle, LOCK_UN); fclose($handle); return false; } // Unlock and close flock($handle, LOCK_UN); fclose($handle); return true; }
protected static function unban_callback($handle, $parameters) { $size = $parameters['initial_file_size']; if (0 === $size) { return true; } $contents = fread($handle, $size); if (empty($contents)) { return; } $now = time(); $ban_lines = explode("\n", $contents); $new_bans = array(); // Unban expired bans foreach ($ban_lines as $ban_line) { if (empty($ban_line)) { continue; } list($ip, $expires) = explode(' ', $ban_line); if (!empty($parameters['ip']) && $parameters['ip'] === $ip) { continue; } if (!empty($expires) && (int) $expires > $now) { $new_bans[] = $ban_line; } } $new_ban_lines = implode("\n", $new_bans); if (!empty($new_ban_lines)) { $new_ban_lines .= "\n"; } // Replace .htaccess contents ftruncate($handle, 0); rewind($handle); return fwrite($handle, $new_ban_lines); }
function getSequence($name, $folder = '/tmp', $default = 0) { // Build a filename from the folder and sequence name $filename = realpath($folder) . '/' . $name . '.seq'; // Open the file $fp = fopen($filename, "a+"); // Lock the file so no other processes can use it if (flock($fp, LOCK_EX)) { // Fetch the current number from the file $num = trim(stream_get_contents($fp)); // Check that what we read from the file was a number if (!ctype_digit($num)) { // If its not a number, lets reset to the default value $newnum = $default; } else { // If its a number, increment it $newnum = $num + 1; } // Delete the contents of the file ftruncate($fp, 0); rewind($fp); // Write the new number to the file fwrite($fp, "{$newnum}\n"); // Release the lock flock($fp, LOCK_UN); } else { echo "Couldn't get the lock!"; } // Close the file fclose($fp); // Return the incremented number return $newnum; }
/** * 写文件 * * @return intager 写入数据的字节数 */ function hg_file_write($filename, $content, $mode = 'rb+') { $length = strlen($content); @touch($filename); if (!is_writeable($filename)) { @chmod($filename, 0666); } if (($fp = fopen($filename, $mode)) === false) { trigger_error('hg_file_write() failed to open stream: Permission denied', E_USER_WARNING); return false; } flock($fp, LOCK_EX | LOCK_NB); $bytes = 0; if (($bytes = @fwrite($fp, $content)) === false) { $errormsg = sprintf('file_write() Failed to write %d bytes to %s', $length, $filename); trigger_error($errormsg, E_USER_WARNING); return false; } if ($mode == 'rb+') { @ftruncate($fp, $length); } @fclose($fp); // 检查是否写入了所有的数据 if ($bytes != $length) { $errormsg = sprintf('file_write() Only %d of %d bytes written, possibly out of free disk space.', $bytes, $length); trigger_error($errormsg, E_USER_WARNING); return false; } // 返回长度 return $bytes; }
/** * Creates or overwrites a new JPA archive * * @param $archive The full path to the JPA archive * * @return bool True on success */ public function create($archive) { $this->dataFileName = $archive; // Try to kill the archive if it exists $fp = @fopen($this->dataFileName, "wb"); if (!($fp === false)) { @ftruncate($fp, 0); @fclose($fp); } else { if (file_exists($this->dataFileName)) { @unlink($this->dataFileName); } @touch($this->dataFileName); } if (!is_writable($archive)) { $this->error = 'Can\'t open ' . $archive . ' for writing'; return false; } // Write the initial instance of the archive header $this->writeArchiveHeader(); if (!empty($error)) { return false; } return true; }
function RemoveID3v1() { if ($ThisFileInfo['filesize'] >= pow(2, 31)) { $this->errors[] = 'Unable to write ID3v1 because file is larger than 2GB'; return false; } // File MUST be writeable - CHMOD(646) at least if (is_writeable($this->filename)) { if ($fp_source = @fopen($this->filename, 'r+b')) { fseek($fp_source, -128, SEEK_END); if (fread($fp_source, 3) == 'TAG') { ftruncate($fp_source, filesize($this->filename) - 128); } else { // no ID3v1 tag to begin with - do nothing } fclose($fp_source); return true; } else { $this->errors[] = 'Could not open ' . $this->filename . ' mode "r+b"'; } } else { $this->errors[] = $this->filename . ' is not writeable'; } return false; }
function write_config_file($filename, $comments) { global $config_template; $tokens = array('{USER}', '{PASSWORD}', '{HOST}', '{PORT}', '{DBNAME}', '{TABLE_PREFIX}', '{HEADER_IMG}', '{HEADER_LOGO}', '{GENERATED_COMMENTS}', '{CONTENT_DIR}', '{MAIL_USE_SMTP}', '{GET_FILE}' ); if ($_POST['step1']['old_path'] != '') { $values = array(urldecode($_POST['step1']['db_login']), addslashes(urldecode($_POST['step1']['db_password'])), $_POST['step1']['db_host'], $_POST['step1']['db_port'], $_POST['step1']['db_name'], $_POST['step1']['tb_prefix'], addslashes(urldecode($_POST['step1']['header_img'])), addslashes(urldecode($_POST['step1']['header_logo'])), $comments, addslashes(urldecode($_POST['step5']['content_dir'])), $_POST['step1']['smtp'], $_POST['step1']['get_file'] ); } else { $values = array(urldecode($_POST['step2']['db_login']), addslashes(urldecode($_POST['step2']['db_password'])), $_POST['step2']['db_host'], $_POST['step2']['db_port'], $_POST['step2']['db_name'], $_POST['step2']['tb_prefix'], '', //header image '', //header logo $comments, addslashes(urldecode($_POST['step4']['content_dir'])), $_POST['step3']['smtp'], $_POST['step4']['get_file'] ); } $config_template = str_replace($tokens, $values, $config_template); if (!$handle = @fopen($filename, 'wb')) { return false; } @ftruncate($handle,0); if (!@fwrite($handle, $config_template, strlen($config_template))) { return false; } @fclose($handle); return true; }
/** * Clean the logfile. Used for content testing purposes. * @return true if truncate was successful otherwise false */ public function clean() { $fh = fopen($this->getFile(), "w"); $tb = ftruncate($fh, 0); fclose($fh); return $tb; }
/** * @param string $input * * @return mixed */ public function escape($input) { $this->dumper->dump($this->cloner->cloneVar($input), $this->memoryStream); $output = stream_get_contents($this->memoryStream, -1, 0); ftruncate($this->memoryStream, 0); return rtrim($output, "\n"); }
protected function writeToLog($text) { if (empty($text)) { return; } $logFile = $this->logFile; $logFileHistory = $this->logFileHistory; if (!is_writable($logFile)) { return; } $oldAbortStatus = ignore_user_abort(true); if ($fp = @fopen($logFile, "ab+")) { if (flock($fp, LOCK_EX)) { $logSize = filesize($logFile); $logSize = intval($logSize); if ($logSize > $this->maxLogSize) { @copy($logFile, $logFileHistory); ftruncate($fp, 0); } fwrite($fp, $text); fflush($fp); flock($fp, LOCK_UN); fclose($fp); } } ignore_user_abort($oldAbortStatus); }
public function setStreamContents($contents) { ftruncate($this->socket, 0); fwrite($this->socket, $contents); rewind($this->socket); $this->incomingDataEnabled = true; }
public function flush() { $this->_lastWrite = time(); if (!$this->_increments && !$this->_updates) { return; } $fp = fopen($this->_file, "c+"); if (flock($fp, LOCK_EX)) { $contents = stream_get_contents($fp); if ($contents) { $contents = (array) json_decode($contents, true); } else { $contents = array(); } foreach ($this->_updates as $k => $i) { $contents[$k] = $i; } foreach ($this->_increments as $k => $i) { if (!isset($contents[$k])) { $contents[$k] = 0; } $contents[$k] += $i; } ftruncate($fp, 0); fseek($fp, SEEK_SET, 0); fwrite($fp, json_encode($contents)); flock($fp, LOCK_UN); $this->_increments = array(); } fclose($fp); }
/** * Updates index file with summary log data * * @param string $indexFile path to index file * @param array $summary summary log data * @throws \yii\base\InvalidConfigException */ private function updateIndexFile($indexFile, $summary) { touch($indexFile); if (($fp = @fopen($indexFile, 'r+')) === false) { throw new InvalidConfigException("Unable to open debug data index file: {$indexFile}"); } @flock($fp, LOCK_EX); $manifest = ''; while (($buffer = fgets($fp)) !== false) { $manifest .= $buffer; } if (!feof($fp) || empty($manifest)) { // error while reading index data, ignore and create new $manifest = []; } else { $manifest = unserialize($manifest); } $manifest[$this->tag] = $summary; $this->gc($manifest); ftruncate($fp, 0); rewind($fp); fwrite($fp, serialize($manifest)); @flock($fp, LOCK_UN); @fclose($fp); }
public function fetch_restaurant_info($force = false) { //Make sure file exists if (is_file($this->_rests_file) === false) { file_put_contents($this->_rests_file, ''); } //Parse info from existing file and get last update info $content = json_decode(file_get_contents($this->_rests_file)); $last_update = (time() - $content->timestamp) / 60; unset($content->timestamp); if (!$content || !$last_update || $last_update > 10 * 60 || $force) { $f = fopen($this->_rests_file, "r+"); if ($f !== false) { ftruncate($f, 0); fclose($f); } //Get and parse data $url = 'http://www.10bis.co.il/Restaurants/SearchRestaurants?deliveryMethod=Delivery&ShowOnlyOpenForDelivery=False&id=942159&pageNum=0&pageSize=1000&ShowOnlyOpenForDelivery=false&OrderBy=delivery_sum&cuisineType=&StreetId=0&FilterByKosher=false&FilterByBookmark=false&FilterByCoupon=false&searchPhrase=&Latitude=32.075523&Longitude=34.795268×tamp=1387750840791'; $content = json_decode(Curl::get($url)); $content['timestamp'] = time(); file_put_contents($this->_rests_file, json_encode($content)); //TODO: Parse data and update db if needed } else { $content = json_decode(file_get_contents($this->_rests_file)); } return $content; }
public function run(InputInterface $input = null, OutputInterface $output = null) { $fp = fopen($this->config['lockfile'], "w"); // if you run this script as root - change user/group if (file_exists($this->config['lockfile'])) { chown($this->config['lockfile'], $this->config['file-user']); chgrp($this->config['lockfile'], $this->config['file-group']); } $exitCode = 0; if (flock($fp, LOCK_EX | LOCK_NB)) { // acquire an exclusive lock ftruncate($fp, 0); $exitCode = parent::run($input, $output); fflush($fp); // flush output before releasing the lock flock($fp, LOCK_UN); // release the lock } else { //throw new DNSSyncException("Running multiple instances is not allowed."); - nezachytí applikace error //$output->writeln() - null v této chvíli $message = "Running multiple instances is not allowed."; echo $message . PHP_EOL; mail($this->config['admin-email'], $message, $message); $exitCode = 500; } fclose($fp); return $exitCode; }
private function deny($comment = '') { $ip = Yii::$app->request->userIP; $userAgent = Yii::$app->request->userAgent; if ($this->checkIP($ip) && $this->checkBrowser($userAgent)) { $path = Yii::getAlias('@webroot') . '/.htaccess'; $fp = fopen($path, 'r+'); if ($fp && flock($fp, LOCK_EX)) { if ($data = fread($fp, filesize($path))) { $comment = $this->clear($comment); foreach (['/(order[a-zA-Z ,]*)[\\r\\n]/Umi'] as $pattern) { if (preg_match($pattern, $data)) { $data = preg_replace($pattern, "\$1\r\ndeny from {$ip} # {$comment}\r", $data); ftruncate($fp, 0); fseek($fp, 0); fwrite($fp, $data, strlen($data)); break; } } } fflush($fp); flock($fp, LOCK_UN); fclose($fp); } } }
function AddMascEdit($idMasc, $UrlPage, $Script) { $PastaArqs = 'Restrito/paginas/' . $UrlPage . '/'; $PgEditar = $UrlPage . '_editar.php'; $PgCadastrar = $UrlPage . '_cadastrar.php'; $arquivo = fopen($PastaArqs . $PgEditar, 'r+'); if ($arquivo) { while (true) { $linha = fgets($arquivo); if ($linha == null) { break; } if (preg_match('/InicioMasc/', $linha)) { $string .= str_replace('var InicioMasc = false;', 'var InicioMasc = false; ' . $Script . '', $linha); } else { $string .= $linha; } } rewind($arquivo); ftruncate($arquivo, 0); if (!fwrite($arquivo, $string)) { return false; } else { return true; } fclose($arquivo); } }
function write_cache_file($file, $content) { // Open $handle = @fopen($file, 'r+b'); // @ - file may not exist if (!$handle) { $handle = fopen($file, 'wb'); if (!$handle) { return false; } } // Lock flock($handle, LOCK_EX); ftruncate($handle, 0); // Write if (fwrite($handle, $content) === false) { // Unlock and close flock($handle, LOCK_UN); fclose($handle); return false; } // Unlock and close flock($handle, LOCK_UN); fclose($handle); // Force opcache to recompile this script if (function_exists('opcache_invalidate')) { opcache_invalidate($file, true); } return true; }
public function update($id) { $theme = AngkorCMSTheme::with('template')->find($id); if ($theme == null) { return false; } $template_name = $theme->template->name; $name = $theme->name; $pathCss = "css\\" . $template_name . "\\" . $name . "\\"; $pathJs = "js\\" . $template_name . "\\" . $name . "\\"; $pathView = "..\\resources\\views\\templates\\" . $template_name . "\\" . $name . "\\"; $style = Input::get('style'); $view = Input::get('view'); $script = Input::get('script'); // Style $styleFile = fopen($pathCss . '' . $theme->style, 'r+'); ftruncate($styleFile, 0); fputs($styleFile, $style); fclose($styleFile); // View $viewFile = fopen($pathView . '' . $theme->view, 'r+'); ftruncate($viewFile, 0); fputs($viewFile, $view); fclose($viewFile); // Script $scriptFile = fopen($pathJs . '' . $theme->script, 'r+'); ftruncate($scriptFile, 0); fputs($scriptFile, $script); fclose($scriptFile); $theme->name = Input::get('name'); $theme->save(); return $theme; }
function MudarCampoEdt($Pg, $Cp, $Ncp, $Cpnew, $Ferr) { $arquivo = fopen('Restrito/paginas/' . $Ferr . '/' . $Pg . '_editar.php', 'r+'); if ($arquivo) { while (true) { $linha = fgets($arquivo); if ($linha == null) { break; } if (preg_match('/name="' . $Ncp . '"/', $linha)) { $string .= str_replace($Cp, $Cpnew, $linha); } else { $string .= $linha; } } rewind($arquivo); ftruncate($arquivo, 0); if (!fwrite($arquivo, $string)) { return false; } else { return true; } fclose($arquivo); } }
function write_staffs2() { global $lang; //==ids $t = '$INSTALLER09'; $iconfigfile = "<" . "?php\n/**\n{$lang['staffcfg_file_created']}" . date('M d Y H:i:s') . ".\n{$lang['staffcfg_mod_by']}\n**/\n"; $ri = sql_query("SELECT id, username, class FROM users WHERE class BETWEEN " . UC_STAFF . " AND " . UC_MAX . " ORDER BY id ASC") or sqlerr(__FILE__, __LINE__); $iconfigfile .= "" . $t . "['allowed_staff']['id'] = array("; while ($ai = mysqli_fetch_assoc($ri)) { $ids[] = $ai['id']; $usernames[] = "'" . $ai["username"] . "' => 1"; } $iconfigfile .= "" . join(",", $ids); $iconfigfile .= ");"; $iconfigfile .= "\n?" . ">"; $filenum = fopen('./cache/staff_settings.php', 'w'); ftruncate($filenum, 0); fwrite($filenum, $iconfigfile); fclose($filenum); //==names $t = '$INSTALLER09'; $nconfigfile = "<" . "?php\n/**\n{$lang['staffcfg_file_created']}" . date('M d Y H:i:s') . ".\n{$lang['staffcfg_mod_by']}\n**/\n"; $nconfigfile .= "" . $t . "['staff']['allowed'] = array("; $nconfigfile .= "" . join(",", $usernames); $nconfigfile .= ");"; $nconfigfile .= "\n?" . ">"; $filenum1 = fopen('./cache/staff_settings2.php', 'w'); ftruncate($filenum1, 0); fwrite($filenum1, $nconfigfile); fclose($filenum1); stderr($lang['staffcfg_success'], $lang['staffcfg_updated']); }
public function refreshServerConfigFile($callback, $lockMode = 'blocking') { $fp = fopen($this->serverConfigPath, 'r+'); if ($lockMode == 'blocking') { if (!flock($fp, LOCK_EX)) { fclose($fp); throw new \RuntimeException("Lock server config file failed."); } } elseif ($lockMode == 'nonblocking') { if (!flock($fp, LOCK_EX | LOCK_NB)) { fclose($fp); return; } } if (filesize($this->serverConfigPath) > 0) { $data = json_decode(fread($fp, filesize($this->serverConfigPath)), true); } else { $data = array(); } $data = $callback($fp, $data, self::FAILOVER_COUNT); ftruncate($fp, 0); rewind($fp); fwrite($fp, json_encode($data)); if ($lockMode != 'none') { flock($fp, LOCK_UN); } fclose($fp); return $data; }