/**
  * main method
  *
  * @param  string $tempDir an other directory to clear of all folders and files, if desired
  * @return void
  */
 public function main($tempDir = null)
 {
     if (empty($tempDir)) {
         $tempDir = Configure::read('Attachments.tmpUploadsPath');
     }
     if (!Folder::isAbsolute($tempDir)) {
         $this->out('The path must be absolute, "' . $tempDir . '" given.');
         exit;
     }
     $Folder = new Folder();
     if ($Folder->cd($tempDir) === false) {
         $this->out('Path "' . $tempDir . '" doesn\'t seem to exist.');
         exit;
     }
     $dir = new Folder($tempDir);
     $folders = $dir->read();
     $files = $dir->findRecursive();
     $deletedFiles = 0;
     $deletedFolders = 0;
     $this->out('Found ' . count($folders[0]) . ' folders and ' . count($files) . ' files');
     foreach ($files as $filePath) {
         $file = new File($filePath);
         // only delete if last change is longer than 24 hours ago
         if ($file->lastChange() < time() - 24 * 60 * 60 && $file->delete()) {
             $deletedFiles++;
         }
         $file->close();
     }
     foreach ($folders[0] as $folderName) {
         $folder = new Folder($dir->pwd() . $folderName);
         // only delete if folder is empty
         if ($folder->dirsize() === 0 && $folder->delete()) {
             $deletedFolders++;
         }
     }
     $this->out('Deleted ' . $deletedFolders . ' folders and ' . $deletedFiles . ' files.');
 }
