Example #1
0
 public function getInfo()
 {
     $extensionsDir = $this->getExtensionsDir();
     $dirs = array_diff(scandir($extensionsDir), ['.', '..']);
     $extensions = [];
     $installed = json_decode(file_get_contents(public_path('vendor/composer/installed.json')), true);
     foreach ($dirs as $dir) {
         if (file_exists($manifest = $extensionsDir . '/' . $dir . '/composer.json')) {
             $extension = json_decode(file_get_contents($manifest), true);
             if (empty($extension['name'])) {
                 continue;
             }
             if (isset($extension['extra']['flarum-extension']['icon'])) {
                 $icon =& $extension['extra']['flarum-extension']['icon'];
                 if ($file = array_get($icon, 'image')) {
                     $file = $extensionsDir . '/' . $dir . '/' . $file;
                     if (file_exists($file)) {
                         $mimetype = pathinfo($file, PATHINFO_EXTENSION) === 'svg' ? 'image/svg+xml' : finfo_file(finfo_open(FILEINFO_MIME_TYPE), $file);
                         $data = file_get_contents($file);
                         $icon['backgroundImage'] = 'url(\'data:' . $mimetype . ';base64,' . base64_encode($data) . '\')';
                     }
                 }
             }
             foreach ($installed as $package) {
                 if ($package['name'] === $extension['name']) {
                     $extension['version'] = $package['version'];
                 }
             }
             $extension['id'] = $dir;
             $extensions[$dir] = $extension;
         }
     }
     return $extensions;
 }
 public function getSolutionsByOption($user_id, array $inputs)
 {
     $query = $this->model->list()->withWired($user_id);
     // 채점번호의 역순, 공개된 제출만
     $query = $query->latest('solutions.id')->whereHidden(false);
     // 채점하는 문제가 공개된 것일 경우만
     $query = $query->joinProblem()->where('status', 1);
     // 문제번호로 검색
     $problem_id = array_get($inputs, 'problem_id', 0);
     if ($problem_id > 0) {
         $query = $query->whereProblem($problem_id);
     }
     // 유저이름으로 검색
     $username = array_get($inputs, 'username', '');
     if ($username != '') {
         $query = $query->joinUser()->whereName($username);
     }
     // 언어종류로 검색
     $lang_id = array_get($inputs, 'lang_id', 0);
     if ($lang_id > 0) {
         $query = $query->whereLang($lang_id);
     }
     // 결과종류로 검색
     $result_id = array_get($inputs, 'result_id', 0);
     if ($result_id > 0) {
         $query = $query->whereResult($result_id);
     }
     return $query;
 }
Example #3
0
 /**
  * @param $model
  * @param $type
  * @param $input
  * @return $this
  */
 public function preProcess($model, $type, $input)
 {
     $structure = $input->get('structure');
     $structure['news_id'] = (int) array_get($structure, 'news_id');
     $input->put('structure', $structure);
     return parent::preProcess($model, $type, $input);
 }
Example #4
0
 /**
  * {@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);
 }
Example #5
0
 /**
  * Load language pack resources from the given directory.
  *
  * @param string $directory
  */
 public function loadLanguagePackFrom($directory)
 {
     $name = $title = basename($directory);
     if (file_exists($manifest = $directory . '/composer.json')) {
         $json = json_decode(file_get_contents($manifest), true);
         if (empty($json)) {
             throw new RuntimeException("Error parsing composer.json in {$name}: " . json_last_error_msg());
         }
         $locale = array_get($json, 'extra.flarum-locale.code');
         $title = array_get($json, 'extra.flarum-locale.title', $title);
     }
     if (!isset($locale)) {
         throw new RuntimeException("Language pack {$name} must define \"extra.flarum-locale.code\" in composer.json.");
     }
     $this->locales->addLocale($locale, $title);
     if (!is_dir($localeDir = $directory . '/locale')) {
         throw new RuntimeException("Language pack {$name} must have a \"locale\" subdirectory.");
     }
     if (file_exists($file = $localeDir . '/config.js')) {
         $this->locales->addJsFile($locale, $file);
     }
     if (file_exists($file = $localeDir . '/config.css')) {
         $this->locales->addCssFile($locale, $file);
     }
     foreach (new DirectoryIterator($localeDir) as $file) {
         if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
             $this->locales->addTranslations($locale, $file->getPathname());
         }
     }
 }
