コード例 #1
6
ファイル: Compiler.php プロジェクト: fedeisas/lithium
 /**
  * Compiles a template and writes it to a cache file, which is used for inclusion.
  *
  * @param string $file The full path to the template that will be compiled.
  * @param array $options Options for compilation include:
  *        - `path`: Path where the compiled template should be written.
  *        - `fallback`: Boolean indicating that if the compilation failed for some
  *                      reason (e.g. `path` is not writable), that the compiled template
  *                      should still be returned and no exception be thrown.
  * @return string The compiled template.
  */
 public static function template($file, array $options = array())
 {
     $cachePath = Libraries::get(true, 'resources') . '/tmp/cache/templates';
     $defaults = array('path' => $cachePath, 'fallback' => false);
     $options += $defaults;
     $stats = stat($file);
     $oname = basename(dirname($file)) . '_' . basename($file, '.php');
     $oname .= '_' . ($stats['ino'] ?: hash('md5', $file));
     $template = "template_{$oname}_{$stats['mtime']}_{$stats['size']}.php";
     $template = "{$options['path']}/{$template}";
     if (file_exists($template)) {
         return $template;
     }
     $compiled = static::compile(file_get_contents($file));
     if (is_writable($cachePath) && file_put_contents($template, $compiled) !== false) {
         foreach (glob("{$options['path']}/template_{$oname}_*.php", GLOB_NOSORT) as $expired) {
             if ($expired !== $template) {
                 unlink($expired);
             }
         }
         return $template;
     }
     if ($options['fallback']) {
         return $file;
     }
     throw new TemplateException("Could not write compiled template `{$template}` to cache.");
 }
コード例 #2
1
ファイル: CacheHelper.php プロジェクト: rashijani/dragonphp
 public static function getCache($dir, $cacheName, $maxAge, $deserialize = false, $plainCache = false)
 {
     if (is_dir($dir)) {
         $cacheFile = $dir . $cacheName;
         if (is_file($cacheFile)) {
             // get file stats
             $fileInfo = stat($cacheFile);
             $lastModified = $fileInfo['mtime'];
             $now = mktime();
             //echo '<p>time now = ' . $now;
             $diff = $now - $lastModified;
             //echo '<p>time elapsed = ' .$diff;
             if ($diff >= $maxAge) {
                 //echo 'clearing cache';
                 unlink($cacheFile);
                 return false;
             }
             //echo '<p>returning cache';
             if ($deserialize == false && $plainCache == false) {
                 include_once $cacheFile;
             } else {
                 if ($deserialize == false && $plainCache) {
                     $data = file_get_contents($cacheFile);
                 } else {
                     $data = unserialize(file_get_contents($cacheFile));
                 }
             }
             return $data;
         } else {
             return false;
         }
     }
 }
コード例 #3
0
ファイル: class.file.php プロジェクト: bachnx92/vemaybay
 /**
  * constructor
  *
  * @param string $path the path to a file or folder
  */
 function __construct($path = null)
 {
     if (!is_null($path)) {
         if (file_exists($path)) {
             $this->filePath = $path;
             if (is_file($this->filePath)) {
                 $this->fileStat = @stat($path);
                 $this->fileInfo['size'] = $this->fileStat[7];
                 $this->fileInfo['atime'] = $this->fileStat[8];
                 $this->fileInfo['ctime'] = $this->fileStat[10];
                 $this->fileInfo['mtime'] = $this->fileStat[9];
                 $this->fileInfo['path'] = $path;
                 $this->fileInfo['name'] = basename($path);
                 $this->fileInfo['is_writable'] = $this->isWritable();
                 $this->fileInfo['is_readable'] = $this->isReadable();
             } elseif (is_dir($this->filePath)) {
                 $this->fileStat = @stat($path);
                 $this->fileInfo['name'] = basename($path);
                 $this->fileInfo['path'] = $path;
                 $this->fileInfo['atime'] = $this->fileStat[8];
                 $this->fileInfo['ctime'] = $this->fileStat[10];
                 $this->fileInfo['mtime'] = $this->fileStat[9];
                 $this->fileInfo['is_writable'] = $this->isWritable();
                 $this->fileInfo['is_readable'] = $this->isReadable();
             }
         } else {
             trigger_error('No such file exists. ' . $path, E_USER_NOTICE);
         }
     }
 }
コード例 #4
0
 function ftok($pathname, $id)
 {
     if (!($s = stat($pathname))) {
         return -1;
     }
     return sprintf('%u', ord($id[0]) << 24 | ($s['dev'] & 0xff) << 16 | $s['ino'] & 0xffff);
 }
コード例 #5
0
ファイル: filesystem.php プロジェクト: alphashuro/audeprac
 /**
  * Load properties from a given file properties
  * 
  * @param $file string The filename to scan
  * @param $contents boolean Load the contents
  * @param $loadId boolean Load id from database
  * @return boolean result
  */
 function loadFromFile($file, $contents = false, $loadId = false)
 {
     if (!JFile::exists($file) && !JFolder::exists($file . DS)) {
         return false;
     }
     $info = @stat($file);
     $this->scandate = $this->_db->getNullDate();
     $this->filename = basename($file);
     $this->fullpath = $file;
     $this->permission = fileperms($file) & 0777;
     $this->size = filesize($file);
     $ctime =& JFactory::getDate($info['ctime']);
     $mtime =& JFactory::getDate($info['mtime']);
     $this->ctime = $ctime->toMySQL();
     $this->mtime = $mtime->toMySQL();
     $this->uid = $info['uid'];
     $this->gid = $info['gid'];
     $this->type = '';
     if (is_file($file)) {
         $this->type = 'file';
         $this->hash_md = md5_file($file);
         if ($contents) {
             $f = new JD_File($file);
             $this->contents = $f->read();
         }
     } elseif (is_dir($file)) {
         $this->type = 'dir';
     }
     if ($loadId) {
         $this->_db->setQuery('SELECT id FROM #__jdefender_filesystem WHERE fullpath = ' . $this->fullpath . ' LIMIT 1');
         $this->id = $this->_db->loadResult();
     }
     return true;
 }