Esempio n. 2
0
 /**
  * testLastChange method
  *
  * @return void
  */
 public function testLastChange()
 {
     $someFile = new File(TMP . 'some_file.txt', false);
     $this->assertFalse($someFile->lastChange());
     $this->assertTrue($someFile->open('r+'));
     $this->assertWithinRange(time(), $someFile->lastChange(), 2);
     $someFile->write('something');
     $this->assertWithinRange(time(), $someFile->lastChange(), 2);
     $someFile->close();
     $someFile->delete();
 }
 /**
  * Process the tasks when they need to run
  *
  * @access private
  * @return void
  */
 private function runjobs()
 {
     $dir = new Folder(TMP);
     // set processing flag so function takes place only once at any given time
     $processing = count($dir->find('\\.scheduler_running_flag'));
     $processingFlag = new File($dir->slashTerm($dir->pwd()) . '.scheduler_running_flag');
     if ($processing && time() - $processingFlag->lastChange() < $this->processingTimeout) {
         $this->out("Scheduler already running! Exiting.");
         return false;
     } else {
         $processingFlag->delete();
         $processingFlag->create();
     }
     if (!$this->storePath) {
         $this->storePath = TMP;
     }
     // look for a store of the previous run
     $store = "";
     $storeFilePath = $this->storePath . $this->storeFile;
     if (file_exists($storeFilePath)) {
         $store = file_get_contents($storeFilePath);
     }
     $this->out('Reading from: ' . $storeFilePath);
     // build or rebuild the store
     if ($store != '') {
         $store = json_decode($store, true);
     } else {
         $store = $this->schedule;
     }
     // run the jobs that need to be run, record the time
     foreach ($this->schedule as $name => $job) {
         $now = new DateTime();
         $task = $job['task'];
         $action = $job['action'];
         // if the job has never been run before, create it
         if (!isset($store[$name])) {
             $store[$name] = $job;
         }
         // figure out the last run date
         $tmptime = $store[$name]['lastRun'];
         if ($tmptime == null) {
             $tmptime = new DateTime("1969-01-01 00:00:00");
         } elseif (is_array($tmptime)) {
             $tmptime = new DateTime($tmptime['date'], new DateTimeZone($tmptime['timezone']));
         } elseif (is_string($tmptime)) {
             $tmptime = new DateTime($tmptime);
         }
         // determine the next run time based on the last
         if (substr($job['interval'], 0, 1) === 'P') {
             $tmptime->add(new DateInterval($job['interval']));
             // "P10DT4H" http://www.php.net/manual/en/class.dateinterval.php
         } else {
             $tmptime->modify($job['interval']);
             // "next day 10:30" http://www.php.net/manual/en/datetime.formats.relative.php
         }
         // is it time to run? has it never been run before?
         if ($tmptime <= $now) {
             $this->hr();
             $this->out("Running {$name}");
             $this->hr();
             if (!isset($this->{$task})) {
                 $this->{$task} = $this->Tasks->load($task);
                 // load models if they aren't already
                 // foreach ($this->$task->uses as $mk => $mv) {
                 // 	if (!isset($this->$task->$mv)) {
                 // 		App::uses('AppModel', 'Model');
                 // 		App::uses($mv, 'Model');
                 // 		$this->$task->$mv = new $mv();
                 // 	}
                 // }
             }
             // grab the entire schedule record incase it was updated..
             $store[$name] = $this->schedule[$name];
             // execute the task and store the result
             $store[$name]['lastResult'] = call_user_func_array(array($this->{$task}, $action), $job['args']);
             // assign it the current time
             $now = new DateTime();
             $store[$name]['lastRun'] = $now->format('Y-m-d H:i:s');
         }
     }
     // write the store back to the file
     file_put_contents($this->storePath . $this->storeFile, json_encode($store));
     // remove processing flag
     $processingFlag->delete();
 }
 public function upload($system, $path)
 {
     // UPLOAD THE FILE TO THE RIGHT SYSTEM
     if ($system == 'production') {
         $other = 'development';
     } else {
         $other = 'production';
     }
     $path = str_replace('___', '/', $path);
     $file = new File('../../' . $other . $path);
     $file2 = new File('../../' . $system . $path);
     if (!$file2->exists()) {
         $dirs = explode('/', $path);
         $prod = new Folder('../../' . $system);
         for ($i = 0; $i < sizeof($dirs) - 1; $i++) {
             if (!$prod->cd($dirs[$i])) {
                 $prod->create($dirs[$i]);
                 $prod->cd($dirs[$i]);
             }
         }
     }
     if ($file->copy('../../' . $system . $path)) {
         if (touch('../../' . $system . $path, $file->lastChange())) {
             $this->Flash->success(__('File copied successfully.'));
         } else {
             $this->Flash->success(__('File copied successfully, but time not updated.'));
         }
     } else {
         $this->Flash->error(__('Unable copy file. '));
     }
     return $this->redirect($this->referer());
 }
 /**
  * Check the not modified header.
  *
  * @param \Psr\Http\Message\ServerRequestInterface $request The request to check.
  * @param \Cake\Filesystem\File $file The file object to compare.
  * @return bool
  */
 protected function isNotModified($request, $file)
 {
     $modifiedSince = $request->getHeaderLine('If-Modified-Since');
     if (!$modifiedSince) {
         return false;
     }
     return strtotime($modifiedSince) === $file->lastChange();
 }
 /**
  * _removeExpiredLock
  *
  * @return void
  */
 protected function _removeExpiredLock()
 {
     $dir = new Folder(CONFIG . $this->_config['lockout']['file_path'], true);
     $files = $dir->find();
     foreach ($files as $fileName) {
         $file = new File($dir->pwd() . DS . $fileName);
         $lastChange = Time::createFromTimestamp($file->lastChange());
         if ($lastChange->wasWithinLast($this->_config['lockout']['expires'])) {
             continue;
         }
         $file->delete();
     }
 }
