Get the filter to use with the model for searching

@param boolean $useRequest Use the request as source (when false, the session is used)
@return array or false
342075
public function getSearchFilter($useRequest = true)
    {
        $filter = parent::getSearchFilter($useRequest);

        unset($filter['AUTO_SEARCH_TEXT_BUTTON']);

        $where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db, null, 'yyyy-MM-dd HH:mm:ss');
        if ($where) {
            $filter[] = $where;
        }

        if (! isset($filter['gto_id_organization'])) {
            $filter['gto_id_organization'] = $this->currentUser->getRespondentOrgFilter();
        }
        $filter['gsu_active']  = 1;

        // When we dit not select a specific status we skip the deleted status
        if (!isset($filter['token_status'])) {
            $filter['grc_success'] = 1;
        }

        if (isset($filter['main_filter'])) {
            switch ($filter['main_filter']) {
                case 'hasnomail':
                    $filter[] = sprintf(
                            "((gr2o_email IS NULL OR gr2o_email = '' OR gr2o_email NOT RLIKE '%1\$s') AND
                                ggp_respondent_members = 1 AND gto_id_relationfield IS NULL) 
                             OR
                             ((grr_email IS NULL OR grr_email = '' OR grr_email NOT RLIKE '%1\$s') AND
                                ggp_respondent_members = 1 AND gto_id_relationfield IS NOT NULL)",
                            str_replace('\'', '\\\'', trim(\MUtil_Validate_SimpleEmail::EMAIL_REGEX, '/'))
                            );
                    $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)';
                    $filter['gto_completion_time'] = null;
                    // Exclude not mailable, we don't want to ask them for email if we are not allowed to used it anyway
                    $filter['gr2o_mailable'] = 1;
                    $filter['gr2t_mailable'] = 1;
                    break;

                case 'notmailable':
                    $filter[] = '(gr2o_mailable = 0 OR gr2t_mailable = 0) AND ggp_respondent_members = 1';
                    $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)';
                    $filter['gto_completion_time'] = null;
                    break;

                case 'notmailed':
                    $filter['gto_mail_sent_date'] = null;
                    $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)';
                    $filter['gto_completion_time'] = null;
                    break;

                case 'tomail':
                    $filter[] = sprintf(
                            "(gr2o_email IS NOT NULL AND gr2o_email != '' AND gr2o_email RLIKE '%1\$s' AND
                                ggp_respondent_members = 1 AND gto_id_relationfield IS NULL)
                              OR
                              (grr_email IS NOT NULL AND grr_email != '' AND grr_email RLIKE '%1\$s' AND
                                ggp_respondent_members = 1 AND gto_id_relationfield IS NOT NULL)",
                            str_replace('\'', '\\\'', trim(\MUtil_Validate_SimpleEmail::EMAIL_REGEX, '/'))
                            );
                    $filter['gto_mail_sent_date'] = null;
                    $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)';
                    $filter['gto_completion_time'] = null;
                    // Exclude not mailable
                    $filter['gr2o_mailable'] = 1;
                    $filter['gr2t_mailable'] = 1;
                    break;

                case 'toremind':
                    // $filter['can_email'] = 1;
                    $filter[] = 'gto_mail_sent_date < CURRENT_TIMESTAMP';
                    $filter[] = '(gto_valid_until IS NULL OR gto_valid_until >= CURRENT_TIMESTAMP)';
                    $filter['gto_completion_time'] = null;
                    break;

                default:
                    break;
            }
            unset($filter['main_filter']);
        }

        return $filter;
    }
