public function afterDelete(Event $event, Banner $banner, \ArrayObject $options)
 {
     $bannerFile = new File(WWW_ROOT . 'img' . DS . $banner->image);
     $bannerFile->delete();
     $bannerFile->close();
     Cache::clear(false, 'banners_manager_cache');
 }
 public function afterDelete(Event $event, PhotoThumbnail $photo, \ArrayObject $config)
 {
     if (!empty($photo->path)) {
         $file = new File(WWW_ROOT . 'img' . DS . $photo->path);
         $file->delete();
         $file->close();
     }
 }
 public function delete($system, $path)
 {
     $path = str_replace('___', '/', $path);
     $file = new File('../../' . $system . $path);
     if ($file->delete()) {
         $this->Flash->success(__('File removed successfully.'));
     } else {
         $this->Flash->error(__('Unable remove file.'));
     }
     return $this->redirect($this->referer());
 }
 public function del()
 {
     if ($this->request->is('ajax')) {
         $data = $this->request->data;
         $foto = $this->CategoriasFotos->findById($data['id'])->first();
         if ($this->CategoriasFotos->delete($foto)) {
             $url = str_replace('../', '', $foto->url);
             $ft = new File($url);
             $ft->delete();
         }
     }
 }
示例#5
0
 /**
  * Delete file action.
  *
  * @return \Cake\Network\Response|void
  */
 public function deleteFile()
 {
     $path = $this->request->query('path');
     if ($this->request->is('post') && is_file($path)) {
         $File = new File($path);
         if ($File->delete()) {
             $this->Flash->success(__d('file_manager', 'File successfully removed'));
         } else {
             $this->Flash->success(__d('file_manager', 'An error occurred while removing a file'));
         }
     }
     return $this->redirect(['action' => 'browse']);
 }
 /**
  * Deletes a file for the given FileField instance.
  *
  * File name must be passes as `file` GET parameter.
  *
  * @param string $name EAV attribute name
  * @return void
  * @throws \Cake\Network\Exception\NotFoundException When invalid attribute name
  *  is given
  */
 public function delete($name)
 {
     $this->loadModel('Field.FieldInstances');
     $instance = $this->_getInstance($name);
     if ($instance && !empty($this->request->query['file'])) {
         $file = normalizePath(WWW_ROOT . "/files/{$instance->settings['upload_folder']}/{$this->request->query['file']}", DS);
         $file = new File($file);
         $file->delete();
     }
     $response = '';
     $this->viewBuilder()->layout('ajax');
     $this->title(__d('field', 'Delete File'));
     $this->set(compact('response'));
 }