Example #6
0
 /**
  * Parse an array of episodes into a collection of Episode models
  * @param  Array $episodes The array of episodes to parse
  * @return \Illuminate\Support\Collection 
  */
 private function parseEpisodes($episodes)
 {
     $episodes = collect($episodes);
     return $episodes->map(function ($episode) {
         return new Episode(['title' => array_get($episode, 'title'), 'subtitle' => array_get($episode, 'subtitle'), 'synopsis' => array_get($episode, 'synopses.medium'), 'release_date' => array_get($episode, 'release_date_time')]);
     });
 }
 function processView()
 {
     $GLOBALS['system']->includeDBClass('person');
     $this->_search_params = array();
     $search = trim(array_get($_REQUEST, 'search', array_get($_REQUEST, 'tel', '')));
     $tel = preg_replace('/[^0-9]/', '', $search);
     if ($search == '') {
         return;
     }
     if (!empty($tel)) {
         // Look for phone number matches
         $this->_family_data = $GLOBALS['system']->getDBObjectData('family', array('home_tel' => $tel));
         $this->_person_data = $GLOBALS['system']->getDBObjectData('person', array('mobile_tel' => $tel, 'work_tel' => $tel));
     }
     if (empty($tel) || empty($this->_family_data) && empty($this->_person_data)) {
         // Look for family name, person name, group name or person email
         $this->_family_data = $GLOBALS['system']->getDBObjectData('family', array('family_name' => $search . '%'));
         $this->_person_data = Person::getPersonsByName($search);
         $this->_group_data = $GLOBALS['system']->getDBObjectData('person_group', array('name' => $search . '%'), 'OR', 'name');
         if (FALSE !== strpos($search, '@')) {
             // Add email search
             $this->_person_data += $GLOBALS['system']->getDBObjectData('person', array('email' => $search));
         }
         if (empty($this->_group_data)) {
             $this->_group_data = $GLOBALS['system']->getDBObjectData('person_group', array('name' => '%' . $search . '%'), 'OR', 'name');
         }
     }
     $numResults = count($this->_family_data) + count($this->_group_data) + count($this->_person_data);
     if ($numResults == 1) {
         // For a single result, just redirect to its detail view, don't show a list
         if (!empty($this->_person_data)) {
             add_message("One matching person found");
             redirect('persons', array('search' => NULL, 'personid' => key($this->_person_data)));
         } else {
             if (!empty($this->_family_data)) {
                 add_message("One matching family found");
                 redirect('families', array('search' => NULL, 'familyid' => key($this->_family_data)));
             } else {
                 if (!empty($this->_group_data)) {
                     add_message("One matching group found");
                     redirect('groups', array('search' => NULL, 'groupid' => key($this->_group_data)));
                 }
             }
         }
     }
     // Put all archived results at the end of the list
     foreach (array('_person_data', '_family_data', '_group_data') as $var) {
         $archiveds = array();
         $ref =& $this->{$var};
         foreach ($ref as $k => $v) {
             if (array_get($v, 'status') == 'archived' || array_get($v, 'is_archived')) {
                 $archiveds[$k] = $v;
                 unset($ref[$k]);
             }
         }
         foreach ($archiveds as $k => $v) {
             $ref[$k] = $v;
         }
     }
 }
Example #8
0
 /**
  * Get a URL segment OR query string using "dot" notation.
  *
  * <code>
  * // Get the name of the service
  * $parser = $this->get('name');
  * </code>
  *
  * @param  array $options
  * @return mixed
  */
 public function get($key)
 {
     if (isset($this->segments[$key])) {
         return array_get($this->segments, $key, null);
     }
     return array_get($this->query, $key, null);
 }
 /**
  * Get the country name.
  *
  * @return null|string
  */
 public function name()
 {
     if (!($key = $this->object->getValue())) {
         return;
     }
     return trans(array_get($this->object->getOptions(), $key));
 }
