Adds ran database queries to the request

@param Request $request

@return Request
4836
public function resolve(Request $request)
    {
        $request->databaseQueries = array_merge($request->databaseQueries, $this->getDatabaseQueries());

        return $request;
    }
999396
public function directCreateAction(Request $request)
    {
        $filter = new Filter();
        $filter->setName($request->request->get('filter_name'));
        $filter->setDescription($request->request->get('filter_description'));
        $filter->setState($request->request->getBoolean('filter_public') ? FilterStateEnum::ALL : FilterStateEnum::SELF);
        $filter->setCreatorUsername($this->getUser()->getUsername());

        $filter->setRoute($request->request->get('filter_route'));
        $filter->setArguments(json_decode($request->request->get('filter_route_arguments'), true));
        $filter->setConditions(json_decode($request->get('filter_conditions'), true));

        if (!is_array($filter->getConditions()) || !is_array($filter->getArguments())) {
            throw new BadRequestHttpException();
        }

        if ($this->router->getRouteCollection()->get($filter->getRoute()) === null) {
            throw new BadRequestHttpException();
        }

        $this->entityManager->persist($filter);
        $this->entityManager->flush();

        return $this->redirect($this->router->generate(
            $filter->getRoute(),
            array_merge($filter->getArguments(), $filter->getConditions())
        ));
    }
811086
public function manualMySql(Request $request)
    {
        $this->admControlInit($request, '/dashboard/db/all');
        if ($this->v["uID"] == 1) { // && in_array($_SERVER["REMOTE_ADDR"], ['192.168.10.1'])) {
    		$this->v["manualMySql"] = 'Connected successfully<br />';
            $db = mysqli_connect(env('DB_HOST', 'localhost'), env('DB_USERNAME', 'homestead'), 
                env('DB_PASSWORD', 'secret'), env('DB_DATABASE', 'homestead'));
            if ($db->connect_error) {
                $this->v["manualMySql"] = "Connection failed: " . $db->connect_error . '<br />';
            }
    		$this->v["lastSql"] = '';
    		$this->v["lastResults"] = [];
    		if ($request->has('mys') && trim($request->mys) != '') {
    		    $this->v["lastSql"] = trim($request->mys);
    		    $this->v["manualMySql"] .= '<b>Statements submitted...</b><br />';
    		    $statements = $GLOBALS["SL"]->mexplode(';', $request->mys);
    		    foreach ($statements as $sql) {
    		        $cnt = 0;
    		        if (trim($sql) != '') {
                        ob_start();
                        $res = mysqli_query($db, $sql);
                        $errorCatch = ob_get_contents();
                        ob_end_clean();
                        $this->v["lastResults"][$cnt][0] = $sql;
                        $this->v["lastResults"][$cnt][1] = $errorCatch;
                        if ($res->isNotEmpty()) {
                            ob_start();
                            print_r($res);
                            $this->v["lastResults"][$cnt][2] = ob_get_contents();
                            ob_end_clean();
                        }
                        $cnt++;
                    }
                }
    		}
    		mysqli_close($db);
    		return view('vendor.survloop.admin.db.manualMySql', $this->v);
    	}
        return $this->redir('/dashboard/db/export');
    }
1319213
public function run(&$query, $model, $request)
    {
        $this->query = $query;
        $this->getAttributes($model);
        $this->parseRequest($request);

        return $this->query();
    }
338503
protected function getRefererQueryParameters(Request $request)
    {
        $referer = $request->server->get('HTTP_REFERER');
        $request = Request::create($referer);

        return (array) $request->query->getIterator();
    }
823442
public static function fromRequest(Request $request)
    {
        return (new static)
                ->batchId($request->batch_id)
                ->uuids($request->uuids)
                ->beforeSequence($request->before)
                ->tag($request->tag)
                ->familyHash($request->family_hash)
                ->limit($request->take ?? 50);
    }