示例#7
0
 public function afterDelete(Event $event, Entity $entity, $options)
 {
     $config = $this->_config;
     foreach ($config['fields'] as $field) {
         $entityField = $entity->get($field);
         if (!empty($entityField)) {
             $filePath = $config['root'] . $entityField;
             $file = new File($filePath, false, 755);
             if ($file->exists() === true) {
                 $file->delete();
             }
         }
     }
 }
 /**
  * Test that js files are properly processed
  *
  * @return void
  */
 public function testShrinkJs()
 {
     $ret = $this->Shrink->build(['base.js', 'base.coffee'], 'js');
     // verify the result has the proper keys
     $this->assertArrayHasKey('path', $ret);
     $this->assertArrayHasKey('webPath', $ret);
     // verify we were returned a file
     $this->assertFileExists($ret['path']);
     // verify the contents
     $cacheFile = new File($ret['path']);
     $result = $cacheFile->read();
     $cacheFile->delete();
     $cacheFile->close();
     $expectedfile = new File(WWW_ROOT . 'js/base.shrink.js');
     $expect = $expectedfile->read();
     $expectedfile->close();
     $this->assertEquals($expect, $result);
 }
 public function delete($id = null)
 {
     $this->request->allowMethod(['post', 'delete']);
     $conteudo = $this->Conteudos->get($id);
     $this->loadModel('ConteudosFotos');
     $fotos = $this->ConteudosFotos->findAllByConteudoId($id);
     foreach ($fotos as $foto) {
         $url = str_replace('../', '', $foto->url);
         $file = new File($url);
         if ($file->delete()) {
             $this->ConteudosFotos->delete($foto);
         }
     }
     if ($this->Conteudos->delete($conteudo)) {
         $this->Flash->success(__('Conteúdo deletado!'));
     } else {
         $this->Flash->error(__('Ops... Algo de errado aconteceu, por favor, tente novamente!'));
     }
     return $this->redirect(['action' => 'index']);
 }
 private function deleteFile(Attachment $attachment, $recursive = false)
 {
     $return = true;
     $dir = new Folder(Configure::read('Upload.path') . $attachment->get('file_path'));
     if ($recursive) {
         $files = $dir->findRecursive($attachment->get('file_name') . '.*', true);
     } else {
         $files = $dir->find($attachment->get('file_name') . '.*');
     }
     foreach ($files as $file) {
         $fileTmp = new File($file);
         if ($fileTmp->exists()) {
             if (!$fileTmp->delete()) {
                 $return = false;
             }
         } else {
             $return = false;
         }
     }
     return $return;
 }
 /**
  *  Image manipulation view - Includes a small toolbox for basic
  *  image editing before saving or discarding changes
  */
 public function edit($id, $action = null, array $params = null)
 {
     $image = $this->Images->get($id, ['contain' => 'Uploads']);
     if ($this->request->is(['post', 'put'])) {
         $imgFile = new File($image->upload->full_path);
         // Backup original
         $backupFile = new File(TMP . DS . time() . 'bak');
         $imgFile->copy($backupFile->path);
         if (!$image->hasTmp()) {
             return $this->Flash->error('Sorry, we lost your edit...');
         }
         // Open tmp file
         $tmpFile = new File($image->tmp_path_full);
         // Copy tmp file to permanent location
         if (!$tmpFile->copy($imgFile->path)) {
             return $this->Flash->error('Could not save image');
         }
         // Change recorded image dimentions and size
         $image->upload->size = $tmpFile->size();
         $image->width = $this->Image->width($tmpFile->path);
         $image->height = $this->Image->height($tmpFile->path);
         // Delete tmp file
         $image->deleteTmp();
         if (!$this->Images->save($image)) {
             // Restore file with matching, original size and dimentions
             $backupFile->copy($imgFile->path);
             $backupFile->delete();
             $this->Flash->error('Could not save image.');
             return $this->redirect();
         } else {
             $this->Flash->success('Image edited successfully.');
             return $this->redirect();
         }
     } else {
         if (!$image->hasTmp()) {
             $image->makeTmp();
         }
     }
     $this->set(['image' => $image, 'route' => $this->RedirectUrl->load()]);
 }
 /**
  * test that js files are properly queued and processed
  *
  * @return void
  */
 public function testShrinkJs()
 {
     $this->Shrink->js(['base.js', 'base.coffee']);
     $tag = $this->Shrink->fetch('js');
     // did it create a link tag?
     $this->assertRegExp('/^\\<script\\s/', $tag);
     // grab the url if it has one (it always should)
     preg_match('/src="(?P<url>.+?)"/', $tag, $matches);
     $this->assertArrayHasKey('url', $matches);
     // verify the file exists
     $url = $matches['url'];
     $file = new File(WWW_ROOT . $url);
     $this->assertTrue($file->exists());
     // verify the contents
     $result = $file->read();
     $file->delete();
     $file->close();
     $expectedfile = new File(WWW_ROOT . 'js/base.shrink.js');
     $expect = $expectedfile->read();
     $expectedfile->close();
     $this->assertEquals($expect, $result);
 }
 /**
  * Uploads a ZIP package to the server.
  *
  * @return bool True on success
  */
 public function upload()
 {
     if (!isset($this->_package['tmp_name']) || !is_readable($this->_package['tmp_name'])) {
         $this->_error(__d('installer', 'Invalid package.'));
         return false;
     } elseif (!isset($this->_package['name']) || !str_ends_with(strtolower($this->_package['name']), '.zip')) {
         $this->_error(__d('installer', 'Invalid package format, it is not a ZIP package.'));
         return false;
     } else {
         $dst = normalizePath(TMP . $this->_package['name']);
         if (is_readable($dst)) {
             $file = new File($dst);
             $file->delete();
         }
         if (move_uploaded_file($this->_package['tmp_name'], $dst)) {
             $this->_dst = $dst;
             return true;
         }
     }
     $this->_error(__d('installer', 'Package could not be uploaded, please check write permissions on /tmp directory.'));
     return false;
 }
 /**
  * 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.');
 }
 /**
  * Delete file on server represented by entity being deleted
  */
 public function beforeDelete(Event $event, Entity $entity, \ArrayObject $options)
 {
     Configure::load('UploadManager.uploads', 'default');
     $storagePath = Configure::read('Uploads.storagePath');
     $file = new File($entity->path);
     $folder = $file->Folder();
     // Check for empty directories on successful delete
     if ($file->delete()) {
         // Delete type folder if empty
         if (!$folder->find()) {
             $oldFolder = $folder;
             $folder->cd($folder->realpath($folder->pwd() . DS . '..'));
             $oldFolder->delete();
             // Check for other possible empty parent (owner storage)
             if ($folder->pwd() !== $storagePath) {
                 if (!$folder->find()) {
                     $folder->delete();
                 }
             }
         }
     } else {
         $event->stopPropagation();
     }
 }
