/** * Limpa a string informada removendo todos os acentos. * * @link http://blog.thiagobelem.net/removendo-acentos-de-uma-string-urls-amigaveis * * @param string $str * @param string $slug * * @return string */ public static function CleanString($str, $slug = false) { $str = \Illuminate\Support\Str::lower($str); /* Códigos de substituição */ $codes = array(); $codes['a'] = array('à', 'á', 'ã', 'â', 'ä'); $codes['e'] = array('è', 'é', 'ê', 'ë'); $codes['i'] = array('ì', 'í', 'î', 'ï'); $codes['o'] = array('ò', 'ó', 'õ', 'ô', 'ö'); $codes['u'] = array('ù', 'ú', 'û', 'ü'); $codes['c'] = array('ç'); $codes['n'] = array('ñ'); $codes['y'] = array('ý', 'ÿ'); /* Substituo os caracteres da string */ foreach ($codes as $key => $values) { $str = str_replace($values, $key, $str); } if ($slug) { /* Troca tudo que não for letra ou número por um caractere ($slug) */ $str = preg_replace("/[^a-z0-9]/i", $slug, $str); /* Tira os caracteres ($slug) repetidos */ $str = preg_replace("/" . $slug . "{2,}/i", $slug, $str); /* Remove os caracteres ($slug) do início/fim da string */ $str = trim($str, $slug); } return $str; }
/** * Execute the console command. * * @return mixed */ public function fire() { $this->max_per_request = $this->option('max-per-request'); \DB::table('villes')->truncate(); $filename = realpath(dirname(__FILE__) . '/../../../data/france.csv'); $this->info('Filename: ' . $filename); $fs = new Filesystem(); if (!$fs->exists($filename)) { $this->error("Data file not found", 1); return; } $resource = @fopen($filename, 'r'); if (!$resource) { $this->error(error_get_last(), 1); return; } $headers = fgets($resource); $csv = array(); $now = \Carbon\Carbon::now(); while (null != ($line = fgets($resource))) { $line = preg_replace('/"/', '', $line); $line = explode(',', $line); $csv[] = ['postcode' => $line[0], 'insee' => $line[1], 'name' => $line[3], 'slug' => Str::lower($line[5]), 'region' => Str::lower($line[8]), 'region_code' => $line[7], 'department' => Str::lower($line[10]), 'department_code' => $line[9], 'longitude' => $line[12], 'latitude' => $line[11], 'created_at' => $now, 'updated_at' => $now]; } $this->info('Nombre de villes a importer: ' . count($csv)); do { $max = count($csv) > $this->max_per_request ? $this->max_per_request : count($csv); $slice = array_splice($csv, 0, $max); \DB::table('villes')->insert($slice); } while (count($csv)); }
/** * Execute for city */ private function fireCity() { $this->info('** In progress: cities **'); \DB::table('cities')->truncate(); $filename = realpath(dirname(__FILE__) . '/../../../data/france.csv'); $this->info('Filename: ' . $filename); $fs = new Filesystem(); if (!$fs->exists($filename)) { $this->error("Data file not found", 1); return; } $resource = @fopen($filename, 'r'); if (!$resource) { $this->error(error_get_last(), 1); return; } $headers = fgets($resource); $csv = array(); $now = \Carbon\Carbon::now(); while (null != ($line = fgetcsv($resource, null, ',', '"'))) { if (array(null) === $line) { continue; } // 0:code postal, 1:insee, 2:article, 3:ville, 4:ARTICLE, 5:VILLE, 6:libelle, // 7:region, 8:nom region, 9:dep, 10:nom dep, 11:latitude, 12:longitude, // 13:soundex, 14:metaphone $csv[] = ['postcode' => $line[0], 'insee' => $line[1], 'article' => $line[2], 'name' => $line[3], 'article_up' => $line[4], 'name_up' => $line[5], 'slug' => Str::slug($line[3]), 'clean' => $line[6], 'region' => Str::lower($line[8]), 'region_code' => $line[7], 'department' => Str::lower($line[10]), 'department_code' => $line[9], 'longitude' => $line[12], 'latitude' => $line[11], 'created_at' => $now, 'updated_at' => $now]; } $this->info('Number of cities to import: ' . count($csv)); do { $max = count($csv) > $this->max_per_request ? $this->max_per_request : count($csv); $slice = array_splice($csv, 0, $max); \DB::table('cities')->insert($slice); } while (count($csv)); }
public function generateCasts() { $casts = []; foreach ($this->commandData->inputFields as $field) { switch ($field['fieldType']) { case 'integer': $rule = '"' . Str::lower($field['fieldName']) . '" => "integer"'; break; case 'double': $rule = '"' . Str::lower($field['fieldName']) . '" => "double"'; break; case 'float': $rule = '"' . Str::lower($field['fieldName']) . '" => "float"'; break; case 'boolean': $rule = '"' . Str::lower($field['fieldName']) . '" => "boolean"'; break; case 'string': case 'char': case 'text': $rule = '"' . Str::lower($field['fieldName']) . '" => "string"'; break; default: $rule = ''; break; } if (!empty($rule)) { $casts[] = $rule; } } return $casts; }
/** * @param UploadAvatar $command * @return \Flarum\Core\User * @throws \Flarum\Core\Exception\PermissionDeniedException */ public function handle(UploadAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); if ($actor->id !== $user->id) { $this->assertCan($actor, 'edit', $user); } $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'avatar'); $command->file->moveTo($tmpFile); $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true); $this->validator->assertValid(['avatar' => $file]); $manager = new ImageManager(); $manager->make($tmpFile)->fit(100, 100)->save(); $this->events->fire(new AvatarWillBeSaved($user, $actor, $tmpFile)); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) { $mount->delete($file); } $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $user->save(); $this->dispatchEventsFor($user, $actor); return $user; }
/** * @param UploadAvatar $command * @return \Flarum\Core\Users\User * @throws \Flarum\Core\Exceptions\PermissionDeniedException */ public function handle(UploadAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); // Make sure the current user is allowed to edit the user profile. // This will let admins and the user themselves pass through, and // throw an exception otherwise. if ($actor->id !== $user->id) { $user->assertCan($actor, 'edit'); } $tmpFile = tempnam(sys_get_temp_dir(), 'avatar'); $command->file->moveTo($tmpFile); $manager = new ImageManager(); $manager->make($tmpFile)->fit(100, 100)->save(); event(new AvatarWillBeSaved($user, $actor, $tmpFile)); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) { $mount->delete($file); } $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $user->save(); $this->dispatchEventsFor($user); return $user; }
public function scopeOfType($query, $type) { if ($type === null) { return false; } return $query->whereRaw('lower(`type`) like ?', array(Str::lower($type))); }
/** * {@inheritdoc} */ public function data(ServerRequestInterface $request, Document $document) { $this->assertAdmin($request->getAttribute('actor')); $file = array_get($request->getUploadedFiles(), 'favicon'); $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'favicon'); $file->moveTo($tmpFile); $extension = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION); if ($extension !== 'ico') { $manager = new ImageManager(); $encodedImage = $manager->make($tmpFile)->resize(64, 64, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->encode('png'); file_put_contents($tmpFile, $encodedImage); $extension = 'png'; } $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($this->app->publicPath() . '/assets'))]); if (($path = $this->settings->get('favicon_path')) && $mount->has($file = "target://{$path}")) { $mount->delete($file); } $uploadName = 'favicon-' . Str::lower(Str::quickRandom(8)) . '.' . $extension; $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $this->settings->set('favicon_path', $uploadName); return parent::data($request, $document); }
/** * Display the specified Concept. * GET|HEAD /concepts/{id} * * @param Request $request * @param int $id * @return Response */ public function show(Request $request, $id) { $this->conceptRepository->setPresenter(ConceptPresenter::class); $concept = $this->conceptRepository->apiFindOrFail($id); //concept has to be transformed $response = $this->response(); //todo: move this to middleware in order to handle content negotiation $format = Str::lower($request->get('format', 'json')); $item = $response->item($concept, new ConceptTransformer()); $resource = new Item($concept, new ConceptTransformer()); $properties = []; //make sure we're sending utf-8 //sendResponse always sends json if ('json' == $format) { foreach ($concept->Properties as $conceptProperty) { if ($conceptProperty->profileProperty->has_language) { $properties[$conceptProperty->language][$conceptProperty->ProfileProperty->name] = $conceptProperty->object; } else { $properties[$conceptProperty->ProfileProperty->name] = $conceptProperty->object; } } $result = ['uri' => $concept->uri, 'properties' => $properties]; return $this->sendResponse($result, "Concept retrieved successfully"); } else { //todo: move this to a formatter foreach ($concept->Properties as $conceptProperty) { $properties[$conceptProperty->ProfileProperty->name . '.' . $conceptProperty->language] = $conceptProperty; } ksort($properties, SORT_NATURAL | SORT_FLAG_CASE); //build the xml $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response/>'); $xml->registerXPathNamespace('xml', 'http://www.w3.org/XML/1998/namespace'); $data = $xml->addChild('data'); $data->addAttribute('uri', $concept->uri); $status = $data->addChild('status', $concept->status->display_name); $status->addAttribute('uri', $concept->status->uri); foreach ($properties as $conceptProperty) { $key = $conceptProperty->ProfileProperty->name; if ($conceptProperty->profileProperty->has_language) { $property = $data->addChild($key, $conceptProperty->object); $property->addAttribute('xml:lang', $conceptProperty->language, 'xml'); } else { try { $relatedConcept = $this->conceptRepository->apiFindOrFail($conceptProperty->related_concept_id); } catch (HttpException $e) { } $relatedProperties = []; foreach ($relatedConcept->Properties as $relConceptProperty) { $relatedProperties[$relConceptProperty->ProfileProperty->name . '.' . $relConceptProperty->language] = $relConceptProperty; } $relKey = array_key_exists('prefLabel.en', $relatedProperties) ? 'prefLabel.en' : 'prefLabel.'; $property = $data->addChild($key, $relatedProperties[$relKey]->object); $property->addAttribute('uri', $conceptProperty->object); } } $message = $xml->addChild('message', "Concept retrieved successfully"); return Response::make($xml->asXML(), 200)->header('Content-Type', 'application/xml'); } }
public function saveImage($tmpFile) { $dir = date('Ym/d'); $mount = new MountManager(['source' => new Filesystem(new LocalFS(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new LocalFS(public_path('assets/uploads')))]); $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$dir}/{$uploadName}"); return $this->config['urlPrefix'] . 'uploads/' . $dir . '/' . $uploadName; }
protected function filterColumns($filters) { foreach ($filters as $key => $filter) { $this->collection = $this->collection->filter(function ($row) use($key, $filter) { return strpos(Str::lower($row[$key]), Str::lower($filter)) !== false; }); } }
/** * Display the specified resource. * * @param $link * @return \Illuminate\Http\Response * @internal param int $id */ public function show($link) { $client = new Client(); $baseUrl = 'https://www.youmagine.com/'; $response = $client->get($baseUrl . 'designs/' . $link); $code = $response->getBody(); $xs = Selector::loadHTML($code); // Scrape Youmagine thing information from DOM try { $name = $xs->find('/html/body/div[2]/div/h1')->extract(); $description = $xs->find('//*[@id="information"]/div[2]')->extract(); $files = $xs->findAll('//*[@id="documents"]/div/ul/li[*]/div[3]/div[1]/a')->map(function ($node) { return $node->find('@href')->extract(); }); } catch (NodeNotFoundException $e) { return response()->view('thing.none'); } // Get files $downloadLinks = []; foreach ($files as $file) { $response = $client->get($baseUrl . $file, ['allow_redirects' => false]); $code = $response->getBody(); preg_match('/"(.*?)"/', $code, $downloadLinkMatch); $downloadLinks[] = $downloadLinkMatch[1]; } // Get access token $response = $client->request('POST', 'https://developer.api.autodesk.com/authentication/v1/authenticate', ['form_params' => ['client_id' => env('AUTODESK_CLIENT_ID', ''), 'client_secret' => env('AUTODESK_CLIENT_SECRET', ''), 'grant_type' => 'client_credentials']]); $authToken = json_decode($response->getBody())->access_token; // Create a bucket $bucketKey = Str::lower(Str::random(16)); $response = $client->request('POST', 'https://developer.api.autodesk.com/oss/v2/buckets', ['json' => ['bucketKey' => $bucketKey, 'policyKey' => 'transient'], 'headers' => ['Authorization' => 'Bearer ' . $authToken]]); $bucketKey = json_decode($response->getBody())->bucketKey; // Upload to bucket $bucket = []; foreach ($downloadLinks as $downloadLink) { $fileName = pathinfo($downloadLink)['basename']; $file = fopen(base_path('public/cache/' . $fileName), 'w'); /** @noinspection PhpUnusedLocalVariableInspection */ $response = $client->get($downloadLink, ['sink' => $file]); $file = fopen(base_path('public/cache/' . $fileName), 'r'); $response = $client->request('PUT', 'https://developer.api.autodesk.com/oss/v2/buckets/' . $bucketKey . '/objects/' . $fileName, ['body' => $file, 'headers' => ['Authorization' => 'Bearer ' . $authToken]]); $body = json_decode($response->getBody()); $bucket[] = ['filename' => $body->objectKey, 'urn' => $body->objectId]; } // Set up references $references = ['master' => $bucket[0]['urn'], 'dependencies' => []]; foreach ($bucket as $file) { if ($file['filename'] === $bucket[0]['filename']) { continue; } $references['dependencies'][] = ['file' => $file['urn'], 'metadata' => ['childPath' => $file['filename'], 'parentPath' => $bucket[0]['filename']]]; } $response = $client->post('https://developer.api.autodesk.com/references/v1/setreference', ['json' => $references, 'headers' => ['Authorization' => 'Bearer ' . $authToken]]); // Register data with the viewing services $urn = base64_encode($bucket[0]['urn']); $response = $client->post('https://developer.api.autodesk.com/viewingservice/v1/register', ['json' => ['urn' => $urn], 'headers' => ['Authorization' => 'Bearer ' . $authToken]]); return response()->view('thing.show', compact('name', 'description', 'urn', 'authToken') + ['pollUrl' => 'https://developer.api.autodesk.com/viewingservice/v1/' . $urn, 'dl' => $downloadLinks[0]]); }
/** * @param $value * @return bool */ public function check($value) { $store = $this->session->get('captcha'); if ($this->sensitive) { $value = $this->str->lower($value); $store = $this->str->lower($store); } return $this->hasher->check($value, $store); }
/** * * @param $value * @return bool */ public function check($value) { $store = $this->session->get('captcha' . (Input::has('captcha_id') ? '_' . Input::get('captcha_id') : '')); if ($this->sensitive) { $value = $this->str->lower($value); $store = $this->str->lower($store); } return $this->hasher->check($value, $store); }
/** * Execute the console command. * * @return mixed */ public function fire() { $name = $this->argument('name'); $modelName = Str::studly($this->argument('name')); $tableName = 'crud_' . Str::lower($name); $this->call('crud:migration', ['name' => $name]); $this->call('crud:model', ['name' => $modelName, '--table' => $tableName]); $this->call('crud:controller', ['name' => $modelName]); $this->call('crud:permission', ['name' => $modelName]); }
/** * Retourne une liste d'universitées * completant les premiers caractères d'une recherche */ public function univ() { $term = Str::lower(Input::get('term')); $data = DB::table("universite")->distinct('nomUniv', 'idUniv')->where('nomUniv', 'like', $term . '%')->take(10)->get(); $jsonArr = array(); foreach ($data as $value) { $jsonArr[] = array('value' => $value->nomUniv); } return Response::json($jsonArr); }
private function generateFields() { $fieldTemplate = $this->commandData->templatesHelper->getTemplate('field.blade', $this->viewsPath); $fieldsStr = ''; foreach ($this->commandData->inputFields as $field) { switch ($field['type']) { case 'text': $fieldsStr .= FormFieldsGenerator::text($fieldTemplate, $field) . "\n\n"; break; case 'textarea': $fieldsStr .= FormFieldsGenerator::textarea($fieldTemplate, $field) . "\n\n"; break; case 'password': $fieldsStr .= FormFieldsGenerator::password($fieldTemplate, $field) . "\n\n"; break; case 'email': $fieldsStr .= FormFieldsGenerator::email($fieldTemplate, $field) . "\n\n"; break; case 'file': $fieldsStr .= FormFieldsGenerator::file($fieldTemplate, $field) . "\n\n"; break; case 'checkbox': $fieldsStr .= FormFieldsGenerator::checkbox($fieldTemplate, $field) . "\n\n"; break; case 'radio': $fieldsStr .= FormFieldsGenerator::radio($fieldTemplate, $field) . "\n\n"; break; case 'number': $fieldsStr .= FormFieldsGenerator::number($fieldTemplate, $field) . "\n\n"; break; case 'date': if ($this->commandData->fromTable) { $fieldsStr .= FormFieldsGenerator::date2($fieldTemplate, $field) . "\n\n"; } else { $fieldsStr .= FormFieldsGenerator::date($fieldTemplate, $field) . "\n\n"; } break; case 'select': if ($this->commandData->fromTable) { $modelName = Str::lower(Str::singular($this->commandData->modelName)); $fieldsStr .= FormFieldsGenerator::select2($fieldTemplate, $field, false, $modelName) . "\n\n"; } else { $fieldsStr .= FormFieldsGenerator::select($fieldTemplate, $field) . "\n\n"; } break; } } $templateData = $this->commandData->templatesHelper->getTemplate('fields.blade', $this->viewsPath); $templateData = str_replace('$FIELDS$', $fieldsStr, $templateData); $templateData = str_replace('$MODEL_NAME_PLURAL_CAMEL$', $this->commandData->modelNamePluralCamel, $templateData); $fileName = 'fields.blade.php'; $path = $this->path . $fileName; $this->commandData->fileHelper->writeFile($path, $templateData); $this->commandData->commandObj->info('field.blade.php created'); }
public function getGetdata() { $term = Str::lower(Input::get('term')); $data = array('R' => 'Red', 'O' => 'Orange', 'Y' => 'Yellow', 'G' => 'Green', 'B' => 'Blue', 'I' => 'Indigo', 'V' => 'Violet'); $return_array = array(); foreach ($data as $k => $v) { if (strpos(Str::lower($v), $term) !== FALSE) { $return_array[] = array('value' => $v, 'id' => $k); } } return Response::json($return_array); }
/** * Captcha check * * @param $value * @return bool */ public function check($value) { if (!$this->session->has('captcha')) { return false; } $key = $this->session->get('captcha.key'); if (!$this->session->get('captcha.sensitive')) { $value = $this->str->lower($value); } $this->session->remove('captcha'); return $this->hasher->check($value, $key); }
public function saveImage($tmpFile) { $upManager = new UploadManager(); $auth = new Auth($this->config['accessToken'], $this->config['secretToken']); $token = $auth->uploadToken($this->config['bucketName']); $uploadName = date('Y/m/d/') . Str::lower(Str::quickRandom()) . '.jpg'; list($ret, $error) = $upManager->put($token, $uploadName, file_get_contents($tmpFile)); if (!$ret) { throw new Exception($error->message()); } return rtrim($this->config['baseUrl'], '/') . '/' . $uploadName; }
/** * Get rows count * * @return int */ public function count() { $connection = $this->query->getConnection(); $myQuery = clone $this->query; // if its a normal query ( no union, having and distinct word ) // replace the select with static text to improve performance if (!Str::contains(Str::lower($myQuery->toSql()), ['union', 'having', 'distinct', 'order by', 'group by'])) { $row_count = $connection->getQueryGrammar()->wrap('row_count'); $myQuery->select($connection->raw("'1' as {$row_count}")); } return $connection->table($connection->raw('(' . $myQuery->toSql() . ') count_row_table'))->setBindings($myQuery->getBindings())->count(); }
/** * Replace the model for the given stub. * * @param string $stub * @param string $model * @return string */ protected function replaceModel($stub, $model) { $model = str_replace('/', '\\', $model); if (Str::startsWith($model, '\\')) { $stub = str_replace('NamespacedDummyModel', trim($model, '\\'), $stub); } else { $stub = str_replace('NamespacedDummyModel', $this->laravel->getNamespace() . $model, $stub); } $model = class_basename(trim($model, '\\')); $stub = str_replace('DummyModel', $model, $stub); $stub = str_replace('dummyModelName', Str::lower($model), $stub); return str_replace('dummyPluralModelName', Str::plural(Str::lower($model)), $stub); }
private function createPermissionsFor($ControllerName = '') { $permissions = ['create' => 'Grants create new item permission', 'read' => 'Grants permission to read data from this module', 'update' => 'Grants permission to edit the data in this module', 'delete' => 'Grants permission to delete data from this module']; foreach ($permissions as $permission => $description) { $permission = $ControllerName . ':' . $permission; $model = new Permission(); $model->name = $permission; $model->slug = Str::lower($permission); $model->description = $description; $model->save(); $this->info($permission . ' permission created'); } }
/** * Execute the console command. * * @return void */ public function handle() { if (!$this->confirmToProceed()) { return; } $group = Str::lower($this->argument('group')); $id = Str::lower($this->argument('id')); $theme = $this->getAvailableTheme($group)->get($id); if ($this->validateProvidedTheme($group, $id, $theme)) { $this->laravel['orchestra.memory']->set("site.theme.{$group}", $theme->get('uid')); $this->info("Theme [{$theme->get('name')}] activated on group [{$group}]."); } }
/** * Setup variables and file systems (basically constructor, * but actual trait __contruct()'s are bad apparently) */ private function setup() { $this->public_path = rtrim(config('media.config.public_path'), '/\\') . '/'; $this->files_directory = rtrim(ltrim(config('media.config.files_directory'), '/\\'), '/\\') . '/'; $this->create_sub_directories = config('media.config.sub_directories'); $this->directory = $this->public_path . $this->files_directory; if ($this->create_sub_directories) { $this->directory_uri = Str::lower(class_basename($this)) . '/'; } $this->directory .= $this->directory_uri; if (!empty($this->file)) { $this->filename_original = $this->file->getClientOriginalName(); $this->filename_new = $this->getFilename(); } }
/** * Set attributes to upper case automatically */ public function selfUpperCase() { if (is_array($this->attributes)) { foreach ($this->attributes as $field => $value) { if (is_string($value)) { if (property_exists($this, 'guardedCase')) { if (!in_array($field, $this->guardedCase)) { $this->{$field} = Str::lower($value); } } else { $this->{$field} = Str::lower($value); } } } } }
public function handle(Request $request) { $images = $request->http->getUploadedFiles()['images']; $results = []; foreach ($images as $image_key => $image) { $tmpFile = tempnam(sys_get_temp_dir(), 'image'); $image->moveTo($tmpFile); $urlGenerator = app('Flarum\\Http\\UrlGeneratorInterface'); $dir = 'uploads/' . date('Ym/d'); $path = './assets/' . $dir; $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($path))]); $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $results['img_' . $image_key] = Core::url() . '/assets/' . $dir . '/' . $uploadName; } return new JsonResponse($results); }
public function videoSearch() { $keywords = Input::get('keywords'); $group = Input::get('group'); $searchResult = new Collection(); $videos = Video::orderBy('created_at', 'desc')->get(); if ($keywords != '') { foreach ($videos as $video) { if (Str::contains(Str::lower($video->title), Str::lower($keywords))) { $searchResult->add($video); } } } else { $searchResult = $videos; } return view('bushido::admin.videoSearch')->with('videos', $searchResult)->with('group', $group); }
/** * Create a new repository. * * @param string $model * @return void */ public function create($model) { $model = $this->sanitize($model); $model = ucfirst(Str::studly($model)); $repositoryInterface = Str::studly($model . 'RepositoryInterface'); $repositoryName = Str::studly($model . 'Repository'); $stub = $this->getStub('repository-interface.stub'); $content = $this->prepare($stub, ['model' => $model, 'lower_model' => Str::lower($model), 'class_name' => $repositoryName, 'repository_interface' => $repositoryInterface]); $filePath = $this->path . "/src/Repositories/{$model}/"; $this->ensureDirectory($filePath); $this->files->put($filePath . $repositoryInterface . '.php', $content); $stub = $this->getStub('repository.stub'); $content = $this->prepare($stub, ['model' => $model, 'lower_model' => Str::lower($model), 'class_name' => $repositoryName, 'repository_interface' => $repositoryInterface]); $this->files->put($filePath . $repositoryName . '.php', $content); // Write event handler interface $stub = $this->getStub('event-handler-interface.stub'); $content = $this->prepare($stub, ['model' => $model, 'lower_model' => Str::lower($model)]); $handlerPath = $this->path . "/src/Handlers/{$model}/"; $this->ensureDirectory($handlerPath); $this->files->put($handlerPath . $model . 'EventHandlerInterface.php', $content); // Write event handler $stub = $this->getStub('event-handler.stub'); $content = $this->prepare($stub, ['model' => $model, 'lower_model' => Str::lower($model)]); $this->files->put($handlerPath . $model . 'EventHandler.php', $content); // Write data handler interface $stub = $this->getStub('data-handler-interface.stub'); $content = $this->prepare($stub, ['model' => $model]); $handlerPath = $this->path . "/src/Handlers/{$model}/"; $this->ensureDirectory($handlerPath); $this->files->put($handlerPath . $model . 'DataHandlerInterface.php', $content); // Write data handler $stub = $this->getStub('data-handler.stub'); $content = $this->prepare($stub, ['model' => $model]); $this->files->put($handlerPath . $model . 'DataHandler.php', $content); // Write validator interface $stub = $this->getStub('validator-interface.stub'); $content = $this->prepare($stub, ['model' => $model, 'lower_model' => Str::lower($model)]); $validatorPath = $this->path . "/src/Validator/{$model}/"; $this->ensureDirectory($validatorPath); $this->files->put($validatorPath . $model . 'ValidatorInterface.php', $content); // Write validator $stub = $this->getStub('validator.stub'); $content = $this->prepare($stub, ['model' => $model]); $this->files->put($validatorPath . $model . 'Validator.php', $content); }
/** * Upload provided file and create matching FileRecord object * * @param UploadedFile $file * @param $clientIp * @return FileRecord */ public function uploadFile(UploadedFile $file, $clientIp) { $extension = Str::lower($file->getClientOriginalExtension()); $generatedName = $this->generateName($extension); // Create SHA-256 hash of file $fileHash = hash_file('sha256', $file->getPathname()); // Check if file already exists $existingFile = FileRecord::where('hash', '=', $fileHash)->first(); if ($existingFile) { return $existingFile; } // Query previous scans in VirusTotal for this file if (config('virustotal.enabled') === true) { $this->checkVirusTotalForHash($fileHash); } // Get filesize $filesize = $file->getSize(); // Check max upload size $maxUploadSize = config('upload.max_size'); if ($filesize > $maxUploadSize) { throw new MaxUploadSizeException(); } // Move the file $uploadDirectory = config('upload.directory'); $file->move($uploadDirectory, $generatedName); // Create the record /** @var FileRecord $record */ $record = FileRecord::create(['client_name' => $file->getClientOriginalName(), 'generated_name' => $generatedName, 'filesize' => $filesize, 'hash' => $fileHash, 'uploaded_by_ip' => $clientIp]); return $record; }