Example #10
0
 /**
  * Chunk the request into parts as
  * desired by the request range header.
  *
  * @param Response      $response
  * @param FileInterface $file
  */
 protected function chunk(Response $response, FileInterface $file)
 {
     $size = $chunkStart = $file->getSize();
     $end = $chunkEnd = $size;
     $response->headers->set('Content-length', $size);
     $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
     if (!($range = array_get($_SERVER, 'HTTP_RANGE'))) {
         return;
     }
     list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
     if (strpos($range, ',') !== false) {
         $response->setStatusCode(416, 'Requested Range Not Satisfiable');
         $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
     }
     if ($range == '-') {
         $chunkStart = $size - substr($range, 1);
     } else {
         $range = explode('-', $range);
         $chunkStart = $range[0];
         $chunkEnd = isset($range[1]) && is_numeric($range[1]) ? $range[1] : $size;
     }
     $chunkEnd = $chunkEnd > $end ? $end : $chunkEnd;
     if ($chunkStart > $chunkEnd || $chunkStart > $size || $chunkEnd >= $size) {
         $response->setStatusCode(416, 'Requested Range Not Satisfiable');
         $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
     }
 }
Example #11
0
 /**
  * Generate HTML for object action Edit
  *
  * @param $object Model
  *
  * @return string
  */
 protected function DeleteObjectAction($object, $config)
 {
     if (!$this->isActionTrusted('destroy')) {
         return '';
     }
     return sprintf("<li>%s%s%s</li>", Form::open(['method' => 'post', 'url' => $this->getGeneratedUrl('destroy', [$object->id])]), Form::button(trans(array_get($config, 'label')), ['type' => 'submit', 'onclick' => 'return confirm("Are you sure?")']), Form::close());
 }
 function trait_config_get($clz, $key, $default = null)
 {
     if (!property_exists($clz, 'traitConfigs')) {
         return $default;
     }
     return array_get($clz::$traitConfigs, $key, $default);
 }
Example #13
0
 /**
  * Return the tag links.
  *
  * @param array $attributes
  * @return string
  */
 public function tagLinks(array $attributes = [])
 {
     array_set($attributes, 'class', array_get($attributes, 'class', 'label label-default'));
     return array_map(function ($label) use($attributes) {
         return $this->html->link(implode('/', [$this->settings->value('anomaly.module.posts::module_segment', 'posts'), $this->settings->value('anomaly.module.posts::tag_segment', 'tag'), $label]), $label, $attributes);
     }, (array) $this->object->getTags());
 }
Example #14
0
 /**
  * Cleanup log files
  *
  * @param array $args
  * @return bool
  */
 public function clean(array $args = array())
 {
     // Resolve parameters
     $logRoot = array_get($args, 'root', APPLICATION_PATH . '/data/logs');
     $pattern = array_get($args, 'pattern', '/\\.log$/i');
     $threshold = array_get($args, 'threshold', '1 month ago');
     $verbose = array_get($args, 'verbose', false);
     $count = 0;
     $leanOut = '';
     $verboseOut = '';
     if ($handle = opendir($logRoot)) {
         while (false !== ($entry = readdir($handle))) {
             $isLogFile = preg_match($pattern, $entry);
             $isTooOld = filemtime($logRoot . '/' . $entry) < strtotime($threshold);
             if ($isLogFile && $isTooOld) {
                 @unlink($logRoot . '/' . $entry);
                 ++$count;
                 $verboseOut .= " - {$entry}\n";
             }
         }
         $leanOut = "{$count} log files successfully removed";
         $verboseOut = $leanOut . ":\n" . $verboseOut;
         closedir($handle);
     }
     if ($count) {
         if ($verbose) {
             Garp_Cli::lineOut($verboseOut);
         } else {
             Garp_Cli::lineOut($leanOut);
         }
     } else {
         Garp_Cli::lineOut('No log files matched the given criteria.');
     }
     return true;
 }
 /**
  * Guess the HREF for a button.
  *
  * @param ControlPanelBuilder $builder
  */
 public function guess(ControlPanelBuilder $builder)
 {
     $buttons = $builder->getButtons();
     $sections = $builder->getControlPanelSections();
     $active = $sections->active();
     $module = $this->modules->active();
     foreach ($buttons as &$button) {
         // If we already have an HREF then skip it.
         if (isset($button['attributes']['href'])) {
             continue;
         }
         // Determine the HREF based on the button type.
         switch (array_get($button, 'button')) {
             case 'add':
             case 'new':
             case 'create':
                 $button['attributes']['href'] = $active->getHref('create');
                 break;
             case 'export':
                 if ($module) {
                     $button['attributes']['href'] = $this->url->to('entry/handle/export/' . $module->getNamespace() . '/' . array_get($button, 'namespace') . '/' . array_get($button, 'stream'));
                 }
                 break;
         }
         $type = array_get($button, 'segment', array_get($button, 'button'));
         if (!isset($button['attributes']['href']) && $type) {
             $button['attributes']['href'] = $active->getHref($type);
         }
     }
     $builder->setButtons($buttons);
 }