コード例 #6
0
ファイル: FileUtils.php プロジェクト: kodi/dpls-framework
 function listFiles()
 {
     $validExtensions = array('css', 'php', 'jpg', 'jpeg', 'gif', 'png', 'html', 'js', 'sql', 'flv');
     $files = array();
     $i = 0;
     if ($handle = opendir($this->path)) {
         while (false !== ($file = readdir($handle))) {
             if ($file != "." && $file != ".." && is_file($this->path . $file)) {
                 $extn = explode('.', $file);
                 $ext = array_pop($extn);
                 if (in_array($ext, $validExtensions)) {
                     $fstat = stat($this->path . $file);
                     $files[$i]['name'] = $file;
                     $files[$i]['lastModifiedNice'] = date("M d Y H:i:s", $fstat['mtime']);
                     $files[$i]['lastModified'] = $fstat['mtime'];
                     $files[$i]['size'] = $fstat['size'];
                     //FUNCTION SCALE
                     $files[$i]['ext'] = $ext;
                     $i++;
                 }
             }
         }
         closedir($handle);
     }
     //$this->f=$dirs;
     //$files=columnSort($files,array('name'));
     return $files;
 }
コード例 #7
0
 function ReadData($targetString, &$map, &$mapItem)
 {
     $data[IN] = null;
     $data[OUT] = null;
     $data_time = 0;
     $matches = 0;
     if (preg_match($this->regexpsHandled[0], $targetString, $matches)) {
         $dataFileName = $matches[1];
         $dataItemName = $matches[2];
     }
     if (!file_exists($dataFileName)) {
         wm_warn("WMData ReadData: {$dataFileName} doesn't exist [WMWMDATA01]");
         return array(null, null, 0);
     }
     $fileHandle = fopen($targetString, "r");
     if (!$fileHandle) {
         wm_warn("WMData ReadData: Couldn't open ({$dataFileName}). [WMWMDATA02]\n");
         return array(null, null, 0);
     }
     list($found, $data) = $this->findDataItem($fileHandle, $dataItemName, $data);
     if ($found === true) {
         $stats = stat($dataFileName);
         $data_time = $stats['mtime'];
     } else {
         wm_warn("WMData ReadData: Data name '{$dataItemName}' didn't exist in '{$dataFileName}'. [WMWMDATA03]\n");
     }
     wm_debug(sprintf("WMData ReadData: Returning (%s, %s, %s)\n", string_or_null($data[IN]), string_or_null($data[OUT]), $data_time));
     return array($data[IN], $data[OUT], $data_time);
 }
コード例 #8
0
ファイル: fields.php プロジェクト: rogerwangzy/watchman
 function testFields()
 {
     $dir = PhutilDirectoryFixture::newEmptyFixture();
     $root = realpath($dir->getPath());
     $watch = $this->watch($root);
     $this->assertFileList($root, array());
     $this->watchmanCommand('log', 'debug', 'XXX: touch a');
     touch("{$root}/a");
     $this->assertFileList($root, array('a'));
     $query = $this->watchmanCommand('query', $root, array('fields' => array('name', 'exists', 'new', 'size', 'mode', 'uid', 'gid', 'mtime', 'mtime_ms', 'mtime_us', 'mtime_ns', 'mtime_f', 'ctime', 'ctime_ms', 'ctime_us', 'ctime_ns', 'ctime_f', 'ino', 'dev', 'nlink', 'oclock', 'cclock'), 'since' => 'n:foo'));
     $this->assertEqual(null, idx($query, 'error'));
     $this->assertEqual(1, count($query['files']));
     $file = $query['files'][0];
     $this->assertEqual('a', $file['name']);
     $this->assertEqual(true, $file['exists']);
     $this->assertEqual(true, $file['new']);
     $stat = stat("{$root}/a");
     $compare_fields = array('size', 'mode', 'uid', 'gid', 'ino', 'dev', 'nlink');
     foreach ($compare_fields as $field) {
         $this->assertEqual($stat[$field], $file[$field], $field);
     }
     $time_fields = array('mtime', 'ctime');
     foreach ($time_fields as $field) {
         $this->assertTimeEqual($stat[$field], $file[$field], $file[$field . '_ms'], $file[$field . '_us'], $file[$field . '_ns'], $file[$field . '_f']);
     }
     $this->assertRegex('/^c:\\d+:\\d+:\\d+:\\d+$/', $file['cclock'], "cclock looks clocky");
     $this->assertRegex('/^c:\\d+:\\d+:\\d+:\\d+$/', $file['oclock'], "oclock looks clocky");
 }
コード例 #9
0
ファイル: FilesystemStorageAccess.php プロジェクト: kch42/ste
 public function load($tpl, &$mode)
 {
     $src_fn = $this->sourcedir . "/" . $tpl;
     $transc_fn = $this->transcompileddir . "/" . $tpl . ".php";
     if ($mode == StorageAccess::MODE_SOURCE) {
         $content = @file_get_contents($src_fn);
         if ($content === false) {
             throw new CantLoadTemplate("Template not found.");
         }
         return $content;
     }
     $src_stat = @stat($src_fn);
     $transc_stat = @stat($transc_fn);
     if ($src_stat === false and $transc_stat === false) {
         throw new CantLoadTemplate("Template not found.");
     } else {
         if ($transc_stat === false) {
             $mode = StorageAccess::MODE_SOURCE;
             return file_get_contents($src_fn);
         } else {
             if ($src_stat === false) {
                 include $transc_fn;
                 return $transcompile_fx;
             } else {
                 if ($src_stat["mtime"] > $transc_stat["mtime"]) {
                     $mode = StorageAccess::MODE_SOURCE;
                     return file_get_contents($src_fn);
                 } else {
                     include $transc_fn;
                     return $transcompile_fx;
                 }
             }
         }
     }
 }
