/** * 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(); }
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 main() { $tick_names_and_values = array(); $this->authentication(); $http = new Client(); $this->loadModel('Stocks'); $this->loadModel('Devices'); $token_file = new File("/home/demo/token/token.txt"); $token = $token_file->read(); $token_file->close(); $MyAuthObject = new OAuthObject(array("token_type" => "Bearer", "access_token" => $token)); $OptionsToast = new WNSNotificationOptions(); $OptionsToast->SetAuthorization($MyAuthObject); $OptionsToast->SetX_WNS_REQUESTFORSTATUS(X_WNS_RequestForStatus::Request); $NotifierToast = new WindowsNotificationClass($OptionsToast); $OptionsTile = new WNSNotificationOptions(); $OptionsTile->SetAuthorization($MyAuthObject); $OptionsTile->SetX_WNS_REQUESTFORSTATUS(X_WNS_RequestForStatus::Request); //NOTE: Set the Tile type $OptionsTile->SetX_WNS_TYPE(X_WNS_Type::Tile); $NotifierTile = new WindowsNotificationClass($OptionsTile); $allStocks = $this->Stocks->find('all')->toArray(); //$allStocks = $this->Stocks->find('all')->group(['Stocks.device_id'])->toArray(); //$allStocks = $this->Stocks->Devices->find()->group(['Devices.id'])->toArray(); Debugger::dump('allStocks: '); Debugger::dump($allStocks); $allStocksByDeviceId = array(); for ($i = 0; $i < sizeof($allStocks); $i++) { $actualDeviceId = $allStocks[$i]['device_id']; $added = false; for ($a = 0; $a < sizeof($allStocksByDeviceId); $a++) { if ($allStocksByDeviceId[$a]['device_id'] == $actualDeviceId) { $allStocksByDeviceId[$a]['stocks'][] = $allStocks[$i]; $added = true; } } if (!$added) { $allStocksByDeviceId[] = ['device_id' => $actualDeviceId, 'stocks' => [$allStocks[$i]]]; } } Debugger::dump('allStocksByDeviceId: '); Debugger::dump($allStocksByDeviceId); $someStocks = $this->Stocks->find()->distinct(['tick_name'])->toArray(); for ($i = 0; $i < sizeof($someStocks); $i++) { $response = $http->get('http://download.finance.yahoo.com/d/quotes?f=sl1d1t1v&s=' . $someStocks[$i]['tick_name']); $tick_name = explode(",", $response->body())[0]; $tick_names_and_values[] = [str_replace("\"", "", $tick_name), explode(",", $response->body())[1]]; } Debugger::dump('tick_names_and_values: '); Debugger::dump($tick_names_and_values); $this->sendAllStocksNotificationsInTileNotifications($NotifierTile, $tick_names_and_values, $allStocksByDeviceId); $this->checkMinMaxValuesAndSendToastNotifications($NotifierToast, $tick_names_and_values); //$stuff = implode(",", $stuff); //$now = Time::now(); //$this->createFile('/home/demo/files_created_each_minute/'.$now->i18nFormat('yyyy-MM-dd HH:mm:ss').'.txt', $stuff); }
public function uploadToControllerFolderAndIdFolder($file, $controller, $model, $id) { $filefolder = '../webroot' . DS . 'files'; $tmppath = AMUploadBehavior::checkIfSubfolderExistsAndCreateIfFalseAndReturnPath($filefolder, $controller); $path = AMUploadBehavior::checkIfSubfolderExistsAndCreateIfFalseAndReturnPath($tmppath, $id); $filename = $file['name']; $tmpfile = new File($file['tmp_name']); $fullpath = $path . DS . $filename; $tmpfile->copy($fullpath); $tmpfile->close(); return $fullpath; }
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(); }
/** * Faz uma instalação básica do plugin. * A instalação consiste em criar o arquivo de configurações do plugin no diretório apropriado. * Este método é chamado pelo método PluginStarter::load() quando necessário. * * @param string $pluginName O nome do plugin a ser instalado. * @return void */ public function install($pluginName) { $settingsFileFolder = $this->pluginInstallationFolder . $pluginName . DS; if (Plugin::loaded($pluginName)) { $defaultFile = Plugin::path($pluginName) . 'config' . DS . 'default_settings.php'; $folderHandler = new Folder(); if (!$folderHandler->cd($settingsFileFolder)) { $folderHandler->create($settingsFileFolder); } $fileHandler = new File($defaultFile); $fileHandler->copy($settingsFileFolder . 'settings.php'); $fileHandler->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')); }
/** * 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); }
/** * 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); }
/** * 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.'); }
public function cmdInfo() { $cmdline_fh = new File('/proc/cmdline'); $cmdline_raw = $cmdline_fh->read(); $cmdline_fh->close(); $lines = explode(" ", $cmdline_raw); $cmdline = []; for ($i = 0; $i < sizeof($lines); $i++) { if (trim($lines[$i]) != "") { $info = explode("=", $lines[$i]); if (sizeof($info) < 2) { continue; } if (!strpos($info[0], '.')) { $key = trim($info[0]); } else { $key = substr(strstr(trim($info[0]), '.'), 1); } $val = trim($info[1]); $cmdline[$key] = $val; } } return $cmdline; }
/** * test that compiler "ts" works * * @return void */ public function testCompilerTypescript() { $compiler = ShrinkType::getCompiler('ts', []); // verify the instance $this->assertInstanceOf('\\Shrink\\Lib\\ShrinkCompiler\\ShrinkCompilerInterface', $compiler); if ($compiler->isAvailable()) { // get the result $file = new File(WWW_ROOT . 'js/base.ts'); $result = $compiler->compile($file); $file->close(); // get the expected result $jsfile = new File(WWW_ROOT . 'js/base.ts.js'); $expect = $jsfile->read(); $jsfile->close(); $this->assertEquals($expect, $result, 'Compiled Typescript does not match. Ensure Typescript script command line utility is available. npm install -g typescript'); } else { echo "\nSkipping Typescript tests, no typescript available: npm install -g typescript\n"; } }
/** * 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; }
/** * 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; }
private function upload($id) { if (isset($this->request->data['foto']) and count($this->request->data['foto']) > 0 and $this->request->data['foto']['name'] != '') { $file = new File($this->request->data['foto']['tmp_name'], true, 0644); $ext = explode('/', $this->request->data['foto']['type']); $file->copy(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); $file->close(); try { $img = new \abeautifulsite\SimpleImage(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); $img->auto_orient()->best_fit(500, 500)->save(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } return $id . '.' . strtolower($ext[1]); } else { return null; } }
/** * testCopy method * * @return void */ public function testCopy() { $dest = TMP . 'tests/cakephp.file.test.tmp'; $file = __FILE__; $this->File = new File($file); $result = $this->File->copy($dest); $this->assertTrue($result); $result = $this->File->copy($dest, true); $this->assertTrue($result); $result = $this->File->copy($dest, false); $this->assertFalse($result); $this->File->close(); unlink($dest); $TmpFile = new File('/this/does/not/exist'); $result = $TmpFile->copy($dest); $this->assertFalse($result); $TmpFile->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(); }
function export() { // Step 4: export default.pot file to the relevant directory $wnk_translation = Configure::read('WnkTranslation'); $filename = 'f' . gmdate('YmdHis'); // iterate through all configured languages: foreach ($wnk_translation['trans_lang'] as $k) { if ($k == $wnk_translation['default_lang']) { continue; } $path = ROOT . DS . 'src' . DS . 'Locale' . DS . $k; $folder = new Folder(); if (!file_exists($path)) { $folder->create($path); } $file = $path . DS . $filename; $file = new File($file, true, 0644); $z = 0; $data = TableRegistry::get('WnkTranslation.Translations')->find('all')->where(["locale" => $k])->all(); foreach ($data as $rec) { if ($rec->status == 'Original' or $rec->status == 'TranslatedByUser' or $rec->status == 'TranslatedByMachine') { $file->write('msgid "' . $rec->msgid . '"' . "\n"); $file->write('msgstr "' . $rec->msgstr . '"' . "\n"); $z++; } } $file->close(); if (file_exists($path . DS . 'default.po')) { unlink($path . DS . 'default.po'); } rename($path . DS . $filename, $path . DS . 'default.po'); } return 'Export successful with ' . $z . ' Records'; }
/** * 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(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $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); $this->_stop(); return false; } 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); try { if ($File->exists() && $File->writable()) { $File->write($contents); $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; } finally { $File->close(); } }
/** * 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(); }
public function afterDelete(Event $event, Photo $photo, \ArrayObject $options) { if (!empty($photo->path)) { $file = new File(WWW_ROOT . 'img' . DS . $photo->path); $file->delete(); $file->close(); } Cache::clear(false, 'photo_gallery_cache'); }
/** * 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 = []) { 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']); // run the shrink utility $cacheFile = $this->shrink->build($files[$type], $type); // files will be @$this->files, so this clears them $files[$type] = ['layout' => [], 'view' => []]; // print them how the user wants if ($how == 'embed') { $cacheFileObj = new File($cacheFile['path']); $output = $cacheFileObj->read(); $cacheFileObj->close(); 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="' . $cacheFile['webPath'] . '" rel="stylesheet" type="text/css" />'; } else { return '<script src="' . $cacheFile['webPath'] . '" type="text/javascript"' . ($how == 'async' ? ' async ' : '') . '></script>'; } } }
/** * 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()); }
/** * test that compressor "Jshrink" works * * @return void */ public function testCompressorJshrink() { $comp = ShrinkType::getCompressor('jshrink', []); // verify the instance $this->assertInstanceOf('\\Shrink\\Lib\\ShrinkCompressor\\ShrinkCompressorInterface', $comp); if ($comp->isAvailable()) { // actual result $file = new File(WWW_ROOT . 'js/base.js'); $code = $file->read(); $result = $comp->compress($code); $file->close(); // expected result $minfile = new File(WWW_ROOT . 'js/base.jshrink.js'); $expect = $minfile->read(); $minfile->close(); $this->assertEquals($expect, $result, 'Compressed js does not match. Ensure jshrink package is available via composer.'); } else { echo "\nSkipping Jshrink tests, no Jshrink available via composer.\n"; } }
/** * 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; }
/** * 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(); } }
/** * Processing less file. * * @param $path * @param string $cacheFolder * @return null|string * @throws \Exception */ public function lessProcess($path, $cacheFolder = 'styles') { $output = null; $ext = pathinfo($path, PATHINFO_EXTENSION); if (!$ext) { $path .= '.less'; } $systemPath = $path; $segments = explode('/', $path); $lessFolder = ROOT . DS . 'webroot' . DS . 'less'; list($plugin, $path) = $this->_View->pluginSplit($path, false); $webRoot = ROOT . DS . 'webroot' . DS; $isPlugin = Plugin::loaded($plugin); $this->_imageFull = WWW_ROOT . DS . 'img' . DS; // Set data for plugin less. if ($plugin && $isPlugin) { $pluginPath = Plugin::path($plugin); $lessFolder = $pluginPath . 'webroot' . DS . 'less'; $webRootPlg = $pluginPath . 'webroot' . DS; $this->_type = 'plugin:' . $plugin; $this->_imageFull = $webRootPlg . 'img' . DS; } $lessFile = $lessFolder . DS . $path; // Set data for module less. if (strpos($segments[0], ':')) { list($type, $name) = explode(':', $segments[0]); if ($type == 'modules') { $modulePath = ROOT . DS . 'modules' . DS . $name . DS . 'assets' . DS; $lessFile = $modulePath . 'less' . DS . $segments[1]; $this->_type = 'modules:' . $name; $this->_imageFull = $modulePath . 'img' . DS; } } if (file_exists($lessFile)) { $less = new \lessc(); $fileHash = md5(serialize(md5_file($lessFile))); $cssFileName = $fileHash . '.css'; $less->registerFunction('url', array($this, 'lessPhpUrl')); $less->addImportDir(Plugin::path('Union/Core') . 'webroot' . DS . 'less' . DS); if (!DEBUG) { $formatter = new \lessc_formatter_compressed(); $less->setFormatter($formatter); $less->setPreserveComments(false); $cssFileName = $fileHash . '.min.css'; } $updateFile = false; try { $cssFile = $webRoot . 'cache' . DS . $cacheFolder . DS . $cssFileName; if (file_exists($cssFile)) { $cacheRes = fopen($cssFile, 'r'); $firstLine = fgets($cacheRes); fclose($cacheRes); if (!preg_match("#{$fileHash}#i", $firstLine)) { $updateFile = true; } } else { $updateFile = true; } $output = '/cache/' . $cacheFolder . '/' . $cssFileName; if ($this->_lessCompile) { $updateFile = true; } if ($updateFile) { $css = $less->compileFile($lessFile); $css = $this->_getLessFileComment($fileHash, $systemPath) . $css; $file = new File($cssFile, true); $file->write($css); $file->close(); } } catch (Exception $error) { die('<strong>' . __d('union_dev', 'Less Error:') . '</strong><br/><pre>' . $error->getMessage() . '</pre>'); } } return $output; }
/** * Reads out a file, and echos the content to the client. * * @param File $file File object * @param array $range The range to read out of the file. * @return bool True is whole file is echoed successfully or false if client connection is lost in between */ protected function _sendFile($file, $range) { $compress = $this->outputCompressed(); $file->open('rb'); $end = $start = false; if ($range) { list($start, $end) = $range; } if ($start !== false) { $file->offset($start); } $bufferSize = 8192; set_time_limit(0); session_write_close(); while (!feof($file->handle)) { if (!$this->_isActive()) { $file->close(); return false; } $offset = $file->offset(); if ($end && $offset >= $end) { break; } if ($end && $offset + $bufferSize >= $end) { $bufferSize = $end - $offset + 1; } echo fread($file->handle, $bufferSize); if (!$compress) { $this->_flushBuffer(); } } $file->close(); return true; }
/** * Checks if the given VERSION.txt file is a valid CakePHP version file. * * @param string $file Full path to the VERSION.txt file. * @return bool True if file is found */ public function isCakeVersionFile($file) { $fh = new File($file); $content = $fh->read(); if (strpos($content, 'CakePHP') == true) { return true; } $fh->close(); return false; }