示例#16
0
 /**
  * test a script file in the webroot/theme dir.
  *
  * @return void
  */
 public function testScriptInTheme()
 {
     $this->skipIf(!is_writable(WWW_ROOT), 'Cannot write to webroot.');
     $testfile = WWW_ROOT . '/test_theme/js/__test_js.js';
     $File = new File($testfile, true);
     $this->Html->Url->request->webroot = '/';
     $this->Html->Url->theme = 'TestTheme';
     $result = $this->Html->script('__test_js.js');
     $expected = ['script' => ['src' => '/test_theme/js/__test_js.js']];
     $this->assertHtml($expected, $result);
     $File->delete();
 }
 /**
  * Prepares install from remote URL.
  *
  * @return bool True on success
  */
 protected function _getFromUrl()
 {
     try {
         $http = new Client(['redirect' => 3]);
         // follow up to 3 redirections
         $response = $http->get($this->params['source'], [], ['headers' => ['X-Requested-With' => 'XMLHttpRequest']]);
     } catch (\Exception $ex) {
         $response = false;
         $this->err(__d('installer', 'Could not download the package. Details: {0}', $ex->getMessage()));
         return false;
     }
     if ($response && $response->isOk()) {
         $this->params['source'] = TMP . substr(md5($this->params['source']), 24) . '.zip';
         $file = new File($this->params['source']);
         $responseBody = $response->body();
         if (is_readable($file->pwd())) {
             $file->delete();
         }
         if (!empty($responseBody) && $file->create() && $file->write($responseBody, 'w+', true)) {
             $file->close();
             return $this->_getFromFile();
             $this->err(__d('installer', 'Unable to extract the package.'));
             return false;
         }
         $this->err(__d('installer', 'Unable to download the file, check write permission on "{0}" directory.', [TMP]));
         return false;
     }
     $this->err(__d('installer', 'Could not download the package, no .ZIP file was found at the given URL.'));
     return false;
 }
 public function edit($id)
 {
     if ($this->request->is('post')) {
         $data = $this->request->data;
         $position = $this->Positions->get($data['position_id']);
         if ($position->type == 'image') {
             $uploader = new FileUploader();
             $uploader->allowTypes('image/jpg', 'image/jpeg', 'image/png', 'image/gif')->setDestination(TMP . 'uploads');
             $uploadedImage = $uploader->upload($data['image']);
             if ($uploadedImage) {
                 $image = new Image($uploadedImage);
                 $image->resizeTo($position->width, $position->height, $position->mode);
                 $banner = $image->save(WWW_ROOT . 'img/banners/');
                 if ($banner) {
                     $data['image'] = 'banners/' . $banner->getFilename();
                 } else {
                     $data['image'] = '';
                 }
                 $file = new File($uploadedImage);
                 $file->delete();
                 $image->close();
             } else {
                 $data['image'] = '';
             }
         } else {
             $data['image'] = '';
         }
         if (empty($data['image'])) {
             unset($data['image']);
         }
         $banner = $this->Banners->get($id);
         $banner = $this->Banners->patchEntity($banner, $data);
         if ($this->Banners->save($banner)) {
             $this->Flash->set('Banner salvo!', ['element' => 'ControlPanel.alert_success']);
         } else {
             $this->Flash->set($banner->getErrorMessages(), ['element' => 'ControlPanel.alert_danger']);
         }
     }
     $banner = $this->Banners->get($id);
     $options = Configure::read('MswAgencia.Plugins.BannersManager.Settings.Options');
     $positionsList = $this->Positions->getPositionsAvailableList();
     $this->set('options', $options);
     $this->set('positionsList', $positionsList, $banner->position_id);
     $this->set('banner', $banner);
 }
 /**
  * Delete the old upload file before to save the new file.
  *
  * We can not just rely on the copy file with the overwrite, because if you use
  * an identifier like :md5 (Who use a different name for each file), the copy
  * function will not delete the old file.
  *
  * @param \Cake\ORM\Entity $entity  The entity that is going to be saved.
  * @param bool|string      $field   The current field to process.
  * @param bool|string      $newFile The new file path.
  * @param array            $options The configuration options defined by the user.
  *
  * @return bool
  */
 protected function _deleteOldUpload(Entity $entity, $field = false, $newFile = false, array $options = [])
 {
     if ($field === false || $newFile === false) {
         return true;
     }
     $fileInfo = pathinfo($entity->{$field});
     $newFileInfo = pathinfo($newFile);
     if (isset($options['defaultFile']) && (is_bool($options['defaultFile']) || is_string($options['defaultFile']))) {
         $this->_defaultFile = $options['defaultFile'];
     }
     if ($fileInfo['basename'] == $newFileInfo['basename'] || $fileInfo['basename'] == pathinfo($this->_defaultFile)['basename']) {
         return true;
     }
     if ($this->_prefix) {
         $entity->{$field} = str_replace($this->_prefix, "", $entity->{$field});
     }
     $file = new File($this->_config['root'] . $entity->{$field}, false);
     if ($file->exists()) {
         $file->delete();
         return true;
     }
     return false;
 }
