/**
  * Format:
  *
  * n: name
  * v: version
  * l: location
  * p: parent
  */
 private function composer()
 {
     $path = app_path() . '\\..\\composer.lock';
     if (!file_exists($path)) {
         return;
     }
     // Parse composer.lock
     $content = @file_get_contents($path);
     $list = @json_decode($content);
     if (!$list) {
         return;
     }
     $list = object_get($list, 'packages', []);
     // Determe the parent of the composer modules, most likely this will
     // resolve to laravel/laravel.
     $parent = '';
     $parent_path = realpath(app_path() . '\\..\\composer.json');
     if (file_exists($parent_path)) {
         $parent_object = @json_decode(@file_get_contents($parent_path));
         if ($parent_object) {
             $parent = object_get($parent_object, 'name', '');
         }
     }
     // Store base package, which is laravel/laravel.
     $packages = [['n' => $parent, 'l' => $parent_path, 'v' => '']];
     // Add each composer module to the packages list,
     // but respect the parent relation.
     foreach ($list as $package) {
         $packages[] = ['n' => $package->name, 'v' => $package->version, 'p' => $parent, 'l' => $parent_path];
     }
     return $packages;
 }
 /**
  * На самом деле тут у меня фантация играет по полной, поймать мошеника это круто
  * можно было реализовать из hidden risk некую битовую маску и по ней уже обсчитывать мошеников
  * @param Collection $leaders
  * @param []Collection $prevLeaders
  * @return []Collection
  */
 public function __invoke(Collection $leaders, array $prevLeaders)
 {
     $leaders->each(function ($value) use($prevLeaders) {
         $id = object_get($value, 'id', null);
         $score = object_get($value, 'score', null);
         // Идем по списку лидеров
         foreach ($prevLeaders as $leaders) {
             $leaders->each(function ($leader) use($id, $score) {
                 // Если личдер найден
                 if ($leader->id === $id) {
                     // И он есть в  hidden risk
                     if (isset($this->hidRisk[$id])) {
                         // Удаляем его
                         unset($this->hidRisk[$id]);
                     }
                     // Если сейчас у него очков больше чем в прошлый раз
                     if ($leader->score < $score / static::RISK_GROWTH_SCOPE) {
                         $this->result[$id] = $leader;
                     } else {
                         $this->hidRisk[$id] = $leader;
                     }
                 }
             });
         }
         if (isset($this->hidRisk[$id])) {
             $this->result[$id] = $value;
         }
     });
     return $this->result;
 }
 /**
  * @param ResponseInterface $responseInterface
  * @return mixed
  * @throws HttpResponseException
  * @throws \HttpInvalidParamException
  */
 protected function responseHandler(ResponseInterface $responseInterface)
 {
     // Проверяем код http, если не 200 или 201, то все нормально
     if ($this->checkHttpResponse($responseInterface)) {
         // Получаем тело запроса
         $body = json_decode($responseInterface->getBody());
         // Проверяем на json ошибки
         if (json_last_error() !== JSON_ERROR_NONE) {
             throw new HttpResponseException('Json invalid - ' . json_last_error_msg());
         }
         // Получем стус в ответе
         if ($status = object_get($body, 'status', null)) {
             if ($status === 'error') {
                 throw new HttpResponseException(object_get($body, 'message', null), object_get($body, 'code', 500));
             }
         }
         $parameter = 'leaderboard';
         if ($leaders = object_get($body, $parameter, null)) {
             return $leaders;
         } else {
             throw new \HttpInvalidParamException('Parameter - ' . $parameter);
         }
     }
     throw new HttpResponseException($responseInterface->getBody(), $responseInterface->getStatusCode());
 }
Example #4
0
 public function get_parent_behavior()
 {
     if (!$this->parent_behavior && $this->parent_obj) {
         $this->parent_behavior = object_get($this->parent_obj, 'acts_as_' . self::$name);
     }
     return $this->parent_behavior;
 }