228500
protected function search(ModelCriteria $query, Request $request)
    {
        $filters = $this->getFilters($request);

        if (empty($filters)) {
            return $query;
        }

        $conditions = array();

        $columns = $this->getSearchColumns($request);

        if (is_array($filters)) {
            foreach ($columns as $name => $condition) {
                $items = explode('.', $name);
                $i = 0;
                $values = $filters;

                while (is_array($values) && array_key_exists($items[$i], $values)) {
                    $values = $values[$items[$i]];
                    $i++;
                }

                if (is_array($values)) {
                    continue;
                } else {
                    $value = trim($values);
                }

                if (empty($value) && !is_numeric($value)) {
                    continue;
                }

                $query->condition(
                    'search_'.$name,
                    sprintf($condition, $value)
                );

                $conditions[] = 'search_'.$name;
            }

            if (!empty($conditions)) {
                return $query->where($conditions, 'and');
            }
        } else {
            $value = trim($filters);

            foreach ($columns as $name => $condition) {
                $query->condition(
                    'search_'.$name,
                    sprintf($condition, $value)
                );

                $conditions[] = 'search_'.$name;
            }

            if (!empty($conditions)) {
                return $query->where($conditions, 'or');
            }
        }
    }
390484
public function getSearchFilter($useRequest = true)
    {
        $filter = parent::getSearchFilter($useRequest);

        if (isset($filter['gr2t_id_track']) && $filter['gr2t_id_track']) {
            switch ($filter['gr2t_id_track']) {
                case 'show_without_track':
                    $filter[] = "NOT EXISTS (SELECT * FROM gems__respondent2track
                           WHERE gr2o_id_user = gr2t_id_user AND gr2o_id_organization = gr2t_id_organization)";
                    // Intentional fall through
                case 'show_all':
                    unset($filter['gr2t_id_track']);
                    break;

                case 'show_with_track':
                default:
                    $model = $this->getModel();
                    if (! $model->hasAlias('gems__respondent2track')) {
                        $model->addTable(
                                'gems__respondent2track',
                                array('gr2o_id_user' => 'gr2t_id_user', 'gr2o_id_organization' => 'gr2t_id_organization')
                                );
                    }
                    if (! $model->hasAlias('gems__tracks')) {
                        $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track'));
                    }
                    if (! isset($filter['__active_tracks'], $filter['__active_tracks'][$filter['gr2t_id_track']])) {
                        unset($filter['gr2t_id_track']);
                    }

            }
        }

        if (! isset($filter['show_with_track'])) {
            $filter['show_with_track'] = 1;
        }

        unset($filter['__active_tracks']);

        return $filter;
    }
784117
private function filterRequest(Request $request)
    {
        $event = $this->eventDispatcher->raiseEvent(new FilterRequestEvent($request));
        if ($event->hasResponse()) {
            $rsp = $event->getResponse();
            if ($rsp instanceof Response) {
                $this->eventDispatcher->raiseEvent(new FilterResponseEvent($request, $rsp));

                return $rsp;
            } elseif ($rsp instanceof Request) {
                $this->guardAgainstInfiniteRedirection($request, $rsp);

                return $this->dispatch($rsp);
            }
        }

        //The event handlers did not return a Request or a Response so invoke the controller
        $response = $this->controllerDispatcher->runController($request);
        $this->eventDispatcher->raiseEvent(new FilterResponseEvent($request, $response));

        return $response;
    }
1307697
public function getSearchFilter($useRequest = false)
    {
        if (null !== $this->_searchFilter) {
            return $this->_searchFilter;
        }

        $this->_searchFilter = parent::getSearchFilter($useRequest);

        $this->_searchFilter[] = 'gto_start_time IS NOT NULL';
        if (!isset($this->_searchFilter['incomplete']) || !$this->_searchFilter['incomplete']) {
            $this->_searchFilter[] = 'gto_completion_time IS NOT NULL';
        }

        if (isset($this->_searchFilter['dateused']) && $this->_searchFilter['dateused']) {
            $where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($this->_searchFilter, $this->db);
            if ($where) {
                $this->_searchFilter[] = $where;
            }
        }

        $this->_searchFilter['gco_code'] = 'consent given';
        $this->_searchFilter['grc_success'] = 1;

        if (isset($this->_searchFilter['ids'])) {
            $idStrings = $this->_searchFilter['ids'];

            $idArray = preg_split('/[\s,;]+/', $idStrings, -1, PREG_SPLIT_NO_EMPTY);

            if ($idArray) {
                $this->_searchFilter['gto_id_respondent'] = $idArray;
            }
        }

        return $this->_searchFilter;
    }