コード例 #10
0
ファイル: File.php プロジェクト: nmx/Modyllic
 static function load($file, $schema)
 {
     # A preparsed schemafile will have a .sqlc extension
     $file_bits = explode(".", $file);
     array_pop($file_bits);
     $sqlc_file = implode(".", $file_bits) . ".sqlc";
     $sqlc = @stat($sqlc_file);
     $sql = @stat($file);
     if (!$sql) {
         throw new Modyllic_Loader_Exception("{$file}: File not found.");
     } else {
         if (!$sqlc or $sqlc[7] == 0 or $sqlc[9] < $sql[9]) {
             if (($data = @file_get_contents($file)) === false) {
                 throw new Modyllic_Loader_Exception("Error opening {$file}");
             }
             $parser = new Modyllic_Parser();
             $parser->partial($schema, $data, $file, ";");
         } else {
             if (($data = @file_get_contents($sqlc_file)) === false) {
                 throw new Modyllic_Loader_Exception("Error opening {$sqlc_file}");
             }
             $subschema = unserialize($data);
             if ($subschema === FALSE) {
                 throw new Modyllic_Loader_Exception("Error unserializing {$sqlc_file}");
             }
             $schema->merge($subschema);
         }
     }
 }
コード例 #11
0
 public function _getListFiles()
 {
     $files = array();
     if (is_dir($this->fullpath) && ($handle = opendir($this->fullpath))) {
         $i = 0;
         // check each files ...
         while (false !== ($file = readdir($handle))) {
             // do not display . and the root ..
             if ($file == '.' || $file == '..') {
                 continue;
             }
             $object = new stdClass();
             $file_stat = stat($this->fullpath . $file);
             // make the link depending on if it's a file or a dir
             $object->is_dir = false;
             $object->is_file = true;
             $object->link = '<a href="' . get_url('sidebarlink/view' . $this->path . $file) . '">' . $file . '</a>';
             $object->name = $file;
             // humain size
             $object->size = convert_size($file_stat['size']);
             // permission
             list($object->perms, $object->chmod) = $this->_getPermissions($this->fullpath . $file);
             // date modification
             $object->mtime = date('D, j M, Y', $file_stat['mtime']);
             $files[$object->name] = $object;
             $i++;
         }
         // while
         closedir($handle);
     }
     uksort($files, 'strnatcmp');
     return $files;
 }
コード例 #12
0
 /**
  * @param string $filename
  * @param string $path
  * @return Map
  * @throws \InvalidArgumentException
  */
 function get($filename, $path)
 {
     if (mb_detect_encoding($filename, 'UTF-8', true) === false) {
         $utf8Filename = utf8_encode($filename);
     } else {
         $utf8Filename = $filename;
     }
     if (!file_exists($this->mapDirectory . $path . $filename)) {
         $this->db()->execute('DELETE FROM Maps WHERE path=%s AND filename=%s', $this->db()->quote($path), $this->db()->quote($utf8Filename));
         throw new \InvalidArgumentException($this->mapDirectory . $path . $utf8Filename . ': file does not exist');
     }
     $fileStats = stat($this->mapDirectory . $path . $filename);
     $result = $this->db()->execute('SELECT * FROM Maps WHERE path=%s AND filename=%s AND size=%d AND mTime=FROM_UNIXTIME(%d)', $this->db()->quote($path), $this->db()->quote($utf8Filename), $fileStats['size'], $fileStats['mtime']);
     if (!$result->recordCount()) {
         $mapInfo = \DedicatedManager\Utils\GbxReader\Map::read($this->mapDirectory . $path . $filename);
         $map = new Map();
         $fields = array('uid', 'name', 'environment', 'mood', 'type', 'displayCost', 'nbLaps', 'authorLogin', 'authorNick', 'authorZone', 'authorTime', 'goldTime', 'silverTime', 'bronzeTime', 'authorScore', 'size', 'mTime');
         $this->db()->execute('INSERT INTO Maps(path, filename, %s) ' . 'VALUES (%s,%s,%s,%s,%s,%s,%s,%d,%d,%s,%s,%s,%d,%d,%d,%d,%d,%d,FROM_UNIXTIME(%d)) ' . 'ON DUPLICATE KEY UPDATE ' . \ManiaLib\Database\Tools::getOnDuplicateKeyUpdateValuesString($fields), implode(',', $fields), $this->db()->quote($map->path = $path), $this->db()->quote($map->filename = $utf8Filename), $this->db()->quote($map->uid = $mapInfo->uid), $this->db()->quote($map->name = $mapInfo->name), $this->db()->quote($map->environment = $mapInfo->environment), $this->db()->quote($map->mood = $mapInfo->mood), $this->db()->quote($map->type = $mapInfo->type), $map->displayCost = $mapInfo->displayCost, $map->nbLaps = $mapInfo->nbLaps, $this->db()->quote($map->authorLogin = $mapInfo->author->login), $this->db()->quote($map->authorNick = $mapInfo->author->nickname), $this->db()->quote($map->authorZone = $mapInfo->author->zone), $map->authorTime = $mapInfo->authorTime, $map->goldTime = $mapInfo->goldTime, $map->silverTime = $mapInfo->silverTime, $map->bronzeTime = $mapInfo->bronzeTime, $map->authorScore = $mapInfo->authorScore, $fileStats['size'], $fileStats['mtime']);
         if ($mapInfo->thumbnail) {
             imagejpeg($mapInfo->thumbnail, MANIALIB_APP_PATH . '/www/media/images/thumbnails/' . $map->uid . '.jpg', 100);
         }
     } else {
         $map = Map::fromRecordSet($result);
     }
     return $map;
 }