Example #5
0
 public function __get($key)
 {
     if ($this->isEloquent()) {
         return $this->data->__get($key);
     }
     return object_get($this->data, $key);
 }
Example #6
0
 /**
  * @param null                 $key
  * @param string               $guard
  *
  * @var \Illuminate\Auth\Guard $auth
  * @return \PortOneFive\Essentials\Users\User|false
  */
 function visitor($key = null, $guard = null)
 {
     $auth = app('auth');
     if (!$auth->guard($guard)->check()) {
         return false;
     }
     return $key == null ? $auth->guard()->user() : object_get($auth->guard()->user(), $key);
 }
Example #7
0
 /**
  * Resolve value by uses as attribute as raw.
  *
  * @param  \SimpleXMLElement  $content
  * @param  string  $use
  * @param  mixed  $default
  *
  * @return mixed
  */
 protected function getRawValueAttribute(SimpleXMLElement $content, $use, $default = null)
 {
     list($value, $attribute) = explode('::', $use, 2);
     if (is_null($parent = object_get($content, $value))) {
         return $default;
     }
     $attributes = $parent->attributes();
     return Arr::get($attributes, $attribute, $default);
 }
 /**
  * Ping our cachet installation.
  *
  * @return bool True, if we get a response.
  * @throws CachetException If the status code returned wasn't what we expected.
  */
 public function ping()
 {
     $res = $this->client->get('ping');
     if ($res->getStatusCode() !== 200) {
         throw new CachetException('Invalid response code!');
     }
     $json = $this->json($res);
     return object_get($json, 'data', '') == 'Pong!';
 }
Example #9
0
 /**
  * @param      $key
  * @param null $default
  *
  * @return mixed
  */
 public function get($key, $default = null)
 {
     // Check for a Presenter Method first
     if (method_exists($this, $key)) {
         return $this->{$key}($default);
     }
     // Ok, now try to access the entities attribute
     return object_get($this->entity, $key, $default);
 }
function smarty_function_admin_relations($params = array(), &$smarty)
{
    require_once $smarty->_get_plugin_filepath('function', 'admin_link');
    $relations = array('parent' => 'edit ', 'children' => 'add/edit ');
    $object = null;
    $wrap = false;
    $links = array();
    $output = '';
    foreach ($params as $_key => $_value) {
        ${$_key} = $_value;
    }
    if (empty($object)) {
        $smarty->trigger_error("admin_relations: missing 'object' parameter", E_USER_NOTICE);
        return;
    }
    // cycle relations
    foreach ($relations as $relation_name => $relation_prefix) {
        // cycle object's 'get_' variables
        $i = 0;
        foreach ($object->{'get_' . $relation_name} as $model_name => $model_params) {
            AppModel::RelationNameParams($model_name, $model_params);
            // get controller
            $controller = Globe::Init($model_name, 'controller');
            // TODO replace by ::singleton, find others
            // action & text
            switch ($relation_name) {
                case 'parent':
                    $action = ($model = object_get($object, $model_name)) ? 'edit' . DS . $model->id : null;
                    $text = ucwords(AppInflector::titleize($model_name));
                    $image = 'page_white_edit';
                    break;
                case 'children':
                    $prefix = $i == 0 ? '' : AppInflector::tableize(get_class($object)) . '_id=';
                    $action = '?filter=' . $prefix . $object->id;
                    $text = ucwords(AppInflector::pluralize(AppInflector::titleize($model_name)));
                    $image = 'magnifier';
                    break;
                default:
                    $action = '';
                    $text = AppInflector::titleize($model_name);
                    $image = 'magnifier';
                    break;
            }
            // build link
            $links[] = smarty_function_admin_link(array('controller' => AppInflector::fileize(get_class($controller), 'controller'), 'action' => $action, 'text' => "<span>{$relation_prefix}{$text}</span>" . ' <img src="/assets/images/admin/silk/' . $image . '.png" width="16" height="16">'), $smarty);
            $i++;
        }
    }
    foreach ($links as $link) {
        $output .= "<li>{$link}</li>\n";
    }
    if ($wrap) {
        $output = '<ul class="relations">' . $output . '</ul>';
    }
    return $output;
}
Example #11
0
 /**
  * Because a title slug can be created from multiple sources (such as an article title, a category title.etc.),
  * this allows us to search out those fields from related objects and return the combined values.
  *
  * @param array $fields
  * @return array
  */
 public function getTitleFields(array $fields)
 {
     $fields = array_map(function ($field) {
         if (str_contains($field, '.')) {
             return object_get($this, $field);
             // this acts as a delimiter, which we can replace with /
         } else {
             return $this->{$field};
         }
     }, $fields);
     return $fields;
 }