示例#20
0
 /**
  * test item() with enclosure data.
  *
  * @return void
  */
 public function testItemEnclosureLength()
 {
     if (!is_writable(WWW_ROOT)) {
         $this->markTestSkipped('Webroot is not writable.');
     }
     $testExists = is_dir(WWW_ROOT . 'tests');
     $tmpFile = WWW_ROOT . 'tests/cakephp.file.test.tmp';
     $File = new File($tmpFile, true);
     $this->assertTrue($File->write('123'), 'Could not write to ' . $tmpFile);
     clearstatcache();
     $item = ['title' => ['value' => 'My Title', 'cdata' => true], 'link' => 'http://www.example.com/1', 'description' => ['value' => 'descriptive words', 'cdata' => true], 'enclosure' => ['url' => '/tests/cakephp.file.test.tmp'], 'pubDate' => '2008-05-31 12:00:00', 'guid' => 'http://www.example.com/1', 'category' => [['value' => 'CakePHP', 'cdata' => true, 'domain' => 'http://www.cakephp.org'], ['value' => 'Bakery', 'cdata' => true]]];
     $result = $this->Rss->item(null, $item);
     if (!function_exists('mime_content_type')) {
         $type = null;
     } else {
         $type = mime_content_type($tmpFile);
     }
     $expected = ['<item', '<title', '<![CDATA[My Title]]', '/title', '<link', 'http://www.example.com/1', '/link', '<description', '<![CDATA[descriptive words]]', '/description', 'enclosure' => ['url' => $this->Rss->Url->build('/tests/cakephp.file.test.tmp', true), 'length' => filesize($tmpFile), 'type' => $type], '<pubDate', date('r', strtotime('2008-05-31 12:00:00')), '/pubDate', '<guid', 'http://www.example.com/1', '/guid', 'category' => ['domain' => 'http://www.cakephp.org'], '<![CDATA[CakePHP]]', '/category', '<category', '<![CDATA[Bakery]]', '/category', '/item'];
     if ($type === null) {
         unset($expected['enclosure']['type']);
     }
     $this->assertHtml($expected, $result);
     $File->delete();
     if (!$testExists) {
         $Folder = new Folder(WWW_ROOT . 'tests');
         $Folder->delete();
     }
 }
 /**
  * _removeFile
  *
  * @param string $file Path of the file
  * @return bool
  */
 protected function _removeFile($file)
 {
     $_file = new File($file);
     if ($_file->exists()) {
         $_file->delete();
         $folder = $_file->folder();
         if (count($folder->find()) === 0) {
             $folder->delete();
         }
         return true;
     }
     return false;
 }
