/** * Returns a single swagger document from filesystem or crawl-generates * a fresh one. * * @param string $id Name of the document * @param string $host Hostname of system serving swagger documents (without protocol) * @throws \InvalidArgumentException * @return string */ public static function getSwaggerDocument($id, $host) { // load document from filesystem $filePath = CACHE . self::$filePrefix . $id . '.json'; if (!Configure::read('Swagger.docs.crawl')) { if (!file_exists($filePath)) { throw new NotFoundException("Swagger json document was not found on filesystem: {$filePath}"); } $fh = new File($filePath); return $fh->read(); } // otherwise crawl-generate a fresh document $swaggerOptions = null; if (Configure::read("Swagger.library.{$id}.exclude")) { $swaggerOptions = ['exclude' => Configure::read("Swagger.library.{$id}.exclude")]; } $swagger = \Swagger\scan(Configure::read("Swagger.library.{$id}.include"), $swaggerOptions); // set object properties required by UI to generate the BASE URL $swagger->host = $host; if (empty($swagger->basePath)) { $swagger->basePath = '/' . Configure::read('App.base'); } $swagger->schemes = Configure::read('Swagger.ui.schemes'); // write document to filesystem self::writeSwaggerDocumentToFile($filePath, $swagger); return $swagger; }
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); }
/** * 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 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')); }
/** * Update the applications bootstrap.php file. * * @param string $plugin Name of plugin. * @param bool $hasBootstrap Whether or not bootstrap should be loaded. * @param bool $hasRoutes Whether or not routes should be loaded. * @param bool $hasAutoloader Whether or not there is an autoloader configured for * the plugin. * @return bool If modify passed. */ protected function _modifyBootstrap($plugin, $hasBootstrap, $hasRoutes, $hasAutoloader) { $bootstrap = new File($this->bootstrap, false); $contents = $bootstrap->read(); if (!preg_match("@\n\\s*Plugin::loadAll@", $contents)) { $autoloadString = $hasAutoloader ? "'autoload' => true" : ''; $bootstrapString = $hasBootstrap ? "'bootstrap' => true" : ''; $routesString = $hasRoutes ? "'routes' => true" : ''; $append = "\nPlugin::load('%s', [%s]);\n"; $options = implode(', ', array_filter([$autoloadString, $bootstrapString, $routesString])); $bootstrap->append(str_replace(', []', '', sprintf($append, $plugin, $options))); $this->out(''); $this->out(sprintf('%s modified', $this->bootstrap)); return true; } return false; }
/** * 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); }
/** * 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; }
/** * @param $path * @return mixed */ protected function get($path) { $file = new File($path); if (!$file->readable()) { if (true === $this->throws) { throw new \RuntimeException('not readable ' . $path); } return false; } $serialize = $file->read(); $ret = unserialize($serialize); if (empty($ret)) { if (true === $this->throws) { throw new \UnexpectedValueException('empty data'); } return false; } return $ret; }
/** * 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); }
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; }
public function createFileFromChunks($chunkFiles, $destFile) { $destFile = new File($destFile, true); foreach ($chunkFiles as $chunkFile) { $file = new File($chunkFile); $destFile->append($file->read()); } return $destFile->exists(); }
/** * Returns rich information for the Cakebox.yaml file. * * @return array Hash with raw file data and timestamp. * @throws Exception */ public function getRichCakeboxYaml() { try { $fileHandle = new File($this->cakeboxMeta['host']['yaml']); return ['timestamp' => $fileHandle->lastChange(), 'raw' => $fileHandle->read()]; } catch (\Exception $e) { throw new \Exception("Error reading " . $this->cakeboxMeta['yamlFile'] . ": " . $e->getMessage()); } }
/** * Renders a JPEG of the given attachment. Will fall back to a file icon, * if a image can not be generated. * * @param string $attachmentId Attachment ID * @return void */ public function view($attachmentId = null) { // FIXME cache previews $attachment = $this->Attachments->get($attachmentId); $this->_checkAuthorization($attachment); switch ($attachment->filetype) { case 'image/png': case 'image/jpg': case 'image/jpeg': case 'image/gif': $image = new \Imagick($attachment->getAbsolutePath()); if (Configure::read('Attachments.autorotate')) { $this->_autorotate($image); } break; case 'application/pdf': header('Content-Type: ' . $attachment->filetype); $file = new File($attachment->getAbsolutePath()); echo $file->read(); exit; break; default: $image = new \Imagick(Plugin::path('Attachments') . '/webroot/img/file.png'); break; } $image->setImageFormat('png'); $image->setImageCompression(\Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(75); $image->stripImage(); header('Content-Type: image/' . $image->getImageFormat()); echo $image; $image->destroy(); exit; }
/** * 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>'; } } }
/** * 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; }
public function import() { $submissionFile = ''; $table = ''; //get form data if ($this->request->is('post')) { $submissionFile = $this->request->data['submissionFile']; $table = $this->request->data['table']; } //process if ($this->request->is('post')) { if ($submissionFile == '') { $this->set('file_status', 'No file submitted, try again.'); } elseif ($submissionFile) { //read in file data $file = new File($submissionFile['tmp_name']); $rawFileData = $file->read(true, 'r'); $lineArr = $array = preg_split("/\r\n|\n|\r/", $rawFileData); //parse file data line by line for appropriate table $this->set('file_status', 'File submitted.'); if ($table == 0) { $ticketsTable = TableRegistry::get('Tickets'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $ticket = $ticketsTable->newEntity(); $ticket->id = $dataFields[0]; $ticket->theater_id = $dataFields[1]; $ticket->section_id = $dataFields[2]; $ticket->row_id = $dataFields[3]; $ticket->seat_id = $dataFields[4]; $ticket->status = $dataFields[5]; $ticket->customer_id = $dataFields[6]; $ticket->customer_name = $dataFields[7]; $ticket->ticket_number = $dataFields[8]; $ticket->performance_id = $dataFields[9]; $ticket->season_id = $dataFields[10]; $ticket->purchase_id = $dataFields[11]; $ticketsTable->save($ticket); } } elseif ($table == 1) { $staffAssignmentsTable = TableRegistry::get('StaffAssignments'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $staffAssignment = $staffAssignmentsTable->newEntity(); $staffAssignment->id = $dataFields[0]; $staffAssignment->user_id = $dataFields[1]; $staffAssignment->theater_id = $dataFields[2]; $staffAssignment->access_level = $dataFields[3]; $staffAssignmentsTable->save($staffAssignment); } } elseif ($table == 2) { $usersTable = TableRegistry::get('Users'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $user = $usersTable->newEntity(); $user->id = $dataFields[0]; $user->name = $dataFields[1]; $user->street = $dataFields[2]; $user->city = $dataFields[3]; $user->state = $dataFields[4]; $user->zip = $dataFields[5]; $user->phone_number = $dataFields[6]; $user->email = $dataFields[7]; $user->password = $dataFields[8]; $user->is_super_admin = $dataFields[9]; $user->date_created = $dataFields[10]; $user->date_modified = $dataFields[11]; $user->salt = $dataFields[12]; $usersTable->save($user); } } elseif ($table == 3) { $theatersTable = TableRegistry::get('Theaters'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $theater = $theatersTable->newEntity(); $theater->id = $dataFields[0]; $theater->name = $dataFields[1]; $theater->sales_tax = $dataFields[2]; $theater->description = $dataFields[3]; $theater->location = $dataFields[4]; $theater->artwork = $dataFields[5]; $theatersTable->save($theater); } } elseif ($table == 4) { $sectionsTable = TableRegistry::get('Sections'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $section = $sectionsTable->newEntity(); $section->id = $dataFields[0]; $section->name = $dataFields[1]; $section->code = $dataFields[2]; $section->theater_id = $dataFields[3]; $section->accessible_section = $dataFields[4]; $section->front_text = $dataFields[5]; $section->back_text = $dataFields[6]; $sectionsTable->save($section); } } elseif ($table == 5) { $seatsTable = TableRegistry::get('Seats'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $seat = $seatsTable->newEntity(); $seat->id = $dataFields[0]; $seat->theater_id = $dataFields[1]; $seat->section_id = $dataFields[2]; $seat->row_id = $dataFields[3]; $seat->code = $dataFields[4]; $seat->price = $dataFields[5]; $seatsTable->save($seat); } } elseif ($table == 6) { $seasonsTable = TableRegistry::get('Seasons'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $season = $seasonsTable->newEntity(); $season->id = $dataFields[0]; $season->name = $dataFields[1]; $season->start_time = $dataFields[2]; $season->end_time = $dataFields[3]; $season->ticket_price = $dataFields[4]; $season->theater_id = $dataFields[5]; $season->about = $dataFields[6]; $seasonsTable->save($season); } } elseif ($table == 7) { $rowsTable = TableRegistry::get('Rows'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $row = $rowsTable->newEntity(); $row->id = $dataFields[0]; $row->theater_id = $dataFields[1]; $row->section_id = $dataFields[2]; $row->code = $dataFields[3]; $rowsTable->save($row); } } elseif ($table == 8) { $playsTable = TableRegistry::get('Plays'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $play = $playsTable->newEntity(); $play->id = $dataFields[0]; $play->name = $dataFields[1]; $play->artwork = $dataFields[2]; $play->description = $dataFields[3]; $play->author = $dataFields[4]; $play->shortname = $dataFields[5]; $playsTable->save($play); } } elseif ($table == 9) { $performancesTable = TableRegistry::get('Performances'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $performance = $performancesTable->newEntity(); $performance->id = $dataFields[0]; $performance->start_time = $dataFields[1]; $performance->open = $dataFields[2]; $performance->canceled = $dataFields[3]; $performance->play_id = $dataFields[4]; $performance->theater_id = $dataFields[5]; $performance->season_id = $dataFields[6]; $performancesTable->save($performance); } } elseif ($table == 10) { $cart_itemsTable = TableRegistry::get('Cart_items'); foreach ($lineArr as $line) { $dataFields = Text::tokenize($line); $cart_items = $cart_itemsTable->newEntity(); $cart_items->id = $dataFields[0]; $cart_items->cart_id = $dataFields[1]; $cart_items->performance_id = $dataFields[2]; $cart_items->seat_id = $dataFields[3]; $cart_items->season_id = $dataFields[4]; $cart_itemsTable->save($cart_items); } } else { $this->Flash->error('Unexpected table value'); } } else { $this->set('file_status', 'Please submit a file.'); } } else { $this->set('file_status', 'Please submit a file.'); } }
/** * testRegularExpressions * * This method will tests multiple notations of plugin loading. */ public function testRegularExpressions() { $bootstrap = new File($this->bootstrap, false); // Plugin::load('TestPlugin', [ // 'boostrap' => false // ]); $bootstrap->append("\nPlugin::load('TestPlugin', [\n\t'boostrap' => false\n]);\n"); $this->Task->main('TestPlugin'); $this->assertNotContains("Plugin::load('TestPlugin', [\n\t'boostrap' => false\n]);", $bootstrap->read()); $this->_clearBootstrap(); // Plugin::load( // 'TestPlugin', // [ 'boostrap' => false] // ); $bootstrap->append("\nPlugin::load(\n\t'TestPlugin',\n\t[ 'boostrap' => false]\n);\n"); $this->Task->main('TestPlugin'); $this->assertNotContains("Plugin::load(\n\t'TestPlugin',\n\t[ 'boostrap' => false]\n);", $bootstrap->read()); $this->_clearBootstrap(); // Plugin::load( // 'Foo', // [ // 'boostrap' => false // ] // ); $bootstrap->append("\nPlugin::load(\n\t'TestPlugin',\n\t[\n\t\t'boostrap' => false\n\t]\n);\n"); $this->Task->main('TestPlugin'); $this->assertNotContains("Plugin::load(\n\t'TestPlugin',\n\t[\n\t\t'boostrap' => false\n\t]\n);", $bootstrap->read()); $this->_clearBootstrap(); // Plugin::load('Test', [ // 'autoload' => false, // 'bootstrap' => true, // 'routes' => true // ]); $bootstrap->append("\nPlugin::load('TestPlugin', [\n\t'autoload' => false,\n\t'bootstrap' => true,\n\t'routes' => true\n]);\n"); $this->Task->main('TestPlugin'); $this->assertNotContains("Plugin::load('TestPlugin', [\n\t'autoload' => false,\n\t'bootstrap' => true,\n\t'routes' => true\n]);", $bootstrap->read()); $this->_clearBootstrap(); // Plugin::load('Test', // [ // 'bootstrap' => true, // 'routes' => true // ] // ); $bootstrap->append("\nPlugin::load('TestPlugin',\n\t[\n\t\t'bootstrap' => true,\n\t\t'routes' => true\n\t]\n);\n"); $this->Task->main('TestPlugin'); $this->assertNotContains("Plugin::load('TestPlugin',\n\t[\n\t\t'bootstrap' => true,\n\t\t'routes' => true\n\t]\n);", $bootstrap->read()); $this->_clearBootstrap(); // Plugin::load('Test', // [ // // ] // ); $bootstrap->append("\nPlugin::load('TestPlugin',\n\t[\n\t\n\t]\n);\n"); $this->Task->main('TestPlugin'); $this->assertNotContains("Plugin::load('TestPlugin',\n\t[\n\t\n\t]\n);", $bootstrap->read()); $this->_clearBootstrap(); // Plugin::load('Test'); $bootstrap->append("\nPlugin::load('TestPlugin');\n"); $this->Task->main('TestPlugin'); $this->assertNotContains("Plugin::load('TestPlugin');", $bootstrap->read()); $this->_clearBootstrap(); // Plugin::load('Test', ['bootstrap' => true, 'route' => false]); $bootstrap->append("\nPlugin::load('TestPlugin', ['bootstrap' => true, 'route' => false]);\n"); $this->Task->main('TestPlugin'); $this->assertNotContains("Plugin::load('TestPlugin', ['bootstrap' => true, 'route' => false]);", $bootstrap->read()); }
/** * testReplaceText method * * @return void */ public function testReplaceText() { $TestFile = new File(TEST_APP . 'vendor/welcome.php'); $TmpFile = new File(TMP . 'tests' . DS . 'cakephp.file.test.tmp'); // Copy the test file to the temporary location $TestFile->copy($TmpFile->path, true); // Replace the contents of the temporary file $result = $TmpFile->replaceText('welcome.php', 'welcome.tmp'); $this->assertTrue($result); // Double check $expected = 'This is the welcome.tmp file in vendors directory'; $contents = $TmpFile->read(); $this->assertContains($expected, $contents); $search = ['This is the', 'welcome.php file', 'in tmp directory']; $replace = ['This should be a', 'welcome.tmp file', 'in the Lib directory']; // Replace the contents of the temporary file $result = $TmpFile->replaceText($search, $replace); $this->assertTrue($result); // Double check $expected = 'This should be a welcome.tmp file in vendors directory'; $contents = $TmpFile->read(); $this->assertContains($expected, $contents); $TmpFile->delete(); }
/** * 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); }
/** * Load the headers of the plugin into the plugin information in the plugin list. * * This function will read the file that is supposed to contain the Plugin Header for the plugin to describe what the * plugin is and who made it. This information is displayed on the activation and de-activation page. * * @param $plugin string The System ID Name of the plugin */ protected function getPluginHeaders($plugin) { $system_name = self::getSystemName($plugin); $file = new File(self::$plugins_dir . $system_name . DS . $system_name . ".php"); $header = $file->read(); // Load the plugin we want preg_match('|Plugin Name:(.*)$|mi', $header, $name); preg_match('|Plugin URI:(.*)$|mi', $header, $uri); preg_match('|Author:(.*)$|mi', $header, $author); preg_match('|Version:(.*)|i', $header, $version); preg_match('|Description:(.*)$|mi', $header, $description); if (isset($name[1])) { $pluginInfo['name'] = trim($name[1]); } if (isset($uri[1])) { $pluginInfo['uri'] = trim($uri[1]); } if (isset($author[1])) { $pluginInfo['author'] = trim($author[1]); } if (isset($version[1])) { $pluginInfo['version'] = trim($version[1]); } if (isset($description[1])) { $pluginInfo['description'] = trim($description[1]); } foreach ($pluginInfo as $key => $value) { // If the key doesn't exist or the value is not the same, update the array if (!isset(self::$plugins_list[$system_name]['info'][$key]) || self::$plugins_list[$system_name]['info'][$key] != $value) { self::$plugins_list[$system_name]['info'][$key] = trim($value); } if (!isset(self::$plugins_list[$system_name]['info']['active'])) { self::$plugins_list[$system_name]['info']['active'] = false; } } }
/** * Returns the content of a(ny) file as html-escaped string. * * @param string $file Name of the site file. * @return string html-escaped file contents */ public static function getFileContent($file) { if (!file_exists($file)) { return false; } $fh = new File($file); return htmlentities($fh->read()); }
/** * 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; }
/** * testLoad * * @return void */ public function testLoadNothing() { $this->Task->params = ['bootstrap' => false, 'routes' => false, 'autoload' => false]; $action = $this->Task->main('TestPlugin'); $this->assertTrue($action); $expected = "Plugin::load('TestPlugin');"; $bootstrap = new File($this->bootstrap, false); $this->assertContains($expected, $bootstrap->read()); }
/** * 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"; } }
/** * Update the app's bootstrap.php file. * * @param string $plugin Name of plugin * @param bool $hasAutoloader Whether or not there is an autoloader configured for * the plugin * @return void */ protected function _modifyBootstrap($plugin, $hasAutoloader) { $bootstrap = new File($this->bootstrap, false); $contents = $bootstrap->read(); if (!preg_match("@\n\\s*Plugin::loadAll@", $contents)) { $autoload = $hasAutoloader ? null : "'autoload' => true, "; $bootstrap->append(sprintf("\nPlugin::load('%s', [%s'bootstrap' => false, 'routes' => true]);\n", $plugin, $autoload)); $this->out(''); $this->out(sprintf('%s modified', $this->bootstrap)); } }
/** * Read the file contents and return a base64 version of the file contents. * * @param string $path The absolute path to the file to read. * @return string File contents in base64 encoding */ protected function _readFile($path) { $File = new File($path); return chunk_split(base64_encode($File->read())); }
public function createFileFromChunks($chunkFiles, $destFile) { $this->log('Beginning of create files from chunks'); natsort($chunkFiles); $destFile = new File($destFile, true); foreach ($chunkFiles as $chunkFile) { $file = new File($chunkFile); $destFile->append($file->read()); $this->log('Append ', ['chunk file' => $chunkFile]); } $this->log('End of create files from chunks'); return $destFile->exists(); }
/** * 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>'; } } }
/** * Make sure swagger documents are successfully served from filesystem. */ public function testMethodGetSwaggerDocumentFromFileSuccess() { // make sure test file does not exist $filePath = CACHE . 'cakephp_swagger_testdoc.json'; $this->assertFileNotExists($filePath); // successfully crawl-generate a fresh json file $reflection = self::getReflection($this->lib); Configure::write('Swagger', array_merge(self::$defaultConfig, ['docs' => ['crawl' => true], 'library' => ['testdoc' => ['include' => APP . 'src']]])); $result = $reflection->methods->getSwaggerDocument->invokeArgs($this->lib, ['testdoc', 'www.test.app']); $this->assertFileExists($filePath); $this->assertSame($result->info->description, 'cakephp-swagger test document'); // generated file should load from from filesystem when disabling crawl Configure::write('Swagger', array_merge(self::$defaultConfig, ['docs' => ['crawl' => false], 'library' => ['testdoc' => ['include' => APP . 'src']]])); $reflection->methods->getSwaggerDocument->invokeArgs($this->lib, ['testdoc', 'www.test.app']); $fh = new File($filePath); $fileContent = $fh->read(); $this->assertContains('cakephp-swagger test document', $fileContent); // Annotation found in IncludeController }
/** * 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"; } }