/** * main * */ public function main() { $default = APP . 'Locale' . DS . 'default.pot'; $response = $this->in("What is the full path you would like to merge file (created pot file)?\nExample:" . $default . "\n[Q]uit", null, $default); if (strtoupper($response) === 'Q') { $this->out('Merge Aborted'); $this->_stop(); } $created = new File($response, false, 0755); if (!$created->exists()) { $this->err('The file path you supplied was not found. Please try again.'); $this->_stop(); } $default = APP . 'Locale' . DS . 'ja' . DS . 'default.po'; $response = $this->in("What is the full path you would like to merge file (current po file)?\nExample: " . $default . "\n[Q]uit", null, $default); if (strtoupper($response) === 'Q') { $this->out('Merge Aborted'); $this->_stop(); } $current = new File($response, false, 0755); if (!$current->exists()) { $this->err('The file path you supplied was not found. Please try again.'); $this->_stop(); } $createdTranslations = Translations::fromPoFile($created->path); $createdTranslations->addFromPoFile($current->path); $merged = $createdTranslations->toPoString(); $this->createFile($current->path, $merged); }
/** * Download an attachment realated to an article. * * @throws \Cake\Network\Exception\NotFoundException When it missing an arguments or when the file doesn't exist. * @throws \Cake\Network\Exception\ForbiddenException When the user is not premium. * * @return \Cake\Network\Exception\ForbiddenException * \Cake\Network\Exception\NotFoundException * \Cake\Network\Response */ public function download() { $this->loadModel('Users'); $user = $this->Users->find()->where(['id' => $this->request->session()->read('Auth.User.id')])->first(); if (is_null($user) || !$user->premium) { throw new ForbiddenException(); } if (!isset($this->request->type)) { throw new NotFoundException(); } switch ($this->request->type) { case "blog": $this->loadModel('BlogAttachments'); $attachment = $this->BlogAttachments->get($this->request->id); if (!$attachment) { throw new NotFoundException(); } $file = new File($attachment->url); if (!$file->exists()) { throw new NotFoundException(); } $this->response->file($file->path, ['download' => true, 'name' => $attachment->name]); $this->BlogAttachments->patchEntity($attachment, ['download' => $attachment->download + 1]); $this->BlogAttachments->save($attachment); break; default: throw new NotFoundException(); } return $this->response; }
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(); } } } }
/** * Load a YAML configuration file * located in ROOT/config/yaml/FILENAME * * We can use it like this: * LoaderComponent::load('FILENAME.yml') * * @uses Cake\Filesystem\File * @param string The file name, extend with .yml * @param string The callback filename, if the first name parameter file doesn't exist, looking for the callback file * @throws \Exception * @return array The yaml data in array format */ public static function load($file, $callback = null) { $path = ROOT . DS . 'config' . DS . 'yaml' . DS . $file; $oFile = new File($path); if (!$oFile->exists()) { if (is_null($callback)) { throw new Exception($path . " doesn't exists!!"); } else { return static::load($callback); } } if (in_array($file, array_keys(static::$_loadedConfig))) { $config = static::$_loadedConfig[$file]; } else { $config = Yaml::parse($oFile->read()); static::$_loadedConfig[$file] = $config; } return $config; }
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; }
/** * select2GetImage method * * @return void */ public function select2GetImage($table, $id, $imageSrcCol = null) { if (!$this->request->is('ajax')) { return; } $this->autoRender = false; $this->viewBuilder()->layout('ajax'); $this->loadModel($table); $q = $this->{$table}->find('all')->where(["{$table}.id" => $id]); //if image not exists if (!is_null($imageSrcCol) && $imageSrcCol != 'undefined') { $pluginPath = Plugin::path('LightStrap'); foreach ($q as $item) { $imageFile = new File(WWW_ROOT . 'files' . DS . $item->{$imageSrcCol}); if (!$imageFile->exists()) { $item->path = '../light_strap/img/no_image.png'; } } } echo json_encode($q->toArray()); }
/** * 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); }
/** * Check to see if a temporary file for this entity's original * file exists. * * @return boolean Success */ public function hasTmp() { $tmp = new File($this->tmpPathFull); return $tmp->exists(); }
/** * 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; }
/** * To check if a Table Model exists in the path of model * * @param string $tableName Table name in underscore case * @param string $pluginName Plugin name if exists * @return bool */ public function modelExist($tableName, $pluginName = null) { $file = new File($this->getModelPath($pluginName) . $tableName . 'Table.php'); if ($file->exists()) { return true; } return false; }
/** * _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; }
/** * 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 string $field The current field to process. * @param array $options The configuration options defined by the user. * @param string $newFile The new file path. * * @return bool */ private function deleteOldUpload(Entity $entity, $field = '', array $options = [], $newFile) { $fileInfo = pathinfo($entity->{$field}); $newFileInfo = pathinfo($newFile); /** * Check if the user has set an option for the defaultFile, else use the default defaultFile config. */ if (isset($options['defaultFile']) && (is_bool($options['defaultFile']) || is_string($options['defaultFile']))) { $this->_defaultFile = $options['defaultFile']; } /** * If the old file have the same name as the new file, let the copy * function do the overwrite. * * Or if the old file have the same name as the defaultFile, do not delete it. * For example, if you use a default_avatar.png for all new members, this condition * will make sure that the default_avatar.png will not be deleted. * */ if ($fileInfo['basename'] == $newFileInfo['basename'] || $fileInfo['basename'] == $this->_defaultFile) { return true; } if ($this->_prefix) { /** * Replace the prefix. This is useful when you use a custom directory at the root * of webroot and you use the Html Helper to display your image. * * (Because the Html Helper is pointed to the img/ directory by default) */ $entity->{$field} = str_replace($this->_prefix, "", $entity->{$field}); } /** * Instance the File. */ $file = new File($entity->{$field}, false); /** * If the file exist, than delete it. */ if ($file->exists()) { $file->delete(); return true; } return false; }
/** * To check if a Table Model exists in the path of model * * @param string $tableName Table name in underscore case * @param string $pluginName Plugin name if exists * @return bool */ public function tableExists($tableName, $pluginName = null) { $file = new File($this->getModelPath($pluginName) . $tableName . 'Table.php'); return $file->exists(); }
public function moveUploadedFile($file, $destFile) { $file = new File($file); if ($file->exists()) { return $file->copy($destFile); } return false; }
/** * Creates a file at given path * * @param string $path Where to put the file. * @param string $contents Content to put in the file. * @return bool Success * @link http://book.cakephp.org/3.0/en/console-and-shells.html#creating-files */ public function createFile($path, $contents) { $path = str_replace(DS . DS, DS, $path); $this->_io->out(); if (is_file($path) && empty($this->params['force']) && $this->interactive) { $this->_io->out(sprintf('<warning>File `%s` exists</warning>', $path)); $key = $this->_io->askChoice('Do you want to overwrite?', ['y', 'n', 'a', 'q'], 'n'); if (strtolower($key) === 'q') { $this->_io->out('<error>Quitting</error>.', 2); return $this->_stop(); } if (strtolower($key) === 'a') { $this->params['force'] = true; $key = 'y'; } if (strtolower($key) !== 'y') { $this->_io->out(sprintf('Skip `%s`', $path), 2); return false; } } else { $this->out(sprintf('Creating file %s', $path)); } $File = new File($path, true); if ($File->exists() && $File->writable()) { $data = $File->prepare($contents); $File->write($data); $this->_io->out(sprintf('<success>Wrote</success> `%s`', $path)); return true; } $this->_io->err(sprintf('<error>Could not write to `%s`</error>.', $path), 2); return false; }
public function delete($path) { $root = WWW_ROOT; $fullPath = $root . $path; $dir = new File($path, false); if (!$dir->exists()) { $dir = new Folder($path); } if ($dir->delete()) { $this->Flash->success(__('Deleted successfully.')); } else { $this->Flash->error(__('Could not delete.')); } return $this->redirect($this->referer()); }
/** * 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>'; } } }
/** * 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; }
/** * Tests the exists() method. * * @return void */ public function testExists() { $tmpFile = TMP . 'tests/cakephp.file.test.tmp'; $file = new File($tmpFile, true, 0777); $this->assertTrue($file->exists(), 'absolute path should exist'); $file = new File('file://' . $tmpFile, false); $this->assertTrue($file->exists(), 'file:// should exist.'); $file = new File('/something/bad', false); $this->assertFalse($file->exists(), 'missing file should not exist.'); }
/** * afterDelete handle * @param \Cake\Event\Event $event The beforeSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that is going to be saved. * @return void */ public function afterDelete(Event $event, Entity $entity) { // get config $config = $this->_config; // go through each field foreach ($config['fields'] as $field => $path) { // get uploaded file and delete it $previous = $entity->get($field); if ($previous) { $old = new File($config['root'] . str_replace('/', DS, $previous), false); if ($old->exists()) { $old->delete(); } } } }
/** * get Types with file cache? * //TODO: use normal cache * * @return array */ protected function _getTypes() { $handle = new File(FILE_CACHE . 'mime_types.txt', true, 0770); if (!$handle->exists()) { # create and fill: ext||type||name||img (array serialized? separated by ||?) $MimeTypes = TableRegistry::get('Data.MimeTypes'); $mimeTypes = $MimeTypes->find('all', ['fields' => ['name', 'ext', 'type', 'MimeTypeImages.name', 'MimeTypeImages.ext'], 'conditions' => ['MimeTypes.active' => 1], 'contain' => ['MimeTypeImages']]); $content = []; foreach ($mimeTypes as $m) { $img = !empty($m->mime_type_image['ext']) ? $m->mime_type_image['name'] . '.' . $m->mime_type_image['ext'] : ''; $content[] = ['ext' => $m['ext'], 'name' => $m['name'], 'type' => $m['type'], 'img' => $img]; } # add special types? (file not found icon, default fallback icon, generic file ext icon...) if (!$handle->write(serialize($content), 'w', true)) { throw new \Exception('Write error'); } } else { //$handle->open('r', true); $content = $handle->read(); if ($content === false) { return []; } $content = @unserialize($content); if ($content === false || !is_array($content)) { return []; } } return $content; }
/** * Download a single file * * @param upload entity to be downloaded * @return response - file download on success or error message */ public function download(Upload $upload) { $path = $upload->path; $type = $upload->type; $name = $upload->original_name; $file = new File(WWW_ROOT . DS . $path); if (!$file->exists()) { return $this->Flash->error('Could not retrieve file'); } $this->response->type($type); $this->response->file($path, ['download' => true, 'name' => $name]); return $this->response; }
/** * passiveCaching method * * Cache all resolutions of source image to cache folder * settings gets from $this->_configData * * @param string $filePath path to file * @param string $semanticType semantic type of file * @return void */ public function passiveCaching($filePath, $semanticType = 'default') { $this->autoRender = false; $file = new File($filePath); if ($file->exists()) { $this->_sourceFile = $file->path; $this->_requestedUri = $file->name; } if (isset($this->_configData[$semanticType])) { $this->_resolutions = array_keys($this->_configData[$semanticType]); } else { header("Status: Wrong semantic type"); exit; } // does the $this->_cachePath directory exist already? if (!is_dir("{$this->_pluginDocumentRoot}/{$this->_cachePath}")) { // no if (!mkdir("{$this->_pluginDocumentRoot}/{$this->_cachePath}", 0755, true)) { // so make it if (!is_dir("{$this->_pluginDocumentRoot}/{$this->_cachePath}")) { // check again to protect against race conditions // uh-oh, failed to make that directory header("Failed to create cache directory at: {$this->_pluginDocumentRoot}/{$this->_cachePath}"); exit; } } } // check if the file exists at all if (!file_exists($this->_sourceFile)) { header("Status: 404 Not Found; file = {$this->_sourceFile}"); exit; } /* if the requested URL starts with a slash, remove the slash */ if (substr($this->_requestedUri, 0, 1) == "/") { $this->_requestedUri = substr($this->_requestedUri, 1); } /* whew might the cache file be? */ // $currentResolution = (string) $this->_resolution; if (isset($this->_configData[$semanticType])) { foreach ($this->_configData[$semanticType] as $resolution => $imageOperations) { if ($imageOperations == 'original') { continue; } $cacheFile = $this->_pluginDocumentRoot . DS . $this->_cachePath . DS . $semanticType . DS . $resolution . DS . $this->_requestedUri; if (file_exists($cacheFile)) { // it exists cached at that size $this->_createCacheDir($cacheFile); $this->_refreshCache($this->_sourceFile, $cacheFile, $imageOperations); } else { $this->_createCacheDir($cacheFile); $this->Imagine->processImage($this->_sourceFile, $cacheFile, [], $imageOperations); } } } }
/** * 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); } }
/** * testCreate method * * @return void */ public function testCreate() { $tmpFile = TMP . 'tests/cakephp.file.test.tmp'; $File = new File($tmpFile, true, 0777); $this->assertTrue($File->exists()); }
/** * Write the files that need to be stored * * @return void */ protected function _writeFiles() { $overwriteAll = false; if (!empty($this->params['overwrite'])) { $overwriteAll = true; } foreach ($this->_storage as $domain => $sentences) { $output = $this->_writeHeader(); foreach ($sentences as $sentence => $header) { $output .= $header . $sentence; } $filename = $domain . '.pot'; $File = new File($this->_output . $filename); $response = ''; while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') { $this->out(); $response = $this->in(sprintf('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename), ['y', 'n', 'a'], 'y'); if (strtoupper($response) === 'N') { $response = ''; while (!$response) { $response = $this->in("What would you like to name this file?", null, 'new_' . $filename); $File = new File($this->_output . $response); $filename = $response; } } elseif (strtoupper($response) === 'A') { $overwriteAll = true; } } $File->write($output); $File->close(); } }
/** * Write content in to the file. * * @param string $path * @param string $content * @return void */ protected function _write($path, $content) { $File = new File($path); $File->write($content); $File->exists(); }
/** * Setup for display or download the given file. * * If $_SERVER['HTTP_RANGE'] is set a slice of the file will be * returned instead of the entire file. * * ### Options keys * * - name: Alternate download name * - download: If `true` sets download header and forces file to be downloaded rather than displayed in browser * * @param string $path Path to file. If the path is not an absolute path that resolves * to a file, `APP` will be prepended to the path. * @param array $options Options See above. * @return void * @throws \Cake\Network\Exception\NotFoundException */ public function file($path, array $options = []) { $options += ['name' => null, 'download' => null]; if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) { throw new NotFoundException('The requested file contains `..` and will not be read.'); } if (!is_file($path)) { $path = APP . $path; } $file = new File($path); if (!$file->exists() || !$file->readable()) { if (Configure::read('debug')) { throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path)); } throw new NotFoundException(__d('cake', 'The requested file was not found')); } $extension = strtolower($file->ext()); $download = $options['download']; if ((!$extension || $this->type($extension) === false) && $download === null) { $download = true; } $fileSize = $file->size(); if ($download) { $agent = env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) { $contentType = 'application/octet-stream'; } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/force-download'; } if (!empty($contentType)) { $this->type($contentType); } if ($options['name'] === null) { $name = $file->name; } else { $name = $options['name']; } $this->download($name); $this->header('Content-Transfer-Encoding', 'binary'); } $this->header('Accept-Ranges', 'bytes'); $httpRange = env('HTTP_RANGE'); if (isset($httpRange)) { $this->_fileRange($file, $httpRange); } else { $this->header('Content-Length', $fileSize); } $this->_clearBuffer(); $this->_file = $file; }
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()); }