/** * Cria um plugin de teste e o carrega para conseguir rodar os testes. */ public function setUp() { parent::setUp(); $testData = ['full_path' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS, 'config_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'config' . DS, 'css_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'webroot' . DS . '_assets' . DS . 'css' . DS, 'js_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'webroot' . DS . '_assets' . DS . 'js' . DS, 'img_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'webroot' . DS . '_assets' . DS . 'img' . DS, 'packages_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'webroot' . DS . '_assets' . DS . 'packages' . DS]; $pluginFolder = new Folder($testData['full_path'], self::CREATE_FOLDER_IF_NOT_EXISTS, self::PLUGIN_FOLDER_PERMISSIONS); $pluginFolder->create($testData['config_folder']); $pluginFolder->create($testData['css_folder']); $pluginFolder->create($testData['js_folder']); $pluginFolder->create($testData['img_folder']); $pluginFolder->create($testData['packages_folder'] . 'sample_package'); $defaultSettingsFile = new File($testData['config_folder'] . 'default_settings.php', true); $defaultSettingsFile->write("<?php \n\t\t\treturn [\n\t\t\t\t'MyApplication.Modules.ThemeInstallerTest.Settings' => \n\t\t\t\t\t['Default' => true]\n\t\t\t\t]; \n\t\t?>"); $defaultSettingsFile->close(); $file = new File($testData['css_folder'] . 'sample.css', true); $file->write('#id { }'); $file->close(); $file = new File($testData['js_folder'] . 'sample.js', true); $file->write('#id { }'); $file->close(); $file = new File($testData['packages_folder'] . 'sample_package' . DS . 'sample.css', true); $file->write('#id { }'); $file->close(); $file = new File($testData['packages_folder'] . 'sample_package' . DS . 'sample.js', true); $file->write('#id { }'); $file->close(); $bootstrapFile = new File($testData['config_folder'] . 'bootstrap.php', true); $bootstrapFile->close(); }
/** * Write swagger document to filesystem. * * @param string $path Full path to the json document including filename * @param string $content Swagger content * @throws Cake\Network\Exception\InternalErrorException * @return bool */ protected static function writeSwaggerDocumentToFile($path, $content) { $fh = new File($path, true); if (!$fh->write($content)) { throw new InternalErrorException('Error writing Swagger json document to filesystem'); } return true; }
/** * tearDown method * * @return void */ public function tearDown() { parent::tearDown(); unset($this->shell); Plugin::unload(); $bootstrap = new File($this->bootstrap, false); $bootstrap->write($this->originalBootstrapContent); }
/** * Write data in json file. * * @return void */ protected function _write() { $this->_bufferActivated(); $this->_bufferLoaded(); $JSON = new JSON($this->_buffer); $file = Path::loadedFolder() . $this->_config['file']; $File = new File($file); $File->write($JSON->write()); }
public function afterSave(Event $event, Entity $site, \ArrayObject $options) { $sitePath = WWW_ROOT . '..' . DS . self::SITES_DIR . DS . 'site' . $site->id; $folder = new Folder(); if (!$folder->create($sitePath, 0755)) { throw new InternalErrorException('Error create site files'); } $indexHtml = new File($sitePath . DS . 'index.html', true, 0644); $indexHtml->write($site->content); }
/** * write serialize data. * @param bool $overwrite * @return bool */ public function write($overwrite = false) { $path = $this->getPath(); if (true === $this->writable() && false === $overwrite) { throw new ExistsFileException('exists ' . $path); } $file = new File($path); if (!$file->write($this->export())) { throw new \RuntimeException('save failed ' . $path); } return true; }
/** * Update the applications bootstrap.php file. * * @param string $plugin Name of plugin. * @return bool If modify passed. */ protected function _modifyBootstrap($plugin) { $finder = "/\nPlugin::load\\((.|.\n|\n\\s\\s|\n\t|)+'{$plugin}'(.|.\n|)+\\);\n/"; $bootstrap = new File($this->bootstrap, false); $contents = $bootstrap->read(); if (!preg_match("@\n\\s*Plugin::loadAll@", $contents)) { $contents = preg_replace($finder, "", $contents); $bootstrap->write($contents); $this->out(''); $this->out(sprintf('%s modified', $this->bootstrap)); return true; } return false; }
public function testInstalledPluginSettingsFileWillNotBeOverrridenOnLoad() { $starter = new PluginStarter(); $starter->load('PluginInstallerTest'); $installedSettingsFile = new File(ROOT . DS . 'config' . DS . 'Plugins' . DS . 'PluginInstallerTest' . DS . 'settings.php'); $defaultSettingsFile = new File(ROOT . DS . 'plugins' . DS . 'PluginInstallerTest' . DS . 'config' . DS . 'default_settings.php'); $installedSettingsFile->write("<?php \n\t\t\treturn [\n\t\t\t\t'MyApplication.Modules.PluginInstallerTest.Settings' => \n\t\t\t\t\t['Default' => false]\n\t\t\t\t]; \n\t\t?>"); $installedSettingsFile->close(); $starter->load('PluginInstallerTest'); $installedSettingsFile = new File(ROOT . DS . 'config' . DS . 'Plugins' . DS . 'PluginInstallerTest' . DS . 'settings.php'); $this->assertEquals(strcmp($installedSettingsFile->md5(), $defaultSettingsFile->md5()) === 0, false); $installedSettingsFile->close(); $defaultSettingsFile->close(); }
public function add() { $broch = $this->request->data; if (!empty($this->request->data)) { //hacking in blank default values since there is no inputs for the following $this->request->data['location'] = ''; $this->request->data['restrict_access'] = 0; $this->request->data['max_restricted_qty'] = 0; if ($this->request->data['image']['tmp_name'] != '') { $file = new File($this->request->data['image']['tmp_name']); $filename = $this->request->data['image']['name']; $data = $file->read(); $file->close(); $file = new File(WWW_ROOT . '/img/brochures/' . $filename, true); $file->write($data); $file->close(); unset($this->request->data['image']); $image = ['filename' => $filename, 'caption' => $filename]; $image = $this->Brochures->Images->newEntity($image); if ($image = $this->Brochures->Images->save($image)) { $this->Flash->set(__('The brochure image could not be saved. Please, try again.')); } $this->request->data['image_id'] = ''; } else { $image = ''; } try { $brochure = $this->Brochures->newEntity($this->request->data, ['accessibleFields' => ['sku' => true], 'contain' => 'Images']); if ($image) { $brochure->image = $image; } if ($brochure = $this->Brochures->save($brochure)) { $this->Flash->set(__('The brochure has been saved')); // $this->_notifyWarehouse($broch); $this->redirect(array('action' => 'index')); } else { $this->Flash->set(__('The brochure could not be saved. Please, try again.')); } } catch (Exception $e) { $this->Flash->set(__('The brochure could not be saved. Please, try again.')); } } $images = $this->Brochures->Images->find('list', array('fields' => array('id', 'caption'))); //$images['0'] = "None"; $this->LoadModel('Suppliers'); $suppliers = $this->Suppliers->find('list', ['fields' => array('company', 'id'), 'order' => ['Suppliers.company']]); //$suppliers['0'] = "None"; $this->set(compact('images', 'suppliers')); }
/** * Compare the result to the contents of the file * * @param string $path partial path to test comparison file * @param string $result test result as a string * @return void */ public function assertSameAsFile($path, $result) { if (!file_exists($path)) { $path = $this->_compareBasePath . $path; } if ($this->_updateComparisons === null) { $this->_updateComparisons = env('UPDATE_TEST_COMPARISON_FILES'); } if ($this->_updateComparisons) { $file = new File($path, true); $file->write($result); } $expected = file_get_contents($path); $this->assertTextEquals($expected, $result); }
public function upload($path = null) { $root = WWW_ROOT; $fullPath = $root . $path; if ($this->request->is('post')) { foreach ($this->request->data['file'] as $file) { $new = new File($fullPath . DS . $file['name'], false); if (!$new->exists()) { $new->create(); $new->write(file_get_contents($file['tmp_name'])); } } if (count($this->request->data['file']) > 1) { $this->Flash->success(__('The files have been saved.')); } else { $this->Flash->success(__('The file has been saved.')); } return $this->redirect(['action' => 'index', $path]); } $this->Flash->error(__('The file(s) could not be saved.')); }
/** * Save file. * * @param string $file the file to save * @return boolean true on success */ public function save($file) { $return = false; if ($this->imgFormat) { $src = $this->imgSource; $src_x = $this->_x; $src_y = $this->_y; // smart resize thumbnail image if ($this->thumbResize) { $resizedWidth = @($this->thumbHeight / $this->imgHeight) * $this->imgWidth; $resizedHeight = @($this->thumbWidth / $this->imgWidth) * $this->imgHeight; if ($this->thumbWidth <= $resizedWidth) { $width = $resizedWidth; $height = $this->thumbHeight; $src_x = intval(($resizedWidth - $this->thumbWidth) / 2); } else { $width = $this->thumbWidth; $height = $resizedHeight; $src_y = intval(($resizedHeight - $this->thumbHeight) / 2); } $src = imagecreatetruecolor($width, $height); // save transparent colors if ($this->imgFormat == 'png') { imagecolortransparent($src, imagecolorallocate($src, 0, 0, 0)); imagealphablending($src, false); imagesavealpha($src, true); } // get and reallocate transparency-color for gif if ($this->imgFormat == 'gif') { imagealphablending($src, false); $transindex = imagecolortransparent($this->imgSource) <= imagecolorstotal($src) ? imagecolortransparent($this->imgSource) : imagecolorstotal($src); if ($transindex >= 0) { $transcol = imagecolorsforindex($this->imgSource, $transindex); $transindex = imagecolorallocatealpha($src, $transcol['red'], $transcol['green'], $transcol['blue'], 127); imagefill($src, 0, 0, $transindex); } } if (function_exists('imagecopyresampled')) { @imagecopyresampled($src, $this->imgSource, 0, 0, 0, 0, $width, $height, $this->imgWidth, $this->imgHeight); } else { @imagecopyresized($src, $this->imgSource, 0, 0, 0, 0, $width, $height, $this->imgWidth, $this->imgHeight); } // restore transparency for gif if ($this->imgFormat == 'gif') { if ($transindex >= 0) { imagecolortransparent($src, $transindex); for ($y = 0; $y < imagesy($src); ++$y) { for ($x = 0; $x < imagesx($src); ++$x) { if ((imagecolorat($src, $x, $y) >> 24 & 0x7f) >= 100) { imagesetpixel($src, $x, $y, $transindex); } } } } } } // create thumbnail image $thumbnail = imagecreatetruecolor($this->thumbWidth, $this->thumbHeight); // save transparent colors for png if ($this->imgFormat == 'png') { imagecolortransparent($thumbnail, imagecolorallocate($src, 0, 0, 0)); imagealphablending($thumbnail, false); imagesavealpha($thumbnail, true); } // get and reallocate transparency-color for gif if ($this->imgFormat == 'gif') { imagealphablending($thumbnail, false); $transindex = imagecolortransparent($src); if ($transindex >= 0) { $transcol = imagecolorsforindex($src, $transindex); $transindex = imagecolorallocatealpha($thumbnail, $transcol['red'], $transcol['green'], $transcol['blue'], 127); imagefill($thumbnail, 0, 0, $transindex); } } @imagecopy($thumbnail, $src, 0, 0, $src_x, $src_y, $this->thumbWidth, $this->thumbHeight); // restore transparency for gif if ($this->imgFormat == 'gif') { if ($transindex >= 0) { imagecolortransparent($thumbnail, $transindex); for ($y = 0; $y < imagesy($thumbnail); ++$y) { for ($x = 0; $x < imagesx($thumbnail); ++$x) { if ((imagecolorat($thumbnail, $x, $y) >> 24 & 0x7f) >= 100) { imagesetpixel($thumbnail, $x, $y, $transindex); } } } } } // save thumbnail to file ob_start(); switch ($this->imgFormat) { case 'gif': $return = imagegif($thumbnail); break; case 'jpeg': $return = imagejpeg($thumbnail, null, $this->thumbQuality); break; case 'png': $return = imagepng($thumbnail); break; } $output = ob_get_contents(); ob_end_clean(); $File = new File($file); $File->write($output); $File->close(); // free memory resources imagedestroy($thumbnail); imagedestroy($src); } return $return; }
public function export() { if ($this->request->is('post')) { $listLang = []; foreach (Configure::read('Core.System.language') as $key => $item) { $listLang = array_merge($listLang, [$key => $item['key']]); } $lang = $this->request->data['language']; $list = $this->Languages->find(); $content = ""; $path = APP . "Locale/{$listLang[$lang]}/default.po"; foreach ($list as $item) { $content .= 'msgid "' . $item->key . '"' . "\n" . 'msgstr "' . $item->{$lang} . '"' . "\n"; } if ($File = new File($path, true, 0777)) { $File->write($content); Cache::clearGroup('persistent'); $this->Flash->success(__('language exported', true)); } else { $this->Flash->error(__('language can not be exported', true)); } $this->redirect(array('action' => 'index')); } }
/** * @param $path * @param $fileName * @param $fileId * @return \Cake\Network\Response|null */ private function sendFile($path, $fileName, $fileId, $bucketName) { $S3Client = new WRS3Client(); $plainUrl = $S3Client->getObjectUrl($bucketName, $path); $tempPath = ROOT . DS . 'tmp' . DS . 'cache' . DS . $fileId . $fileName; $file = new File($tempPath, true, 0644); $file->write(@file_get_contents($plainUrl)); $this->response->file($tempPath); return $this->response; }
/** * clearBootstrap * * Helper to clear the bootstrap file. * * @return void */ protected function _clearBootstrap() { $bootstrap = new File($this->bootstrap, false); $bootstrap->write($this->originalBootstrapContent); }
/** * Copy the TestApp route file so it can be modified. * * @return void */ protected function _cloneRoutes() { $File = new File(TEST_APP . 'TestApp/Config/routes.php'); $contents = $File->read(); mkdir(TMP . 'BakeTestApp/Config/', 0777, true); $File = new File(TMP . 'BakeTestApp/Config/routes.php'); $File->write($contents); }
/** * 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>'; } } }
/** * 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; }
/** * Export entire database to PHP fixtures. * * By default, all generated PHP files will be placed in `/tmp/fixture/` * directory, this can be changed using the `--destination` argument. * * @return bool */ public function main() { $options = (array) $this->params; $destination = normalizePath("{$options['destination']}/"); if (is_string($options['tables'])) { $options['tables'] = explode(',', $options['tables']); } if (is_string($options['no-data'])) { $options['no-data'] = explode(',', $options['no-data']); } if (file_exists($destination)) { $dst = new Folder($destination); $dst->delete(); $this->out(__d('system', 'Removing existing directory: {0}', $destination), 1, Shell::VERBOSE); } else { new Folder($destination, true); $this->out(__d('system', 'Creating directory: {0}', $destination), 1, Shell::VERBOSE); } $db = ConnectionManager::get('default'); $db->connect(); $schemaCollection = $db->schemaCollection(); $tables = $schemaCollection->listTables(); foreach ($tables as $table) { if (!empty($options['tables']) && !in_array($table, $options['tables'])) { $this->out(__d('system', 'Table "{0}" skipped', $table), 1, Shell::VERBOSE); continue; } $Table = TableRegistry::get($table); $Table->behaviors()->reset(); $fields = ['_constraints' => [], '_indexes' => [], '_options' => (array) $Table->schema()->options()]; $columns = $Table->schema()->columns(); $records = []; $primaryKeys = []; foreach ($Table->schema()->indexes() as $indexName) { $index = $Table->schema()->index($indexName); if (!empty($index['columns'])) { $fields['_indexes']["{$table}_{$indexName}_index"] = $index; } } foreach ($columns as $column) { $fields[$column] = $Table->schema()->column($column); } foreach ($Table->schema()->constraints() as $constraint) { $constraintName = in_array($constraint, $columns) ? Inflector::underscore("{$table}_{$constraint}") : $constraint; $fields['_constraints'][$constraintName] = $Table->schema()->constraint($constraint); if (isset($fields['_constraints']['primary']['columns'])) { $primaryKeys = $fields['_constraints']['primary']['columns']; } } foreach ($fields as $column => $info) { if (isset($info['length']) && in_array($column, $primaryKeys) && isset($info['autoIncrement']) && $info['autoIncrement'] === true) { unset($fields[$column]['length']); } } // FIX: We need RAW data for time instead of Time Objects $originalTypes = []; foreach ($Table->schema()->columns() as $column) { $type = $Table->schema()->columnType($column); $originalTypes[$column] = $type; if (in_array($type, ['date', 'datetime', 'time'])) { $Table->schema()->columnType($column, 'string'); } } if ($options['mode'] === 'full') { foreach ($Table->find('all') as $row) { $row = $row->toArray(); if ($this->params['no-id'] && isset($row['id'])) { unset($row['id']); } $records[] = $row; } } $className = Inflector::camelize($table) . 'Fixture'; if ($options['fixture'] && in_array($className, ['AcosFixture', 'UsersFixture'])) { $records = []; } // undo changes made by "FIX" foreach ($originalTypes as $column => $type) { $fields[$column]['type'] = $type; } if (empty($fields['_indexes'])) { unset($fields['_indexes']); } $fields = $this->_arrayToString($fields); $records = in_array($table, $options['no-data']) ? '[]' : $this->_arrayToString($records); $fixture = $this->_classFileHeader($className); $fixture .= "{\n"; $fixture .= "\n"; $fixture .= " /**\n"; $fixture .= " * Table name.\n"; $fixture .= " *\n"; $fixture .= " * @var string\n"; $fixture .= " */\n"; $fixture .= " public \$table = '{$table}';\n"; $fixture .= "\n"; $fixture .= " /**\n"; $fixture .= " * Table columns.\n"; $fixture .= " *\n"; $fixture .= " * @var array\n"; $fixture .= " */\n"; $fixture .= " public \$fields = {$fields};\n"; $fixture .= "\n"; $fixture .= " /**\n"; $fixture .= " * Table records.\n"; $fixture .= " *\n"; $fixture .= " * @var array\n"; $fixture .= " */\n"; $fixture .= " public \$records = {$records};\n"; $fixture .= "}\n"; $file = new File(normalizePath("{$destination}/{$className}.php"), true); $file->write($fixture, 'w', true); $this->out(__d('system', 'Table "{0}" exported!', $table), 1, Shell::VERBOSE); } $this->out(__d('system', 'Database exported to: {0}', $destination)); return true; }
/** * Writes output to file * * @param string $destination Absolute file path to write to * @param bool $create Create file if it does not exist (if true) * @param string $html Html to write * @return bool */ public function write($destination, $create = true, $html = null) { $output = $this->output($html); $File = new File($destination, $create); return $File->write($output) && $File->close(); }
/** * testDirSize method * * @return void */ public function testDirSize() { $path = TMP . 'tests' . DS; $Folder = new Folder($path . 'config_non_existent', true); $this->assertEquals(0, $Folder->dirSize()); $File = new File($Folder->pwd() . DS . 'my.php', true, 0777); $File->create(); $File->write('something here'); $File->close(); $this->assertEquals(14, $Folder->dirSize()); }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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(); } }
/** * Simulates direct writing to a system file by creating the file in /tmp * using default credentials, then shelling a `mv` to the desired location * as root. * * @param string $file Full path to the file to write. * @param string $content Containing file body. * @return boolean True if the write is successful */ protected function _writeSystemFile($file, $content) { $this->_log("Writing system file"); $tempFile = '/tmp/' . String::uuid(); $fh = new File($tempFile, true); $fh->write($content); // Move the tempfile if (!$this->shell("mv {$tempFile} {$file}", 'root')) { $this->_error("* Error moving {$tempFile} to {$file}"); return false; } $this->_log("* Successfully wrote {$file}"); return true; }
/** * 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(); } }
public function save($name, $dados = array()) { $dir = new Folder(ROOT . DS . 'config' . DS . 'schema' . DS, true, 0777); $file = new File($dir->pwd() . $name); $file->write(implode("\n", $dados)); $file->close(); }
/** * 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; }
/** * testWrite method * * @return void */ public function testWrite() { if (!($tmpFile = $this->_getTmpFile())) { return false; } if (file_exists($tmpFile)) { unlink($tmpFile); } $TmpFile = new File($tmpFile); $this->assertFalse(file_exists($tmpFile)); $this->assertFalse(is_resource($TmpFile->handle)); $testData = ['CakePHP\'s', ' test suite', ' was here ...', '']; foreach ($testData as $data) { $r = $TmpFile->write($data); $this->assertTrue($r); $this->assertTrue(file_exists($tmpFile)); $this->assertEquals($data, file_get_contents($tmpFile)); $this->assertTrue(is_resource($TmpFile->handle)); $TmpFile->close(); } unlink($tmpFile); }