コード例 #13
0
ファイル: Min.php プロジェクト: dqneo/ethnam
 /**
  *  最小値のチェックを行う
  *
  *  @access public
  *  @param  string  $name       フォームの名前
  *  @param  mixed   $var        フォームの値
  *  @param  array   $params     プラグインのパラメータ
  */
 public function validate($name, $var, $params)
 {
     $true = true;
     $type = $this->getFormType($name);
     if (isset($params['min']) == false || $this->isEmpty($var, $type)) {
         return $true;
     }
     switch ($type) {
         case VAR_TYPE_INT:
             if ($var < $params['min']) {
                 if (isset($params['error'])) {
                     $msg = $params['error'];
                 } else {
                     $msg = _et('Please input more than %d(int) to {form}.');
                 }
                 return Ethna::raiseNotice($msg, E_FORM_MIN_INT, array($params['min']));
             }
             break;
         case VAR_TYPE_FLOAT:
             if ($var < $params['min']) {
                 if (isset($params['error'])) {
                     $msg = $params['error'];
                 } else {
                     $msg = _et('Please input more than %f(float) to {form}.');
                 }
                 return Ethna::raiseNotice($msg, E_FORM_MIN_FLOAT, array($params['min']));
             }
             break;
         case VAR_TYPE_DATETIME:
             $t_min = strtotime($params['min']);
             $t_var = strtotime($var);
             if ($t_var < $t_min) {
                 if (isset($params['error'])) {
                     $msg = $params['error'];
                 } else {
                     $msg = _et('Please input datetime value %s or later to {form}.');
                 }
                 return Ethna::raiseNotice($msg, E_FORM_MIN_DATETIME, array($params['min']));
             }
             break;
         case VAR_TYPE_FILE:
             $st = stat($var['tmp_name']);
             if ($st[7] < $params['min'] * 1024) {
                 if (isset($params['error'])) {
                     $msg = $params['error'];
                 } else {
                     $msg = _et('Please specify file whose size is more than %d KB.');
                 }
                 return Ethna::raiseNotice($msg, E_FORM_MIN_FILE, array($params['min']));
             }
             break;
         case VAR_TYPE_STRING:
             $params['mbstrmin'] = $params['min'];
             unset($params['min']);
             $vld = $this->plugin->getPlugin('Validator', 'Mbstrmin');
             return $vld->validate($name, $var, $params);
             break;
     }
     return $true;
 }
コード例 #14
0
ファイル: Stream.php プロジェクト: necromant2005/AOP
    /**
     * Opens the script file and converts markup.
     */
    public function stream_open($path, $mode, $options, &$opened_path)
    {
        // get the view script source
        $path        = str_replace('zend.view://', '', $path);
        $this->_data = file_get_contents($path);

        /**
         * If reading the file failed, update our local stat store
         * to reflect the real stat of the file, then return on failure
         */
        if ($this->_data === false) {
            $this->_stat = stat($path);
            return false;
        }

        /**
         * Call callbacks
         *
         */
        foreach (self::getWrappers() as $wrapper) {
            $this->_data = $wrapper->process($this->_data);
        }

        /**
         * file_get_contents() won't update PHP's stat cache, so we grab a stat
         * of the file to prevent additional reads should the script be
         * requested again, which will make include() happy.
         */
        $this->_stat = stat($path);

        return true;
    }
コード例 #15
0
ファイル: cronCleanup.php プロジェクト: 5haman/knowledgetree
function cleanupTempDirectory($dir, $force = false)
{
    $dir = str_replace('\\', '/', $dir);
    if (strpos($dir, '/tmp') === false) {
        return;
    }
    $dh = opendir($dir);
    while (($name = readdir($dh)) !== false) {
        if (substr($name, 0, 1) == '.') {
            continue;
        }
        $kti = substr($name, 0, 3) == 'kti';
        // remove files starting with kti (indexer temp files created by open office)
        $fullname = $dir . '/' . $name;
        if (!$kti && !$force) {
            $info = stat($fullname);
            if ($info['ctime'] >= time() - 24 * 60 * 60) {
                continue;
            }
            // remove files that have been accessed in the last 24 hours
        }
        if (is_dir($fullname)) {
            cleanupTempDirectory($fullname, true);
            rmdir($fullname);
        } else {
            unlink($fullname);
        }
    }
    closedir($dh);
}
コード例 #16
0
ファイル: PluginList.php プロジェクト: eberhardte/moosh
 public function execute()
 {
     $filepath = $this->expandedOptions['path'];
     $stat = stat($filepath);
     if (!$stat || time() - $stat['mtime'] > 60 * 60 * 24 || !$stat['size']) {
         unlink($filepath);
         file_put_contents($filepath, fopen(self::$APIURL, 'r'));
     }
     $jsonfile = file_get_contents($filepath);
     if ($jsonfile === false) {
         die("Can't read json file");
     }
     $data = json_decode($jsonfile);
     $fulllist = array();
     foreach ($data->plugins as $k => $plugin) {
         if (!$plugin->component) {
             continue;
         }
         $fulllist[$plugin->component] = array();
         foreach ($plugin->versions as $v => $version) {
             foreach ($version->supportedmoodles as $supportedmoodle) {
                 $fulllist[$plugin->component]['releases'][$supportedmoodle->release] = $version;
             }
             $fulllist[$plugin->component]['url'] = $version->downloadurl;
         }
     }
     ksort($fulllist);
     foreach ($fulllist as $k => $plugin) {
         $versions = array_keys($plugin['releases']);
         sort($versions);
         echo "{$k}," . implode(",", $versions) . "," . $plugin['url'] . "\n";
     }
 }
コード例 #17
0
ファイル: Compiler.php プロジェクト: pavan-git/visualphpunit
 /**
  *  Retrieves the compiled filename, and caches the file
  *  if it is not already cached.
  *
  *  @param string $file      The file location.
  *  @param array $options    The compilation options, which take the
  *                           following keys:
  *                           'path' - The path where where the cached file
  *                           should be stored.
  *  @access public
  *  @return string
  */
 public static function compile($file, $options = array())
 {
     $options += array('path' => 'compiled/');
     $stats = stat($file);
     $dir = dirname($file);
     $location = basename(dirname($dir)) . '_' . basename($dir) . '_' . basename($file, '.html');
     $template = 'template_' . $location . '_' . $stats['mtime'] . '_' . $stats['ino'] . '_' . $stats['size'] . '.html';
     $template = $options['path'] . $template;
     if (file_exists($template)) {
         return $template;
     }
     $compiled = self::_replace(file_get_contents($file));
     $template_dir = dirname($template);
     if (!is_dir($template_dir) && !mkdir($template_dir, 0755, true)) {
         return false;
     }
     if (!is_writable($template_dir) || file_put_contents($template, $compiled) === false) {
         return false;
     }
     $pattern = $template_dir . '/template_' . $location . '_*.html';
     foreach (glob($pattern) as $old) {
         if ($old !== $template) {
             unlink($old);
         }
     }
     return $template;
 }