示例#22
0
 /**
  * testReplaceText method
  *
  * @return void
  */
 public function testReplaceText()
 {
     $TestFile = new File(TEST_APP . 'vendor/welcome.php');
     $TmpFile = new File(TMP . 'tests' . DS . 'cakephp.file.test.tmp');
     // Copy the test file to the temporary location
     $TestFile->copy($TmpFile->path, true);
     // Replace the contents of the temporary file
     $result = $TmpFile->replaceText('welcome.php', 'welcome.tmp');
     $this->assertTrue($result);
     // Double check
     $expected = 'This is the welcome.tmp file in vendors directory';
     $contents = $TmpFile->read();
     $this->assertContains($expected, $contents);
     $search = ['This is the', 'welcome.php file', 'in tmp directory'];
     $replace = ['This should be a', 'welcome.tmp file', 'in the Lib directory'];
     // Replace the contents of the temporary file
     $result = $TmpFile->replaceText($search, $replace);
     $this->assertTrue($result);
     // Double check
     $expected = 'This should be a welcome.tmp file in vendors directory';
     $contents = $TmpFile->read();
     $this->assertContains($expected, $contents);
     $TmpFile->delete();
 }
示例#23
0
 /**
  * Write staged changes
  *
  * If it's a dry run though - only show what will be done, don't do anything
  *
  * @param string $path file path
  * @return void
  */
 public function commit($path = null)
 {
     if (!$path) {
         foreach (array_keys($this->_staged['change']) as $path) {
             $this->commit($path);
         }
         foreach ($this->_staged['move'] as $path => $to) {
             if (isset($this->_staged['change'][$path])) {
                 continue;
             }
             $this->commit($path);
         }
         foreach ($this->_staged['delete'] as $path) {
             $this->commit($path);
         }
         $Folder = new Folder(TMP . 'upgrade');
         $Folder->delete();
         return;
     }
     $dryRun = !empty($this->params['dry-run']);
     $isMove = isset($this->_staged['move'][$path]);
     $isChanged = isset($this->_staged['change'][$path]) && count($this->_staged['change'][$path]) > 1;
     $isDelete = in_array($path, $this->_staged['delete']);
     if (!$isMove && !$isChanged && !$isDelete) {
         return;
     }
     $gitCd = sprintf('cd %s && ', escapeshellarg(dirname($path)));
     if ($isDelete) {
         $this->out(sprintf('<info>Delete %s</info>', Debugger::trimPath($path)));
         if ($dryRun) {
             return true;
         }
         if (!empty($this->params['git'])) {
             exec($gitCd . sprintf('git rm -f %s', escapeshellarg($path)));
             return;
         }
         if (is_dir($path)) {
             $Folder = new Folder($path);
             return $Folder->delete();
         }
         $File = new File($path, true);
         return $File->delete();
     }
     if ($isMove && !$isChanged) {
         $to = $this->_staged['move'][$path];
         $this->out(sprintf('<info>Move %s to %s</info>', Debugger::trimPath($path), Debugger::trimPath($to)));
         if ($dryRun || !file_exists($path)) {
             return true;
         }
         if (!empty($this->params['git'])) {
             return $this->_gitMove($gitCd, $path, $to);
         }
         if (is_dir($path)) {
             $Folder = new Folder($path);
             return $Folder->move($to);
         }
         $File = new File($to, true);
         return $File->write(file_get_contents($path)) && unlink($path);
     }
     $start = reset($this->_staged['change'][$path]);
     end($this->_staged['change'][$path]);
     $final = end($this->_staged['change'][$path]);
     $oPath = TMP . 'upgrade' . DS . $start;
     $uPath = TMP . 'upgrade' . DS . $final;
     exec('git diff --no-index ' . escapeshellarg($oPath) . ' ' . escapeshellarg($uPath), $output);
     $output = implode($output, "\n");
     $i = strrpos($output, $final);
     $diff = substr($output, $i + 41);
     if ($isMove) {
         $to = $this->_staged['move'][$path];
         $this->out(sprintf('<info>Move %s to %s and update</info>', Debugger::trimPath($path), Debugger::trimPath($to)));
     } else {
         $this->out(sprintf('<info>Update %s</info>', Debugger::trimPath($path)));
     }
     $this->out($diff, 1, $dryRun ? Shell::NORMAL : SHELL::VERBOSE);
     if ($dryRun || !file_exists($path)) {
         return true;
     }
     if ($isMove) {
         if (!empty($this->params['git'])) {
             $this->_gitMove($gitCd, $path, $to);
         } else {
             unlink($path);
         }
         $path = $to;
     }
     $File = new File($path, true);
     return $File->write(file_get_contents($uPath));
 }