Example #16
0
 /**
  * @param EditTag $command
  * @return \Flarum\Tags\Tag
  * @throws \Flarum\Core\Exception\PermissionDeniedException
  */
 public function handle(EditTag $command)
 {
     $actor = $command->actor;
     $data = $command->data;
     $tag = $this->tags->findOrFail($command->tagId, $actor);
     $this->assertCan($actor, 'edit', $tag);
     $attributes = array_get($data, 'attributes', []);
     if (isset($attributes['name'])) {
         $tag->name = $attributes['name'];
     }
     if (isset($attributes['slug'])) {
         $tag->slug = $attributes['slug'];
     }
     if (isset($attributes['description'])) {
         $tag->description = $attributes['description'];
     }
     if (isset($attributes['color'])) {
         $tag->color = $attributes['color'];
     }
     if (isset($attributes['isHidden'])) {
         $tag->is_hidden = (bool) $attributes['isHidden'];
     }
     if (isset($attributes['isRestricted'])) {
         $tag->is_restricted = (bool) $attributes['isRestricted'];
     }
     event(new TagWillBeSaved($tag, $actor, $data));
     $this->validator->assertValid($tag->getDirty());
     $tag->save();
     return $tag;
 }
Example #17
0
 public function getDataFromRequest(Request $request)
 {
     $data = parent::getDataFromRequest($request);
     $data['creditAmount'] = array_get($data, 'creditAmount', '') ?: 0;
     $data['donationAmount'] = array_get($data, 'donationAmount', '') ?: 0;
     return $data;
 }
Example #18
0
 public function index(BaseRequest $request)
 {
     $query_params = ['filters' => [], 'search' => [], 'per_page' => (int) array_get($request->all(), 'per_page', 10), 'page' => (int) array_get($request->all(), 'page', 1)];
     $searchQuery = array_get($request, 'searchQuery');
     /*
      * Default Values
      */
     if (count($this->default_values) > 0) {
         foreach ($this->default_values as $k => $v) {
             $query_params['filters'][$k] = $v;
         }
     }
     /*
      * Filters
      */
     if (count($this->filter_values) > 0) {
         foreach ($this->filter_values as $v) {
             $query_params['filters'][$v] = array_get($request, $v);
         }
     }
     /*
      * Search
      */
     if (count($this->search_fields) > 0) {
         foreach ($this->search_fields as $v) {
             $query_params['search'][$v] = $searchQuery;
         }
     }
     list($headers, $data) = $this->repo->getAll(['*'], $query_params);
     $list = $this->response->paginatedCollection($data, $this->transformer);
     return response()->json($list['data'], 200, $headers);
 }