コード例 #18
0
ファイル: Compiler.php プロジェクト: EHER/chegamos
 /**
  * Compiles a template and writes it to a cache file, which is used for inclusion.
  *
  * @param string $file The full path to the template that will be compiled.
  * @param string $options Options for compilation include:
  *        - `path`: Path where the compiled template should be written.
  *        - `fallback`: Boolean indicating that if the compilation failed for some
  *                      reason (e.g. `path` is not writable), that the compiled template
  *                      should still be returned and no exception be thrown.
  * @return string The compiled template.
  */
 public static function template($file, array $options = array())
 {
     $cachePath = LITHIUM_APP_PATH . '/resources/tmp/cache/templates';
     $defaults = array('path' => $cachePath, 'fallback' => true);
     $options += $defaults;
     $stats = stat($file);
     $dir = dirname($file);
     $oname = basename(dirname($dir)) . '_' . basename($dir) . '_' . basename($file, '.php');
     $template = "template_{$oname}_{$stats['ino']}_{$stats['mtime']}_{$stats['size']}.php";
     $template = "{$options['path']}/{$template}";
     if (file_exists($template)) {
         return $template;
     }
     $compiled = static::compile(file_get_contents($file));
     if (is_writable($cachePath) && file_put_contents($template, $compiled) !== false) {
         foreach (glob("{$options['path']}/template_{$oname}_*.php") as $expired) {
             if ($expired !== $template) {
                 unlink($expired);
             }
         }
         return $template;
     }
     if ($options['fallback']) {
         return $file;
     }
     throw new TemplateException("Could not write compiled template {$template} to cache");
 }
コード例 #19
0
ファイル: view.php プロジェクト: AntBean/alienvault-ossim
function check_writable_relative($dir)
{
    $uid = posix_getuid();
    $gid = posix_getgid();
    $user_info = posix_getpwuid($uid);
    $user = $user_info['name'];
    $group_info = posix_getgrgid($gid);
    $group = $group_info['name'];
    $fix_cmd = '. ' . _("To fix that, execute following commands as root") . ':<br><br>' . "cd " . getcwd() . "<br>" . "mkdir -p {$dir}<br>" . "chown {$user}:{$group} {$dir}<br>" . "chmod 0700 {$dir}";
    if (!is_dir($dir)) {
        $config_nt = array('content' => _("Required directory " . getcwd() . "{$dir} does not exist") . $fix_cmd, 'options' => array('type' => 'nf_warning', 'cancel_button' => FALSE), 'style' => 'width: 80%; margin: 20px auto;');
        $nt = new Notification('nt_1', $config_nt);
        $nt->show();
        exit;
    }
    if (!($stat = stat($dir))) {
        $config_nt = array('content' => _("Could not stat configs dir") . $fix_cmd, 'options' => array('type' => 'nf_warning', 'cancel_button' => FALSE), 'style' => 'width: 80%; margin: 20px auto;');
        $nt = new Notification('nt_1', $config_nt);
        $nt->show();
        exit;
    }
    // 2 -> file perms (must be 0700)
    // 4 -> uid (must be the apache uid)
    // 5 -> gid (must be the apache gid)
    if ($stat[2] != 16832 || $stat[4] !== $uid || $stat[5] !== $gid) {
        $config_nt = array('content' => _("Invalid perms for configs dir") . $fix_cmd, 'options' => array('type' => 'nf_warning', 'cancel_button' => FALSE), 'style' => 'width: 80%; margin: 20px auto;');
        $nt = new Notification('nt_1', $config_nt);
        $nt->show();
        exit;
    }
}
コード例 #20
0
ファイル: func_system.php プロジェクト: ateliee/php_lib
function statE($filename)
{
    global $G_SYSTEM_SERVER_ENCODE;
    $php_charset = mb_internal_encoding();
    $filename = mb_convert_encoding($filename, $G_SYSTEM_SERVER_ENCODE, $php_charset);
    return stat($filename);
}
コード例 #21
0
ファイル: Stream.php プロジェクト: mindfeederllc/openemr
 /**
  * Opens the script file and converts markup.
  *
  * @param  string $path
  * @param         $mode
  * @param         $options
  * @param         $opened_path
  * @return bool
  */
 public function stream_open($path, $mode, $options, &$opened_path)
 {
     // get the view script source
     $path = str_replace('zend.view://', '', $path);
     $this->data = file_get_contents($path);
     /**
      * If reading the file failed, update our local stat store
      * to reflect the real stat of the file, then return on failure
      */
     if ($this->data === false) {
         $this->stat = stat($path);
         return false;
     }
     /**
      * Convert <?= ?> to long-form <?php echo ?> and <?php ?> to <?php ?>
      *
      */
     $this->data = preg_replace('/\\<\\?\\=/', "<?php echo ", $this->data);
     $this->data = preg_replace('/<\\?(?!xml|php)/s', '<?php ', $this->data);
     /**
      * file_get_contents() won't update PHP's stat cache, so we grab a stat
      * of the file to prevent additional reads should the script be
      * requested again, which will make include() happy.
      */
     $this->stat = stat($path);
     return true;
 }