示例#24
0
 /**
  * Delete image's thumbnails if exists.
  *
  * @param string $imagePath Full path to original image file
  * @return void
  */
 public static function deleteThumbnails($imagePath)
 {
     $imagePath = normalizePath("{$imagePath}/");
     $fileName = basename($imagePath);
     $tmbPath = normalizePath(dirname($imagePath) . '/.tmb/');
     $folder = new Folder($tmbPath);
     $pattern = preg_quote(static::removeExt($fileName));
     foreach ($folder->find(".*{$pattern}.*") as $tn) {
         $tn = new File($tmbPath . $tn);
         $tn->delete();
     }
 }
示例#25
0
 /**
  * Delete empty file in a given path
  *
  * @param string $path Path to folder which contains 'empty' file.
  * @return void
  */
 protected function _deleteEmptyFile($path)
 {
     $File = new File($path);
     if ($File->exists()) {
         $File->delete();
         $this->out(sprintf('<success>Deleted</success> `%s`', $path), 1, Shell::QUIET);
     }
 }
示例#26
0
 public function cleanUp()
 {
     $Handle = new File(FILES . 'mime_types.txt');
     $Handle->delete();
 }
示例#27
0
 /**
  * Deletes the generated thumbnail after a picture record is deleted
  * and sets Users.main_picture_id to null if necessary
  *
  * josegonzalez/cakephp-upload plugin already takes care of deleting
  * the file for the full-size picture
  *
  * @param \Cake\Event\Event $event The afterDelete event that was fired
  * @param \App\Model\Table\Entity\Picture $entity The entity that was deleted
  * @param \ArrayObject $options the options passed to the delete method
  * @return void|false
  */
 public function afterDelete(Event $event, Picture $entity, ArrayObject $options)
 {
     $fullsizeFilename = $entity->filename;
     $thumbFilename = \App\Media\Transformer::generateThumbnailFilename($fullsizeFilename);
     $file = new File(WWW_ROOT . 'img' . DS . 'members' . DS . $entity->user_id . DS . $thumbFilename);
     $file->delete();
     $usersTable = TableRegistry::get('Users');
     $user = $usersTable->get($entity->user_id);
     if ($user->main_picture_id == $entity->id) {
         $user->main_picture_id = null;
         $usersTable->save($user);
     }
 }
 /**
  * _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();
     }
 }
示例#29
0
 /**
  * Run the html string through tidy, and return the (raw) errors. pass back a reference to the
  * normalized string so that the error messages can be linked to the line that caused them.
  *
  * @param string $in ''
  * @param string &$out ''
  * @return string
  */
 public function tidyErrors($in = '', &$out = '')
 {
     $out = preg_replace('@>\\s*<@s', ">\n<", $in);
     // direct access? windows etc
     if (function_exists('tidy_parse_string')) {
         $tidy = tidy_parse_string($out, array(), 'UTF8');
         $tidy->cleanRepair();
         $errors = $tidy->errorBuffer . "\n";
         return $errors;
     }
     // cli
     $File = new File(rtrim(TMP, DS) . DS . rand() . '.html', true);
     $File->write($out);
     $path = $File->pwd();
     $errors = $path . '.err';
     $this->_exec("tidy -eq -utf8 -f {$errors} {$path}");
     $File->delete();
     if (!file_exists($errors)) {
         return '';
     }
     $Error = new File($errors);
     $errors = $Error->read();
     $Error->delete();
     return $errors;
 }
 /**
  * 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();
 }