public function doRegister(Request $request) { $validator = Validator::make($data = $request->all(), Admin::$rules, Admin::$messages); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } if ($validator->passes()) { $confirmation_code = Str::quickRandom(30); $admin = new Admin(); $admin->fullname = ucwords($request->fullname); $admin->mobile_no = $request->mobile_no; $admin->email = $request->email; $admin->password = bcrypt($request->password); $admin->confirmation_code = $confirmation_code; $data = ['confirmation_code' => $confirmation_code, 'username' => $request->username, 'password' => $request->password, 'mobile_no' => $request->mobile_no]; Basehelper::sendSMS($request->mobile_no, 'Hello ' . $request->username . ', you have successfully registere. Your username is ' . $request->username . ' and password is ' . $request->password); // Mail::send('emails.verify', $data, function($message) use ($admin, $data){ // $message->from('no-reply@employment_bank', 'Employment Bank'); // $message->to(Input::get('email'), $admin->name) // ->subject('Verify your email address'); // }); if (!$admin->save()) { return Redirect::back()->with('message', 'Error while creating your account!<br> Please contact Technical Support'); } return Redirect::route('admin.login')->with('message', 'Account has been created!<br>Now Check your email address to verify your account by checking your spam folder or inboxes for verification link after that you can login'); //sendConfirmation() Will go the email and sms as needed } else { return Redirect::back()->withInput()->withErrors($validation); // ->with('message', 'There were validation errors.'); } }
/** * Search for physicians. * * @return JSON */ public function search(Request $request) { $physicians = null; $searchDistance = $request->distance ? $request->distance : 0; $coords = $this->getCoordinates($request); $orderBy = $request->has('order_by') ? $request->order_by : 'distance'; $sort = $request->has('sort') ? $request->sort : 'asc'; $limit = $request->has('per_page') ? $request->per_page : '25'; // if we don't have a requested distance, we'll cycle through // our fallback distances until we get at least 1 result; // if we don't have anything by our max distance, we'll return 0. if (!$request->has('distance')) { while (!$physicians || $physicians->count() == 0) { $searchDistance = $this->getNextDistance($searchDistance); $physicians = Physician::withinDistance($coords['lat'], $coords['lon'], $searchDistance)->alias($request->alias_id)->name($request->q)->gender($request->gender); if ($searchDistance == $this->maxDistance) { break; } } } else { $physicians = Physician::withinDistance($coords['lat'], $coords['lon'], $searchDistance)->alias($request->alias_id)->name($request->q)->gender($request->gender); } $alias = Alias::find($request->alias_id); $queryMeta = ['city' => Str::title(urldecode($request->city)), 'state' => mb_strtoupper($request->state), 'zip' => $request->zip ? $request->zip : $this->getZip($request->city, $request->state), 'alias' => $alias ? $alias->alias : null, 'alias_id' => $alias ? $alias->id : null, 'aggregate' => AggregateReporter::report($physicians, $request->alias_id), 'q' => $request->q, 'gender' => $request->gender, 'count' => $physicians ? $physicians->count() : 0, 'radius' => $searchDistance, 'order_by' => $request->order_by, 'sort' => $request->sort, 'center' => ['lat' => $coords['lat'], 'lon' => $coords['lon']]]; $physicians = $physicians->orderBy($orderBy, $sort)->paginate($limit)->appends($request->query()); return $this->response->withPaginator($physicians, new PhysicianTransformer(), null, $queryMeta); }
/** * Overrides the models boot method. */ public static function boot() { parent::boot(); self::creating(function ($tag) { $tag->slug = Str::slug($tag->name); }); }
public function run() { DB::table('projects')->delete(); Project::create(['name' => 'Deployer', 'hash' => Str::random(60), 'repository' => 'https://github.com/REBELinBLUE/deployer.git', 'url' => 'http://deploy.app', 'group_id' => 2, 'private_key' => '-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAmrMjtajVvmd99T8xwUNrIFbrzSmZ6VCM89hfm4Ut9atv29gG l2HFPJY7VtslXDJVL67w5EUMspy82tkAX7F03iaarSsbo6nC16UTfbfNTi44Snm0 T/5RMavSOnOMRJ8BQcfzqge4oIQzVGXOs0YvNFdSt4paBp9dssKS+7yP/hDvgAVz +LE3IcIeO26aXATcuB4zq3vjaqSzWZGdNhOJZ4EmjgmOq9+k3SAmooHkF+p/14MJ tq0ZK9KjSGbHfyKMi2EuvwllFCY19eqsV7dcMDIsMKUW2diFC52dJSO+EF47nA/j sNDisFsIC7DeeVVBl1TpaV9RidqeZmdx+mF9AQIDAQABAoIBAH4qhYAdTx03eGGw hVqSKmc4nJ05RX4kJKCmoerLZh1LETJh75Y8tchg2cpPdhvILPNzoKD6s41kCR4P BqAEsUSQhWufka4bwH1w8wGACp+tUFllAqqOxhdVg2IKZKZ+a18DvPS50ViQGPDH CxnorozoftyTqDJofNlSmN9X/LN+RZ1zRJRaPkBvSkYOCT4gnJLmHLGN7eJsHQeR EJe83E4VPZ+2faBHEigXAHc4rh63iRxmmqqlcrItXzONZZUOjXwBNqZs4aVl+DZd 1pPiB9nOT9zLiy9ZwHZfIRIF3LkWAVsIkzOPDw9wLNgzI60uiLlYY1ODua8maqDP m5eOT7ECgYEAzbVdEVngZd/jRlAo/LOLyy6NbZP4fli26hZjJBAJ8HhI93JEcxts l/1E3rUME2a+F8CQ5FlGP02k66sB5lhzCg81Ym4fxbIP1n09IPmaRzSdM55SpbFy 7OV4VyrJKl7g2Y/utdb17DjYGovu+HX978j1iOH8qUruwAZyWshqdW0CgYEAwIVO AohxuytN1GlQW4byQvHO4y+AXtZJ4iuBiyOqGhYs8bcnbV3+B0UTHtJyM8Novzj6 OcgiCEHP0Kj6Lj9RYu2sBvsgyfxEURdkHD7DPpYKlheCd7I1a9qk4/UyGx11YdnP bcqrxv6e2FPBXNZGTXGBmHtIItxHYBEehguRLWUCgYALpR61or7fRYNaMaOAWrGp OONstpm0nVUNf2LxYa8OW+DVkTRqx7yoBgBmEx2x43kTYyVQp/UgFEcnyDB9V7h7 c0z0W4OU73WSENjrCvY+3a2ghG/tTVRSMNNVK+jjayeTaWB8DsUxMC6bohxPGG7d qiSsMQ7ajpFhcXv7w6izKQKBgQC+Pz0+vYz+NCXeQRAa0nj29LPIx7kofsRWTz3d vKmsy7swRhkdN6P/lR/29mnKg1EwnmKP1RjkZfyyKznHl+SaSVoVL/dQAw2TwPS6 AL+6SlU9yw+vrxihc1g8uKICL5M+1hnoWj50EEvyZJoRXuHsR72UbEd1w454/ZHX TvjxDQKBgCtikMNAqTParY/tX0xNohD7+svTKZt92CxW7Q/17H26ehFKUQvw6Agd ulR2AVTGi6STEgzXf6UP5CAVhYRw9irCAQYpceL0GVzfZPQsXyLuMCnJ8UD6CBRn i5vkNY4OZdOuEV9boFOFYa58WRNK7vthHkZJj++Amu3dZ6RHBlLQ -----END RSA PRIVATE KEY-----', 'public_key' => 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCasyO1qNW+Z331PzHBQ2sgVuvNKZnpUIzz2F+bhS31q2/b2Aa' . 'XYcU8ljtW2yVcMlUvrvDkRQyynLza2QBfsXTeJpqtKxujqcLXpRN9t81OLjhKebRP/lExq9I6c4xEnwFBx/OqB7' . 'ighDNUZc6zRi80V1K3iloGn12ywpL7vI/+EO+ABXP4sTchwh47bppcBNy4HjOre+NqpLNZkZ02E4lngSaOCY6r3' . '6TdICaigeQX6n/Xgwm2rRkr0qNIZsd/IoyLYS6/CWUUJjX16qxXt1wwMiwwpRbZ2IULnZ0lI74QXjucD+Ow0OKw' . 'WwgLsN55VUGXVOlpX1GJ2p5mZ3H6YX0B deploy@deployer', 'last_run' => null, 'build_url' => 'http://ci.rebelinblue.com/build-status/image/3?branch=master']); }
/** * {@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); }
public static function slug($name) { $extension = self::getExtension($name); $name = str_replace($extension, '', $name); $name = Str::slug($name); return $name . strtolower($extension); }
/** * Gets the value of an environment variable. Supports boolean, empty and null. * * @param string $key * @param mixed $default * * @return mixed */ function env($key, $default = null) { $value = getenv($key); if ($value === false) { return value($default); } switch (strtolower($value)) { case 'true': case '(true)': return true; case 'false': case '(false)': return false; case 'empty': case '(empty)': return ''; case 'null': case '(null)': return; } if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) { return substr($value, 1, -1); } return $value; }
/** * Upload un torrent * * @access public * @return View torrent.upload * */ public function upload() { $user = Auth::user(); // Post et fichier upload if (Request::isMethod('post')) { // No torrent file uploaded OR an Error has occurred if (Input::hasFile('torrent') == false) { Session::put('message', 'You must provide a torrent for the upload'); return View::make('torrent.upload', array('categories' => Category::all(), 'user' => $user)); } else { if (Input::file('torrent')->getError() != 0 && Input::file('torrent')->getClientOriginalExtension() != 'torrent') { Session::put('message', 'An error has occurred'); return View::make('torrent.upload', array('categories' => Category::all(), 'user' => $user)); } } // Deplace et decode le torrent temporairement TorrentTools::moveAndDecode(Input::file('torrent')); // Array from decoded from torrent $decodedTorrent = TorrentTools::$decodedTorrent; // Tmp filename $fileName = TorrentTools::$fileName; // Info sur le torrent $info = Bencode::bdecode_getinfo(getcwd() . '/files/torrents/' . $fileName, true); // Si l'announce est invalide ou si le tracker et privée if ($decodedTorrent['announce'] != route('announce', ['passkey' => $user->passkey]) && Config::get('other.freeleech') == true) { Session::put('message', 'Your announce URL is invalid'); return View::make('torrent.upload', array('categories' => Category::all(), 'user' => $user)); } // Find the right category $category = Category::find(Input::get('category_id')); // Create the torrent (DB) $torrent = new Torrent(['name' => Input::get('name'), 'slug' => Str::slug(Input::get('name')), 'description' => Input::get('description'), 'info_hash' => $info['info_hash'], 'file_name' => $fileName, 'num_file' => $info['info']['filecount'], 'announce' => $decodedTorrent['announce'], 'size' => $info['info']['size'], 'nfo' => Input::hasFile('nfo') ? TorrentTools::getNfo(Input::file('nfo')) : '', 'category_id' => $category->id, 'user_id' => $user->id]); // Validation $v = Validator::make($torrent->toArray(), $torrent->rules); if ($v->fails()) { if (file_exists(getcwd() . '/files/torrents/' . $fileName)) { unlink(getcwd() . '/files/torrents/' . $fileName); } Session::put('message', 'An error has occured may bee this file is already online ?'); } else { // Savegarde le torrent $torrent->save(); // Compte et sauvegarde le nombre de torrent dans cette catégorie $category->num_torrent = Torrent::where('category_id', '=', $category->id)->count(); $category->save(); // Sauvegarde les fichiers que contient le torrent $fileList = TorrentTools::getTorrentFiles($decodedTorrent); foreach ($fileList as $file) { $f = new TorrentFile(); $f->name = $file['name']; $f->size = $file['size']; $f->torrent_id = $torrent->id; $f->save(); unset($f); } return Redirect::route('torrent', ['slug' => $torrent->slug, 'id' => $torrent->id])->with('message', trans('torrent.your_torrent_is_now_seeding')); } } return View::make('torrent.upload', array('categories' => Category::all(), 'user' => $user)); }
protected function initValidator() { $class = $this->getValidatorClass(); if ($class) { $validator = new $class(); $this->validator_messages = $validator->messages(); $this->validator_rules = $validator->rules(); foreach ($this->validator_rules as $element_name => $element_rules) { if (false !== mb_strpos($element_name, '.')) { $element_name = str_replace('.', '][', $element_name) . ']'; $e = explode(']', $element_name, 2); $element_name = implode('', $e); } foreach ($this->getElementsByName($element_name) as $el) { $element_rules = explode('|', $element_rules); foreach ($element_rules as $rule) { $_rule = explode(':', $rule); $rule_name = Arr::get($_rule, 0); $rule_params = Arr::get($_rule, 1); $rule_params = explode(',', $rule_params); $method = Str::camel('rule_' . $rule_name); if (method_exists($el, $method)) { call_user_func_array([$el, $method], $rule_params); } } } } } return $this; }
/** * Generates a random token * * @param String $str [description] * * @return String [description] */ function token($str = null) { $str = isset($str) ? $str : \Illuminate\Support\Str::random(); $value = str_shuffle(sha1($str . microtime(true))); $token = hash_hmac('sha1', $value, env('APP_KEY')); return $token; }
/** * Generate a random key for the application. * * @param string $cipher * @return string */ protected function getRandomKey($cipher) { if ($cipher === 'AES-128-CBC') { return Str::random(16); } return Str::random(32); }
public function initVariables() { $this->modelNamePlural = Str::plural($this->modelName); $this->modelNameCamel = Str::camel($this->modelName); $this->modelNamePluralCamel = Str::camel($this->modelNamePlural); $this->initDynamicVariables(); }
public function setNameAttribute($value) { $this->attributes['name'] = trim($value); if (!$this->slug) { $this->attributes['slug'] = Str::slug($value); } }
public function run() { $films = []; $faker = Faker\Factory::create('es_MX'); for ($i = 0; $i < self::AMOUNT; $i++) { $film = array(); $film['title'] = implode(' ', $faker->words(rand(3, 6))); $film['slug'] = \Illuminate\Support\Str::slug($film['title']) . '-' . rand(0, 4); $film['original_title'] = 'Original' . $film['title']; $film['years'] = self::getListOfYears(); $film['duration'] = $faker->time(); $film['genre_id'] = rand(0, 10); $film['director'] = self::getListOfNames($faker); $film['script'] = self::getListOfNames($faker); $film['photographic'] = self::getListOfNames($faker); $film['music'] = self::getListOfNames($faker); $film['edition'] = self::getListOfNames($faker); $film['production'] = self::getListOfNames($faker); $film['cast'] = self::getListOfNames($faker); $film['synopsis'] = $faker->paragraphs(rand(1, 5), true); $film['notes'] = $faker->paragraphs(rand(0, 6), true); $film['trailer'] = '<iframe width="560" height="315" src="https://www.youtube.com/embed/Gjg_Mi0zLlg" frameborder="0" allowfullscreen></iframe>'; $film['created_at'] = new DateTime(); $film['updated_at'] = new DateTime(); array_push($films, $film); } DB::table('films')->truncate(); DB::table('films')->insert($films); }
/** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveByCredentials(array $credentials) { if (empty($credentials)) { return null; } $index = null; $values = null; foreach ($credentials as $key => $value) { if (!Str::contains($key, 'password')) { $index = is_null($index) ? $key : $index . '_' . $key; $values = is_null($values) ? [] : $values; $values[] = $value; } } if (is_null($index) || is_null($values)) { return null; } $values = count($values) == 1 ? $values[0] : $values; $result = $this->createModel()->newQuery()->getQuery()->r()->getAll($values, ['index' => $index])->run(); $result = $this->hydrate($result); if ($result) { $result = $result->first(); } return $result; }
/** * Update the model in the database. * * @param array $attributes * @return bool|int */ public function update(array $attributes = []) { if (isset($attributes['alias']) && empty($attributes['alias'])) { $name = $this->name; if (isset($attributes['name'])) { $name = $attributes['name']; } $attributes['alias'] = Str::slug($name) . '-' . Uuid::generate(4); } if (isset($attributes['galleries'])) { if (empty($attributes['galleries'])) { $attributes['galleries'] = []; } $attributes['galleries'] = json_encode($attributes['galleries']); } if (isset($attributes['attributes'])) { if (empty($attributes['attributes'])) { $attributes['attributes'] = []; } $attributes['attributes'] = json_encode($attributes['attributes']); } if (!parent::update($attributes)) { throw new Exception('Cannot update product.'); } return $this; }
/** * Send the given notification. * * @param mixed $notifiable * @param \Illuminate\Notifications\Notification $notification * @return void */ public function send($notifiable, Notification $notification) { if (!$notifiable->routeNotificationFor('mail')) { return; } $message = $notification->toMail($notifiable); if ($message instanceof Mailable) { return $message->send($this->mailer); } $this->mailer->send($message->view, $message->data(), function ($m) use($notifiable, $notification, $message) { $recipients = empty($message->to) ? $notifiable->routeNotificationFor('mail') : $message->to; if (!empty($message->from)) { $m->from($message->from[0], isset($message->from[1]) ? $message->from[1] : null); } if (is_array($recipients)) { $m->bcc($recipients); } else { $m->to($recipients); } $m->subject($message->subject ?: Str::title(Str::snake(class_basename($notification), ' '))); foreach ($message->attachments as $attachment) { $m->attach($attachment['file'], $attachment['options']); } foreach ($message->rawAttachments as $attachment) { $m->attachData($attachment['data'], $attachment['name'], $attachment['options']); } }); }
/** * Authenticate the incoming request for a given channel. * * @param \Illuminate\Http\Request $request * @return mixed */ public function auth($request) { if (Str::startsWith($request->channel_name, ['private-', 'presence-']) && !$request->user()) { throw new HttpException(403); } return parent::verifyUserCanAccessChannel($request, str_replace(['private-', 'presence-'], '', $request->channel_name)); }
/** * Run migrations for the specified module. * * @param string $slug * @return mixed */ protected function migrate($slug) { $moduleName = Str::studly($slug); if ($this->module->exists($slug)) { $pretend = $this->option('pretend'); $path = $this->getMigrationPath($slug); $this->migrator->run($path, $pretend); // Once the migrator has run we will grab the note output and send it out to // the console screen, since the migrator itself functions without having // any instances of the OutputInterface contract passed into the class. foreach ($this->migrator->getNotes() as $note) { if (!$this->option('quiet')) { $this->output->writeln($note); } } // Finally, if the "seed" option has been given, we will re-run the database // seed task to re-populate the database, which is convenient when adding // a migration and a seed at the same time, as it is only this command. if ($this->option('seed')) { $this->call('module:seed', ['module' => $slug, '--force' => true]); } } else { return $this->error("Module [{$moduleName}] does not exist."); } }
/** * Edite l'article voulu * * @access public * @param $slug Slug de l'article à édité * @param $id Id de l'article * @return post.admin_edit_post */ public function edit($slug, $id) { $post = Article::find($id); if (Request::isMethod('post')) { $input = Input::all(); $post->title = $input['title']; $post->slug = Str::slug($post->title); $post->content = $input['content']; //$post->user_id = Auth::user()->id; // Verifie qu'une image à était upload if (Input::hasFile('image') && Input::file('image')->getError() == 0) { // Le fichier est bien une image if (in_array(Input::file('image')->getClientOriginalExtension(), array('jpg', 'jpeg', 'bmp', 'png', 'tiff'))) { // Déplace et ajoute le nom à l'objet qui sera sauvegarder $post->image = 'article-' . uniqid() . '.' . Input::file('image')->getClientOriginalExtension(); Input::file('image')->move(getcwd() . '/files/img/', $post->image); } else { // Image null car invalide ou mauvais format $post->image = null; } } else { // Erreur sur l'image donc null $post->image = null; } $v = Validator::make($post->toArray(), $post->rules); if ($v->fails()) { Session::put('message', 'An error has occured'); } else { $post->save(); return Redirect::route('admin_article_index')->with('message', 'Your article has been modified'); } } return View::make('Admin.article.edit', array('post' => $post)); }
/** * @param string $name * @param int $size * @param string $background_color * @param string $text_color * @param string $font_file * @return ImageManagerStatic * @throws Exception */ public static function create($name = '', $size = 512, $background_color = '#666', $text_color = '#FFF', $font_file = '../../../font/OpenSans-Semibold.ttf') { if (strlen($name) <= 0) { throw new Exception('Name must be at least 2 characters.'); } if ($size <= 0) { throw new Exception('Input must be greater than zero.'); } if ($font_file === '../../../font/OpenSans-Semibold.ttf') { $font_file = __DIR__ . "/" . $font_file; } if (!file_exists($font_file)) { throw new Exception("Font file not found"); } $str = ""; $name_ascii = strtoupper(Str::ascii($name)); $words = preg_split("/[\\s,_-]+/", $name_ascii); if (count($words) >= 2) { $str = $words[0][0] . $words[1][0]; } else { $str = substr($name_ascii, 0, 2); } $img = ImageManagerStatic::canvas($size, $size, $background_color)->text($str, $size / 2, $size / 2, function ($font) use($size, $text_color, $font_file) { $font->file($font_file); $font->size($size / 2); $font->color($text_color); $font->align('center'); $font->valign('middle'); }); return $img; }
/** * Install the components. * * @return void */ public function install() { if (Str::contains(file_get_contents(base_path('.env')), 'AUTHY_SECRET')) { return; } (new Filesystem())->append(base_path('.env'), file_get_contents(SPARK_HEX_STUB_PATH . '/.env')); }
/** * Add a root if the URL is relative (helper method of the hasLink function). * * @return string */ protected function absoluteUrl() { if (!Str::startsWith($this->url, ['http', 'https'])) { return URL::to($this->url); } return $this->url; }
/** * @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; }
/** * Get the authorization bearer token from the headers, useful when AUTHing a user hitting the API that * has already logged in. */ public function getTokenFromHeaders() { $bearer = Request::header('authorization'); if (Str::startsWith($bearer, 'Bearer ')) { $this->token = Str::substr($bearer, 7); } }
/** * Render a menu structure from the database * * @param string $menukey * @return string|null */ public function make($menukey) { $menukey = Str::slug($menukey); $menu = Menu::where('slug', '=', $menukey)->first(); $renderer = new LavarySidebarRenderer(); return $renderer->renderToHtml($menu); }
public function testMap() { $router = new Router(new Dispatcher()); $mapper = $this->make(); $mapper->map($router); $routes = $router->getRoutes(); $controllers = $this->getControllers(); $this->assertGreaterThan(0, $routes->count(), 'Each mapper should define at least one route.'); /** @var Route $route */ foreach ($routes as $route) { $name = $route->getPath(); // Check that it has a controller if (!array_key_exists('controller', $route->getAction())) { $this->fail('Route: ' . $name . ' has an invalid handler.' . ' Only use controller handlers.'); } $parts = explode('@', $route->getAction()['controller']); // Check that it is controller@method definition if (count($parts) < 2) { $this->fail('Route: ' . $name . ' has an invalid handler: ' . $route->getActionName() . '. Only use controller@method handlers.'); } // Check it begins with an HTTP method if (!Str::startsWith($parts[1], $this->methods)) { $this->fail('Route: ' . $name . ' has an invalid handler name: ' . $route->getActionName() . '. The handler name should begin with an HTTP method.'); } // Make sure the controller is white-listed if (!in_array($parts[0], $controllers)) { $this->fail('Route: ' . $name . ' has an invalid controller' . '. Make sure the test matches the directory controllers.'); } // Make sure the class method exists if (!method_exists($parts[0], $parts[1])) { $this->fail('Route: ' . $name . ' has an invalid handler.' . ' Make sure the method exists.'); } } }
/** * @param \Lio\Accounts\User $user * @param \Lio\Accounts\UserUpdaterListener $listener * @param array $data * @return mixed */ private function updateUser(User $user, UserUpdaterListener $listener, array $data) { $oldEmail = $user->email; $user->fill($data); // If the email changed, the user will need to re-confirm it. if ($data['email'] !== $oldEmail) { $user->confirmed = false; // Set a confirmation code for the user. He'll need to verify his email address // with this code before he can use certain sections on the website. $confirmationCode = Str::random(30); // We'll generate a new one if we find a user with the same code. while ($this->users->getByConfirmationCode($confirmationCode) !== null) { $confirmationCode = Str::random(30); } $user->confirmation_code = $confirmationCode; } // check the model validation if (!$this->users->save($user)) { return $listener->userValidationError($user->getErrors()); } // Send a confirmation email to the user. if ($data['email'] !== $oldEmail) { $this->confirmation->send($user); } return $listener->userUpdated($user, $data['email'] !== $oldEmail); }
/** * Validates the Turkish Identity Number over HTTP connection to goverment sys * @param array ['tcno' => string, 'isim' => string, 'soyisim' => string, 'dogumyili' => int] * @return bool */ public static function validate($data = []) { if (!static::verify($data)) { return false; } if (count(array_diff(static::$validationfields, array_keys($data))) != 0) { return false; } foreach (static::$validationfields as $field) { $data[$field] = Str::upper($data[$field]); } $post_data = '<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <TCKimlikNoDogrula xmlns="http://tckimlik.nvi.gov.tr/WS"> <TCKimlikNo>' . $data['tcno'] . '</TCKimlikNo> <Ad>' . $data['isim'] . '</Ad> <Soyad>' . $data['soyisim'] . '</Soyad> <DogumYili>' . $data['dogumyili'] . '</DogumYili> </TCKimlikNoDogrula> </soap:Body> </soap:Envelope>'; $ch = curl_init(); // CURL options $options = array(CURLOPT_URL => 'https://tckimlik.nvi.gov.tr/Service/KPSPublic.asmx', CURLOPT_POST => true, CURLOPT_POSTFIELDS => $post_data, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HEADER => false, CURLOPT_HTTPHEADER => array('POST /Service/KPSPublic.asmx HTTP/1.1', 'Host: tckimlik.nvi.gov.tr', 'Content-Type: text/xml; charset=utf-8', 'Content-Length: ' . strlen($post_data), 'SOAPAction: "http://tckimlik.nvi.gov.tr/WS/TCKimlikNoDogrula"')); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); return strip_tags($response) === 'true' ? true : false; }
/** * Controller Auto-Router * * @param string $controller eg. 'Admin\\UserController' * @param array $request_methods eg. array('get', 'post', 'put', 'delete') * @param string $prefix eg. admin.users * @param array $disallowed eg. array('private_method that starts with one of request methods) * @return Closure */ public static function autoRoute($controller, $request_methods, $disallowed = array(), $prefix = '') { return function () use($controller, $prefix, $disallowed, $request_methods) { //get all defined functions $methods = get_class_methods(App::make($controller)); //laravel methods to disallow by default $disallowed_methods = array('getBeforeFilters', 'getAfterFilters', 'getFilterer'); //build list of functions to not allow if (is_array($disallowed)) { $disallowed_methods = array_merge($disallowed_methods, $disallowed); } //if there is a index method then lets just bind it and fill the gap in route_names if (in_array('getIndex', $methods)) { Lara::fillRouteGaps($prefix, $controller . '@getIndex'); } //over all request methods, get, post, etc foreach ($request_methods as $type) { //filter functions that starts with request method and not in disallowed list $actions = array_filter($methods, function ($action) use($type, $disallowed_methods) { return Str::startsWith($action, $type) && !in_array($action, $disallowed_methods); }); foreach ($actions as $action) { $controller_route = $controller . '@' . $action; // Admin\\Controller@get_login $url = Str::snake(str_replace($type, '', $action)); // login; snake_case //double check and dont bind to already bound gaps filled index if (in_array($action, $methods) && $action !== 'getIndex') { $route = str_replace('..', '.', $prefix . '.' . Str::snake($action)); Route::$type($url, array('as' => $route, 'uses' => $controller_route)); } } } }; }