コード例 #22
0
 public function obtain()
 {
     if (function_exists('posix_geteuid') && function_exists('posix_getegid')) {
         $this->myuid = posix_geteuid();
         $this->mygid = posix_getegid();
     } else {
         $randName = '/tmp/rutorrent-' . rand() . '.tmp';
         @file_put_contents($randName, '');
         $ss = @stat($randName);
         if ($ss) {
             $this->mygid = $ss['gid'];
             $this->myuid = $ss['uid'];
             @unlink($randName);
         }
     }
     $req = new rXMLRPCRequest(new rXMLRPCCommand("to_kb", floatval(1024)));
     if ($req->run()) {
         $this->linkExist = true;
         if (!$req->fault) {
             $this->badXMLRPCVersion = false;
         }
         $req = new rXMLRPCRequest(array(new rXMLRPCCommand("get_directory"), new rXMLRPCCommand("get_session"), new rXMLRPCCommand("system.client_version"), new rXMLRPCCommand("system.library_version"), new rXMLRPCCommand("set_xmlrpc_size_limit", 67108863)));
         if ($req->run() && !$req->fault) {
             $this->directory = $req->val[0];
             $this->session = $req->val[1];
             $this->version = $req->val[2];
             $this->libVersion = $req->val[3];
             $parts = explode('.', $this->version);
             $this->iVersion = 0;
             for ($i = 0; $i < count($parts); $i++) {
                 $this->iVersion = ($this->iVersion << 8) + $parts[$i];
             }
             if (is_dir($this->session) && isLocalMode()) {
                 $ss = @stat($this->session . 'rtorrent.lock');
                 if (!$ss) {
                     $ss = @stat($this->session . 'rtorrent.dht_cache');
                 }
                 if (!$ss) {
                     $ss = @stat($this->session);
                 }
                 if ($ss) {
                     $this->gid = $ss['gid'];
                     $this->uid = $ss['uid'];
                     if (!empty($this->directory) && $this->directory[0] == '~') {
                         if (function_exists('posix_getpwuid')) {
                             $ui = posix_getpwuid($this->uid);
                             $this->directory = $ui["dir"] . substr($this->directory, 1);
                         } else {
                             $req = new rXMLRPCRequest(new rXMLRPCCommand("execute_capture", array("echo", "~")));
                             if ($req->run() && !$req->fault) {
                                 $this->directory = trim($req->val[0]) . substr($this->directory, 1);
                             }
                         }
                     }
                 }
             }
             $this->store();
         }
     }
 }
コード例 #23
0
ファイル: StreamFile.php プロジェクト: whysasse/kmwiki
 /**
  * Stream a file to the browser, adding all the headings and fun stuff.
  * Headers sent include: Content-type, Content-Length, Last-Modified,
  * and Content-Disposition.
  *
  * @param string $fname Full name and path of the file to stream
  * @param array $headers Any additional headers to send
  * @param bool $sendErrors Send error messages if errors occur (like 404)
  * @throws MWException
  * @return bool Success
  */
 public static function stream($fname, $headers = array(), $sendErrors = true)
 {
     wfProfileIn(__METHOD__);
     if (FileBackend::isStoragePath($fname)) {
         // sanity
         wfProfileOut(__METHOD__);
         throw new MWException(__FUNCTION__ . " given storage path '{$fname}'.");
     }
     wfSuppressWarnings();
     $stat = stat($fname);
     wfRestoreWarnings();
     $res = self::prepareForStream($fname, $stat, $headers, $sendErrors);
     if ($res == self::NOT_MODIFIED) {
         $ok = true;
         // use client cache
     } elseif ($res == self::READY_STREAM) {
         wfProfileIn(__METHOD__ . '-send');
         $ok = readfile($fname);
         wfProfileOut(__METHOD__ . '-send');
     } else {
         $ok = false;
         // failed
     }
     wfProfileOut(__METHOD__);
     return $ok;
 }