563633
public function getByUser($userId, $paginate = null)
    {
        $query = $this->model->where('user_id', $userId);

        if (!is_null($paginate)) {
            return $query->paginate($paginate);
        }

        return $query->get();
    }
978101
public function searchAction(Request $request)
    {
        $queryString = $request->query->get('q');
        $index = $request->query->get('index', null);
        $locale = $request->query->get('locale', null);

        $page = $this->listRestHelper->getPage();
        $limit = $this->listRestHelper->getLimit();
        $startTime = microtime(true);

        $indexes = $index ? [$index] : $this->getAllowedIndexes();

        $query = $this->searchManager->createSearch($queryString);

        if ($locale) {
            $query->locale($locale);
        }

        $query->indexes($indexes);
        $query->setLimit($limit);

        $time = microtime(true) - $startTime;

        $adapter = new ArrayAdapter(iterator_to_array($query->execute()));
        $pager = new Pagerfanta($adapter);
        $pager->setMaxPerPage($limit);
        $pager->setCurrentPage($page);

        $representation = new SearchResultRepresentation(
            new CollectionRepresentation($pager->getCurrentPageResults(), 'result'),
            'sulu_search_search',
            [
                'locale' => $locale,
                'query' => $query,
                'index' => $index,
            ],
            (int) $page,
            (int) $limit,
            $pager->getNbPages(),
            'page',
            'limit',
            false,
            $adapter->getNbResults(),
            $this->getIndexTotals($adapter->getArray()),
            number_format($time, 8)
        );

        $view = View::create($representation);
        $context = new Context();
        $context->enableMaxDepth();
        $view->setContext($context);

        return $this->viewHandler->handle($view);
    }
861802
public function buildSearch(SearchRequest $request, $filters = null)
    {
        $search = new Search();

        /** @var FilterInterface[] $filters */
        $filters = $filters ? $filters : $this->all();
        foreach ($filters as $name => $filter) {
            $filter->modifySearch($search, $request->get($name), $request);
        }

        return $search;
    }
1074729
protected function getFilters(Request $request)
    {
        $type = $this->getFilterType($request);

        if (!$type) {
            return $request->query->get('search')['value'];
        }

        $filter = new $type();

        $param = $filter->getBlockPrefix();

        return $request->query->get($param);
    }
675559
public function getOAuthCallbackAction(Request $request)
    {
        $this->initSessionBag();

        if ($request->query->get("state") != $this->sessionBag->get("hash")) {
            throw new UserException("Invalid session verification hash");
        }

        $guzzle = new GuzzleClient();
        try {
            $response = $guzzle->post($this->getTokenUrl(), array("body" => array(
                "client_id" => $this->getClientId(),
                "client_secret" => $this->getClientSecret(),
                "grant_type" => $this->grantType,
                "redirect_uri" => $this->getCallbackUrl($request),
                "code" => $request->query->get("code")
            )));
        } catch (ClientException $e) {
            $errCode = $e->getResponse()->getStatusCode();
            if ($errCode == 400) {
                $desc = jsonDecode($e->getResponse()->getBody(true), true);
                $code = empty($desc["code"]) ? 0 : $desc["code"];
                $message = empty($desc["error_message"]) ? "Unknown error from API." : $desc["error_message"];

                throw new UserException(
                    "OAuth authentication failed[{$code}]: {$message}",
                    null,
                    [
                        'response' => $e->getResponse()->getBody()
                    ]
                );
            } else {
                throw $e;
            }
        }

        $responseData = jsonDecode($response->getBody(true));

        $this->storeOAuthData($responseData);
        return $this->returnResult($responseData);
    }