Example #19
0
 public function render()
 {
     $this->loadFiles();
     $args = $this->arguments;
     $seq = $this->seq();
     // set default file upload options
     $fileuploadOptions = ['previewMaxWidth' => 280, 'previewMaxHeight' => 120, 'previewCrop' => false, 'autoUpload' => false, 'acceptFileTypes' => "(\\.|\\/)(.*)\$", 'maxFileSize' => 5000000, 'replaceFileInput' => false, 'disableImageResize' => true, 'imageCrop' => false, 'imageMaxWidth' => 480, 'imageMaxHeight' => 240];
     // set file
     if (isset($args['file'])) {
         $file = File::find($args['file']);
         if ($file === null) {
             unset($args['file']);
         } else {
             $filename = $file->clientname;
             $args['file'] = $filename;
         }
     }
     // resolve arguments
     $fileuploadOptions = array_merge($fileuploadOptions, array_get($args, 'fileuploadOptions', []));
     $args = array_add($args, 'width', 420);
     $args = array_add($args, 'height', 240);
     array_set($fileuploadOptions, 'previewMaxWidth', $args['width']);
     array_set($fileuploadOptions, 'previewMaxHeight', $args['height']);
     $types = array_get($args, 'types');
     if ($types !== null) {
         array_set($fileuploadOptions, 'acceptFileTypes', '(\\.|\\/)(' . implode('|', (array) $types) . ')$');
     }
     array_set($args, 'fileuploadOptions', $fileuploadOptions);
     // render template
     $this->template = \View::make($this->view, ['args' => $args, 'seq' => $seq])->render();
     return parent::render();
 }
Example #20
0
 /**
  * Return list of entries;
  * This is a generic function which is suitable for most use cases, but can 
  * easily be overridden as needed
  * 
  * @param array $params
  * @return \App\Models\Base
  */
 public function all($params = [])
 {
     if (array_get($params, 'sortby')) {
         $this->model = $this->model->orderBy(array_get($params, 'sortby'), array_get($params, 'dir') ? array_get($params, 'dir') : 'asc');
     }
     if (array_get($params, 'ids')) {
         $this->model = $this->model->whereIn('id', array_get($params, 'ids'));
     }
     foreach ($params as $search => $value) {
         if (in_array($search, $this->excludeFilters)) {
             // we don't want to search by these
             continue;
         }
         if (!$value) {
             // must have a value
             continue;
         }
         // if the passed in param is an array, as in filter[some_attribute], drill down
         if (is_array($value)) {
             $this->model = $this->model->where(function ($query) use($value, $search) {
                 foreach ($value as $key2 => $value2) {
                     $orWheres = explode('|', $key2);
                     // if fields are separated by a pipe, |, then we'll treat them as 'orWhere' statements
                     foreach ($orWheres as $orWhere) {
                         $query->orWhere($orWhere, 'like', '%' . $value2 . '%');
                     }
                 }
             });
         } else {
             // if the passed in param is not an array
             $this->model = $this->model->where($search, 'like', '%' . $value . '%');
         }
     }
     return $this->model;
 }
Example #21
0
 /**
  * 사용자가 위젯 설정 페이지에 입력한 설정값을 저장하기 전에 전처리 한다.
  *
  * @param array $inputs 사용자가 입력한 설정값
  *
  * @return array
  */
 public function resolveSetting(array $inputs = [])
 {
     $content = array_get($inputs, 'content');
     //$content = '<![CDATA['.$content.']]>';
     array_set($inputs, 'content', $content);
     return $inputs;
 }
 function processView()
 {
     $this->_family =& $GLOBALS['system']->getDBObject('family', $_REQUEST['familyid']);
     $GLOBALS['system']->includeDBClass('person');
     $this->_person = new Person();
     if (array_get($_REQUEST, 'new_person_submitted')) {
         $GLOBALS['system']->doTransaction('begin');
         $this->_person = new Person();
         $this->_person->processForm();
         $this->_person->setValue('familyid', $this->_family->id);
         if ($this->_person->create()) {
             if (!empty($_POST['execute_plan'])) {
                 foreach ($_POST['execute_plan'] as $planid) {
                     $plan = $GLOBALS['system']->getDBObject('action_plan', $planid);
                     $plan->execute('person', $this->_person->id, process_widget('plan_reference_date', array('type' => 'date')));
                 }
             }
             $GLOBALS['system']->doTransaction('commit');
             add_message('New family member added');
             redirect('families', array('familyid' => $this->_family->id));
             // exits
         } else {
             $GLOBALS['system']->doTransaction('rollback');
         }
     } else {
         $this->_person->setValue('last_name', $this->_family->getValue('family_name'));
     }
 }