1283946
public function query(Request $request)
    {
        $query = (string) $request->request->get('qry');

        // since the query comes from a submited form, normalize crlf,cr,lf ...
        $query = StringHelper::crlfNormalize($query);

        $json = [
            'query' => $query
        ];

        $options = SearchEngineOptions::fromRequest($this->app, $request);

        $perPage = (int) $this->getSettings()->getUserSetting($this->getAuthenticatedUser(), 'images_per_page');

        $page = (int) $request->request->get('pag');
        $firstPage = $page < 1;

        $engine = $this->getSearchEngine();
        if ($page < 1) {
            $engine->resetCache();
            $page = 1;
        }

        $options->setFirstResult(($page - 1) * $perPage);
        $options->setMaxResults($perPage);

        $user = $this->getAuthenticatedUser();
        $userManipulator = $this->getUserManipulator();
        $userManipulator->logQuery($user, $query);

        try {
            $result = $engine->query($query, $options);

            if ($this->getSettings()->getUserSetting($user, 'start_page') === 'LAST_QUERY') {
                // try to save the "fulltext" query which will be restored on next session
                try {
                    // local code to find "FULLTEXT" value from jsonQuery
                    $findFulltext = function($clause) use(&$findFulltext) {
                        if(array_key_exists('_ux_zone', $clause) && $clause['_ux_zone']=='FULLTEXT') {
                            return $clause['value'];
                        }
                        if($clause['type']=='CLAUSES') {
                            foreach($clause['clauses'] as $c) {
                                if(($r = $findFulltext($c)) !== null) {
                                    return $r;
                                }
                            }
                        }
                        return null;
                    };

                    $userManipulator->setUserSetting($user, 'last_jsonquery', (string)$request->request->get('jsQuery'));

                    $jsQuery = @json_decode((string)$request->request->get('jsQuery'), true);
                    if(($ft = $findFulltext($jsQuery['query'])) !== null) {
                        $userManipulator->setUserSetting($user, 'start_page_query', $ft);
                    }
                }
                catch(\Exception $e) {
                    // no-op
                }
            }

            // log array of collectionIds (from $options) for each databox
            $collectionsReferencesByDatabox = $options->getCollectionsReferencesByDatabox();
            foreach ($collectionsReferencesByDatabox as $sbid => $references) {
                $databox = $this->findDataboxById($sbid);
                $collectionsIds = array_map(function(CollectionReference $ref){return $ref->getCollectionId();}, $references);
                $this->getSearchEngineLogger()->log($databox, $result->getQueryText(), $result->getTotal(), $collectionsIds);
            }

            $proposals = $firstPage ? $result->getProposals() : false;

            $npages = $result->getTotalPages($perPage);

            $page = $result->getCurrentPage($perPage);

            $queryESLib = $result->getQueryESLib();

            $string = '';

            if ($npages > 1) {
                $d2top = ($npages - $page);
                $d2bottom = $page;

                if (min($d2top, $d2bottom) < 4) {
                    if ($d2bottom < 4) {
                        if($page != 1){
                            $string .= "<a id='PREV_PAGE' class='btn btn-primary btn-mini'></a>";
                        }
                        for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i++) {
                            if ($i == $page)
                                $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'"/>';
                            else
                                $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>';
                        }
                        if ($npages > 4)
                            $string .= "<a id='NEXT_PAGE' class='btn btn-primary btn-mini'></a>";
                        $string .= '<a href="#" class="btn btn-primary btn-mini search-navigate-action" data-page="' . $npages . '" id="last"></a>';
                    } else {
                        $start = $npages - 4;
                        if (($start) > 0){
                            $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="1" id="first"></a>';
                            $string .= '<a id="PREV_PAGE" class="btn btn-primary btn-mini"></a>';
                        }else
                            $start = 1;
                        for ($i = ($start); $i <= $npages; $i++) {
                            if ($i == $page)
                                $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'" />';
                            else
                                $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>';
                        }
                        if($page < $npages){
                            $string .= "<a id='NEXT_PAGE' class='btn btn-primary btn-mini'></a>";
                        }
                    }
                } else {
                    $string .= '<a class="btn btn-primary btn-mini btn-mini search-navigate-action" data-page="1" id="first"></a>';

                    for ($i = ($page - 2); $i <= ($page + 2); $i++) {
                        if ($i == $page)
                            $string .= '<input type="text" value="' . $i . '" size="' . (strlen((string) $i)) . '" class="btn btn-mini search-navigate-input-action" data-initial-value="' . $i . '" data-total-pages="'.$npages.'" />';
                        else
                            $string .= '<a class="btn btn-primary btn-mini search-navigate-action" data-page="'.$i.'">' . $i . '</a>';
                    }

                    $string .= '<a href="#" class="btn btn-primary btn-mini search-navigate-action" data-page="' . $npages . '" id="last"></a>';
                }
            }
            $string .= '<div style="display:none;"><div id="NEXT_PAGE"></div><div id="PREV_PAGE"></div></div>';

            $explain = $this->render(
                "prod/results/infos.html.twig",
                [
                    'results'=> $result,
                    'esquery' => $this->getAclForUser()->is_admin() ?
                        json_encode($queryESLib['body'], JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES) :
                        null
                ]
            );

            $infoResult = '<div id="docInfo">'
                . $this->app->trans('%number% documents<br/>selectionnes', ['%number%' => '<span id="nbrecsel"></span>'])
                . '<div class="detailed_info_holder"><img src="/assets/common/images/icons/dots.png" class="image-normal"><img src="/assets/common/images/icons/dots-darkgreen-hover.png" class="image-hover">'
                . '<div class="detailed_info">
                    <table>
                        <thead>
                            <tr>
                                <th>Nb</th>
                                <th>Type</th>
                                <th>File size</th>
                                <th>Duration</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>1</td>
                                <td>Audio</td>
                                <td>1 Mb</td>
                                <td>00:04:31</td>
                            </tr>
                            <tr>
                                <td>1</td>
                                <td>Documents</td>
                                <td>20 Kb</td>
                                <td>N/A</td>
                            </tr>
                            <tr>
                                <td>4</td>
                                <td>Images</td>
                                <td>400 Kb</td>
                                <td>N/A</td>
                            </tr>
                            <tr>
                                <td>1</td>
                                <td>Video</td>
                                <td>19 Mb</td>
                                <td>00:20:36</td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td>6</td>
                                <td>Total</td>
                                <td>24.20 Mb</td>
                                <td>00:25:17</td>
                            </tr>
                        </tfoot>
                    </table></div></div>'
                . '</div><a href="#" class="search-display-info" data-infos="' . str_replace('"', '&quot;', $explain) . '">'
                . $this->app->trans('%total% reponses', ['%total%' => '<span>'.$result->getTotal().'</span>']) . '</a>';

            $json['infos'] = $infoResult;
            $json['navigationTpl'] = $string;
            $json['navigation'] = [
                'page' => $page,
                'perPage' => $perPage
            ];

            $prop = null;

            if ($firstPage) {
                $propals = $result->getSuggestions();
                if (count($propals) > 0) {
                    foreach ($propals as $prop_array) {
                        if ($prop_array->getSuggestion() !== $query && $prop_array->getHits() > $result->getTotal()) {
                            $prop = $prop_array->getSuggestion();
                            break;
                        }
                    }
                }
            }

            if ($result->getTotal() === 0) {
                $template = 'prod/results/help.html.twig';
            } else {
                $template = 'prod/results/records.html.twig';
            }
            $json['results'] = $this->render($template, ['results'=> $result]);


            // add technical fields
            $fieldsInfosByName = [];
            foreach(ElasticsearchOptions::getAggregableTechnicalFields() as $k => $f) {
                $fieldsInfosByName[$k] = $f;
                $fieldsInfosByName[$k]['trans_label'] = $this->app->trans($f['label']);
                $fieldsInfosByName[$k]['labels'] = [];
                foreach($this->app->getAvailableLanguages() as $locale => $lng) {
                    $fieldsInfosByName[$k]['labels'][$locale] = $this->app->trans($f['label'], [], "messages", $locale);
                }
            }

            // add databox fields
            // get infos about fields, fusionned and by databox
            $fieldsInfos = [];  // by databox
            foreach ($this->app->getDataboxes() as $databox) {
                $sbasId = $databox->get_sbas_id();
                $fieldsInfos[$sbasId] = [];
                foreach ($databox->get_meta_structure() as $field) {
                    $name = $field->get_name();
                    $fieldsInfos[$sbasId][$name] = [
                      'label'    => $field->get_label($this->app['locale']),
                      'labels'   => $field->get_labels(),
                      'type'     => $field->get_type(),
                      'business' => $field->isBusiness(),
                      'multi'    => $field->is_multi(),
                    ];

                    // infos on the "same" field (by name) on multiple databoxes !!!
                    // label(s) can be inconsistants : the first databox wins
                    if (!isset($fieldsInfosByName[$name])) {
                        $fieldsInfosByName[$name] = [
                            'label'       => $field->get_label($this->app['locale']),
                            'labels'      => $field->get_labels(),
                            'type'        => $field->get_type(),
                            'field'       => $field->get_name(),
                            'query'       => "field." . $field->get_name() . ":%s",
                            'trans_label' => $field->get_label($this->app['locale']),
                        ];
                        $field->get_label($this->app['locale']);
                    }
                }
            }

            // populates fileds infos
            $json['fields'] = $fieldsInfos;

            // populates rawresults
            // need acl so the result will not include business fields where not allowed
            $acl = $this->getAclForUser();
            $json['rawResults'] = [];
            /** @var ElasticsearchRecord $record */
            foreach($result->getResults() as $record) {
                $rawRecord = $record->asArray();

                $sbasId = $record->getDataboxId();
                $baseId = $record->getBaseId();

                $caption = $rawRecord['caption'];
                if($acl && $acl->has_right_on_base($baseId, \ACL::CANMODIFRECORD)) {
                    $caption = array_merge($caption, $rawRecord['privateCaption']);
                }

                // read the fields following the structure order
                $rawCaption = [];
                foreach($fieldsInfos[$sbasId] as $fieldName=>$fieldInfos) {
                    if(array_key_exists($fieldName, $caption)) {
                        $rawCaption[$fieldName] = $caption[$fieldName];
                    }
                }
                $rawRecord['caption'] = $rawCaption;
                unset($rawRecord['privateCaption']);

                $json['rawResults'][$record->getId()] = $rawRecord;
            }

            // populates facets (aggregates)
            $facets = [];
            // $facetClauses = [];
            foreach ($result->getFacets() as $facet) {
                $facetName = $facet['name'];

                if(array_key_exists($facetName, $fieldsInfosByName)) {

                    $f = $fieldsInfosByName[$facetName];

                    $facet['label'] = $f['trans_label'];
                    $facet['labels'] = $f['labels'];
                    $facet['type'] = strtoupper($f['type']) . "-AGGREGATE";
                    $facets[] = $facet;

                    // $facetClauses[] = [
                    //    'type'  => strtoupper($f['type']) . "-AGGREGATE",
                    //    'field' => $f['field'],
                    //    'facet' => $facet
                    // ];
                }
            }

            // $json['jsq'] = $facetClauses;

            $json['facets'] = $facets;
            $json['phrasea_props'] = $proposals;
            $json['total_answers'] = (int) $result->getAvailable();
            $json['next_page'] = ($page < $npages && $result->getAvailable() > 0) ? ($page + 1) : false;
            $json['prev_page'] = ($page > 1 && $result->getAvailable() > 0) ? ($page - 1) : false;
            $json['form'] = $options->serialize();
            $json['queryCompiled'] = $result->getQueryCompiled();
            $json['queryAST'] = $result->getQueryAST();
            $json['queryESLib'] = $queryESLib;
        }
        catch(\Exception $e) {
            // we'd like a message from the parser so get all the exceptions messages
            $msg = '';
            for(; $e; $e=$e->getPrevious()) {
                $msg .= ($msg ? "\n":"") . $e->getMessage();
            }
            $template = 'prod/results/help.html.twig';
            $result = [
                'error' => $msg
            ];
            $json['results'] = $this->render($template, ['results'=> $result]);
        }


        return $this->app->json($json);
    }