954163
public static function get_users_in_context(userlist $userlist) {
        global $DB;

        $context = $userlist->get_context();

        if (!$context instanceof \context_module) {
            return;
        }

        $params = [
            'instanceid' => $context->instanceid,
            'module' => 'workshop',
        ];

        // One query to fetch them all, one query to find them, one query to bring them all and into the userlist add them.
        $sql = "SELECT ws.authorid, ws.gradeoverby, wa.reviewerid, wa.gradinggradeoverby, wr.userid
                  FROM {course_modules} cm
                  JOIN {modules} m ON cm.module = m.id AND m.name = :module
                  JOIN {workshop} w ON cm.instance = w.id
                  JOIN {workshop_submissions} ws ON ws.workshopid = w.id
             LEFT JOIN {workshop_assessments} wa ON wa.submissionid = ws.id
             LEFT JOIN {workshop_aggregations} wr ON wr.workshopid = w.id
                 WHERE cm.id = :instanceid";

        $userids = [];
        $rs = $DB->get_recordset_sql($sql, $params);

        foreach ($rs as $r) {
            if ($r->authorid) {
                $userids[$r->authorid] = true;
            }
            if ($r->gradeoverby) {
                $userids[$r->gradeoverby] = true;
            }
            if ($r->reviewerid) {
                $userids[$r->reviewerid] = true;
            }
            if ($r->gradinggradeoverby) {
                $userids[$r->gradinggradeoverby] = true;
            }
            if ($r->userid) {
                $userids[$r->userid] = true;
            }
        }

        $rs->close();

        if ($userids) {
            $userlist->add_users(array_keys($userids));
        }
    }
1251498
public function store(UserRequest $request)
    {
        $input = $request->except('roles');

        if ($request->has('password')) {
            $input['password'] = bcrypt($request->password);
        } else {
            unset($input['password']);
        }

        $record = $this->model->create($input);

        if ($request->has('roles')) {
            $record->syncRoles($request->roles);
        }

        $this->notify([
            'type' => 'success',
            'title' => 'Successful create user!',
            'description' => 'User is created successfully!',
        ]);

        return redirect(route('user.edit', ['id' => $record->id]));
    }
852055
public function getSearchRequest($filter, $limit = 1, $conditions = [])
    {
        $self = $this;

        return new StorageDataRequest(
            [$limit, $conditions],
            function ($limit, $conditions) use ($self) {
                $timeout = $conditions['timeout'] ?? 1;
                $consumer = $self->getRouter()->getConsumer($self->getResource(), $timeout);
                $results = [];

                while ($limit--) {
                    $results[] = $consumer->readOne();
                }

                return $results;
            }
        );
    }
127513
public function get( $key, $user_id = null, $single = true, $default = '' ) {
		if ( ! isset( $user_id ) ) {
			$user_id = $this->user_id;
		}
		if ( $user_id <= 0 ) {
			return $this->apply_filters( 'get_user_meta', $default, $key, $user_id, $single, $default );
		}

		return $this->apply_filters( 'get_user_meta', get_user_meta( $user_id, $this->get_meta_key( $key ), $single ), $key, $user_id, $single, $default, $this->get_user_prefix() );
	}
