public function convert() { $validator = Validator::make(Input::all(), ['from' => 'required|min:3|max:3', 'to' => 'required|min:3|max:3']); if ($validator->fails()) { return response()->json([$validator->errors()])->setStatusCode(422, 'Validation Failed'); } $from = Currency::find(Input::get('from')); $to = Currency::find(Input::get('to')); $precision = (int) Config::get('laravel-currency.laravel-currency.precision'); $multiplier = pow(10, (int) Config::get('laravel-currency.laravel-currency.precision')); $amount = (double) Input::get('amount') ?: 1; if ($from == $to) { return response()->json($amount); } $amount = round($amount * $multiplier); if ($from && ($from->base == Input::get('to') || $from->base == $to->code)) { return response()->json(round($amount / $from->price, $precision)); } if ($to && ($to->base == Input::get('from') || $to->base == $from->code)) { return response()->json(round($amount * $to->price / pow($multiplier, 2), $precision)); } if (!$from || !$to) { return response()->json(['error' => Lang::get('currency.error.not_found')])->setStatusCode(404, 'Currency Not Found'); } if ($from->base !== $to->base) { throw new Exception('Cannot convert currencies with different bases.'); } return response()->json(round($amount / $from->price * $to->price / $multiplier, $precision)); }
public function setPassword() { if ($this->request->method() === 'GET') { return $this->showForm(['token' => $this->request->input('token')]); } $person = Person::findByEmail($this->request->input('email')); if (!$person->isValid()) { return $this->showForm(['error' => Lang::get('boomcms::recover.errors.invalid_email'), 'token' => $this->request->input('token')]); } $tokens = $this->app['auth.password.tokens']; $token = $tokens->exists($person, $this->request->input('token')); if (!$token) { return $this->showForm(['error' => Lang::get('boomcms::recover.errors.invalid_token'), 'token' => $this->request->input('token')]); } if ($this->request->input('password1') != $this->request->input('password2')) { return $this->showForm(['error' => Lang::get('boomcms::recover.errors.password_mismatch'), 'token' => $this->request->input('token')]); } if ($this->request->input('password1') && $this->request->input('password2')) { $tokens->delete($token); $tokens->deleteExpired(); $person->setEncryptedPassword($this->auth->hash($this->request->input('password1'))); Person::save($person); $this->auth->login($person); return redirect('/'); } else { return $this->showForm(['error' => Lang::get('boomcms::recover.errors.password_mismatch'), 'token' => $this->request->input('token')]); } }
/** * @param Request $request * @param Closure $next */ public function handle($request, Closure $next) { Lang::setFallback(self::getDefault()); $setLocale = Session::get('setLocale'); //flash data if (Config::get('app.locale_use_cookie')) { if ($setLocale) { Session::set('locale', $setLocale); } if (Session::has('locale')) { App::setLocale(Session::get('locale')); } else { self::autoDetect(); } } else { if (Config::get('app.locale_use_url')) { if ($setLocale) { self::setLocaleURLSegment($setLocale); } else { $lang = self::getLocaleFromURL(); if ($lang) { App::setLocale($lang); } else { if ($request->segment(1) != 'locale') { //ignore set-locale URL self::autoDetect(); self::setLocaleURLSegment(self::get()); } } } } } View::share('lang', self::get()); }
public function runCrawler() { switch (Input::get('action')) { case 'recreateurls': foreach (Page::all() as $page) { $page->url = Page::getUrl($page->id); $page->save(); } die("Recreated URL:s"); break; case 'crawl': Crawler::url(Input::get('crawl_url'), Input::get('crawl_found_links') ? true : false); if (Input::get('crawl_convert')) { Crawler::createPages(); } break; case 'convertToPages': Crawler::convertToPages(); break; default: return Response::json('Invalid action', 400); break; } if (Request::ajax()) { return Response::json(Lang::get('cms::m.crawler-done'), 200); } else { return Redirect::route('crawler')->with('flash_notice', Lang::get('cms::m.crawler-done')); } }
public function index() { $title = Lang::get('lang.destinations'); $destinations = Destinations::where('active', '=', 1)->where('isDomestic', '=', '1')->orderBy('ordering')->paginate(6); $destinations->setPath('destinations'); return view('destinations.index', compact('destinations', 'title')); }
/** * @return array */ public function notificationPayload() { $message = Lang::get('heartbeats.recovered_message', ['job' => $this->heartbeat->name]); $url = route('projects', ['id' => $this->heartbeat->project_id]); $payload = ['attachments' => [['fallback' => $message, 'text' => $message, 'color' => 'good', 'fields' => [['title' => Lang::get('notifications.project'), 'value' => sprintf('<%s|%s>', $url, $this->heartbeat->project->name), 'short' => true]], 'footer' => Lang::get('app.name'), 'ts' => time()]]]; return $payload; }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $locale = config('app.locale'); $adminLocale = config('typicms.admin_locale'); $locales = config('translatable.locales'); // If locale is present in app.locales… if (in_array(Input::get('locale'), $locales)) { // …store locale in session Session::put('locale', Input::get('locale')); } // Set app.locale config(['app.locale' => Session::get('locale', $locale)]); // Set Translator locale to typicms.admin_locale config Lang::setLocale($adminLocale); $localesForJS = []; foreach ($locales as $key => $locale) { $localesForJS[] = ['short' => $locale, 'long' => trans('global.languages.' . $locale)]; } // Set Locales to JS. JavaScript::put(['_token' => csrf_token(), 'encrypted_token' => Crypt::encrypt(csrf_token()), 'adminLocale' => $adminLocale, 'locales' => $localesForJS, 'locale' => config('app.locale')]); // set curent user preferences to Config if ($request->user()) { $prefs = $request->user()->preferences; config(['typicms.user' => $prefs]); } return $next($request); }
/** * Boot the service provider * * @return void */ public function boot() { //Register the packages assets $this->package('mscharl/pretty-error-page'); //add a language namespace to allow customizing of translations Lang::addNamespace('pretty-error-page-customized', app_path('lang/packages/mscharl/pretty-error-page')); }
/** * Logout the user * * @return Redirect */ public function getLogout() { //Logout the user Auth::logout(); //Redirect to login page return Redirect::to('admin/login')->with('success', Lang::get('firadmin::admin.messages.logout-success')); }
/** * Ensure user is logged in * * @return */ public function auth() { if (!$this->auth->check()) { $redirect = '?redirect=' . urlencode(Request::path()); return Redirect::to('/auth/login' . $redirect)->with('error_message', Lang::get('messages.login_access_denied')); } }
/** * Return a modules. * * @return \Illuminate\Support\Collection */ public function get(Module $module) { $moduleName = $module->getName(); if (Lang::has("{$moduleName}::module.title")) { $module->localname = Lang::get("{$moduleName}::module.title"); } else { $module->localname = $module->getStudlyName(); } if (Lang::has("{$moduleName}::module.description")) { $module->description = Lang::get("{$moduleName}::module.description"); } $package = $this->packageVersion->getPackageInfo("societycms/module-{$moduleName}"); if (isset($package->name) && strpos($package->name, '/')) { $module->vendor = explode('/', $package->name)[0]; } $module->version = isset($package->version) ? $package->version : 'N/A'; $module->versionUrl = '#'; $module->isCore = $this->isCoreModule($module); if (isset($package->source->url)) { $packageUrl = str_replace('.git', '', $package->source->url); $module->versionUrl = $packageUrl . '/tree/' . $package->dist->reference; } $module->license = $package->license; return $module; }
public function latest() { if ($this->isLoggedIn && $this->request->has('personal') && $this->request->get('personal') == 'true') { $isCached = false; $bans = $this->repository->getPersonalBans($this->user->settings()->playerIds()); } else { $isCached = Cache::has('bans.latest'); $bans = $this->repository->getLatestBans(); } if ($this->request->has('type') && $this->request->get('type') == 'rss') { $feed = Feed::make(); $feed->title = sprintf('Latest Battlefield Bans by %s', Config::get('bfacp.site.title')); $feed->description = sprintf('Latest Battlefield Bans by %s', Config::get('bfacp.site.title')); $feed->setDateFormat('datetime'); $feed->link = URL::to('api/bans/latest?type=rss'); $feed->lang = 'en'; foreach ($bans as $ban) { $title = sprintf('%s banned for %s', $ban['player']['SoldierName'], $ban['record']['record_message']); $view = View::make('system.rss.ban_entry_content', ['playerId' => $ban['player']['PlayerID'], 'playerName' => $ban['player']['SoldierName'], 'banreason' => $ban['record']['record_message'], 'sourceName' => $ban['record']['source_name'], 'sourceId' => $ban['record']['source_id'], 'banReason' => $ban['record']['record_message']]); $feed->add($title, $ban['record']['source_name'], $ban['player']['profile_url'], $ban['ban_startTime'], $title, $view->render()); } return $feed->render('atom'); } return MainHelper::response(['cols' => Lang::get('dashboard.bans.columns'), 'bans' => $bans], null, null, null, $isCached, true); }
public function show(Tag $tag) { $posts = Tag::find($tag->id)->posts()->latest()->get(); $title = Lang::get('tags.index.title', ['tag' => $tag->name]); $header = Lang::get('tags.index.header', ['tag' => $tag->name]); return view('posts.index', compact('posts', 'title', 'header')); }
public function __construct() { parent::__construct(Lang::get('oauth.unauthorized_client'), 14002); $this->httpStatusCode = 401; $errorType = class_basename($this); $this->errorType = snake_case(strtr($errorType, array('Exception' => ''))); }
public function getFeedAssessments() { $feed = $this->metabans->feed(); $assessments = $this->metabans->assessments(); $feed_assessments = ['feed' => $feed, 'assessments' => $assessments]; return MainHelper::response($feed_assessments + ['locales' => Lang::get('common.metabans')], null, null, null, false, true); }
/** * Update the resource in storage. * * @param Request $request * @return Response */ public function update(Request $request) { $banner = Banner::find(1); $data = $request->all(); $data['images'] = $banner->images ? $banner->images : []; $i = 0; $files = json_decode($data['files_deleted']); foreach ($files as $file) { if (($key = array_search($file, $data['images'])) !== false) { unset($data['images'][$key]); $image = new Image(); $image->setPath($this->path); $image->delete($file); } } foreach ($_FILES['images']['tmp_name'] as $tmpPath) { if (!empty($tmpPath)) { $fileName = date('His.dmY') . '.' . $i++ . '.jpg'; $image = new Image(); $image->setFile($tmpPath); $image->setPath($this->path); $image->fit(Image::BANNER)->upload($fileName); array_push($data['images'], $fileName); } } // Hàm unset() khiến key của array ko còn là dãy số liên tiếp // Lúc này Laravel sẽ ko đối xử và lưu 'images' như kiểu array mà là kiểu Json, cần sửa chữa vấn đề này $data['images'] = array_values($data['images']); $banner->fill($data)->save(); return Redirect::back()->with('flash_message', Lang::get('system.update')); }
/** * Save separately the model attributes and polyglot ones * * @param Polyglot $model * * @return boolean|null */ public function saving(Polyglot $model) { // Extract polyglot attributes $translated = $this->extractTranslatedAttributes($model); // If no localized attributes, continue if (empty($translated)) { return true; } // Save new model if (!$model->exists) { $model->save(); } // Get the current lang and Lang model $lang = array_get($translated, 'lang', Lang::getLocale()); $langModel = $model->{$lang}; $translated['lang'] = $lang; // If no Lang model or the fallback was returned, create a new one if (!$langModel || $langModel->lang !== $lang) { $langModel = $model->getLangClass(); $langModel = new $langModel($translated); $model->translations()->save($langModel); $model->setRelation($lang, $langModel); } $langModel->fill($translated); // Save and update model timestamp if ($model->exists && $model->timestamps && $langModel->getDirty()) { $time = $model->freshTimestamp(); $model->setUpdatedAt($time); } if ($model->save() && $langModel->save()) { return true; } }
/** * Execute the console command. * * @return mixed */ public function handle() { if (!$this->verifyInstalled() || $this->hasRunningDeployments() || $this->composerOutdated() || $this->nodeOutdated() || !$this->checkRequirements()) { return -1; } $bring_back_up = false; if (!App::isDownForMaintenance()) { $this->error(Lang::get('app.not_down')); if (!$this->confirm(Lang::get('app.switch_down'))) { return; } $bring_back_up = true; $this->call('down'); } $this->backupDatabase(); $this->updateConfiguration(); $this->clearCaches(); $this->migrate(); $this->optimize(); $this->restartQueue(); $this->restartSocket(); // If we prompted the user to bring the app down, bring it back up if ($bring_back_up) { $this->call('up'); } }
public function index() { $posts = Post::latest('published_at')->published()->get(); $title = Lang::get('posts.index.title'); $header = Lang::get('posts.index.header'); return View('posts.index', compact('posts', 'title', 'header')); }
/** * Remove the specified subcategory from storage. * * @param Request $request * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id = null) { /* * -------------------------------------------------------------------------- * Delete subcategory * -------------------------------------------------------------------------- * Check if selected variable is not empty so user intends to select multiple * rows at once, and prepare the feedback message according the type of * deletion action. */ if (!empty(trim($request->input('selected_sub')))) { $subcategory_ids = explode(',', $request->input('selected_sub')); $delete = Subcategory::whereIn('id', $subcategory_ids)->delete(); $message = Lang::get('alert.subcategory.delete_all', ['count' => $delete]); } else { $subcategory = Subcategory::findOrFail($id); $message = Lang::get('alert.subcategory.delete', ['subcategory' => $subcategory->subcategory]); $delete = $subcategory->delete(); } if ($delete) { return redirect(route('admin.category.index'))->with(['status' => 'warning', 'message' => $message]); } else { return redirect()->back()->withErrors(['error' => Lang::get('alert.error.database')]); } }
/** * Shows the live scoreboard */ public function scoreboard() { $games = Game::with(['servers' => function ($query) { $query->active()->orderBy('ServerName'); }])->get(); return View::make('scoreboard', compact('games'))->with('page_title', Lang::get('navigation.main.items.scoreboard.title')); }
/** * Attempt to find the user id of the currently logged in user * Supports Cartalyst Sentry/Sentinel based authentication, as well as stock Auth. * * Thanks to https://github.com/VentureCraft/revisionable/blob/master/src/Venturecraft/Revisionable/RevisionableTrait.php * * @throws NoUserLoggedInException * * @return int|string|null */ protected static function getCurrentUserId() { /* * Check if we're allowed to return no user ID to the model, if so we'll return NULL */ if (Config::get('inventory' . InventoryServiceProvider::$packageConfigSeparator . 'allow_no_user')) { return; } /* * Accountability is enabled, let's try and retrieve the current users ID */ try { if (class_exists($class = '\\Cartalyst\\Sentry\\Facades\\Laravel\\Sentry') || class_exists($class = '\\Cartalyst\\Sentinel\\Laravel\\Facades\\Sentinel')) { if ($class::check()) { return $class::getUser()->id; } } elseif (class_exists('Illuminate\\Auth') || class_exists('Illuminate\\Support\\Facades\\Auth')) { if (\Auth::check()) { return \Auth::user()->getAuthIdentifier(); } } } catch (\Exception $e) { } /* * Couldn't get the current logged in users ID, throw exception */ $message = Lang::get('inventory::exceptions.NoUserLoggedInException'); throw new NoUserLoggedInException($message); }
public function diffForHumans(Carbon $other = null) { $isNow = $other === null; if ($isNow) { $other = static::now($this->tz); } $isFuture = $this->gt($other); $delta = $other->diffInSeconds($this); // 4 weeks per month, 365 days per year... good enough!! $divs = array('second' => self::SECONDS_PER_MINUTE, 'minute' => self::MINUTES_PER_HOUR, 'hour' => self::HOURS_PER_DAY, 'day' => self::DAYS_PER_WEEK, 'week' => 4, 'month' => self::MONTHS_PER_YEAR); $unit = 'year'; foreach ($divs as $divUnit => $divValue) { if ($delta < $divValue) { $unit = $divUnit; break; } $delta = floor($delta / $divValue); } if ($delta == 0) { $delta = 1; } // Código adaptado para utilizar el gestor de idiomas de Laravel $txt = 'carbonlocale'; if ($isFuture) { return Lang::choice("{$txt}.future.{$unit}", $delta, compact('delta')); } return Lang::choice("{$txt}.past.{$unit}", $delta, compact('delta')); }
public function getTourCategory($subcategory_id) { $subCategory = DB::table('jos_estateagent_tour_subcategory')->where('TOUR_SUBCATEGORY', $subcategory_id)->first(); $titleCategory = Translations::getTranslation($subCategory->TOUR_CATEGORY, 'jos_estateagent_tour_category', 'tour_category_title', Lang::locale())->value; $titleSubCategory = Translations::getTranslation($subcategory_id, 'jos_estateagent_tour_subcategory', 'tour_subcategory_title', Lang::locale())->value; return array($titleCategory, $titleSubCategory); }
public function __construct() { $this->middleware('auth'); // Fetch the Site Settings object $this->currentModelName = Lang::get('crud.competitor'); View::share('currentModelName', $this->currentModelName); }
/** * Getter: Status text for management view * @return string */ public function getStatusTextAttribute() { if ((int) $this->status === 1) { return Lang::get('laravel-commentary::texts.management.status_approved'); } return Lang::get('laravel-commentary::texts.management.status_unapproved'); }
/** * Handle a login request to the application. * Requires $this->usernameField, password, remember request fields. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function login(Request $request) { $this->validate($request, [$this->usernameField => 'required', 'password' => 'required']); // Check whether this controller is using ThrottlesLogins trait $throttles = in_array(ThrottlesLogins::class, class_uses_recursive(get_class($this))); if ($throttles && $this->hasTooManyLoginAttempts($request)) { return $this->sendLockoutResponse($request); } $credentials = $request->only($this->usernameField, 'password'); // Try to authenticate using username or NIM if (Auth::attempt(['username' => $request[$this->usernameField], 'password' => $request['password']], $request->has('remember')) || Auth::attempt(['nim' => $request[$this->usernameField], 'password' => $request['password']], $request->has('remember'))) { // Authentication successful if ($throttles) { $this->clearLoginAttempts($request); } return redirect()->intended($this->redirectLogin); } // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. if ($throttles) { $this->incrementLoginAttempts($request); } $failedLoginMessage = Lang::has('auth.failed') ? Lang::get('auth.failed') : 'These credentials do not match our records.'; return redirect()->back()->withInput($request->only($this->usernameField, 'remember'))->withErrors([$this->usernameField => $failedLoginMessage]); }
/** * This function will create a new user object and return the newly created user object. * * @param array $userInfo This should have the properties: username, firstname, lastname, password, ui_language * * @return mixed */ public function registerUser(array $userInfo, $userLanguage) { $user = \User::create($userInfo); //make the first user an admin if (\User::all()->count() <= 1) { $user->is_admin = 1; } // Trim trailing whitespace from user first and last name. $user->firstname = trim($user->firstname); $user->lastname = trim($user->lastname); $user->save(); \Setting::create(['ui_language' => $userLanguage, 'user_id' => $user->id]); /* Add welcome note to user - create notebook, tag and note */ //$notebookCreate = Notebook::create(array('title' => Lang::get('notebooks.welcome_notebook_title'))); $notebookCreate = new \Notebook(); $notebookCreate->title = Lang::get('notebooks.welcome_notebook_title'); $notebookCreate->save(); $notebookCreate->users()->attach($user->id, ['umask' => \PaperworkHelpers::UMASK_OWNER]); //$tagCreate = Tag::create(array('title' => Lang::get('notebooks.welcome_note_tag'), 'visibility' => 0)); $tagCreate = new \Tag(); $tagCreate->title = Lang::get('notebooks.welcome_note_tag'); $tagCreate->visibility = 0; $tagCreate->user_id = $user->id; $tagCreate->save(); //$tagCreate->users()->attach($user->id); $noteCreate = new \Note(); $versionCreate = new \Version(['title' => Lang::get('notebooks.welcome_note_title'), 'content' => Lang::get('notebooks.welcome_note_content'), 'content_preview' => mb_substr(strip_tags(Lang::get('notebooks.welcome_note_content')), 0, 255), 'user_id' => $user->id]); $versionCreate->save(); $noteCreate->version()->associate($versionCreate); $noteCreate->notebook_id = $notebookCreate->id; $noteCreate->save(); $noteCreate->users()->attach($user->id, ['umask' => \PaperworkHelpers::UMASK_OWNER]); $noteCreate->tags()->sync([$tagCreate->id]); return $user; }
public function __construct() { // $this->middleware('auth'); // Fetch the Site Settings object $this->currentModelName = Lang::get('crud.shiaiCategory'); View::share('currentModelName', $this->currentModelName); }
/** * Get a string from language file. * * @param string $string * @param string $default * @param array $parameters * @return mixed */ function t($string, $default = null, $parameters = []) { if (Lang::has($string)) { return Lang::get($string, $parameters); } return $default; }