1271289
public function bindRequest(Request $request)
    {
        $query = $request->query;
        $session = $request->getSession();

        $adminListName = 'listconfig_'.$request->get('_route');

        $this->page = $request->query->getInt('page', 1);
        // Allow alphanumeric, _ & . in order by parameter!
        $this->orderBy = preg_replace('/[^[a-zA-Z0-9\_\.]]/', '', $request->query->get('orderBy', ''));
        $this->orderDirection = $request->query->getAlpha('orderDirection', '');

        // there is a session and the filter param is not set
        if ($session->has($adminListName) && !$query->has('filter')) {
            $adminListSessionData = $request->getSession()->get($adminListName);
            if (!$query->has('page')) {
                $this->page = $adminListSessionData['page'];
            }

            if (!$query->has('orderBy')) {
                $this->orderBy = $adminListSessionData['orderBy'];
            }

            if (!$query->has('orderDirection')) {
                $this->orderDirection = $adminListSessionData['orderDirection'];
            }
        }

        // save current parameters
        $session->set(
            $adminListName,
            array(
                'page' => $this->page,
                'orderBy' => $this->orderBy,
                'orderDirection' => $this->orderDirection,
            )
        );

        $this->getFilterBuilder()->bindRequest($request);
    }
12677
public function bindRequest(Request $request)
    {
        $query = $request->query;
        $session = $request->getSession();

        $adminListName = 'listconfig_' . $request->get('_route');

        $this->page = $request->query->getInt('page', 1);
        $this->limit = $request->query->getInt('limit', $this->getLimitOptions()[0]);

        $adminListSessionData = $request->getSession()->get($adminListName);
        if (!$query->has('limit') && null !== $adminListSessionData && isset($adminListSessionData['limit'])) {
            $this->limit = $adminListSessionData['limit'];
        }

        if ($request->query->has('limit') && !$request->query->has('page')) {
            $this->page = 1;
        }

        // Allow alphanumeric, _ & . in order by parameter!
        $this->orderBy = preg_replace('/[^[a-zA-Z0-9\_\.]]/', '', $request->query->get('orderBy', ''));
        $this->orderDirection = $request->query->getAlpha('orderDirection', '');

        // there is a session and the filter param is not set
        if ($session->has($adminListName) && !$query->has('filter')) {
            if (!$query->has('page') && !$query->has('limit')) {
                $this->page = $adminListSessionData['page'];
            }

            if (!$query->has('orderBy')) {
                $this->orderBy = $adminListSessionData['orderBy'];
            }

            if (!$query->has('orderDirection')) {
                $this->orderDirection = $adminListSessionData['orderDirection'];
            }
        }

        // save current parameters
        $session->set(
            $adminListName,
            [
                'page' => $this->page,
                'limit' => $this->limit,
                'orderBy' => $this->orderBy,
                'orderDirection' => $this->orderDirection,
            ]
        );

        // Remove limit from query param so it doesn't affect the session of the filter builder
        $request->query->remove('limit');
        $this->getFilterBuilder()->bindRequest($request);
    }