Example #23
0
 /**
  * Push a new job onto the queue after a delay.
  *
  * @param  \DateTime|int  $delay
  * @param  string  $job
  * @param  mixed   $data
  * @param  string  $queue
  * @return void
  */
 public function later($delay, $job, $data = '', $queue = null)
 {
     $payload = $this->createPayload($job, $data);
     $delay = $this->getSeconds($delay);
     $this->getConnection()->zadd($this->getQueue($queue) . ':delayed', $this->getTime() + $delay, $payload);
     return array_get(json_decode($payload, true), 'id');
 }
 /**
  * Get the failed validation message for the request.
  *
  * @param  \Illuminate\Http\Request $request
  * @return string|null
  */
 public function getFailedValidationMessage(Request $request)
 {
     $messages = method_exists($this, 'failedValidationMessages') ? $this->failedValidationMessages() : [];
     $method = strtoupper($request->method());
     $path = $request->path();
     return array_get($messages, "{$method}.{$path}", $this->fallbackValidationMessages($method));
 }
 /**
  * Attempts to authenticate the user.
  *
  * @param \App\Models\User\User  $user
  * @param \Illuminate\Auth\Guard $auth
  *
  * @return \Illuminate\Http\RedirectResponse
  */
 public function callback(User $user, Guard $auth)
 {
     try {
         $payload = $this->socialite->user();
     } catch (Exception $e) {
         $this->flash('Failed to sign in via GitHub, did you decline?', Controller::FLASH_ERROR);
         return redirect()->route('get::front.home');
     }
     try {
         $response = app('GuzzleHttp\\Client')->get('https://api.github.com/user/emails?access_token=' . $payload->token, ['headers' => ['Accept' => 'application/vnd.github.v3+json']]);
         $emails = $response->json();
     } catch (Exception $e) {
         $this->flash('Failed to sign in via GitHub, is your GitHub account verified?', Controller::FLASH_ERROR);
         return redirect()->route('get::front.home');
     }
     $email = array_filter($emails, function ($email) {
         return $email['primary'];
     });
     if (count($email) === 0) {
         $this->flash('Failed to sign in via GitHub, is your GitHub account verified?', Controller::FLASH_ERROR);
         return redirect()->route('get::front.home');
     }
     $email = array_get(array_values($email)[0], 'email');
     $user = $user->firstOrCreate(['uid' => $payload->id]);
     $user->update(['token' => $payload->token, 'email' => $email, 'nickname' => $payload->nickname, 'name' => $payload->nickname]);
     $auth->login($user, true);
     return redirect()->intended('/home');
 }
Example #26
0
 /**
  * Attempt to log a user into the application.
  *
  * @param  array  $arguments
  * @return void
  */
 public function attempt($arguments = array())
 {
     $valid = false;
     // Get the username fields
     $usernames = Config::get('verify::verify.username');
     $usernames = !is_array($usernames) ? array($usernames) : $usernames;
     foreach ($usernames as $identify_by) {
         $user = $this->model()->where($identify_by, '=', array_get($arguments, $identify_by))->first();
         if (!is_null($user)) {
             // Is user password is valid?
             if (!Hash::check($user->salt . array_get($arguments, 'password'), $user->password)) {
                 throw new UserPasswordIncorrectException('User password is incorrect');
             }
             // Valid user, but are they verified?
             if (!$user->verified) {
                 throw new UserUnverifiedException('User is unverified');
             }
             // Is the user disabled?
             if ($user->disabled) {
                 throw new UserDisabledException('User is disabled');
             }
             // Is the user deleted?
             if ($user->deleted) {
                 throw new UserDeletedException('User is deleted');
             }
             $valid = true;
             break;
         }
     }
     if ($valid) {
         return $this->login($user->get_key(), array_get($arguments, 'remember'));
     } else {
         throw new UserNotFoundException('User can not be found');
     }
 }