コード例 #24
0
ファイル: ajax.php プロジェクト: verbazend/AWFA
 public function backup_status()
 {
     // Make sure the serial exists.
     if (pb_backupbuddy::_POST('serial') == '' || empty(pb_backupbuddy::$options['backups'][$_POST['serial']])) {
         echo '!' . pb_backupbuddy::$format->localize_time(time()) . '|~|0|~|' . round(memory_get_peak_usage() / 1048576, 2) . '|~|error|~|Error #5445589. Invalid backup serial (' . htmlentities(pb_backupbuddy::_POST('serial')) . '). Please check directory permissions and your PHP error_log as an early backup function (such as pre_backup) may have failed. Fatal error.' . "\n";
         echo '!' . pb_backupbuddy::$format->localize_time(time()) . '|~|0|~|' . round(memory_get_peak_usage() / 1048576, 2) . '|~|action|~|halt_script' . "\n";
     } else {
         // Return the status information since last retrieval.
         $return_status = '!' . pb_backupbuddy::$format->localize_time(time()) . "|~|0|~|0|~|ping\n";
         //error_log( print_r( pb_backupbuddy::$options['backups'], true ) );
         foreach (pb_backupbuddy::$options['backups'][$_POST['serial']]['steps'] as $step) {
             if ($step['start_time'] != 0 && $step['finish_time'] == 0) {
                 // A step has begun but has not finished. This should not happen but the WP cron is funky. Wait a while before continuing.
                 pb_backupbuddy::status('details', 'Waiting for function `' . $step['function'] . '` to complete. Started ' . (time() - $step['start_time']) . ' seconds ago.', $_POST['serial']);
                 if (time() - $step['start_time'] > 300) {
                     pb_backupbuddy::status('warning', 'The function `' . $step['function'] . '` is taking an abnormally long time to complete (' . (time() - $step['start_time']) . ' seconds). The backup may have stalled.', $_POST['serial']);
                 }
             } elseif ($step['start_time'] == 0) {
                 // Step that has not started yet.
             } else {
                 // Last case: Finished. Skip.
                 // Do nothing.
             }
         }
         /********** Begin file sizes for status updates. *********/
         $temporary_zip_directory = pb_backupbuddy::$options['backup_directory'] . 'temp_zip_' . $_POST['serial'] . '/';
         if (file_exists($temporary_zip_directory)) {
             // Temp zip file.
             $directory = opendir($temporary_zip_directory);
             while ($file = readdir($directory)) {
                 if ($file != '.' && $file != '..') {
                     $stats = stat($temporary_zip_directory . $file);
                     $return_status .= '!' . pb_backupbuddy::$format->localize_time(time()) . '|~|' . round(microtime(true) - pb_backupbuddy::$start_time, 2) . '|~|' . round(memory_get_peak_usage() / 1048576, 2) . '|~|details|~|' . __('Temporary ZIP file size', 'it-l10n-backupbuddy') . ': ' . pb_backupbuddy::$format->file_size($stats['size']) . "\n";
                     $return_status .= '!' . pb_backupbuddy::$format->localize_time(time()) . '|~|' . round(microtime(true) - pb_backupbuddy::$start_time, 2) . '|~|' . round(memory_get_peak_usage() / 1048576, 2) . '|~|action|~|archive_size^' . pb_backupbuddy::$format->file_size($stats['size']) . "\n";
                 }
             }
             closedir($directory);
             unset($directory);
         }
         if (file_exists(pb_backupbuddy::$options['backups'][$_POST['serial']]['archive_file'])) {
             // Final zip file.
             $stats = stat(pb_backupbuddy::$options['backups'][$_POST['serial']]['archive_file']);
             $return_status .= '!' . pb_backupbuddy::$format->localize_time(time()) . '|~|' . round(microtime(true) - pb_backupbuddy::$start_time, 2) . '|~|' . round(memory_get_peak_usage() / 1048576, 2) . '|~|details|~|' . __('Final ZIP file size', 'it-l10n-backupbuddy') . ': ' . pb_backupbuddy::$format->file_size($stats['size']) . "\n";
             $return_status .= '!' . pb_backupbuddy::$format->localize_time(time()) . '|~|' . round(microtime(true) - pb_backupbuddy::$start_time, 2) . '|~|' . round(memory_get_peak_usage() / 1048576, 2) . '|~|action|~|archive_size^' . pb_backupbuddy::$format->file_size($stats['size']) . "\n";
         }
         /********** End file sizes for status updates. *********/
         $status_lines = pb_backupbuddy::get_status(pb_backupbuddy::_POST('serial'), true, false, true);
         // Clear file, dont unlink file (pclzip cant handle files unlinking mid-zip), dont show getting status message.
         if ($status_lines !== false) {
             // Only add lines if there is status contents.
             foreach ($status_lines as $status_line) {
                 //$return_status .= '!' . $status_line[0] . '|' . $status_line[3] . '|' . $status_line[4] . '( ' . $status_line[1] . 'secs / ' . $status_line[2] . 'MB )' . "\n";
                 $return_status .= '!' . implode('|~|', $status_line) . "\n";
             }
         }
         // Return messages.
         echo $return_status;
     }
     die;
 }
コード例 #25
0
ファイル: Stream.php プロジェクト: robotr/mvcDemo
 /**
  * Opens the script file and converts markup
  * @param string $path
  * @param string $mode
  * @param array $options
  * @param int $openedPath
  * @return bool
  */
 public function stream_open($path, $mode, $options, &$openedPath)
 {
     // get the view script source
     $path = str_replace('slick.view://', '', $path);
     $this->_data = file_get_contents($path);
     /**
      * If reading the file failed, update our local stat store
      * to reflect the real stat of the file, then return on failure
      */
     if ($this->_data === false) {
         $this->_stat = stat($path);
         return false;
     }
     /**
      * replace short-open tags, parse php-tags
      */
     $this->_data = preg_replace('/\\<\\?\\=/', '<?php echo ', $this->_data);
     $this->_data = preg_replace('/<\\?(?!xml|php)/s', '<?php ', $this->_data);
     /**
      * force update PHP's stat cache, to prevent additional reads
      * should the script be requested again
      */
     $this->_stat = stat($path);
     return true;
 }
コード例 #26
0
ファイル: twodeep.php プロジェクト: swn73/watchman
 function testTwoDeep()
 {
     $dir = new WatchmanDirectoryFixture();
     $root = $dir->getPath();
     $watch = $this->watch($root);
     $this->assertFileList($root, array());
     $this->assertEqual(true, mkdir("{$root}/foo"));
     $this->assertEqual(true, mkdir("{$root}/foo/bar"));
     // Guarantee that 111's mtime is greater than its directory's
     sleep(1);
     $this->assertEqual(3, file_put_contents("{$root}/foo/bar/111", "111"));
     $this->watchmanCommand('log', 'debug', 'XXX: created 111');
     $this->assertFileList($root, array("foo", "foo/bar", "foo/bar/111"));
     $query = $this->watchmanCommand('find', $root, 'foo/bar/111');
     $wfile = $query['files'][0];
     clearstatcache();
     $sfile = stat("{$root}/foo/bar/111");
     $query = $this->watchmanCommand('find', $root, 'foo/bar');
     $wdir = $query['files'][0];
     clearstatcache();
     $sdir = stat("{$root}/foo/bar");
     $this->watchmanCommand('log', 'debug', 'XXX: perform assertions');
     $compare_fields = array('size', 'mode', 'uid', 'gid', 'ino', 'dev', 'nlink', 'mtime', 'ctime');
     foreach ($compare_fields as $field) {
         $this->assertEqual($sfile[$field], $wfile[$field], "file: {$field} {$sfile[$field]} vs watchman {$wfile[$field]}");
         $this->assertEqual($sdir[$field], $wdir[$field], "dir: {$field} {$sdir[$field]} vs watchman {$wdir[$field]}");
     }
     $this->watchmanCommand('log', 'debug', 'XXX: remove it all');
     w_rmdir_recursive("{$root}/foo/bar");
     $this->assertFileList($root, array("foo"));
 }