Example #12
0
function array_extract(&$array, $keys, $unset = false)
{
    if (is_string($keys)) {
        $keys = array($keys);
    }
    $output = array();
    foreach ($keys as $key) {
        $output[$key] = is_array($array) ? array_get($array, $key) : object_get($array, $key);
        if ($unset) {
            unset($array[$key]);
        }
    }
    return $output;
}
 /**
  * Replaces placeholders in title
  * Matches all {{rule}} placeholders, escaped @{{ blocks (w/ optional }})
  * Technically also matches "{{something"
  *
  * @param $title        string Title with placeholders
  * @param $replacedWith object Things to replace with
  *
  * @return mixed
  */
 protected function replacePlaceholders($title, $replacedWith)
 {
     return preg_replace_callback('/(\\@)?\\{\\{([\\w\\d\\.]+)(?:\\}\\})/', function ($matches) use($replacedWith) {
         if ($matches[1] == '@') {
             // Escape
             return substr($matches[0], 1);
         }
         // Find the requested thing
         $value = object_get($replacedWith, $matches[2]);
         if ($value) {
             return $value;
         }
         // No idea
         return $matches[0];
     }, $title);
 }
Example #14
0
 public static function pluck($array, $value, $key = null)
 {
     $results = [];
     foreach ($array as $item) {
         $itemValue = is_object($item) ? object_get($item, $value) : array_get($item, $value);
         // If the key is "null", we will just append the value to the array and keep
         // looping. Otherwise we will key the array using the value of the key we
         // received from the developer. Then we'll return the final array form.
         if (is_null($key)) {
             $results[] = $itemValue;
         } else {
             $itemKey = is_object($item) ? object_get($item, $key) : array_get($item, $key);
             $results[$itemKey] = $itemValue;
         }
     }
     return $results;
 }
 /**
  * @param Collection $leaders
  * @param []Collection $prevLeaders Массив ранее собраных списков
  * @return array
  */
 public function __invoke(Collection $leaders, array $prevLeaders)
 {
     $leaders->each(function ($value) use($prevLeaders) {
         $id = object_get($value, 'id', null);
         $place = object_get($value, 'place', null);
         $this->result[$id] = 0;
         foreach ($prevLeaders as $leaders) {
             $leaders->each(function ($value) use($id, $place) {
                 if ($value->id === $id) {
                     if ($value->place !== $place) {
                         $this->result[$id]++;
                     }
                 }
             });
         }
     });
     return $this->result;
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function validate($item)
 {
     if (!isset($item)) {
         $item = new stdClass();
     }
     if (!$this->test($item)) {
         return false;
     }
     foreach ($this->properties as $name => $validator) {
         if (!is_object($item) || object_get($item, $name) === null) {
             return false;
         }
         if (!$validator->validate(object_get($item, $name))) {
             return false;
         }
     }
     return true;
 }
 private function redirectedFromProvider($provider, $listener)
 {
     try {
         $userData = $this->getSocialUser($provider);
         $accessConfig = Config::get('socialite-login.limit-access', []);
         foreach ($accessConfig as $property => $regex) {
             $value = object_get($userData, $property);
             if (is_string($value) and preg_match($regex, $value)) {
                 continue;
             }
             throw new Exception('Access denied.');
         }
     } catch (Exception $e) {
         return $listener->loginFailure($provider, $e);
     }
     $user = $this->users->findOrCreateUser($provider, $userData);
     $remember = true;
     $this->auth->login($user, $remember);
     return $listener->loginSuccess($user);
 }
Example #18
0
 /**
  * @param $columnId
  * @param $row
  *
  * @return mixed
  */
 public function getColumnDisplay($columnId, Model $row)
 {
     if ($this->hasColumnDisplayMutator($columnId)) {
         return $this->mutateColumn($columnId, $row);
     }
     return object_get($row, $columnId);
 }
 /**
  * Get an item from an array or object using "dot" notation.
  *
  * @param  mixed   $target
  * @param  string  $key
  * @param  mixed   $default
  * @return mixed
  *
  * @throws \InvalidArgumentException
  */
 function data_get($target, $key, $default = null)
 {
     if (is_array($target)) {
         return array_get($target, $key, $default);
     } elseif (is_object($target)) {
         return object_get($target, $key, $default);
     } else {
         throw new \InvalidArgumentException("Array or object must be passed to data_get.");
     }
 }
 /**
  * Filter by Panels, if '*' is provided then
  * check this panel exists within the defined
  * panels. Else look for specific panels.
  *
  * @param $attrs
  * @param $filterWith
  * @return bool
  */
 public function filterPanel($attrs, $filterWith)
 {
     $panels = $this->app['panel']->getPanels();
     $page = $this->app['http']->get('page', false);
     if (!$page && function_exists('get_current_screen')) {
         $page = object_get(get_current_screen(), 'id', $page);
     }
     foreach ($filterWith as $filter) {
         $filtered = array_filter($panels, function ($panel) use($page, $filter) {
             return $page === $panel['slug'] && str_is($filter, $panel['slug']);
         });
         if (count($filtered) > 0) {
             return true;
         }
     }
     return false;
 }
Example #21
0
 public static function hasLineItems($string)
 {
     if (is_null(object_get($string, 'order_details'))) {
         throw new Exception("required 'order_details' attribute not found or is not in the correct format");
     }
 }
 /**
  * Get the model by query hit.
  *
  * @param QueryHit $hit
  * @return \Illuminate\Database\Eloquent\Collection|Model|static
  */
 public function model(QueryHit $hit)
 {
     $repository = $this->createModelByClassUid(object_get($hit, 'class_uid'));
     $model = $repository->find(object_get($hit, 'private_key'));
     return $model;
 }
 /**
  * @param Request $request
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  */
 public function getDownloadResults(Request $request, $formId)
 {
     /** @var Form $form */
     $form = Form::find($formId);
     $data['headers'] = FormField::where(['form_id' => $formId])->get();
     $data['results'] = $form->resultsForUser(Auth::user());
     $data['tzoffset'] = intval($request->get('tzoffset', 0)) * -1;
     Excel::create('resultados', function ($excel) use($data) {
         $excel->getDefaultStyle()->getAlignment()->setWrapText(true);
         $excel->sheet('Hoja 1', function (LaravelExcelWorksheet $sheet) use($data) {
             $contents = [];
             foreach ($data['results'] as $key => $result) {
                 $row = [];
                 foreach ($data['headers'] as $header) {
                     if ($header->type == 'hidden' && object_get($header->config, 'dataType') == 'json') {
                         $row[$header->name] = json_encode(object_get($result->results, $header->alias), JSON_UNESCAPED_UNICODE);
                     } else {
                         $row[$header->name] = $this->remove_emoji(object_get($result->results, $header->alias));
                     }
                     if (gettype($row[$header->name]) === 'array') {
                         $row[$header->name] = implode(',', $row[$header->name]);
                     }
                     if (substr($row[$header->name], 0, 1) === '=') {
                         $row[$header->name] = ' ' . $row[$header->name];
                     }
                 }
                 $row['Fecha'] = $result->created_at->addMinutes($data['tzoffset']);
                 $contents[] = $row;
             }
             $sheet->fromArray($contents);
         });
     })->export('xls');
 }
Example #24
0
 /**
  * Returns a new package instance from the provided array.
  *
  * @param array $array
  * @param bool  $strict
  *
  * @return PackageContract
  * @throws \InvalidArgumentException
  */
 public static function fromArray(array $array, $strict = true)
 {
     $details = (object) $array;
     $packageNameDetails = self::parseVendorAndPackage(object_get($details, 'name', null));
     $description = object_get($details, 'description', null);
     $license = object_get($details, 'license', null);
     $authors = object_get($details, 'authors', null);
     // Throw exceptions if the developer wants us to be super strict.
     if ($strict) {
         self::throwInvalidArgumentException($description, 'Invalid package description.');
         self::throwInvalidArgumentException($license, 'Invalid package license.');
         self::throwInvalidArgumentException($authors, 'Invalid package authors.');
     }
     $package = new Package();
     $package->setAuthors($authors);
     $package->setDescription($description);
     $package->setLicense($license);
     $package->setVendor($packageNameDetails[0]);
     $package->setPackage($packageNameDetails[1]);
     return $package;
 }
Example #25
0
 /**
  * Get the attribute value from the model by name
  *
  * @param mixed $model
  * @param string $name
  * @return mixed
  */
 protected function getModelValueAttribute($model, $name)
 {
     $transformedName = $this->transformKey($name);
     if (is_string($model)) {
         return $model;
     } elseif (is_object($model)) {
         return object_get($model, $transformedName);
     } elseif (is_array($model)) {
         return array_get($model, $transformedName);
     }
 }
 /**
  * @param \stdClass[] $results
  * @return array
  */
 protected function parseResults($results)
 {
     $return = [];
     foreach ($results as $result) {
         $return[object_get($result, '__interval__')] = object_get($result, '__aggregate__');
     }
     return $return;
 }
Example #27
0
 /**
  * Get an item from an array or object using "dot" notation.
  *
  * @param  mixed   $target
  * @param  string  $key
  * @param  mixed   $default
  * @return mixed
  *
  * @throws \InvalidArgumentException
  */
 function data_get($target, $key, $default = null)
 {
     if (is_array($target)) {
         return array_get($target, $key, $default);
     } elseif (is_object($target)) {
         return object_get($target, $key, $default);
     }
 }
 /**
  * Get the model value that should be assigned to the field.
  *
  * @param  string  $name
  * @return mixed
  */
 protected function getModelValueAttribute($name)
 {
     if (is_object($this->model)) {
         return object_get($this->model, $this->transformKey($name));
     } elseif (is_array($this->model)) {
         return array_get($this->model, $this->transformKey($name));
     }
 }
 /**
  * Procesa el envio de formularios desde el sitio publico
  * @param Request $request
  * @return \Illuminate\Http\RedirectResponse
  */
 public function postProcessForm(Request $request)
 {
     $success_message = [];
     $language = Language::find($request->input('language_id', null));
     if (!$language) {
         $language = $this->site->getDefaultLanguage();
     }
     App::setLocale($language->code);
     setlocale(LC_ALL, $this->language->locale_code);
     /** @var Form $form */
     $form = Form::find($request->input('form_id'));
     $form_results = new FormResult();
     $form_results->form_id = $form->id;
     $form_results->assigned_user_id = $form->user->id;
     $results = $validations = $niceNames = [];
     foreach ($form->fields as $field) {
         if ($field->type == 'file') {
             $results[$field->alias] = $request->input('hidden-field-' . $field->alias, '');
         } elseif ($field->type == 'hidden' && object_get($field->config, 'dataType') == 'json') {
             $jsonValue = $request->input('field-' . $field->alias, '');
             if (gettype($jsonValue) == 'string') {
                 $jsonValue = json_decode($jsonValue) ?: $jsonValue;
             }
             $results[$field->alias] = $jsonValue;
         } else {
             $results[$field->alias] = $request->input('field-' . $field->alias, '');
             $validations[$field->alias] = $field->getValidations();
         }
     }
     $validator = Validator::make($results, $validations);
     foreach ($validator->errors()->toArray() as $fieldName => $error) {
         $niceNames[$fieldName] = lang('module_forms.' . $fieldName, $this->getDefaultFieldName($form->fields, $fieldName));
     }
     $validator->setAttributeNames($niceNames);
     if ($validator->fails()) {
         if ($request->ajax()) {
             return response()->json(['success' => false, 'message' => 'Ha ocurrido un error al procesar los datos.', 'errors' => $validator->errors()]);
         } else {
             return redirect($request->header('referer'))->withErrors($validator->errors())->withInput();
         }
     }
     $form_results->results = $results;
     $form_results->save();
     Event::fire('moduleforms.pre-send', ['form_results' => $form_results]);
     if (App::bound('moduleforms:pre-send:messages')) {
         $customMessage = App::make('moduleforms:pre-send:messages');
     }
     //Se recargan los resultados en caso de que fueran modificados por algun evento
     $form_results = FormResult::find($form_results->id);
     if ($form->user) {
         $form_results->assign($form->user);
     }
     if (isset($form->config->assignmentRules)) {
         $form_results->notifyUsers($form->config->assignmentRules);
     }
     if (object_get($form, 'config.client_email_field', null)) {
         $form_results->notifyClient($form->config->client_email_field);
     }
     //Se actualizan los resultados con la información de los usuarios
     $form_results->save();
     $success_message[] = isset($form->config->success_message) ? $form->config->success_message : 'Success';
     if ($request->session()->has('moduleforms.post-save')) {
         $success_message[] = $request->session()->get('moduleforms.post-save');
     }
     if (isset($customMessage)) {
         $success_message[] = $customMessage;
     }
     if (count($success_message) == 0) {
         $success_message = $success_message[0];
     }
     if ($request->ajax()) {
         return response()->json(['success' => true, 'message' => $success_message, 'errors' => []]);
     } else {
         if ($redirectPageId = object_get($form->config, 'success_redirect', null)) {
             $page = Page::find($redirectPageId);
             $redirectTo = $page->getUrl();
         } else {
             $redirectTo = $request->header('referer');
         }
         return response()->redirectTo($redirectTo)->with('success', $success_message);
     }
 }
Example #30
0
 /**
  * @param string $to
  * @param string $template
  */
 protected function sendEmail($to, $template = 'user')
 {
     $form = $this->form;
     $site = $this->form->site;
     $fields = [];
     foreach ($form->fields as $field) {
         if (isset($this->results->{$field->alias})) {
             if (gettype($this->results->{$field->alias}) == 'array' && !($field->type == 'hidden' && object_get($field->config, 'dataType', '') == 'json')) {
                 $value = implode(',', $this->results->{$field->alias});
             } else {
                 $value = $this->results->{$field->alias};
             }
             $fields[$field->alias] = ['name' => $field->name, 'alias' => $field->alias, 'value' => $value, 'options' => $field->getOptions()];
         }
     }
     view()->share(['site' => new TwigSite(App::make('site'))]);
     $subject = $this->getSubject($template);
     $mail_view = 'moduleforms::' . $site->alias . '.' . $form->alias . '.emails.' . $template;
     $mail_data = ['form' => $form, 'fields' => $fields];
     try {
         Mail::send($mail_view, $mail_data, function ($message) use($form, $to, $subject) {
             $message->subject($subject);
             $message->from(env('MAIL_FROM'), env('MAIL_FROMNAME'));
             $message->to($to);
         });
     } catch (\Exception $e) {
         Log::error($e->getMessage());
     }
 }