Example #27
0
 public function postLogin(\Illuminate\Http\Request $request)
 {
     $username = $request->input('username');
     $password = $request->input('password');
     // First try to log in as a local user.
     if (Auth::attempt(array('username' => $username, 'password' => $password))) {
         $this->alert('success', 'You are now logged in.', true);
         return redirect('users/' . Auth::user()->id);
     }
     // Then try with ADLDAP.
     $ldapConfig = \Config::get('adldap');
     if (array_get($ldapConfig, 'domain_controllers', false)) {
         $adldap = new \adldap\adLDAP($ldapConfig);
         if ($adldap->authenticate($username, $password)) {
             // Check that they exist.
             $user = \Ormic\Model\User::where('username', '=', $username)->first();
             if (!$user) {
                 $user = new \Ormic\Model\User();
                 $user->username = $username;
                 $user->save();
             }
             \Auth::login($user);
             //$this->alert('success', 'You are now logged in.', TRUE);
             return redirect('');
             //->with(['You are now logged in.']);
         }
     }
     // If we're still here, authentication has failed.
     return redirect()->back()->withInput($request->only('username'))->withErrors(['Authentication failed.']);
 }
 function speech($candidateName)
 {
     $candidates = ['TheDonald' => new Trump(), 'Hillary' => new Clinton(), 'Bernie' => new Sanders()];
     /** @var CandidateInterface $candidate */
     $candidate = array_get($candidates, $candidateName, new BaseCandidate());
     return $candidate->getSpeech();
 }
Example #29
0
 /**
  * @param StartDiscussion $command
  * @return mixed
  * @throws Exception
  */
 public function handle(StartDiscussion $command)
 {
     $actor = $command->actor;
     $data = $command->data;
     $this->assertCan($actor, 'startDiscussion');
     // Create a new Discussion entity, persist it, and dispatch domain
     // events. Before persistence, though, fire an event to give plugins
     // an opportunity to alter the discussion entity based on data in the
     // command they may have passed through in the controller.
     $discussion = Discussion::start(array_get($data, 'attributes.title'), $actor);
     $this->events->fire(new DiscussionWillBeSaved($discussion, $actor, $data));
     $this->validator->assertValid($discussion->getAttributes());
     $discussion->save();
     // Now that the discussion has been created, we can add the first post.
     // We will do this by running the PostReply command.
     try {
         $post = $this->bus->dispatch(new PostReply($discussion->id, $actor, $data));
     } catch (Exception $e) {
         $discussion->delete();
         throw $e;
     }
     // Before we dispatch events, refresh our discussion instance's
     // attributes as posting the reply will have changed some of them (e.g.
     // last_time.)
     $discussion->setRawAttributes($post->discussion->getAttributes(), true);
     $discussion->setStartPost($post);
     $discussion->setLastPost($post);
     $this->dispatchEventsFor($discussion, $actor);
     $discussion->save();
     return $discussion;
 }
 /**
  * Translate form fields.
  *
  * @param FormBuilder $builder
  */
 public function translate(FormBuilder $builder)
 {
     $translations = [];
     $defaultLocale = config('streams::locales.default');
     $enabledLocales = config('streams::locales.enabled');
     /*
      * For each field if the assignment is translatable
      * then duplicate it and set a couple simple
      * parameters to assist in rendering.
      */
     foreach ($builder->getFields() as $field) {
         if (!array_get($field, 'translatable', false)) {
             $translations[] = $field;
             continue;
         }
         foreach ($enabledLocales as $locale) {
             $translation = $field;
             array_set($translation, 'locale', $locale);
             array_set($translation, 'hidden', $locale !== $locale);
             if ($value = array_get($field, 'values.' . $locale)) {
                 array_set($translation, 'value', $value);
             }
             if ($defaultLocale !== $locale) {
                 array_set($translation, 'hidden', true);
                 array_set($translation, 'required', false);
                 array_set($translation, 'rules', array_diff(array_get($translation, 'rules', []), ['required']));
             }
             $translations[] = $translation;
         }
     }
     $builder->setFields($translations);
 }