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;
 }
Exemple #2
1
 /**
  * Write Log File
  *
  * Generally this function will be called using the global log_message() function
  *
  * @param    string    the error level
  * @param    string    the error message
  * @param    bool    whether the error is a native PHP error
  * @return    bool
  */
 public function write_log($level = 'error', $msg, $php_error = FALSE)
 {
     if ($this->_enabled === FALSE) {
         return FALSE;
     }
     $level = strtoupper($level);
     if (!isset($this->_levels[$level]) or $this->_levels[$level] > $this->_threshold) {
         return FALSE;
     }
     $filepath = $this->_log_path . 'log-' . date('Y-m-d') . '.php';
     $message = '';
     if (!file_exists($filepath)) {
         $message .= "<" . "?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?" . ">\n\n";
     }
     if (!($fp = @fopen($filepath, FOPEN_WRITE_CREATE))) {
         return FALSE;
     }
     $message .= $level . ' ' . ($level == 'INFO' ? ' -' : '-') . ' ' . date($this->_date_fmt) . ' --> ' . $msg . "\n";
     flock($fp, LOCK_EX);
     fwrite($fp, $message);
     flock($fp, LOCK_UN);
     fclose($fp);
     @chmod($filepath, FILE_WRITE_MODE);
     return TRUE;
 }
Exemple #3
0
 /**
  * Free a lock acquired with acquire().
  *
  * @param resource $lockFile The lockfile that was returned by acquire()
  **/
 public static function release($lockFile)
 {
     if ($lockFile) {
         flock($lockFile, LOCK_UN);
         fclose($lockFile);
     }
 }
Exemple #4
0
 public function msg($msg)
 {
     if ($this->on && $this->handle && flock($this->handle, LOCK_EX)) {
         fputs($this->handle, date("[d/m/Y H:i:s] - ") . $msg . "\n");
         flock($this->handle, LOCK_UN);
     }
 }
Exemple #5
0
/**
 * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
 * 注意:服务器需要开通fopen配置
 * @param $word 要写入日志里的文本内容 默认值:空值
 */