Esempio n. 7
0
 /**
  * Processes/minify/combines queued files of the requested type.
  * @param string type - 'js' or 'css'. This should be the end result type
  * @param string how - 'link' for <script src="">, 'async' for <script src="" async>, 'embed' for <script>...js code...</script>
  * @param array files - string name of a file or array containing multiple string of files
  * @return string - the <script> or <link>
  */
 function fetch($type, $how = 'link', $files = array())
 {
     if ($type == 'script') {
         $type = 'js';
     }
     if (!$files) {
         $files =& $this->files;
     }
     if (!$files) {
         return '';
     }
     // ensure the layout files are before the view files
     $files[$type] = array_merge($files[$type]['layout'], $files[$type]['view']);
     // determine the cache file path
     $cacheFile = $this->settings['prefix'] . md5(implode('_', $files[$type])) . '.' . $type;
     $cacheFilePath = preg_replace('/(\\/+|\\+)/', DS, WWW_ROOT . DS . $this->settings[$type]['cachePath'] . DS . $cacheFile);
     $cacheFileObj = new File($cacheFilePath);
     $webCacheFilePath = $this->settings['url'] . preg_replace('/\\/+/', '/', '/' . $this->extraPath . '/' . $this->settings[$type]['cachePath'] . $cacheFile);
     // create Cake file objects and get the max date
     $maxAge = 0;
     foreach ($files[$type] as $k => $v) {
         //$caminho = preg_replace('/(\/+|\\+)/', DS, WWW_ROOT .DS. ($v[0]=='/'? '':$this->settings[$type]['path']) .DS. $v);
         $tmpf = new File(preg_replace('/(\\/+|\\+)/', DS, WWW_ROOT . DS . ($v[0] == '/' ? '' : $this->settings[$type]['path']) . DS . $v));
         //var_dump($tmpf); //path
         //echo '<br><br><br>';
         $files[$type][$k] = array('file' => $tmpf, 'rel_path' => $v);
         $srcMod = $tmpf->lastChange();
         if ($srcMod > $maxAge) {
             $maxAge = $srcMod;
         }
     }
     // has the cache expired (we're debugging, the cache doesn't exist, or too old)?
     $expired = false;
     if ($this->debugging || !$cacheFileObj->exists() || $maxAge > $cacheFileObj->lastChange()) {
         $expired = true;
     }
     // rebuild if it has expired
     if ($expired) {
         $output = '';
         foreach ($files[$type] as $k => $v) {
             $lang = $v['file']->ext();
             // load compiler if it is not already
             if (!isset($this->compilers[$lang])) {
                 $this->compilers[$lang] = ShrinkType::getCompiler($lang, $this->settings);
             }
             $resultType = $this->compilers[$lang]->resultType;
             // load the compressor if it is not already
             $compressorName = $this->settings[$type]['minifier'];
             if (!isset($this->compressors[$compressorName])) {
                 $this->compressors[$compressorName] = ShrinkType::getCompressor($compressorName, $this->settings);
             }
             // compile, compress, combine
             if ($resultType == $type && $v['file']->exists()) {
                 $output .= "/* " . $v['rel_path'] . " */\n";
                 $code = $this->compilers[$lang]->compile($v['file']);
                 // INICIA MODIFICAÇÃO FEITA PELO AUTOR DO "PROJETO STORES"
                 //$code = $this->compressors[$compressorName]->compress($code);
                 $isMinified = strpos($v['file']->path, '.min');
                 if ($type == 'css' && $isMinified === false) {
                     $code = $this->compressors[$compressorName]->compress($code);
                 }
                 if ($type == 'js' && $isMinified === false) {
                     $jshrinkCompressor = new ShrinkCompressorJshrink();
                     $code = $jshrinkCompressor->compress($code);
                 }
                 if ($isMinified !== false) {
                     $patter = '/\\/\\*(.|[\\r\\n])*?\\*\\//';
                     $replacement = ' ';
                     $code = preg_replace($patter, $replacement, $code);
                 }
                 // TERMINA MODIFICAÇÃO FEITA PELO AUTOR DO "PROJETO STORES"
                 $output .= $code . "\n";
             }
         }
         // be sure no duplicate charsets
         if ($type == 'css') {
             $output = preg_replace('/@charset\\s+[\'"].+?[\'"];?/i', '', $output);
             $output = '@charset "' . $this->settings['css']['charset'] . "\";\n" . $output;
         }
         // write the file
         $cacheFileObj->write($output);
     }
     // files will be @$this->files, so this clears them
     $files[$type] = array('layout' => array(), 'view' => array());
     // print them how the user wants
     if ($how == 'embed') {
         $output = $cacheFileObj->read();
         if ($type == 'css') {
             return '<style type="text/css">' . $output . '</style>';
         } else {
             return '<script type="text/javascript">' . $output . '</script>';
         }
     } else {
         if ($type == 'css') {
             return '<link href="' . $webCacheFilePath . '" rel="stylesheet" type="text/css" />';
         } else {
             // MODIFICAÇÃO FEITA PELO AUTOR DO "PROJETO STORES"
             //return '<script src="'. $webCacheFilePath .'" type="text/javascript"'. ($how=='async'? ' async ':'') .'></script>';
             return '<script src="' . $webCacheFilePath . '" ' . ($how == 'async' ? ' async ' : ' defer ') . '></script>';
         }
     }
 }