23242
public function getFilterWidgetAction(Request $request)
    {
        $translator = $this->get('translator');
        $fieldSet = $request->get('fieldset');
        $field = $request->get('field');

        $config = $this->admin->getConfigurationPool()->getContainer()->getParameter('librinfo_varieties');
        $fieldConfig = $config['variety_descriptions'][$fieldSet][$field];
        $choiceType = CustomChoiceType::class;
        $options = $fieldConfig['options'];
        $type = $fieldConfig['type'] != 'textarea' ? $fieldConfig['type'] : 'text';

        if ($type == 'blast_custom_checkbox') {
            $type = 'choice';
            $options = array_merge($options, array(
                'choices' => array('1' => $translator->trans('yes'), '0' => $translator->trans('no')),
            ));
        }

        if ($type == $choiceType) {
            $options['is_filter'] = true;

            if (isset($options['expanded'])) {
                unset($options['expanded']);
            }

            if (isset($options['multiple'])) {
                unset($options['multiple']);
            }
        }

        if ($type == 'blast_tinymce') {
            $type = 'text';
        }

        if (isset($options['choices']) && empty($options['choices'])) {
            unset($options['choices']);
        }

        if (isset($options['choices_class']) && $type != $choiceType) {
            unset($options['choices_class']);
        }

        if (isset($options['blast_choices']) && $type != $choiceType) {
            unset($options['blast_choices']);
        }

        if (isset($options['help'])) {
            unset($options['help']);
        }

        $view = $this->createFormBuilder()
                ->add('value', $type, $options)
                ->getForm()
                ->createView()
        ;

        return $this->render(
            'LibrinfoVarietiesBundle:Form:filter_widget.html.twig',
            array(
                'form' => $view,
            ),
            null
        );
    }
495431
public function getSearchRequest($filter, $limit = 1, $conditions = [])
    {
        $db = $this->_getConnection();
        $table = $this->table;
        $self = $this;

        $request = new StorageDataRequest(
            [$filter, $limit],
            function ($filter, $limit) use ($db, $table, $self) {
                if (!$db) {
                    $self->logError('Missing connection on getSearchRequest on table: ' . $table);
                    return false;
                }
                
                //
                $filterBinds = [];
                foreach ($filter as $id => $filterItem) {
                    $filterBinds[$id] = $filterItem[2];  
                }
                //
                $filterBinds = $this->prepareBind($filterBinds, $db, false);
                //
                foreach ($filter as $id => &$filterItem) {
                    $filterItem[2] = $filterBinds[$id];
                } unset($filterItem);
                
                //
                $filtersWhereArray = $this->_prepapreFilters($filter);
                
                $query = 'SELECT * FROM ' . $table
                    . (!empty($filtersWhereArray) ? ' WHERE (' . implode(' ) AND (', $filtersWhereArray) . ')' : '')
                    . ' LIMIT '.$limit;

                $stmnt = $db->query($query);

                if (!$stmnt) {
                    $this->logError('Cannot execute getSearchRequest on table: ' . $table . ':' . implode(',', $db->errorInfo()), [
                        'code' => $db->errorCode(),
                    ]);

                    return false;
                }

                $result = $stmnt->fetchAll(PDO::FETCH_ASSOC);

                if (!$result && (int) $stmnt->errorCode() > 0) {
                    $this->logError('Error on execution on getSearchRequest on table: ' . $table . ':' . implode(',',
                            $stmnt->errorInfo()), [
                        'code' => $stmnt->errorCode(),
                    ]);

                    return false;
                }

                return $result;
            });

        return $request;
    }
37680
private function parseRequest($request)
    {
        if (empty($request)) {
            return;
        }

        $this->request = $request;

        // Models used in this request.
        $models_used = [];

        // Review each request.
        foreach ($this->request as $name => $filters) {
            // This name is not present in available attributes.
            if (!Arr::has($this->attributes, $name)) {
                continue;
            }

            // Get the settings for the given attribute.
            $settings = Arr::get($this->attributes, $name);

            // Settings is empty.
            if (empty($settings)) {
                continue;
            }

            // Check and validate each of the filters.
            $filters = self::validateFilters($filters, $settings);

            // Search against current model.
            if (($model_name = Arr::get($settings, 'model_name')) === 'self') {
                $this->search_models['self'][$name] = $filters;
                continue;
            }

            // Search against an model via relationship.
            $models_used[$model_name] = true;
            $this->search_models[$model_name][$name] = $filters;
        }

        // Join the models to this query.
        if (count($models_used)) {
            $this->modelJoin($models_used);
        }
    }