function ApiLogResult($word='') {
	$fp = fopen("log.txt","a");
	flock($fp, LOCK_EX) ;
	fwrite($fp,"执行日期:".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}
Exemple #6
0
 function call()
 {
     $args = func_get_args();
     $age = $args[0];
     $filename = $this->cachedir . base64_encode(join('', array_slice($args, 1))) . '.cache';
     $function = $args[1];
     if (file_exists($filename) && time() - filemtime($filename) < $age) {
         include $filename;
         print $output;
         return $return;
     }
     ob_start();
     $return = call_user_func_array($function, array_slice($args, 2));
     $output = ob_get_contents();
     ob_end_flush();
     $fp = fopen($filename, 'w');
     flock($fp, LOCK_EX);
     fwrite($fp, "<?php\r\n");
     if ($return != '') {
         fwrite($fp, '$return = <<<CACHEEOF' . "\r\n" . $return . "\r\nCACHEEOF;\r\n");
     }
     if ($output != '') {
         fwrite($fp, '$output = <<<CACHEEOF' . "\r\n" . $output . "\r\nCACHEEOF;\r\n");
     }
     fwrite($fp, "?>");
     flock($fp, LOCK_UN);
     fclose($fp);
     return $return;
 }
 public static function logger($string)
 {
     $file = $this->root() . "log/sitesearch.log";
     // $file = "./log/sitesearch.log";
     // this is just for testing installation
     /*
      * if (!touch($file)) {
      * echo "FILE ERROR: cannot touch $file with user " . get_current_user() . "\n"; // helps figure out why you
      * can't touch the file
      * return;
      * } else {
      * echo "FILE: touched $file with user " . get_current_user() . "\n"; // helps figure out why you can't touch
      * the file
      * }
      */
     if (!($fh = fopen($file, 'a'))) {
         return;
     }
     flock($fh, LOCK_EX);
     $delim = "\t";
     date_default_timezone_set($conf['timeZone']);
     if (!fwrite($fh, 'StaticUtil[' . date('Y-M-d H:i:s') . ']' . $delim . $string . "\r\n")) {
         return;
     }
     flock($fh, LOCK_UN);
     fclose($fh);
 }
Exemple #8
0
 public function save($str)
 {
     if (!$this->logFilename) {
         return false;
     }
     $hash = md5($str);
     // if we've already logged this during this session, then don't do it again
     if (in_array($hash, $this->itemsLogged)) {
         return true;
     }
     $ts = date("Y-m-d H:i:s");
     $str = $this->cleanStr($str);
     if ($fp = fopen($this->logFilename, "a")) {
         $trys = 0;
         $stop = false;
         while (!$stop) {
             if (flock($fp, LOCK_EX)) {
                 fwrite($fp, "{$ts}{$this->delimeter}{$str}\n");
                 flock($fp, LOCK_UN);
                 $this->itemsLogged[] = $hash;
                 $stop = true;
             } else {
                 usleep(2000);
                 if ($trys++ > 20) {
                     $stop = true;
                 }
             }
         }
         fclose($fp);
         return true;
     } else {
         return false;
     }
 }
function rewrite($filename, $data)
{
    $filenum = fopen($filename, "w");
    flock($filenum, LOCK_EX);
    fwrite($filenum, $data);
    fclose($filenum);
}
Exemple #10
0
function fhtml($txt, $html, $dir = "", $mu = "", $cahehtm)
{
    //$txt = file_get_contents($file);
    if ($dir != '') {
        $newdir = explode("/", $dir);
        $listdir = "";
        foreach ($newdir as $value) {
            $listdir .= "/{$value}";
            if (!is_dir(R_P . "html{$listdir}")) {
                mkdir(R_P . "html{$listdir}", 0777);
            }
        }
    }
    if ($mu != '') {
        $patterns = array("/(=)('|\"{0,1})(lang|image|attach|\\.)(\\/)(\\W?)(.*?)(\\W?)( |'|\"|>{1,2})/is");
        $replace = array("\\1\\2{$mu}\\3\\4\\5\\6\\7\\8");
        $txt = preg_replace($patterns, $replace, $txt);
    }
    if ($cahehtm) {
        P_unlink(R_P . $html);
    }
    $fp = fopen(R_P . $html, "w");
    flock($fp, LOCK_EX);
    fwrite($fp, $txt);
    fclose($fp);
    //关闭指针
    if (is_dir($mu) !== TRUE) {
        mkdir($mu, 0777);
    }
    chmod(R_P . $html, 0777);
}
 /**
  * Logs a message.
  *
  * @param string Message
  * @param string Message priority
  * @param string Message priority name
  */
 public function log($message, $priority, $priorityName)
 {
     $line = sprintf("%s %s [%s] %s%s", strftime('%b %d %H:%M:%S'), 'symfony', $priorityName, $message, DIRECTORY_SEPARATOR == '\\' ? "\r\n" : "\n");
     flock($this->fp, LOCK_EX);
     fwrite($this->fp, $line);
     flock($this->fp, LOCK_UN);
 }
Exemple #12
0
 /**
  * 实时写入日志
  * @param mixed $log
  * @param string $file
  */
 public static function write($log, $file = 'log')
 {
     $yearmonth = date('Ym');
     $logdir = ZTNB_ROOT . '/data/log/';
     $logfile = $logdir . $yearmonth . '_' . $file . '.php';
     if (@filesize($logfile) > 2048000) {
         $dir = opendir($logdir);
         $length = strlen($file);
         $maxid = $id = 0;
         while ($entry = readdir($dir)) {
             if (strpos($entry, $yearmonth . '_' . $file) !== false) {
                 $id = intval(substr($entry, $length + 8, -4));
                 $id > $maxid && ($maxid = $id);
             }
         }
         closedir($dir);
         $logfilebak = $logdir . $yearmonth . '_' . $file . '_' . ($maxid + 1) . '.php';
         @rename($logfile, $logfilebak);
     }
     if ($fp = @fopen($logfile, 'a')) {
         @flock($fp, 2);
         $log = var_export($log, true);
         $datetime = date('Y-m-d H:i:s');
         fwrite($fp, "<?PHP exit;?>\t{$datetime}\t" . str_replace(array('<?', '?>'), '', $log) . "\n");
         fclose($fp);
     }
 }
 function save($name, $data, $time = 86400)
 {
     //
     //We have problems if APC is enabled, so we disable our cache
     //system if it's lodoed to prevent those problems, but we will
     //try to fix it in the near future .. I hope that.
     //
     if (defined('APC_CACHE')) {
         return;
     }
     $name = preg_replace('![^a-z0-9_]!i', '_', $name);
     $data_for_save = '<?' . 'php' . "\n";
     $data_for_save .= '//Cache file, generated for Kleeja at ' . gmdate('d-m-Y h:i A') . "\n\n";
     $data_for_save .= '//No direct opening' . "\n";
     $data_for_save .= '(!defined("IN_COMMON") ? exit("hacking attemp!") : null);' . "\n\n";
     $data_for_save .= '//return false after x time' . "\n";
     $data_for_save .= 'if(time() > ' . (time() + $time) . ') return false;' . "\n\n";
     $data_for_save .= '$data = ' . var_export($data, true) . ";\n\n//end of cache";
     if ($fd = @fopen(PATH . 'cache/' . $name . '.php', 'w')) {
         @flock($fd, LOCK_EX);
         // exlusive look
         @fwrite($fd, $data_for_save);
         @flock($fd, LOCK_UN);
         @fclose($fd);
     }
     return;
 }
Exemple #14
0
 public function create($paths, $filename = FALSE)
 {
     // Sort the paths to make sure that directories come before files
     sort($paths);
     foreach ($paths as $set) {
         // Add each path individually
         $this->add_data($set[0], $set[1], isset($set[2]) ? $set[2] : NULL);
     }
     // File data
     $data = implode('', $this->data);
     // Directory data
     $dirs = implode('', $this->dirs);
     $zipfile = $data . $dirs . "PK" . pack('v', count($this->dirs)) . pack('v', count($this->dirs)) . pack('V', strlen($dirs)) . pack('V', strlen($data)) . "";
     // Zip comment length
     if ($filename == FALSE) {
         return $zipfile;
     }
     if (substr($filename, -3) != 'zip') {
         // Append zip extension
         $filename .= '.zip';
     }
     // Create the file in binary write mode
     $file = fopen($filename, 'wb');
     // Lock the file
     flock($file, LOCK_EX);
     // Write the zip file
     $return = fwrite($file, $zipfile);
     // Unlock the file
     flock($file, LOCK_UN);
     // Close the file
     fclose($file);
     return (bool) $return;
 }
 /**
  * readFromStdin($prompt = 'Enter: ', $echoback = false)
  *
  * 標準入力からの入力を処理する
  *
  * @access    protected
  *
  * @param     string  $message ブラウザ側に出力するメッセージ(省略可、デフォルトは'Authorization Required')
  * @param     boolean $echoback true:エコーバックする/false:エコーバックしない
  *
  * @return    string 入力された内容
  */
 protected function readFromStdin($prompt = 'Enter: ', $echoback = true)
 {
     // 入出力のファイルハンドラをオープン
     $in = fopen('php://stdin', 'r');
     $out = fopen('php://stderr', 'w');
     // プロンプトを出力し、エコーバックオフが指示されていれば止める
     fwrite($out, $prompt);
     if (!$echoback) {
         system('stty -echo');
     }
     // 入力をロックし、キー入力を取得する
     flock($in, LOCK_EX);
     $readtext = fgets($in);
     flock($in, LOCK_UN);
     // エコーバックオフが指示されていれば再開し、PHP_EOLを出力
     if (!$echoback) {
         system('stty echo');
     }
     fwrite($out, PHP_EOL);
     // 入出力のファイルハンドラをクローズ
     fclose($in);
     fclose($out);
     // 取得内容を返却する
     return trim($readtext);
 }
Exemple #16
0
 /**
  * {@inheritdoc}
  */
 protected function doFetch(array $ids)
 {
     $values = array();
     $now = time();
     foreach ($ids as $id) {
         $file = $this->getFile($id);
         if (!($h = @fopen($file, 'rb'))) {
             continue;
         }
         flock($h, LOCK_SH);
         if ($now >= (int) ($expiresAt = fgets($h))) {
             flock($h, LOCK_UN);
             fclose($h);
             if (isset($expiresAt[0])) {
                 @unlink($file);
             }
         } else {
             $value = stream_get_contents($h);
             flock($h, LOCK_UN);
             fclose($h);
             $values[$id] = unserialize($value);
         }
     }
     return $values;
 }
Exemple #17
0
 /**
  * read and get cache file
  * 
  * @param string
  * @return html
  */
 function read($filename)
 {
     $filename = md5($filename);
     $filepath = $this->getConfig('cache_path') . $filename . '.tmp';
     if (!file_exists($filepath)) {
         return FALSE;
     }
     if (!($fp = @fopen($filepath, 'r'))) {
         return FALSE;
     }
     flock($fp, LOCK_SH);
     $cache = '';
     if (filesize($filepath) > 0) {
         $cache = fread($fp, filesize($filepath));
     }
     flock($fp, LOCK_UN);
     fclose($fp);
     // Strip out the embedded timestamp
     if (!preg_match("/(\\d+T_SKY-->)/", $cache, $match)) {
         return FALSE;
     }
     // Has the file expired? If so we'll delete it.
     if (time() >= trim(str_replace('TS--->', '', $match['1']))) {
         if (is_writable($filepath)) {
             @unlink($filepath);
             return FALSE;
         }
     }
     // Display the cache
     return str_replace($match['0'], '', $cache);
 }
Exemple #18
0
 /**
  * Create content from template and data.
  *
  * @param string $name
  * @param array $data
  *
  * @return string|null
  */
 public function getContent($name, array $data = [])
 {
     $path = $this->packageRoot . '/view/_cache/' . str_replace('/', '_', $name);
     if (!file_exists($path) || !$this->cache) {
         $code = $this->compile($name, true, true);
         if (empty($code)) {
             return null;
         }
         $fh = fopen($path, 'wb');
         if (flock($fh, LOCK_EX)) {
             fwrite($fh, $code);
             flock($fh, LOCK_UN);
         }
         fflush($fh);
         fclose($fh);
     }
     $fh = fopen($path, 'rb');
     flock($fh, LOCK_SH);
     if (null !== $this->request) {
         $data = array_replace($data, ['request' => $this->request]);
     }
     $html = self::renderTemplate($path, $data);
     flock($fh, LOCK_UN);
     fclose($fh);
     return $html;
 }
function getActualCache($cacheFile, $cacheAgeLimit, $source)
{
    $fMakeTemplateCache = false;
    if (is_file($cacheFile)) {
        $filetime = filemtime($cacheFile);
        $curtime = time();
        $cacheFilenameAge = $curtime - $filetime;
        //print $cacheFilenameAge;
        if ($cacheFilenameAge > $cacheAgeLimit) {
            $fMakeTemplateCache = true;
        }
    } else {
        $fMakeTemplateCache = true;
    }
    if ($fMakeTemplateCache) {
        //print "Write new cache";
        // Write new cache
        $cacheContent = file_get_contents($source);
        // Открытие текстовых файлов
        $fhCache = fopen($cacheFile, "w");
        $locked = flock($fhCache, LOCK_EX | LOCK_NB);
        if (!$locked) {
            echo 'Не удалось получить блокировку';
            exit(-1);
        }
        fwrite($fhCache, $cacheContent);
    } else {
        //print "Read from cache";
        // Read from cache
        $cacheContent = file_get_contents($cacheFile);
    }
    // Output template
    return $cacheContent;
}
Exemple #20
0
 public function export($location)
 {
     if (file_exists($location) === false) {
         mkdir($location);
     }
     if (substr($location, -1) != DIRECTORY_SEPARATOR) {
         $location .= DIRECTORY_SEPARATOR;
     }
     $file = $location . $this->_group_name . EXT;
     // Write in file
     if (!($h = fopen($file, 'w+'))) {
         return FALSE;
     }
     // Block access to the file
     if (flock($h, LOCK_EX)) {
         $array = $this->getArrayCopy();
         // Modifiers for adjusting appearance
         $replace = array("=> \n" => '=>', 'array (' => 'array(', '  ' => "\t", ' false,' => ' FALSE,', ' true,' => ' TRUE,', ' null,' => ' NULL,', MODPATH => 'MODPATH', APPPATH => 'APPPATH', SYSPATH => 'SYSPATH', DOCROOT => 'DOCROOT');
         $array = var_export($array, true);
         $var = stripslashes(strtr($array, $replace));
         $content = Kohana::FILE_SECURITY . PHP_EOL . PHP_EOL . 'return ' . $var . ';';
         $result = fwrite($h, $content);
         flock($h, LOCK_UN);
     }
     fclose($h);
     return (bool) $result;
 }
Exemple #21
0
function ReWriteConfig()
{
    global $dsql, $configfile;
    if (!is_writeable($configfile)) {
        echo "配置文件'{$configfile}'不支持写入,无法修改系统配置参数!";
        exit;
    }
    $fp = fopen($configfile, 'w');
    flock($fp, 3);
    fwrite($fp, "<" . "?php\r\n");
    $dsql->SetQuery("Select `varname`,`type`,`value`,`groupid` From `#@__sysconfig` order by aid asc ");
    $dsql->Execute();
    while ($row = $dsql->GetArray()) {
        if ($row['type'] == 'number') {
            if ($row['value'] == '') {
                $row['value'] = 0;
            }
            fwrite($fp, "\${$row['varname']} = " . $row['value'] . ";\r\n");
        } else {
            fwrite($fp, "\${$row['varname']} = '" . str_replace("'", '', $row['value']) . "';\r\n");
        }
    }
    fwrite($fp, "?" . ">");
    fclose($fp);
}
 /**
  * Sendout mail queue using the given real mailer
  * @param CakeEmail $realMailer
  */
 public function flush($realMailer)
 {
     $lockfile = $this->_config['queueFolder'] . DS . 'flush.lock';
     touch($lockfile);
     $lock = fopen($lockfile, 'r');
     if (!flock($lock, LOCK_EX)) {
         fclose($lock);
         throw new Exception('Could not get a lock for ' . $lockfile);
     }
     $processed = array();
     while ($queueFile = $this->getNext()) {
         if (array_key_exists($queueFile, $processed)) {
             throw new LogicException(sprintf('Trying to process queue file "%s" more than once.', $queueFile));
         }
         $processed[$queueFile] = true;
         $delFile = false;
         $fh = fopen($queueFile, 'r');
         if (flock($fh, LOCK_EX)) {
             $serialized = fread($fh, filesize($queueFile));
             $cakeMail = unserialize($serialized);
             $delFile = $this->tryRealSend($realMailer, $cakeMail);
             if ($delFile === false) {
                 $this->tryRequeue($queueFile);
             }
             flock($fh, LOCK_UN);
         }
         fclose($fh);
         if ($delFile === true) {
             unlink($queueFile);
         }
     }
     flock($lock, LOCK_UN);
     fclose($lock);
 }
 function fetch($key)
 {
     $filename = $this->getFileName($key);
     if (!file_exists($filename)) {
         return false;
     }
     $fp = fopen($filename, 'r');
     if (!$fp) {
         return false;
     }
     // Getting a shared lock
     flock($fp, LOCK_SH);
     $data = file_get_contents($filename);
     fclose($fp);
     $data = @unserialize($data);
     if (!$data) {
         // If unserializing somehow didn't work out, we'll delete the file
         unlink($filename);
         return false;
     }
     if (time() > $data[0]) {
         // Unlinking when the file was expired
         unlink($filename);
         return false;
     }
     return $data[1];
 }
Exemple #24
0
 /**
  * @return void
  */
 private function loadFile($class, $generator)
 {
     $file = "{$this->tempDirectory}/{$class}.php";
     if (!$this->isExpired($file) && @(include $file) !== FALSE) {
         // @ file may not exist
         return;
     }
     if (!is_dir($this->tempDirectory)) {
         @mkdir($this->tempDirectory);
         // @ - directory may already exist
     }
     $handle = fopen("{$file}.lock", 'c+');
     if (!$handle || !flock($handle, LOCK_EX)) {
         throw new Nette\IOException("Unable to acquire exclusive lock on '{$file}.lock'.");
     }
     if (!is_file($file) || $this->isExpired($file)) {
         list($toWrite[$file], $toWrite["{$file}.meta"]) = $this->generate($class, $generator);
         foreach ($toWrite as $name => $content) {
             if (file_put_contents("{$name}.tmp", $content) !== strlen($content) || !rename("{$name}.tmp", $name)) {
                 @unlink("{$name}.tmp");
                 // @ - file may not exist
                 throw new Nette\IOException("Unable to create file '{$name}'.");
             }
         }
     }
     if (@(include $file) === FALSE) {
         // @ - error escalated to exception
         throw new Nette\IOException("Unable to include '{$file}'.");
     }
     flock($handle, LOCK_UN);
 }
Exemple #25
0
	/**
	 * Get data from CACHE
	 * @param $params
	 * @return array
	 */
	public static function get($params){
		
		$fileName = CACHE_PATH.md5($params['key']);
		if(!file_exists($fileName)) return false;
		
		$h = fopen($fileName, "r");
		
		if(!$h) return false;
		
	  	// Getting a shared lock 
		flock($h, LOCK_SH);
		
		$data = file_get_contents($fileName);
		fclose($h);
		
		if(!$data = @unserialize($data)){
			
			//Remove file
			unlink($fileName);
			return false;
		}
		
		if(time() > $data['ttl']){
			//File expired
			unlink($fileName);
			return false;
		}
		
		return $data['data'];
		
	}
 /** 
  * It writes the message
  *
  * @param string message
  */
 protected function write($message)
 {
     if (flock($this->handler, LOCK_EX | LOCK_NB)) {
         fwrite($this->handler, $message . "\n");
     }
     return;
 }
Exemple #27
0
 /**
  * 	Save an item to the cache
  * 
  * 	@param	Cache id
  * 	@param	Data object
  * 	@param	Cache group id (optional)
  * 	@param	Time to live for this item
  */
 function save($cache_id, $data, $cache_group = NULL, $ttl = NULL)
 {
     if ($cache_group !== NULL) {
         $group_dir = $this->_group_dir($cache_group);
         if (!file_exists($group_dir)) {
             mkdir($group_dir);
         }
     }
     $file = $this->_file($cache_id, $cache_group);
     $cache_file = $file . $this->options['cache_postfix'];
     $expiry_file = $file . $this->options['expiry_postfix'];
     if ($ttl === NULL) {
         $ttl = $this->options['default_ttl'];
     }
     //
     //	Ok, so setting ttl = 0 is not quite forever, but 1000 years
     //	Is your PHP code going to be running for 1000 years? If so dont use this library (or just regenerate the cache then)!
     //
     if ($ttl == 0) {
         $ttl = 31536000000.0;
     }
     //1000 years in seconds
     $expire_time = time() + $ttl;
     $f1 = fopen($expiry_file, 'w');
     $f2 = fopen($cache_file, 'w');
     flock($f1, LOCK_EX);
     flock($f2, LOCK_EX);
     fwrite($f1, $expire_time);
     fwrite($f2, serialize($data));
     flock($f1, LOCK_UN);
     flock($f2, LOCK_UN);
     fclose($f1);
     fclose($f2);
     return $expire_time;
 }
Exemple #28
0
function DetectHtml($filePath)
{
    $fp = @fopen($filePath, 'rb');
    if ($fp === false || !flock($fp, LOCK_SH)) {
        return -1;
    }
    $chunk = fread($fp, 1024);
    flock($fp, LOCK_UN);
    fclose($fp);
    $chunk = strtolower($chunk);
    if (!$chunk) {
        return false;
    }
    $chunk = trim($chunk);
    if (preg_match("/<!DOCTYPE\\W*X?HTML/sim", $chunk)) {
        return true;
    }
    $tags = array('<body', '<head', '<html', '<img', '<pre', '<script', '<table', '<title');
    foreach ($tags as $tag) {
        if (false !== strpos($chunk, $tag)) {
            return true;
        }
    }
    if (preg_match('!type\\s*=\\s*[\'"]?\\s*(?:\\w*/)?(?:ecma|java)!sim', $chunk)) {
        return true;
    }
    if (preg_match('!(?:href|src|data)\\s*=\\s*[\'"]?\\s*(?:ecma|java)script:!sim', $chunk)) {
        return true;
    }
    if (preg_match('!url\\s*\\(\\s*[\'"]?\\s*(?:ecma|java)script:!sim', $chunk)) {
        return true;
    }
    return false;
}
Exemple #29
0
 /**
  * @param string $router
  * @param array $env
  * @return UrlScript
  * @throws \RuntimeException
  */
 public function start($router, $env = array())
 {
     $this->slaughter();
     static $port;
     if ($port === NULL) {
         do {
             $port = rand(8000, 10000);
             if (isset($lock)) {
                 @fclose($lock);
             }
             $lock = fopen(dirname(TEMP_DIR) . '/http-server-' . $port . '.lock', 'w');
         } while (!flock($lock, LOCK_EX | LOCK_NB, $wouldBlock) || $wouldBlock);
     }
     $ini = NULL;
     if (($pid = getmypid()) && ($myprocess = `ps -ww -fp {$pid}`)) {
         $fullArgs = preg_split('~[ \\t]+~', explode("\n", $myprocess)[1], 8)[7];
         if (preg_match('~\\s\\-c\\s(?P<ini>[^ \\t]+)\\s~i', $fullArgs, $m)) {
             $ini = '-c ' . $m['ini'] . ' -n';
         }
     }
     $executable = new PhpExecutableFinder();
     $cmd = sprintf('%s %s -d register_argc_argv=on -t %s -S %s:%d %s', escapeshellcmd($executable->find()), $ini, escapeshellarg(dirname($router)), $ip = '127.0.0.1', $port, escapeshellarg($router));
     if (!is_resource($this->process = proc_open($cmd, self::$spec, $this->pipes, dirname($router), $env))) {
         throw new HttpServerException("Could not execute: `{$cmd}`");
     }
     sleep(1);
     // give him some time to boot up
     $status = proc_get_status($this->process);
     if (!$status['running']) {
         throw new HttpServerException("Failed to start php server: " . stream_get_contents($this->pipes[2]));
     }
     $this->url = new UrlScript('http://' . $ip . ':' . $port);
     return $this->getUrl();
 }
 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;
 }