183851
public function request(ServerRequest $request = null)
    {
        $finding = $this->map->findByRequest($request = ($request ? : $this->request));

        return $this->run($finding);
    }
197688
public function store(Request $request)
    {
        $this->validate($request, $this->validationRules($this->resource));
        $entry = $this->entriesRepository->create($request, $this->resource);

        return redirect('admin/' . $this->resource->slug)->with('success', 'Added');
    }
234684
public function addAction(Request $request)
    {
        $resource = $this->mapper->create($this->validateRequestParameters($request));

        return new Response('', 201, array('Location' => $this->mapper->generateReadUrl($resource)));
    }
121834
final public function run(Request $request)
    {
        $this->request = $request;
        $path = $this->request->getUri()->getPath();
        $this->requestedUri = ($path != "/") ? rtrim($path, "/") : "/";
        $this->requestedMethod = strtoupper($this->request->getMethod());
        $this->requestedRepresentation = $this->request->getAccept();
        $this->verifyRequestMethod();
        $route = $this->findRouteFromRequest();
        $this->prepareResponse($route);
    }
748831
private function setupRunQuery()
    {
        $obj_request = ($this->applyNamespace(new RunQueryRequest()));
        $obj_request->setSuggestedBatchSize(self::BATCH_SIZE); // Avoid having to run multiple batches
        $this->applyTransaction($obj_request->mutableReadOptions()); // ->setReadConsistency('some-val');
        return $obj_request;
    }
