public function run($request) { $number = $request->getVar('number'); if (!$number) { $number = 50; } if (!$request->getVar('run')) { exit("Please supply the run= parameter, and a 'number' parameter (defaults to 50 if not set)"); } $files = File::get()->filter(['FileSize' => 0, 'ClassName:not' => 'Folder', 'CDNFile:PartialMatch' => ':||'])->limit($number); echo "Processing " . $number . " files<br/>\n"; flush(); foreach ($files as $file) { echo "Downloading {$file->ClassName} #{$file->ID} " . $file->Title . " ... "; flush(); $file->ensureLocalFile(); if ($file->localFileExists()) { $file->FileSize = filesize($file->getFullPath()); echo "filesize {$file->FileSize} ... "; flush(); if ($file instanceof CdnImage) { $dim = $file->getDimensions(); echo "dimensions {$dim} ... "; flush(); } $file->write(); unlink($file->getFullPath()); } else { echo " cannot download {$file->Title} - {$file->CDNFile} <br/>\n"; } echo "<br/>\n"; } }
public function testNatGeoFeed() { $sFilePath = "tests" . DIRECTORY_SEPARATOR . "resources" . DIRECTORY_SEPARATOR . "natgeo.xml"; $sFileContents = File::get($sFilePath); #echo $sFileContents; return $this->assertTrue(true); }
public function __construct() { // Carbon Language Carbon::setLocale('tr'); // create home page if non exist count(Menu::where('slug', '/anasayfa')->get()) == 0 ? Menu::create(['title' => 'Anasayfa', 'slug' => '/anasayfa', 'eng_title' => 'Home', 'eng_slug' => '/home'])->save() : null; // create config file if non exist !\File::exists(storage_path('.config')) ? \File::put(storage_path('.config'), json_encode(['brand' => 'Brand Name', 'mail' => '*****@*****.**', 'active' => 1, 'eng' => '0', 'one_page' => '0', 'googlemap' => '', 'header' => ''])) : null; $this->config = json_decode(\File::get(storage_path('.config'))); !\File::exists(storage_path('app/custom/css')) ? \File::makeDirectory(storage_path('app/custom/css'), 0755, true) : null; !\File::exists(storage_path('app/custom/js')) ? \File::makeDirectory(storage_path('app/custom/js'), 0755, true) : null; // get css & js files from custom folder // css $css = \File::allFiles(storage_path('app/custom/css')); if (!empty($css)) { foreach ($css as $cs) { $this->css[$cs->getCtime()] = $cs->getRelativePathname(); } // sort by date ksort($this->css); } // js $js = \File::allFiles(storage_path('app/custom/js')); if (!empty($js)) { foreach ($js as $j) { $this->js[$j->getCtime()] = $j->getRelativePathname(); } // sort by date ksort($this->js); } }
/** * Test that an object can be uploaded against an object with a has_one relation */ public function testUploadRelation() { $this->loginWithPermission('ADMIN'); // Unset existing has_one relation before re-uploading $folder1 = $this->objFromFixture('Folder', 'folder1'); $record = $this->objFromFixture('SelectUploadFieldTest_Record', 'record1'); $record->FirstFileID = null; $record->SecondFileID = null; $record->write(); // Firstly, ensure the file can be uploaded to the default folder $tmpFileName = 'testSelectUploadFile1.txt'; $response = $this->mockFileUpload('FirstFile', $tmpFileName); $this->assertFalse($response->isError()); $this->assertFileExists(ASSETS_PATH . "/SelectUploadFieldTest/FirstDefaultFolder/{$tmpFileName}"); $uploadedFile = File::get()->filter('Name', $tmpFileName)->first(); $this->assertTrue($uploadedFile instanceof File && $uploadedFile->exists(), 'The file object is created'); // If another folder is selected then a different folder should be used $tmpFileName = 'testSelectUploadFile2.txt'; $response = $this->mockFileUpload('FirstFile', $tmpFileName, $folder1->ID); $this->assertFalse($response->isError()); $this->assertFileExists(ASSETS_PATH . "/SelectUploadFieldTest/{$tmpFileName}"); $uploadedFile = File::get()->filter('Name', $tmpFileName)->first(); $this->assertTrue($uploadedFile instanceof File && $uploadedFile->exists(), 'The file object is created'); $this->assertEquals(FolderDropdownField::get_last_folder(), $folder1->ID); // Repeating an upload without presenting a folder should use the last used folder $tmpFileName = 'testSelectUploadFile3.txt'; $response = $this->mockFileUpload('SecondFile', $tmpFileName); $this->assertFalse($response->isError()); $this->assertFileExists(ASSETS_PATH . "/SelectUploadFieldTest/{$tmpFileName}"); $uploadedFile = File::get()->filter('Name', $tmpFileName)->first(); $this->assertTrue($uploadedFile instanceof File && $uploadedFile->exists(), 'The file object is created'); $this->assertEquals(FolderDropdownField::get_last_folder(), $folder1->ID); }
/** * Creates table for displaying unused files. * * @return GridField */ protected function getAssetList() { $where = $this->folder->getUnusedFilesListFilter(); $files = File::get()->where($where); $field = new GridField('AssetList', false, $files); return $field; }
/** * @param array $dir * @param $files * @param \stdClass $category * @return void */ protected function addRecipes(array $dir, $files, \stdClass $category) { foreach ($dir as $value) { if ($value != "." && $value != "..") { $file = \File::get("{$files}/{$value}"); $problem = $this->getParseContents('problem', $file); $solution = $this->getParseContents('solution', $file); $discussion = $this->getParseContents('discussion', $file); $credit = $this->getParseContents('credit', $file); $title = $this->getParseHeader('title', $file); $position = $this->getParseHeader('position', $file); $topics = $this->getParseHeader('topics', $file); if ($problem && $solution && $discussion && $title) { $array = ['problem' => trim($problem), 'category_id' => $category->category_id, 'solution' => trim($this->convertGfm($solution)), 'discussion' => trim($this->convertGfm($discussion)), 'credit' => trim($this->convertGfm($credit)), 'title' => trim($title), 'position' => trim($position)]; try { // new recipes $recipeId = $this->recipe->addRecipe($array); $this->addTags($recipeId, $topics); $this->info("added : {$files}/{$value}"); } catch (QueryException $e) { // update recipes $recipe = $this->recipe->getRecipeFromTitle(trim($title)); $this->recipe->updateRecipe($recipe->recipe_id, ['problem' => trim($problem), 'category_id' => $category->category_id, 'solution' => trim($this->convertGfm($solution)), 'discussion' => trim($this->convertGfm($discussion)), 'position' => trim($position)]); $this->recipeTag->deleteRecipeTags($recipe->recipe_id); $this->addTags($recipe->recipe_id, $topics); $this->comment("Updated : recipe:{$title} : {$files}/{$value}"); } } } } }
public function run() { DB::table('availability_page')->delete(); $success = File::cleanDirectory($this->getImagesPath()); File::put($this->getImagesPath() . '.gitignore', File::get(public_path() . '/../app/storage/cache/.gitignore')); AvailabilityPage::create(['image_name' => ""]); }
public function apply(Transformable $transformable) { $file = \File::get(public_path('assets/img/borders.png')); $img = base64_encode($file); $data = str_ireplace(["\r", "\n"], '', $transformable->getContents()); $data = preg_replace("~<(/?(br|p|dd))[^>]*?>~i", '<\\1>', $data); $data = preg_replace("~</(p|dd)>~i", '', $data); $data = preg_replace("~<(br|p|dd)>~i", static::LINEBREAK, $data); $data = preg_replace('/[ ]{2,}/', ' ', $data); $data = preg_replace("/" . static::LINEBREAK . "[ ]+/s", static::LINEBREAK . " ", $data); $data = str_replace(static::LINEBREAK, '<p>', $data); $page = $transformable->page; $author = $page->author; $charset = $transformable->charset ?: 'utf-8'; $title = $author->fio . " - " . $page->title; $link = \HTML::link(path_join("http://samlib.ru", $author->absoluteLink()), $author->fio) . " - " . \HTML::link(path_join("http://samlib.ru", $page->absoluteLink()), $page->title); $annotation = $page->annotation; $contents = $data; $downloaded = \Lang::get('pages.pages.downloaded', ['url' => \Request::fullUrl()]); if ($charset != 'utf-8') { $e = app('charset-encoder'); $c = $e->remap($charset, true); $title = $e->transform($title, 'utf-8', $c); $link = $e->transform($link, 'utf-8', $c); $annotation = $e->transform($annotation, 'utf-8', $c); $downloaded = $e->transform($downloaded, 'utf-8', $c); } $view = view('pages.html-download', compact('img', 'charset', 'title', 'link', 'annotation', 'contents', 'downloaded')); $transformable->setContents((string) $view); $transformable->setType(static::EXTENSION); return $transformable; }
public function extraer() { $path = public_path(); $this->text = \File::get($path . $this->file); $this->extraerProyecto(); $this->extraerNombreProyecto(); $this->extraerUrg(); $this->extraerDescUrg(); $this->extraerFechas(); $this->extraerFondo(); $this->extraerMontoProyecto(); $this->extraerPartida(); $this->extraerCog(); $this->extraerMontoPartida(); $this->extraerObjetivo(); if (count($this->arr_partida) == count($this->arr_cog) && count($this->arr_partida) == count($this->arr_monto)) { for ($i = 0; $i < count($this->arr_partida); $i++) { $this->arr_recursos[$this->arr_partida[$i]]['cog'] = $this->arr_cog[$i]; $this->arr_recursos[$this->arr_partida[$i]]['d_rm'] = $this->arr_drm[$i]; $this->arr_recursos[$this->arr_partida[$i]]['monto'] = $this->arr_monto[$i]; $this->arr_recursos[$this->arr_partida[$i]]['objetivo'] = $this->arr_rm_objetivo[$this->arr_partida[$i]]; $this->arr_recursos[$this->arr_partida[$i]]['d_objetivo'] = $this->arr_rm_d_objetivo[$this->arr_partida[$i]]; } } }
function upload_file($file) { $extension = $file->getClientOriginalExtension(); $filename = $file->getFilename() . '.' . $extension; Storage::disk('local')->put($filename, File::get($file)); return $filename; }
/** * Funcao para edicao da config do [Modulo] * @param string $controller Nome do controlador * @return void */ public function getFile($controller) { // $this->logic->_getConfigFiles(); // Busca o arquivo especificado $cfg_file = mkny_model_config_path($controller) . '.php'; // Field types $f_types = array_unique(array_values(app()->make('Mkny\\Cinimod\\Logic\\AppLogic')->_getFieldTypes())); // Se o diretorio nao existir if (!realpath(dirname($cfg_file))) { \File::makeDirectory(dirname($cfg_file)); } // Config file data if (!\File::exists($cfg_file)) { $stub = \File::get(__DIR__ . '/../Commands/stubs/model_config.stub'); \Mkny\Cinimod\Logic\UtilLogic::translateStub(array('var_fields_data' => ''), $stub); \File::put($cfg_file, $stub); } // Config file data $config_str = \File::getRequire($cfg_file)['fields']; // Pula o primeiro indice // array_shift($config_str); $valOrder = 1; // Fornece o tipo "types" para todos os campos, para selecao foreach ($config_str as $key => $value) { if (!is_array($config_str[$key])) { $config_str[$key] = array(); } $config_str[$key]['name'] = $key; $config_str[$key]['type'] = isset($value['type']) ? $value['type'] : 'string'; $config_str[$key]['form_add'] = isset($value['form_add']) ? $value['form_add'] : true; $config_str[$key]['form_edit'] = isset($value['form_edit']) ? $value['form_edit'] : true; $config_str[$key]['grid'] = isset($value['grid']) ? $value['grid'] : true; $config_str[$key]['relationship'] = isset($value['relationship']) ? $value['relationship'] : false; $config_str[$key]['required'] = isset($value['required']) ? $value['required'] : false; $config_str[$key]['searchable'] = isset($value['searchable']) ? $value['searchable'] : false; $config_str[$key]['order'] = isset($value['order']) ? $value['order'] : $valOrder++; $config_str[$key]['types'] = array_combine($f_types, $f_types); } if (isset(array_values($config_str)[1]['order'])) { usort($config_str, function ($dt, $db) { if (!isset($db['order'])) { $db['order'] = 0; } if (isset($dt['order'])) { return $dt['order'] - $db['order']; } else { return 0; } }); $newConfig = []; foreach ($config_str as $sortfix) { $newConfig[$sortfix['name']] = $sortfix; } $config_str = $newConfig; } $data['controller'] = $controller; $data['data'] = $config_str; return view('cinimod::admin.generator.config_detailed_new')->with($data); // return view('cinimod::admin.generator.config_detailed')->with($data); }
/** * Store a newly created resource in storage. * * @return Response */ public function store(Request $request) { //obtenemos el campo file definido en el formulario $file1 = $request->file('foto1'); $file2 = $request->file('foto2'); $file3 = $request->file('foto3'); // $input = array('image' => $file1); // $reglas = array('image' => 'mimes:jpeg,png'); // $validacion = Validator::make($input, $reglas); // if ($validacion->fails()) // { // \Session::flash('flash_message', 'Una de las imagenes no es correcta'); // } //obtenemos el nombre del archivo $nombre1 = $file1->getClientOriginalName(); $nombre2 = $file2->getClientOriginalName(); $nombre3 = $file3->getClientOriginalName(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre1, \File::get($file1)); \Storage::disk('local')->put($nombre2, \File::get($file2)); \Storage::disk('local')->put($nombre3, \File::get($file3)); $persona = Persona::find($request->persona_id); $persona->fill($request->all()); $persona->foto1 = $request->persona_id . '|' . $nombre1; $persona->foto2 = $request->persona_id . '|' . $nombre2; $persona->foto3 = $request->persona_id . '|' . $nombre3; $persona->save(); return view('new'); }
/** * Parse a block of YAML into PHP * * @param string $yaml YAML-formatted string to parse * @param string $mode Parsing mode to use * @return array */ public static function parse($yaml, $mode = null) { // start measuring $hash = Debug::markStart('parsing', 'yaml'); $mode = $mode ? $mode : self::getMode(); switch ($mode) { case 'loose': $result = Spyc::YAMLLoad($yaml); break; case 'strict': $result = sYAML::parse($yaml); break; case 'transitional': try { $result = sYaml::parse($yaml); } catch (Exception $e) { Log::error($e->getMessage() . ' Falling back to loose mode.', 'core', 'yaml'); $result = Spyc::YAMLLoad($yaml); } break; default: // check for new lines, is this a file? $has_newline = strpos($yaml, "\n") !== false; if (!$has_newline && File::exists($yaml)) { // seems like it is $yaml = File::get($yaml); } $result = Statamic\Dipper\Dipper::parse($yaml); } // end measuring Debug::markEnd($hash); Debug::increment('parses', 'yaml'); return $result; }
/** * Adds the necessary routes * * @return void */ public function addRoutes() { //Get the routes template content $content = \File::get($this->package_path('Templates/routes.php')); //Append to the routes.php file $this->addToFile('routes.php', 'routes', "\n\n" . $content); }
public function postUpload(Request $req) { $response = array(); if ($req->file('excelF')) { $file = $req->file('excelF'); $extension = $file->getClientOriginalExtension(); $filename = $file->getClientOriginalName(); /*periksa extensi file */ if ('xlsx' !== $extension) { $response['code'] = 404; $response['msg'] = "File berextensi {$extension} dengan nama {$filename}, file Seharusnya Berupa Excel"; // $response['msg']="File Anda $file->getClientOriginalName(), Pastikan File yang Anda upload sesuai dengan format "; return $response; // return $response; } elseif (\Storage::disk('local')->put($file->getFilename() . '.' . $extension, \File::get($file))) { // simpan kedadalam table $entry = new Fileentry(); $entry->mime = $file->getClientMimeType(); $entry->original_filename = $file->getClientOriginalName(); $entry->filename = $file->getFilename() . '.' . $extension; $entry->save(); $response['code'] = 200; $response['msg'] = "File {$entry->original_filename} Telah disimpan"; return $response; } } $response['code'] = 404; $response['msg'] = "Gagal Upload File !!!"; return json_encode($response); // echo '{"TEST1": 454535353,"TEST2": "test2"}'; }
/** * Emulate a call to index.php?p=$vanilla_module_path * Much of this ripped out of Vanilla's index.php */ public function view($segments) { // if a static asset, return it outright $asset = $this->is_static_asset($segments); if ($asset) { return \Response::make(\File::get($asset))->header('Content-Type', $this->get_content_type($asset)); } // otherwise, dispatch into vanilla $user = $this->user; $bootstrap = new VanillaBootstrap(); $bootstrap->call(function () use($user, $segments) { // Create the session and stuff the user in \Gdn::Authenticator()->SetIdentity($user->getKey(), false); \Gdn::Session()->Start(false, false); \Gdn::Session()->SetPreference('Authenticator', 'Gdn_Authenticator'); // Create and configure the dispatcher. $Dispatcher = \Gdn::Dispatcher(); $EnabledApplications = \Gdn::ApplicationManager()->EnabledApplicationFolders(); $Dispatcher->EnabledApplicationFolders($EnabledApplications); $Dispatcher->PassProperty('EnabledApplications', $EnabledApplications); // Process the request. $Dispatcher->Start(); $Dispatcher->Dispatch(implode('/', $segments)); }); }
public function setUp() { if (get_class($this) == "ImageTest") { $this->skipTest = true; } parent::setUp(); if ($this->skipTest) { return; } // Set backend root to /ImageTest AssetStoreTest_SpyStore::activate('ImageTest'); // Copy test images for each of the fixture references $files = File::get()->exclude('ClassName', 'Folder'); foreach ($files as $image) { $filePath = AssetStoreTest_SpyStore::getLocalPath($image); // Only correct for test asset store $sourcePath = BASE_PATH . '/framework/tests/model/testimages/' . $image->Name; if (!file_exists($filePath)) { SS_Filesystem::makeFolder(dirname($filePath)); if (!copy($sourcePath, $filePath)) { user_error('Failed to copy test images', E_USER_ERROR); } } } }
public function __call($method, $arguments) { $extensions = array(".html", ".md", ".markdown", ".textile"); $html = null; foreach ($extensions as $extension) { $full_src = Path::assemble(BASE_PATH, Config::getCurrentThemePath(), 'partials', ltrim($method . $extension, '/')); if (File::exists($full_src)) { // Merge additional variables passed as parameters Statamic_View::$_dataStore = $arguments + Statamic_View::$_dataStore; if ($this->fetchParam('use_context', false, false, true, false)) { $html = Parse::contextualTemplate(File::get($full_src), Statamic_View::$_dataStore, $this->context, 'Statamic_View::callback'); } else { $html = Parse::template(File::get($full_src), Statamic_View::$_dataStore, 'Statamic_View::callback'); } // parse contents if needed if ($extension == ".md" || $extension == ".markdown") { $html = Parse::markdown($html); } elseif ($extension == ".textile") { $html = Parse::textile($html); } } } if (Config::get('enable_smartypants', TRUE)) { $html = Parse::smartypants($html); } return $html; }
/** * Converts a station id to a station string. If the string cannot be converted, * null is returned. * @param $string * @return string or null */ public static function convertToString($string) { // Fetch stations list to compare the station string with $json = \File::get(app_path() . "/stations.json"); $data = json_decode($json); // For each station in the array of stations, attempt comparison foreach ($data->{"@graph"} as $station) { /* * TODO: write an array with station name alternates * * This also solves multilanguage issues since the strings are simply converted * to the proper id :) This way, we can make iRail multilanguage! * * $alternates = array( * "Gent-Sint-Pieters" => array('Ghent-Sint-Pieters', 'Gent Sint Pieters', 'Ghent Sint Pieters') * ) */ /* * Assuming we have a list of station name alternates, we can do even more * comparisons to ensure that this process is functional. * TODO: write a function that loops through station name alternates */ /* If we can find the station name in the string of Nicola's records, * we can return the station data if we get a hit! * Arguably we need to check if there are multiple hits: * TODO: check for multiple hits when using strpos() */ if (strpos($station->{"@id"}, $string) !== false) { return $station; } } return null; }
/** * store a image in our galleryImages directory. * @post("gallery/add/storeImage") * @return Response */ public function storeImage(Request $request) { $files = $request->file('file'); $fileName = $files->getClientOriginalName(); \Storage::disk('gallery')->put($fileName, \File::get($files)); \Storage::disk('thumbs')->put($fileName, \File::get($files)); }
public function store(Request $request) { //dd('jajaja'); $file = $request->file('file'); //obtenemos el campo file obtenido por el formulario $nombre = $file->getClientOriginalName(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); \Excel::load('/storage/public/files/' . $nombre, function ($archivo) use(&$falla) { $result = $archivo->get(); //leer todas las filas del archivo foreach ($result as $key => $value) { $var = new Periodo(); $datos = ['bloque' => $value->bloque, 'inicio' => $value->inicio, 'fin' => $value->fin]; $validator = Validator::make($datos, Periodo::storeRules()); if ($validator->fails()) { Session::flash('message', 'Los Periodos ya existen o el archivo ingresado no es valido'); $falla = true; } else { $var->fill($datos); $var->save(); } } })->get(); if ($falla) { // Fallo la validacion de algun campus, retornar al index con mensaje return redirect()->route('Administrador.periodos.index'); } \Storage::delete($nombre); Session::flash('message', 'Los Periodos fueron agregados exitosamente!'); return redirect()->route('Administrador.periodos.index'); }
public function setupdb($arguments) { $dbpath = path('app') . 'config/database' . EXT; $currentconfig = File::get($dbpath); $driver = isset($arguments['driver']) ? $arguments['driver'] : ''; $host = isset($arguments['host']) ? $arguments['host'] : ''; $database = isset($arguments['database']) ? $arguments['database'] : ''; $username = isset($arguments['username']) ? $arguments['username'] : ''; $password = isset($arguments['password']) ? $arguments['password'] : ''; $charset = isset($arguments['charset']) ? $arguments['charset'] : 'utf8'; switch ($driver) { case 'mysql': $setting_db = "array('mysql' => array(\n\t\t\t\t\t\t\t'driver' => '{$driver}',\n\t\t\t\t\t\t\t'host' => '{$host}',\n\t\t\t\t\t\t\t'database' => '{$database}',\n\t\t\t\t\t\t\t'username' => '{$username}',\n\t\t\t\t\t\t\t'password' => '{$password}',\n\t\t\t\t\t\t\t'charset' => '{$charset}',\n\t\t\t\t\t\t\t'prefix' => '',\n\t\t\t\t\t\t))"; break; case 'sqlite': $setting_db = "array('sqlite' => array(\n\t\t\t\t\t'driver' => '{$driver}',\n\t\t\t\t\t'database' => '{$database}',\n\t\t\t\t\t'prefix' => '',\n\t\t\t\t))"; break; case 'pgsql': $setting_db = "array('pgsql' => array(\n\t\t\t\t\t'driver' => '{$driver}',\n\t\t\t\t\t'host' => '{$host}',\n\t\t\t\t\t'database' => '{$database}',\n\t\t\t\t\t'username' => '{$username}',\n\t\t\t\t\t'password' => '{$password}',\n\t\t\t\t\t'charset' => '{$charset}',\n\t\t\t\t\t'prefix' => '',\n\t\t\t\t\t'schema' => 'public',\n\t\t\t\t))"; break; case 'sqlsrv': $setting_db = "array('sqlsrv' => array(\n\t\t\t\t\t'driver' => '{$driver}',\n\t\t\t\t\t'host' => '{$host}',\n\t\t\t\t\t'database' => '{$database}',\n\t\t\t\t\t'username' => '{$username}',\n\t\t\t\t\t'password' => '{$password}',\n\t\t\t\t\t'prefix' => '',\n\t\t\t\t))"; break; default: $setting_db = ''; break; } $config = str_replace("'default' => '',", "'default' => '{$driver}',", $currentconfig, $count); $config = str_replace("'connections' => array(),", "'connections' => {$setting_db},", $config, $count); File::put($dbpath, $config); }
public static function handle_shortcode($arguments, $url, $parser, $shortcode) { // get all registered cdn things, and see if any of them have URLs that // need to be handled by US, instead of looked up. _if_ we need to handle it, // perform relevant transforms etc. $contentService = singleton('ContentService'); /* @var $contentService ContentService */ $cdns = $contentService->getStoreTypes(); foreach ($cdns as $name => $types) { $reader = $contentService->getReader($name); if ($actualReader = $reader->providerOfUrl($url)) { if ($actualReader instanceof ContentReader) { $contentId = $actualReader->getContentId(); $file = File::get()->filter('CDNFile', $contentId)->first(); if ($file) { if ($file instanceof Image && isset($arguments['width']) && isset($arguments['height'])) { // return the formatted image $cached = $file->ResizedImage($arguments['width'], $arguments['height']); if ($cached) { return $cached->forTemplate(); } } } } } } return parent::handle_shortcode($arguments, $url, $parser, $shortcode); }
/** * Test file migration */ public function testMigration() { // Prior to migration, check that each file has empty Filename / Hash properties foreach (File::get()->exclude('ClassName', 'Folder') as $file) { $filename = $file->generateFilename(); $this->assertNotEmpty($filename, "File {$file->Name} has a filename"); $this->assertEmpty($file->File->getFilename(), "File {$file->Name} has no DBFile filename"); $this->assertEmpty($file->File->getHash(), "File {$file->Name} has no hash"); $this->assertFalse($file->exists(), "File with name {$file->Name} does not yet exist"); $this->assertFalse($file->isPublished(), "File is not published yet"); } // Do migration $helper = new FileMigrationHelper(); $result = $helper->run($this->getBasePath()); $this->assertEquals(5, $result); // Test that each file exists foreach (File::get()->exclude('ClassName', 'Folder') as $file) { $expectedFilename = $file->generateFilename(); $filename = $file->File->getFilename(); $this->assertTrue($file->exists(), "File with name {$filename} exists"); $this->assertNotEmpty($filename, "File {$file->Name} has a Filename"); $this->assertEquals($expectedFilename, $filename, "File {$file->Name} has retained its Filename value"); $this->assertEquals('33be1b95cba0358fe54e8b13532162d52f97421c', $file->File->getHash(), "File with name {$filename} has the correct hash"); $this->assertTrue($file->isPublished(), "File is published after migration"); } }
/** * Asks the module to handle a GET (Read) request * * @param $view * @param $args * @return Response */ protected function handleGet($view, $args) { $artist = $view; if (!isset($artist)) { return new Response(array('message' => "The Hive Radio music artist cover API version {$this->VERSION}", 'usage' => "cover/[artist]"), 200); } else { if (\Cache::has("artist_cover_{$artist}")) { return $this->buildImageResponse(\Cache::get("artist_cover_{$artist}")); } else { $youtube_response = file_get_contents("https://www.googleapis.com/youtube/v3/search?q={$artist}&key=" . \Config::get('icebreath.covers.youtube_api_key') . "&fields=items(id(kind,channelId),snippet(thumbnails(medium)))&part=snippet,id"); $youtube_json = json_decode($youtube_response, true); $items = $youtube_json['items']; $youtube_source = null; for ($i = 0; $i < sizeof($items); $i++) { if ((string) $items[$i]["id"]["kind"] != "youtube#channel") { continue; } else { $youtube_source = $items[$i]["snippet"]["thumbnails"]["medium"]["url"]; break; } } if (isset($youtube_source) && !empty($youtube_source)) { $data = file_get_contents($youtube_source); $expiresAt = Carbon::now()->addHours(\Config::get('icebreath.covers.cache_time')); \Cache::put("artist_cover_{$artist}", $data, $expiresAt); return $this->buildImageResponse($data); } return $this->buildImageResponse(\File::get(base_path() . '/' . \Config::get('icebreath.covers.not_found_img'))); } } }
function salvaArquivosLocal($local, $arquivo, $prefix) { $extArquivo = $arquivo->getClientOriginalExtension(); $nomeArquivo = $prefix . '.' . $extArquivo; $salvaArquivo = Storage::disk($local)->put($nomeArquivo, File::get($arquivo)); return $nomeArquivo; }
public function setUp() { parent::setUp(); $this->logInWithPermission('ADMIN'); Versioned::reading_stage('Stage'); // Set backend root to /AssetFieldTest AssetStoreTest_SpyStore::activate('AssetFieldTest'); $create = function ($path) { Filesystem::makeFolder(dirname($path)); $fh = fopen($path, "w+"); fwrite($fh, str_repeat('x', 1000000)); fclose($fh); }; // Write all DBFile references foreach (AssetFieldTest_Object::get() as $object) { $path = AssetStoreTest_SpyStore::getLocalPath($object->File); $create($path); } // Create a test files for each of the fixture references $files = File::get()->exclude('ClassName', 'Folder'); foreach ($files as $file) { $path = AssetStoreTest_SpyStore::getLocalPath($file); $create($path); } }
/** * Test the GD driver make and get methods. * * @return null */ public function testGDGet() { // GD driver only if (Config::get('placeholdr::placeholdr.driver') !== 'GD') { return; } // Height and width $width = $height = 300; // Text $text = $width . ' X ' . $height; // File path $path = Config::get('placeholdr::placeholdr.placeholdrs_path'); // File name $file_name = md5($width . $height . $text) . '.png'; try { // test create placeholdr $this->assertTrue(Placeholdr::make($width, $height, $text) === $path . $file_name); // Actual image contents after create $image_contents = File::get($path . $file_name); } catch (Exception $e) { $image_contents = ''; } // Run test $this->assertTrue(Placeholdr::get($width, $height, $text) === $image_contents); }
public function run() { DB::table('home_page')->delete(); $success = File::cleanDirectory($this->getImagesPath()); File::put($this->getImagesPath() . '.gitignore', File::get(public_path() . '/../app/storage/cache/.gitignore')); HomePage::create(['headline' => "Industrial Legacy", 'text' => 'RUSTIC DETAILS. MODERN EDGE. REFINED LIVING IN COURT SQUARE. <br> 1 - 4 BEDROOM HOMES FROM $615K. PENTHOUSES PRICED UPON REQUEST.', 'subtext' => 'CHILDREN\'S PLAYROOM, LOUNGE, LIBRARY, GYM, TERRACE AND PARKING', 'image' => $this->copyImage(public_path() . '/backup_images/building/building.jpg')]); }
/** * Output file to user. * Send file content to browser for download progressively. */ public function index() { $file = $this->request->getVar('file'); $fileAssetPath = substr($file, stripos($file, 'assets')); $fileObj = File::get()->filter(array('Filename' => Convert::raw2sql($fileAssetPath)))->first(); if ($fileObj) { $rule = self::RULE_PUBLIC; foreach (self::config()->rules as $key => $value) { $regex = '$^assets/' . trim($key, '/') . '/$'; if (preg_match($regex, $fileAssetPath)) { $rule = $value; } } if (self::config()->cms_access_ignore_rules && Permission::check('CMS_ACCESS')) { $rule = self::RULE_PUBLIC; } if (self::config()->admin_ignore_rules && Permission::check('ADMIN')) { $rule = self::RULE_PUBLIC; } switch ($rule) { case self::RULE_PUBLIC: // Then we do nothing... break; case self::RULE_ADMIN: if (!Permission::check('ADMIN')) { return $this->sendHttpError($fileObj, $rule); } break; case self::RULE_LOGGED_IN: if (!Member::currentUserID()) { return $this->sendHttpError($fileObj, $rule); } break; case self::RULE_OWNER: if ($fileObj->OwnerID != Member::currentUserID()) { return $this->sendHttpError($fileObj, $rule); } break; default: throw new Exception("Rule {$rule} is not defined"); } $filePath = $fileObj->getFullPath(); $mimeType = HTTP::get_mime_type($filePath); $name = $fileObj->Name; $this->audit($fileObj); header("Content-Type: {$mimeType}"); header("Content-Disposition: attachment; filename=\"{$name}\""); header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); set_time_limit(0); $file = @fopen($filePath, "rb"); while (!feof($file)) { print @fread($file, 1024 * 8); ob_flush(); flush(); } exit; } return $this->sendHttpError($fileObj, self::RULE_NOT_FOUND); }