Skip to content
Snippets Groups Projects
MetaGer.php 41.2 KiB
Newer Older
  • Learn to ignore specific revisions
  • use App\lib\TextLanguageDetect\TextLanguageDetect;
    
    use Illuminate\Http\Request;
    use Jenssegers\Agent\Agent;
    
    Dominik Hebeler's avatar
    Dominik Hebeler committed
    use LaravelLocalization;
    
    use Predis\Connection\ConnectionException;
    
        # Einstellungen für die Suche
        protected $fokus;
        protected $eingabe;
        protected $q;
        protected $category;
        protected $time;
        protected $page;
        protected $lang;
        protected $cache = "";
        protected $site;
        protected $hostBlacklist   = [];
        protected $domainBlacklist = [];
        protected $stopWords       = [];
        protected $phrases         = [];
        protected $engines         = [];
        protected $results         = [];
        protected $ads             = [];
    
        protected $products        = [];
    
        protected $warnings        = [];
        protected $errors          = [];
        protected $addedHosts      = [];
    
        protected $startCount      = 0;
    
        # Daten über die Abfrage
        protected $ip;
        protected $language;
        protected $agent;
        # Konfigurationseinstellungen:
        protected $sumaFile;
        protected $mobile;
        protected $resultCount;
        protected $sprueche;
    
        protected $domainsBlacklisted = [];
    
        protected $url;
        protected $languageDetect;
    
    
            if (file_exists(config_path() . "/blacklistDomains.txt") && file_exists(config_path() . "/blacklistUrl.txt")) {
                $tmp                      = file_get_contents(config_path() . "/blacklistDomains.txt");
    
                $this->domainsBlacklisted = explode("\n", $tmp);
    
                $tmp                      = file_get_contents(config_path() . "/blacklistUrl.txt");
                $this->urlsBlacklisted    = explode("\n", $tmp);
            } else {
    
                Log::warning(trans('metaGer.blacklist.failed'));
    
            $dir = app_path() . "/Models/parserSkripte/";
            foreach (scandir($dir) as $filename) {
                $path = $dir . $filename;
                if (is_file($path)) {
                    require $path;
                }
            }
    
    
            $this->languageDetect = new TextLanguageDetect();
            $this->languageDetect->setNameMode("2");
    
            try {
                Cache::has('test');
                $this->canCache = true;
            } catch (ConnectionException $e) {
                $this->canCache = false;
            }
    
        # Erstellt aus den gesammelten Ergebnissen den View
    
        public function createView()
        {
            $viewResults = [];
    
            # Wir extrahieren alle notwendigen Variablen und geben Sie an unseren View:
    
            foreach ($this->results as $result) {
    
                $viewResults[] = get_object_vars($result);
            }
    
            # Wir müssen natürlich noch den Log für die durchgeführte Suche schreiben:
            $this->createLogs();
    
    
            if ($this->fokus === "bilder") {
                switch ($this->out) {
    
                    case 'results':
                        return view('metager3bilderresults')
                            ->with('results', $viewResults)
                            ->with('eingabe', $this->eingabe)
                            ->with('mobile', $this->mobile)
                            ->with('warnings', $this->warnings)
                            ->with('errors', $this->errors)
                            ->with('metager', $this)
    
                            ->with('browser', (new Agent())->browser());
    
                    default:
                        return view('metager3bilder')
                            ->with('results', $viewResults)
                            ->with('eingabe', $this->eingabe)
                            ->with('mobile', $this->mobile)
                            ->with('warnings', $this->warnings)
                            ->with('errors', $this->errors)
                            ->with('metager', $this)
    
                            ->with('browser', (new Agent())->browser());
    
            } else {
                switch ($this->out) {
                    case 'results':
                        return view('metager3results')
                            ->with('results', $viewResults)
                            ->with('eingabe', $this->eingabe)
                            ->with('mobile', $this->mobile)
                            ->with('warnings', $this->warnings)
                            ->with('errors', $this->errors)
                            ->with('metager', $this)
                            ->with('browser', (new Agent())->browser());
                        break;
                    case 'results-with-style':
                        return view('metager3')
                            ->with('results', $viewResults)
                            ->with('eingabe', $this->eingabe)
                            ->with('mobile', $this->mobile)
                            ->with('warnings', $this->warnings)
                            ->with('errors', $this->errors)
                            ->with('metager', $this)
                            ->with('suspendheader', "yes")
                            ->with('browser', (new Agent())->browser());
                        break;
                    default:
                        return view('metager3')
                            ->with('eingabe', $this->eingabe)
                            ->with('mobile', $this->mobile)
                            ->with('warnings', $this->warnings)
                            ->with('errors', $this->errors)
                            ->with('metager', $this)
                            ->with('browser', (new Agent())->browser());
                        break;
                }
    
        public function combineResults()
        {
            foreach ($this->engines as $engine) {
    
                if (isset($engine->next)) {
                    $this->next[] = $engine->next;
                }
                if (isset($engine->last)) {
                    $this->last[] = $engine->last;
                }
    
                foreach ($engine->results as $result) {
                    if ($result->valid) {
    
                foreach ($engine->products as $product) {
                    $this->products[] = $product;
                }
    
            uasort($this->results, function ($a, $b) {
                if ($a->getRank() == $b->getRank()) {
    
                return ($a->getRank() < $b->getRank()) ? 1 : -1;
            });
    
            # Validate Results
            $newResults = [];
    
            foreach ($this->results as $result) {
                if ($result->isValid($this)) {
    
            # Boost implementation
            $this->results = $this->parseBoost($this->results);
    
            #Adgoal Implementation
            $this->results = $this->parseAdgoal($this->results);
    
    
            if (isset($this->startForwards)) {
    
                $this->startCount = $this->startForwards;
    
            } elseif (isset($this->startBackwards)) {
    
                $this->startCount = $this->startBackwards - count($this->results) - 1;
    
            } else {
    
                $this->startCount = 0;
            }
    
    
            foreach ($this->results as $result) {
                if ($counter === 0) {
    
                $result->number = $counter + $this->startCount;
    
                $confidence     = 0;
                if ($firstRank > 0) {
                    $confidence = $result->rank / $firstRank;
                } else {
    
            if (LaravelLocalization::getCurrentLocale() === "en") {
    
                # Wir bieten einen bezahlten API-Zugriff an, bei dem dementsprechend die Werbung ausgeblendet wurde:
                # Aktuell ist es nur die Uni-Mainz. Deshalb überprüfen wir auch nur diese.
                $password = getenv('mainz');
    
                $password = md5($eingabe . $password);
    
                if ($this->password === $password) {
                    $this->ads       = [];
    
    
            if (count($this->results) <= 0) {
    
                $this->errors[] = trans('metaGer.results.failed');
    
            if ($this->canCache() && isset($this->next) && count($this->next) > 0 && count($this->results) > 0) {
    
                $page       = $this->page + 1;
    
                    'page'          => $page,
                    'startForwards' => $this->results[count($this->results) - 1]->number,
                    'engines'       => $this->next,
    
                ];
                Cache::put(md5(serialize($this->next)), serialize($this->next), 60);
    
        public function parseBoost($results)
        {
    
            foreach ($results as $result) {
                if (preg_match('/^(http[s]?\:\/\/)?(www.)?amazon\.de/', $result->anzeigeLink)) {
                    if (preg_match('/\?/', $result->anzeigeLink)) {
                        $result->link .= '&tag=boostmg01-21';
                    } else {
                        $result->link .= '?tag=boostmg01-21';
                    }
                    $result->partnershop = true;
    
                }
            }
            return $results;
    
        public function parseAdgoal($results)
        {
    
            $publicKey  = getenv('adgoal_public');
    
            $privateKey = getenv('adgoal_private');
    
                        $link = "http://" . $link;
                    }
                    $tldList .= parse_url($link, PHP_URL_HOST) . ",";
                    $result->tld = parse_url($link, PHP_URL_HOST);
                }
                $tldList = rtrim($tldList, ",");
    
                # Hashwert
                $hash = md5("meta" . $publicKey . $tldList . "GER");
    
    
                $link   = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
    
                $answer = json_decode(file_get_contents($link));
    
                # Nun müssen wir nur noch die Links für die Advertiser ändern:
    
                    foreach ($results as $result) {
                        if ($hoster === $result->tld) {
    
                            # Hier ist ein Advertiser:
                            # Das Logo hinzufügen:
    
                                $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
    
                                $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
    
                            # Den Link hinzufügen:
                            $publicKey = $publicKey;
                            $targetUrl = $result->anzeigeLink;
    
                            if (strpos($targetUrl, "http") !== 0) {
    
                                $targetUrl = "http://" . $targetUrl;
    
                            }
    
                            $gateHash            = md5($targetUrl . $privateKey);
                            $newLink             = "https://api.smartredirect.de/api_v2/ClickGate.php?p=" . $publicKey . "&k=" . $gateHash . "&url=" . urlencode($targetUrl) . "&q=" . $query;
                            $result->link        = $newLink;
    
    Karl's avatar
    Karl committed
        /*
         * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
         */
    
    
        public function createSearchEngines(Request $request)
        {
            if (!$request->has("eingabe")) {
    
            # Überprüfe, welche Sumas eingeschaltet sind
            $xml                  = simplexml_load_file($this->sumaFile);
    
    Karl's avatar
    Karl committed
            /* Erstellt die Liste der eingestellten Sumas
             * Der einzige Unterschied bei angepasstem Suchfokus ist, dass nicht nach den Typen einer Suma, sondern den im Request mitgegebenen Typen entschieden wird
             * Ansonsten wird genau das selbe geprüft und gemacht:
             * Handelt es sich um spezielle Suchmaschinen die immer an sein müssen
             * Wenn es Overture ist vermerken dass Overture an ist
             * Suma Zähler erhöhen
             * Zu Liste hinzufügen
             */
    
            foreach ($sumas as $suma) {
                if ($this->fokus === "angepasst") {
    
                    if ($request->has($suma["name"])
                        || ($this->fokus !== "bilder"
                            && ($suma["name"]->__toString() === "qualigo"
                                || $suma["name"]->__toString() === "similar_product_ads"
                                || (!$overtureEnabled && $suma["name"]->__toString() === "overtureAds")
    
                                || $suma["name"]->__toString() == "rlvproduct"
    
                            )
                        )
                    ) {
    
                        if (!(isset($suma['disabled']) && $suma['disabled']->__toString() === "1")) {
                            if ($suma["name"]->__toString() === "overture" || $suma["name"]->__toString() === "overtureAds") {
                                $overtureEnabled = true;
    
                            if ($suma["name"]->__toString() !== "qualigo" && $suma["name"]->__toString() !== "similar_product_ads" && $suma["name"]->__toString() !== "overtureAds") {
    
                    $types = explode(",", $suma["type"]);
                    if (in_array($this->fokus, $types)
                        || ($this->fokus !== "bilder"
                            && ($suma["name"]->__toString() === "qualigo"
                                || $suma["name"]->__toString() === "similar_product_ads"
                                || (!$overtureEnabled && $suma["name"]->__toString() === "overtureAds")
    
                                || $suma["name"]->__toString() == "rlvproduct"
    
                            )
                        )
                    ) {
                        if (!(isset($suma['disabled']) && $suma['disabled']->__toString() === "1")) {
                            if ($suma["name"]->__toString() === "overture" || $suma["name"]->__toString() === "overtureAds") {
                                $overtureEnabled = true;
    
                            if ($suma["name"]->__toString() !== "qualigo" && $suma["name"]->__toString() !== "similar_product_ads" && $suma["name"]->__toString() !== "overtureAds") {
    
                            $enabledSearchengines[] = $suma;
                        }
                    }
                }
            }
    
            # Sonderregelung für alle Suchmaschinen, die zu den Minisuchern gehören. Diese können alle gemeinsam über einen Link abgefragt werden
            $subcollections = [];
    
            $tmp            = [];
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['minismCollection'])) {
    
                    $subcollections[] = $engine['minismCollection']->__toString();
    
            if (sizeof($subcollections) > 0) {
                $count                        = sizeof($subcollections) * 10;
                $minisucherEngine             = $xml->xpath('suma[@name="minism"]')[0];
                $subcollections               = urlencode("(" . implode(" OR ", $subcollections) . ")");
    
                $minisucherEngine["formData"] = str_replace("<<SUBCOLLECTIONS>>", $subcollections, $minisucherEngine["formData"]);
                $minisucherEngine["formData"] = str_replace("<<COUNT>>", $count, $minisucherEngine["formData"]);
    
                $enabledSearchengines[]       = $minisucherEngine;
    
                $this->errors[] = trans('metaGer.settings.noneSelected');
    
            # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob eine der Suchmaschinen überhaupt eine Sitesearch unterstützt
            $siteSearchFailed = $this->checkCanNotSitesearch($enabledSearchengines);
    
            if ($request->has('next') && Cache::has($request->input('next')) && unserialize(Cache::get($request->input('next')))['page'] > 1) {
                $next       = unserialize(Cache::get($request->input('next')));
    
                $this->page = $next['page'];
    
                $engines    = $next['engines'];
                if (isset($next['startForwards'])) {
    
                    $this->startForwards = $next['startForwards'];
    
                }
    
                if (isset($next['startBackwards'])) {
    
                    $this->startBackwards = $next['startBackwards'];
    
            } else {
                foreach ($enabledSearchengines as $engine) {
    
    Karl's avatar
    Karl committed
                    # Wenn diese Suchmaschine gar nicht eingeschaltet sein soll
    
                    if (!$siteSearchFailed && strlen($this->site) > 0 && (!isset($engine['hasSiteSearch']) || $engine['hasSiteSearch']->__toString() === "0")) {
                        continue;
                    }
    
    Karl's avatar
    Karl committed
    
                    # Setze Pfad zu Parser
    
                    $path = "App\Models\parserSkripte\\" . ucfirst($engine["package"]->__toString());
    
    Karl's avatar
    Karl committed
                    # Prüfe ob Parser vorhanden
    
                    if (!file_exists(app_path() . "/Models/parserSkripte/" . ucfirst($engine["package"]->__toString()) . ".php")) {
    
                        Log::error(trans('metaGer.engines.noParser', ['engine' => $engine["name"]]));
    
    Karl's avatar
    Karl committed
                    # Es wird versucht die Suchengine zu erstellen
    
                    $time = microtime();
    
    Karl's avatar
    Karl committed
                    try {
    
                        $tmp = new $path($engine, $this);
                    } catch (\ErrorException $e) {
    
                        Log::error(trans('metaGer.engines.cantQuery', ['engine' => $engine["name"], 'error' => var_dump($e)]));
    
    Karl's avatar
    Karl committed
                    # Ausgabe bei Debug-Modus
    
                    if ($tmp->enabled && isset($this->debug)) {
                        $this->warnings[] = $tmp->service . "   Connection_Time: " . $tmp->connection_time . "    Write_Time: " . $tmp->write_time . " Insgesamt:" . ((microtime() - $time) / 1000);
                    }
    
    
    Karl's avatar
    Karl committed
                    # Wenn die neu erstellte Engine eingeschaltet ist, wird sie der Liste hinzugefügt
    
                    if ($tmp->isEnabled()) {
                        $engines[] = $tmp;
                    }
    
            # Wir starten die Suche manuell:
            foreach ($engines as $engine) {
                $engine->startSearch($this);
    
            $this->adjustFocus($sumas, $enabledSearchengines);
    
            /* Nun passiert ein elementarer Schritt.
             * Wir warten auf die Antwort der Suchmaschinen, da wir vorher nicht weiter machen können.
             * Aber natürlich nicht ewig.
             * Die Verbindung steht zu diesem Zeitpunkt und auch unsere Request wurde schon gesendet.
             * Wir geben der Suchmaschine nun bis zu 500ms Zeit zu antworten.
             */
    
            # Wir zählen die Suchmaschinen, die durch den Cache beantwortet wurden:
    
            $canBreak      = false;
            foreach ($engines as $engine) {
                if ($engine->cached) {
                    if ($overtureEnabled && ($engine->name === "overture" || $engine->name === "overtureAds")) {
                        $canBreak = true;
                    }
    
                } else {
                    # Das Array zählt einerseits die Suchmaschinen, auf die wir warten und andererseits
                    # welche Suchmaschinen nicht rechtzeitig geantwortet haben.
                    $enginesToLoad[$engine->name] = false;
    
                }
            }
    
            $this->waitForResults($enginesToLoad, $overtureEnabled, $canBreak);
    
            $this->retrieveResults($engines);
        }
    
    
        # Passt den Suchfokus an, falls für einen Fokus genau alle vorhandenen Sumas eingeschaltet sind
    
        public function adjustFocus($sumas, $enabledSearchengines)
        {
    
            # Findet für alle Foki die enthaltenen Sumas
            $foki = []; # [fokus][suma] => [suma]
    
            foreach ($sumas as $suma) {
                if ((!isset($suma['disabled']) || $suma['disabled'] === "") && (!isset($suma['userSelectable']) || $suma['userSelectable']->__toString() === "1")) {
                    if (isset($suma['type'])) {
    
                        # Wenn foki für diese Suchmaschine angegeben sind
                        $focuses = explode(",", $suma['type']->__toString());
                        foreach ($focuses as $foc) {
    
                            if (isset($suma['minismCollection'])) {
                                $foki[$foc][] = "minism";
                            } else {
                                $foki[$foc][] = $suma['name']->__toString();
                            }
    
                        # Wenn keine foki für diese Suchmaschine angegeben sind
    
                        if (isset($suma['minismCollection'])) {
                            $foki["andere"][] = "minism";
                        } else {
                            $foki["andere"][] = $suma['name']->__toString();
                        }
    
            # Findet die Namen der aktuell eingeschalteten Sumas
    
            foreach ($enabledSearchengines as $realEng) {
    
                $nam = $realEng["name"]->__toString();
    
                if ($nam !== "qualigo" && $nam !== "overtureAds" && $nam !== "rlvproduct") {
    
            # Anschließend werden diese beiden Listen verglichen (jeweils eine der Fokuslisten für jeden Fokus), um herauszufinden ob sie vielleicht identisch sind. Ist dies der Fall, so hat der Nutzer anscheinend Suchmaschinen eines kompletten Fokus eingestellt. Der Fokus wird dementsprechend angepasst.
    
            foreach ($foki as $fok => $engines) {
    
                # Jede eingeschaltete Engine ist für diesen Fokus geeignet
    
                foreach ($fokiEngNames as $fen) {
                    if (!in_array($fen, $realEngNames)) {
    
                # Jede im Fokus erwartete Engine ist auch eingeschaltet
    
                foreach ($realEngNames as $ren) {
                    if (!in_array($ren, $fokiEngNames)) {
    
                # Wenn die Listen identisch sind, setze den Fokus um
    
        public function checkCanNotSitesearch($enabledSearchengines)
        {
            if (strlen($this->site) > 0) {
                $enginesWithSite = 0;
                foreach ($enabledSearchengines as $engine) {
                    if (isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1") {
                        $enginesWithSite++;
    
                    $this->errors[] = trans('metaGer.sitesearch.failed', ['site' => $this->site, 'searchLink' => $this->generateSearchLink("web", false)]);
    
                    $this->warnings[] = trans('metaGer.sitesearch.success', ['site' => $this->site]);
    
        }
    
        public function waitForResults($enginesToLoad, $overtureEnabled, $canBreak)
        {
    
    
            # Auf wie viele Suchmaschinen warten wir?
            $engineCount = count($enginesToLoad);
    
    
            while (true) {
                $time          = (microtime(true) - $timeStart) * 1000;
    
                $loadedEngines = intval(Redis::hlen('search.' . $this->getHashCode()));
    
                if ($overtureEnabled && (Redis::hexists('search.' . $this->getHashCode(), 'overture') || Redis::hexists('search.' . $this->getHashCode(), 'overtureAds'))) {
    
                    if (($engineCount === 0 || $loadedEngines >= $engineCount) && $canBreak) {
    
                    }
    
                } elseif ($time >= 500 && $time < $this->time) {
    
                    if (($engineCount === 0 || ($loadedEngines / ($engineCount * 1.0)) >= 0.8) && $canBreak) {
    
    
            # Wir haben nun so lange wie möglich gewartet. Wir registrieren nun noch die Suchmaschinen, die geanwortet haben.
            $answered = Redis::hgetall('search.' . $this->getHashCode());
            foreach ($answered as $key => $value) {
                $enginesToLoad[$key] = true;
            }
            $this->enginesToLoad = $enginesToLoad;
    
        public function retrieveResults($engines)
        {
            # Von geladenen Engines die Ergebnisse holen
    
            foreach ($engines as $engine) {
                if (!$engine->loaded) {
                    try {
    
                        $engine->retrieveResults($this);
    
            foreach ($engines as $engine) {
                if (!$engine->loaded) {
    
    Karl's avatar
    Karl committed
        /*
         * Ende
         */
    
    
        public function parseFormData(Request $request)
        {
    
            # Sichert, dass der request in UTF-8 formatiert ist
    
            if ($request->input('encoding', '') !== "utf8") {
                # In früheren Versionen, als es den Encoding Parameter noch nicht gab, wurden die Daten in ISO-8859-1 übertragen
                $input = $request->all();
                foreach ($input as $key => $value) {
                    $input[$key] = mb_convert_encoding("$value", "UTF-8", "ISO-8859-1");
                }
                $request->replace($input);
            }
    
            # Zunächst überprüfen wir die eingegebenen Einstellungen:
    
            $this->fokus = $request->input('focus', 'web');
    
                $this->sumaFile = config_path() . "/sumas.xml";
    
                $this->sumaFile = config_path() . "/sumas.xml";
            }
    
            if (!file_exists($this->sumaFile)) {
    
            $this->eingabe = trim($request->input('eingabe', ''));
    
                $this->warnings[] = trans('metaGer.formdata.noSearch');
    
            if (isset($_SERVER['HTTP_LANGUAGE'])) {
    
                $this->language = $_SERVER['HTTP_LANGUAGE'];
    
                $this->language = "";
            }
            # Category
            $this->category = $request->input('category', '');
    
            $this->time = $request->input('time', 1000);
            # Page
    
            $this->page = 1;
    
            # Lang
            $this->lang = $request->input('lang', 'all');
    
            if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
                $this->lang = "all";
    
            $this->mobile = $this->agent->isMobile();
    
            $this->sprueche = $request->input('sprueche', 'off');
    
            # Ergebnisse pro Seite:
            $this->resultCount = $request->input('resultCount', '20');
            # Manchmal müssen wir Parameter anpassen um den Sucheinstellungen gerecht zu werden:
    
            if ($request->has('dart')) {
                $this->time       = 10000;
    
                $this->warnings[] = trans('metaGer.formdata.dartEurope');
    
            if ($this->time <= 500 || $this->time > 20000) {
                $this->time = 1000;
    
            if ($request->has('minism') && ($request->has('fportal') || $request->has('harvest'))) {
                $input    = $request->all();
                $newInput = [];
                foreach ($input as $key => $value) {
                    if ($key !== "fportal" && $key !== "harvest") {
                        $newInput[$key] = $value;
                    }
                }
                $request->replace($newInput);
    
            if (App::isLocale("en")) {
                $this->sprueche = "off";
    
            if ($this->resultCount <= 0 || $this->resultCount > 200) {
                $this->resultCount = 1000;
    
            if ($request->has('onenewspageAll') || $request->has('onenewspageGermanyAll')) {
                $this->time  = 5000;
                $this->cache = "cache";
            }
            if ($request->has('tab')) {
                if ($request->input('tab') === "off") {
    
                $this->password = $request->input('password');
    
            $this->out = $request->input('out', "html");
    
            if ($this->out !== "html" && $this->out !== "json" && $this->out !== "results" && $this->out !== "results-with-style") {
    
        }
    
        public function checkSpecialSearches(Request $request)
        {
    
            if (preg_match("/(.*)\bsite:(\S+)(.*)/si", $this->q, $match)) {
                $this->site = $match[2];
                $this->q    = $match[1] . $match[3];
            }
            if ($request->has('site')) {
    
                $this->site = $request->input('site');
            }
    
            # Wenn die Suchanfrage um das Schlüsselwort "-host:*" ergänzt ist, sollen bestimmte Hosts nicht eingeblendet werden
            while (preg_match("/(.*)(^|\s)-host:(\S+)(.*)/si", $this->q, $match)) {
                $this->hostBlacklist[] = $match[3];
                $this->q               = $match[1] . $match[4];
            }
            if (sizeof($this->hostBlacklist) > 0) {
                $hostString = "";
                foreach ($this->hostBlacklist as $host) {
                    $hostString .= $host . ", ";
                }
                $hostString       = rtrim($hostString, ", ");
    
                $this->warnings[] = trans('metaGer.formdata.hostBlacklist', ['host' => $hostString]);
    
            # Wenn die Suchanfrage um das Schlüsselwort "-domain:*" ergänzt ist, sollen bestimmte Domains nicht eingeblendet werden
            while (preg_match("/(.*)(^|\s)-domain:(\S+)(.*)/si", $this->q, $match)) {
                $this->domainBlacklist[] = $match[3];
                $this->q                 = $match[1] . $match[4];
            }
            if (sizeof($this->domainBlacklist) > 0) {
                $domainString = "";
                foreach ($this->domainBlacklist as $domain) {
                    $domainString .= $domain . ", ";
                }
                $domainString     = rtrim($domainString, ", ");
    
                $this->warnings[] = trans('metaGer.formdata.domainBlacklist', ['domain' => $domainString]);
    
            # Alle mit "-" gepräfixten Worte sollen aus der Suche ausgeschlossen werden.
            while (preg_match("/(.*)(^|\s)-(\S+)(.*)/si", $this->q, $match)) {
                $this->stopWords[] = $match[3];
                $this->q           = $match[1] . $match[4];
            }
            if (sizeof($this->stopWords) > 0) {
                $stopwordsString = "";
                foreach ($this->stopWords as $stopword) {
                    $stopwordsString .= $stopword . ", ";
                }
                $stopwordsString  = rtrim($stopwordsString, ", ");
    
                $this->warnings[] = trans('metaGer.formdata.stopwords', ['stopwords' => $stopwordsString]);
    
            while (preg_match("/(.*)\"(.+)\"(.*)/si", $tmp, $match)) {
                $tmp             = $match[1] . $match[3];
    
                $this->phrases[] = strtolower($match[2]);
    
                $p .= "\"$phrase\", ";
            }
            $p = rtrim($p, ", ");
    
                $this->warnings[] = trans('metaGer.formdata.phrase', ['phrase' => $p]);
    
            if (isset($this->next) && isset($this->next['engines']) && count($this->next['engines']) > 0) {
                $requestData         = $this->request->except(['page', 'out']);
                $requestData['next'] = md5(serialize($this->next));
                $link                = action('MetaGerSearch@search', $requestData);
            } else {
                $link = "#";
            }
            return $link;
    
            foreach ($this->engines as $engine) {
                $engine->rank($this);
            }
    
    Karl's avatar
    Karl committed
        public function removeInvalids()
        {
            $results = [];
            foreach ($this->results as $result) {
                if ($result->isValid($this)) {
                    $results[] = $result;
                }
    
            }
        }
    
    
            if (count($this->ads) > 0) {
                return get_object_vars(array_shift($this->ads));
    
        public function hasProducts()
        {
            if (count($this->products) > 0) {
                return true;
            } else {
                return false;
            }
        }
    
        public function getProducts()
        {
            $return = [];
            foreach ($this->products as $product) {
                $return[] = get_object_vars($product);
            }
            #die(var_dump($return));
            return $return;
    
        }
    
    
            $redis = Redis::connection('redisLogs');
            try
            {
                $logEntry = "";
                $logEntry .= "[" . date(DATE_RFC822, mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"))) . "]";
                $logEntry .= " pid=" . getmypid();
                $logEntry .= " ref=" . $this->request->header('Referer');
                $useragent = $this->request->header('User-Agent');
                $useragent = str_replace("(", " ", $useragent);
                $useragent = str_replace(")", " ", $useragent);
                $useragent = str_replace(" ", "", $useragent);
                $logEntry .= " time=" . round((microtime(true) - $this->starttime), 2) . " serv=" . $this->fokus;
                $logEntry .= " search=" . $this->eingabe;
    
    
                # 2 Arten von Logs in einem wird die Anzahl der Abfragen an eine Suchmaschine gespeichert und in der anderen
                # die Anzahl, wie häufig diese Ergebnisse geliefert hat.
                $enginesToLoad = $this->enginesToLoad;
                $redis->pipeline(function ($pipe) use ($enginesToLoad, $logEntry) {
                    $pipe->rpush('logs.search', $logEntry);
                    foreach ($this->enginesToLoad as $name => $answered) {
                        $pipe->incr('logs.engines.requests.' . $name);
                        if ($answered) {
                            $pipe->incr('logs.engines.answered.' . $name);
                        }
                    }
                });
    
            if (strpos($link, "http://") === 0) {
    
            $link = trim($link, "/");
            $hash = md5($link);