736871
public function addManuallyAction(Request $request)
    {
        $response = $this->getCacheTimeKeeper()->getResponse();
        // response was not modified for this request
        if ($response->isNotModified($request)) {
            return $response;
        }

        $item = new Item();

        /* @var $form Form */
        $form = $this->createForm('entity_item', $item)
            ->handleRequest($request);
        if ($form->isValid()) {
            /* @var $rep ItemRepository */
            $rep = $this->getDoctrine()->getRepository('AnimeDbCatalogBundle:Item');

            // Add a new entry only if no duplicates
            $duplicate = $rep->findDuplicate($item);
            if ($duplicate) {
                $request->getSession()->set(self::NAME_ITEM_ADDED, $item);

                return $this->redirect($this->generateUrl('item_duplicate'));
            } else {
                return $this->addItem($item);
            }
        }

        return $this->render('AnimeDbCatalogBundle:Item:add-manually.html.twig', [
            'form' => $form->createView(),
        ], $response);
    }
839069
public function store(Request $request)
    {
        $query = $this->getQuery();

        try {
            if ($request->input('query')) {
                $filter = new Filter($this->manager->newEntity()->getTable(), $this->queryable);
                $filter->build($query, $request->input('query'));
            }
        } catch (QuerySyntaxException $e) {
            return $this->error(['code' => 'QUERY_SYNTAX_ERROR', 'message' => 'Syntax error']);
        }

        $params = $request->only($this->fillable);

        DB::beginTransaction();

        $result = new Result();

        $query->chunk(100, function ($resources) use ($params, &$result) {
            foreach ($resources as $resource) {
                $result->addErrors($this->getManager()->update($resource, $params)->getErrors());
            }
        });

        if (!$result->ok()) {
            DB::rollBack();

            return $this->response(['errors' => $result->getSimpleErrors()], Response::HTTP_BAD_REQUEST);
        }

        DB::commit();

        return $this->response(null, Response::HTTP_OK);
    }
662573
public function pagerfanta(Request $request)
    {
        $sql = $this->createQueryBuilder('data');
        $sql->select('data');
        $sql->andWhere('data.uploadFile = :uploadFile');
        $sql->setParameter('uploadFile', $request->get('import_id'));

        switch ($request->get('type', 'all')) {
            case 'success':
                $sql->andWhere('data.status = 1 or data.status = 2 or data.status = 0');
                break;
            case 'nochanges':
                $sql->andWhere('data.status = 0');
                break;
            case 'new':
                $sql->andWhere('data.status = 1');
                break;
            case 'update':
                $sql->andWhere('data.status = 2');
                break;
            case 'error':
                $sql->andWhere('data.status = 3');
                break;
        }

        return $sql->getQuery();
    }