Esempio n. 8
0
 /**
  * build - Compile, Compress, Combile the array of files
  * @param array $files - filenames to process
  * @param string $type - js or css to indicate how to compress and which options to use
  * @param string $cacheFile - filename to write the results to, relative to cachePath option
  * @return array - array with the cache file object and the new web path ['file','webPath']
  */
 function build($files, $type, $cacheFile = '')
 {
     // determine the cache file path
     if ($cacheFile === '') {
         $cacheFile = $this->settings['prefix'] . md5(implode('_', $files)) . '.' . $type;
     }
     $cacheFilePath = preg_replace('/(\\/+|\\+)/', DS, WWW_ROOT . DS . $this->settings[$type]['cachePath'] . DS . $cacheFile);
     $cacheFileObj = new File($cacheFilePath);
     $webCacheFilePath = $this->settings['url'] . preg_replace('/\\/+/', '/', '/' . $this->extraPath . '/' . $this->settings[$type]['cachePath'] . $cacheFile);
     // create Cake file objects and get the max date
     $maxAge = 0;
     foreach ($files as $k => $v) {
         $tmpf = new File(preg_replace('/(\\/+|\\+)/', DS, WWW_ROOT . DS . ($v[0] == '/' ? '' : $this->settings[$type]['path']) . DS . $v));
         $files[$k] = ['file' => $tmpf, 'rel_path' => $v];
         $srcMod = $tmpf->lastChange();
         if ($srcMod > $maxAge) {
             $maxAge = $srcMod;
         }
     }
     // has the cache expired (we're debugging, the cache doesn't exist, or too old)?
     $expired = false;
     if ($this->debugging || !$cacheFileObj->exists() || $maxAge > $cacheFileObj->lastChange()) {
         $expired = true;
     }
     // rebuild if it has expired
     if ($expired) {
         $output = '';
         foreach ($files as $k => $v) {
             $lang = $v['file']->ext();
             // load compiler if it is not already
             if (!isset($this->compilers[$lang])) {
                 $this->compilers[$lang] = ShrinkType::getCompiler($lang, $this->settings);
             }
             $resultType = $this->compilers[$lang]->resultType;
             // load the compressor if it is not already
             $compressorName = $this->settings[$type]['minifier'];
             if (!isset($this->compressors[$compressorName])) {
                 $this->compressors[$compressorName] = ShrinkType::getCompressor($compressorName, $this->settings);
             }
             // compile, compress, combine
             if ($resultType == $type && $v['file']->exists()) {
                 $output .= "/* " . $v['rel_path'] . " */\n";
                 $code = $this->compilers[$lang]->compile($v['file']);
                 $code = $this->compressors[$compressorName]->compress($code);
                 $output .= $code . "\n";
             }
             // we are done with this file, close it
             $v['file']->close();
         }
         // be sure no duplicate charsets
         if ($type == 'css') {
             $output = preg_replace('/@charset\\s+[\'"].+?[\'"];?/i', '', $output);
             $output = '@charset "' . $this->settings['css']['charset'] . "\";\n" . $output;
         }
         // write the file
         $cacheFileObj->write($output);
     }
     $ret = ['path' => $cacheFileObj->path, 'webPath' => $webCacheFilePath];
     $cacheFileObj->close();
     return $ret;
 }
Esempio n. 9
0
 /**
  * Returns rich information for the Cakebox.yaml file.
  *
  * @return array Hash with raw file data and timestamp.
  * @throws Exception
  */
 public function getRichCakeboxYaml()
 {
     try {
         $fileHandle = new File($this->cakeboxMeta['host']['yaml']);
         return ['timestamp' => $fileHandle->lastChange(), 'raw' => $fileHandle->read()];
     } catch (\Exception $e) {
         throw new \Exception("Error reading " . $this->cakeboxMeta['yamlFile'] . ": " . $e->getMessage());
     }
 }