コード例 #27
0
 /**
  * test export data
  */
 public function testExportData() {
     $dao = new BackupMySQLDAO();
     $export_file = $dao->export();
     $this->assertTrue( file_exists($export_file) );
     $zip_stats = stat($export_file);
     $this->assertTrue($zip_stats['size'] > 0);
     $za = new ZipArchive();
     $za->open($export_file);
     $zip_files = array();
     for ($i=0; $i<$za->numFiles;$i++) {
         $zfile = $za->statIndex($i);
         $zip_files[$zfile['name']] = $zfile['name'];
     }
     //verify we have create table file
     $this->assertTrue($zip_files["create_tables.sql"]);
     $za->close();
     $q = "show tables";
     $q2 = "show create table ";
     $stmt = $this->pdo->query($q);
     // verify we have all table files
     while($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
         foreach($data as $key => $value) {
             $zfile = '/' . $value .'.txt';
             $this->assertTrue($zip_files[$zfile]);
         }
     }
 }
コード例 #28
0
ファイル: loggerClass.php プロジェクト: openeyes/openeyes
 public function addLogEntry($filename, $status, $process)
 {
     $filedata = stat($filename);
     $fileIdQ = $this->databaseConnection->query("SELECT id,id FROM dicom_files WHERE filename = '" . $filename . "' AND filesize ='" . $filedata['size'] . "' AND filedate='" . date('Y-m-d H:i:s', $filedata['mtime']) . "'");
     $fileIdArr = $fileIdQ->fetch_array();
     $this->databaseConnection->query("INSERT INTO dicom_file_log (event_date_time, dicom_file_id, status, process_name) VALUES (now(), '" . $fileIdArr[0] . "', '" . $status . "', '" . $process . "')");
 }
コード例 #29
0
ファイル: file-manager.php プロジェクト: borisper1/vesi-cms
function displayFiles($path)
{
    echo "<table class='table table-hover file-list'>\n        <thead><th>Nome</th><th>Dimensione</th><th>Ultima modifica</th></thead>";
    $file_array = array_diff(scandir("../" . $path), array('..', '.', '.DS_Store'));
    foreach ($file_array as $file) {
        $url = "../" . $path . "/" . $file;
        if (is_dir($url)) {
            $name = $file;
            $folder_path = $path . "/" . $file;
            $size = formatBytes(getFolderSize($url), 1);
            $date = date("d/m/Y", stat($url)['mtime']);
            echo "<tr><td><span class='fa-stack fa-2x'><i class='fa fa-folder'></i></span> <a href='#' data-path=\"{$folder_path}\" class='file-list-folder'>{$name}</a>";
            echo "<button type='button' class='btn btn-link pull-right lmb remove-folder tooltipped' data-toggle='tooltip' title='Elimina' data-path=\"{$folder_path}\"><i class='fa fa-remove'></i></button>";
            echo "<button type='button' class='btn btn-link pull-right lmb edit-folder tooltipped' data-toggle='tooltip' title='Rinomina' data-path=\"{$folder_path}\"><i class='fa fa-edit'></i></button>";
            echo "</td><td><span class='text-muted'>{$size}</span></td><td><span class='text-muted'>{$date}</span></td></tr>";
        } else {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $content_type = finfo_file($finfo, $url);
            $file_icon = getFileTypeIcon($content_type, $file);
            $size = formatBytes(filesize($url), 1);
            $date = date("d/m/Y", filemtime($url));
            $preview = canPreview($content_type);
            if ($preview == "no") {
                echo "<tr><td><span class='fa-stack fa-2x'><i class='fa {$file_icon}'></i></span> <a href=\"{$url}\" class='file-list' target='_blank'>{$file}</a>";
            } else {
                echo "<tr><td><span class='fa-stack fa-2x'><i class='fa {$file_icon}'></i></span> <a href='#' data-path=\"{$url}\" data-preview_mode='{$preview}' class='file-list-previewable'>{$file}</a>";
            }
            echo "<button type='button' class='btn btn-link pull-right lmb remove-file tooltipped' data-toggle='tooltip' title='Elimina' data-path=\"{$url}\"><i class='fa fa-remove'></i></button>";
            echo "</td><td><span class='text-muted'>{$size}</span></td><td><span class='text-muted'>{$date}</span></td></tr>";
        }
    }
    echo "</table>";
}
コード例 #30
0
 /**
  * Loads all stylesheet files registered through
  * \TYPO3\CMS\Backend\Sprite\SpriteManager::addIconSprite
  *
  * In fact the stylesheet-files are copied to \TYPO3\CMS\Backend\Sprite\SpriteManager::tempPath
  * where they automatically will be included from via
  * \TYPO3\CMS\Backend\Template\DocumentTemplate and
  * \TYPO3\CMS\Core\Resource\ResourceCompressor
  *
  * @return void
  */
 protected function loadRegisteredSprites()
 {
     // Saves which CSS Files are currently "allowed to be in place"
     $allowedCssFilesinTempDir = array(basename($this->cssTcaFile));
     // Process every registeres file
     foreach ((array) $GLOBALS['TBE_STYLES']['spritemanager']['cssFiles'] as $file) {
         $fileName = basename($file);
         // File should be present
         $allowedCssFilesinTempDir[] = $fileName;
         // get-Cache Filename
         $fileStatus = stat(PATH_site . $file);
         $unique = md5($fileName . $fileStatus['mtime'] . $fileStatus['size']);
         $cacheFile = PATH_site . SpriteManager::$tempPath . $fileName . $unique . '.css';
         if (!file_exists($cacheFile)) {
             copy(PATH_site . $file, $cacheFile);
         }
     }
     // Get all .css files in dir
     $cssFilesPresentInTempDir = GeneralUtility::getFilesInDir(PATH_site . SpriteManager::$tempPath, '.css', 0);
     // and delete old ones which are not needed anymore
     $filesToDelete = array_diff($cssFilesPresentInTempDir, $allowedCssFilesinTempDir);
     foreach ($filesToDelete as $file) {
         unlink(PATH_site . SpriteManager::$tempPath . $file);
     }
 }