MetaGer.php 56.3 KB
Newer Older
1 2 3 4
<?php
namespace App;

use App;
5
use Cache;
6
use Illuminate\Http\Request;
Phil Höfer's avatar
Phil Höfer committed
7
use Illuminate\Support\Facades\Redis;
8
use Jenssegers\Agent\Agent;
Dominik Hebeler's avatar
Bugfix  
Dominik Hebeler committed
9
use LaravelLocalization;
10
use Log;
Dominik Hebeler's avatar
Dominik Hebeler committed
11
use Carbon;
12
use Predis\Connection\ConnectionException;
13 14 15

class MetaGer
{
16 17 18 19 20 21 22 23 24 25
    # Einstellungen für die Suche
    protected $fokus;
    protected $eingabe;
    protected $q;
    protected $category;
    protected $time;
    protected $page;
    protected $lang;
    protected $cache = "";
    protected $site;
26
    protected $hostBlacklist = [];
27
    protected $domainBlacklist = [];
28 29 30 31 32 33 34 35 36 37 38
    private $urlBlacklist = [];
    protected $stopWords = [];
    protected $phrases = [];
    protected $engines = [];
    protected $results = [];
    protected $ads = [];
    protected $warnings = [];
    protected $errors = [];
    protected $addedHosts = [];
    protected $startCount = 0;
    protected $canCache = false;
39
    # Daten über die Abfrage$
40
    protected $ip;
Dominik Hebeler's avatar
Dominik Hebeler committed
41
    protected $useragent;
42 43
    protected $language;
    protected $agent;
44
    protected $apiKey = "";
Phil Höfer's avatar
Phil Höfer committed
45
    protected $apiAuthorized = false;
46 47 48 49 50
    # Konfigurationseinstellungen:
    protected $sumaFile;
    protected $mobile;
    protected $resultCount;
    protected $sprueche;
51
    protected $maps;
52
    protected $newtab;
53
    protected $domainsBlacklisted = [];
54
    protected $urlsBlacklisted = [];
55 56
    protected $url;
    protected $languageDetect;
Dominik Hebeler's avatar
Dominik Hebeler committed
57 58
    protected $verificationId;
    protected $verificationCount;
59

60 61
    public function __construct()
    {
62
        # Timer starten
63
        $this->starttime = microtime(true);
64
        # Versuchen Blacklists einzulesen
65
        if (file_exists(config_path() . "/blacklistDomains.txt") && file_exists(config_path() . "/blacklistUrl.txt")) {
66
            $tmp = file_get_contents(config_path() . "/blacklistDomains.txt");
67
            $this->domainsBlacklisted = explode("\n", $tmp);
68 69
            $tmp = file_get_contents(config_path() . "/blacklistUrl.txt");
            $this->urlsBlacklisted = explode("\n", $tmp);
70
        } else {
71
            Log::warning("Achtung: Eine, oder mehrere Blacklist Dateien, konnten nicht geöffnet werden");
72 73
        }

74
        # Parser Skripte einhängen
75 76 77 78
        $dir = app_path() . "/Models/parserSkripte/";
        foreach (scandir($dir) as $filename) {
            $path = $dir . $filename;
            if (is_file($path)) {
79
                require_once $path;
80 81 82
            }
        }

83
        # Cachebarkeit testen
84 85 86 87 88 89
        try {
            Cache::has('test');
            $this->canCache = true;
        } catch (ConnectionException $e) {
            $this->canCache = false;
        }
90
    }
91

92
    # Erstellt aus den gesammelten Ergebnissen den View
93
    public function createView($quicktipResults = null)
94
    {
95 96
        # Hiermit werden die evtl. ausgewählten SuMas extrahiert, damit die Input-Boxen richtig gesetzt werden können
        $focusPages = [];
Aria Givi's avatar
Aria Givi committed
97

98 99
        foreach ($this->request->all() as $key => $value) {
            if ($value === 'on') {
Aria Givi's avatar
Aria Givi committed
100
                $focusPages[] = str_replace('param_', '', str_replace('engine_', '', $key));
101 102 103
            }
        }

104
        $viewResults = [];
105
        # Wir extrahieren alle notwendigen Variablen und geben Sie an unseren View:
106
        foreach ($this->results as $result) {
107 108 109 110
            $viewResults[] = get_object_vars($result);
        }
        # Wir müssen natürlich noch den Log für die durchgeführte Suche schreiben:
        $this->createLogs();
111 112
        if ($this->fokus === "bilder") {
            switch ($this->out) {
113
                case 'results':
114
                    return view('resultpages.results_images')
115 116 117 118 119
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
120
                        ->with('apiAuthorized', $this->apiAuthorized)
121
                        ->with('metager', $this)
122
                        ->with('browser', (new Agent())->browser());
123
                default:
124
                    return view('resultpages.resultpage_images')
125 126 127 128 129
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
130
                        ->with('apiAuthorized', $this->apiAuthorized)
131
                        ->with('metager', $this)
132
                        ->with('browser', (new Agent())->browser());
133
            }
134 135 136
        } else {
            switch ($this->out) {
                case 'results':
137
                    return view('resultpages.results')
138 139 140 141 142
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
143
                        ->with('apiAuthorized', $this->apiAuthorized)
144
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
145 146
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
147 148
                    break;
                case 'results-with-style':
149
                    return view('resultpages.resultpage')
150 151 152 153 154
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
155
                        ->with('apiAuthorized', $this->apiAuthorized)
156 157
                        ->with('metager', $this)
                        ->with('suspendheader', "yes")
Dominik Hebeler's avatar
Dominik Hebeler committed
158 159
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
160
                    break;
Phil Höfer's avatar
Phil Höfer committed
161
                case 'rich':
162
                    return view('resultpages.metager3rich')
163
                        ->with('results', $viewResults)
Phil Höfer's avatar
Phil Höfer committed
164 165 166 167
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
168
                        ->with('apiAuthorized', $this->apiAuthorized)
Phil Höfer's avatar
Phil Höfer committed
169
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
170 171
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
Phil Höfer's avatar
Phil Höfer committed
172
                    break;
173
                case 'rss20':
174
                    return view('resultpages.metager3resultsrss20')
175 176
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
Phil Höfer's avatar
Phil Höfer committed
177
                        ->with('apiAuthorized', $this->apiAuthorized)
178
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
179 180
                        ->with('resultcount', sizeof($viewResults))
                        ->with('fokus', $this->fokus);
181
                    break;
Aria Givi's avatar
Aria Givi committed
182
                case 'atom10':
183 184
                    return response()->view('resultpages.metager3resultsatom10', ['results' => $viewResults, 'eingabe' => $this->eingabe, 'metager' => $this, 'resultcount' => sizeof($viewResults)])
                        ->header('Content-Type', 'application/xml');
Aria Givi's avatar
Aria Givi committed
185
                    break;
186
                case 'result-count':
187 188
                    # Wir geben die Ergebniszahl und die benötigte Zeit zurück:
                    return sizeof($viewResults) . ";" . round((microtime(true) - $this->starttime), 2);
189
                    break;
190
                default:
191
                    return view('resultpages.resultpage')
192
                        ->with('eingabe', $this->eingabe)
193
                        ->with('focusPages', $focusPages)
194 195 196
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
197
                        ->with('apiAuthorized', $this->apiAuthorized)
198
                        ->with('metager', $this)
199
                        ->with('browser', (new Agent())->browser())
200 201
                        ->with('quicktips', $quicktipResults)
                        ->with('resultcount', count($this->results));
202 203
                    break;
            }
204 205 206
        }
    }

Phil Höfer's avatar
Phil Höfer committed
207
    public function prepareResults()
208
    {
Phil Höfer's avatar
Phil Höfer committed
209
        $engines = $this->engines;
210

Phil Höfer's avatar
Phil Höfer committed
211 212
        // combine
        $combinedResults = $this->combineResults($engines);
213 214 215 216

        # Wir bestimmen die Sprache eines jeden Suchergebnisses
        $this->results = $this->addLangCodes($this->results);

Phil Höfer's avatar
Phil Höfer committed
217 218 219 220 221
        // sort
        //$sortedResults = $this->sortResults($engines);
        // filter
        // augment (boost&adgoal)
        // authorize
Phil Höfer's avatar
Phil Höfer committed
222 223 224
        if ($this->apiKey) {
            $this->apiAuthorized = $this->authorize($this->apiKey);
        }
Phil Höfer's avatar
Phil Höfer committed
225
        // misc (WiP)
226
        if ($this->fokus == "nachrichten") {
227 228 229
            $this->results = array_filter($this->results, function ($v, $k) {
                return !is_null($v->getRank());
            }, ARRAY_FILTER_USE_BOTH);
230 231 232 233 234 235 236 237 238 239
            uasort($this->results, function ($a, $b) {
                $datea = $a->getDate();
                $dateb = $b->getDate();
                return $dateb - $datea;
            });
        } else {
            uasort($this->results, function ($a, $b) {
                if ($a->getRank() == $b->getRank()) {
                    return 0;
                }
240

241 242 243
                return ($a->getRank() < $b->getRank()) ? 1 : -1;
            });
        }
244

245 246
        # Validate Results
        $newResults = [];
247 248
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
249
                $newResults[] = $result;
250 251
            }

252 253 254
        }
        $this->results = $newResults;

255 256 257
        #Adgoal Implementation
        $this->results = $this->parseAdgoal($this->results);

Dominik Hebeler's avatar
Dominik Hebeler committed
258 259 260
        # Human Verification
        $this->results = $this->humanVerification($this->results);

261
        $counter = 0;
262
        $firstRank = 0;
263

264
        if (isset($this->startForwards)) {
265
            $this->startCount = $this->startForwards;
266
        } elseif (isset($this->startBackwards)) {
267
            $this->startCount = $this->startBackwards - count($this->results) - 1;
268
        } else {
269 270 271
            $this->startCount = 0;
        }

272 273
        foreach ($this->results as $result) {
            if ($counter === 0) {
274
                $firstRank = $result->rank;
275 276
            }

277
            $counter++;
278
            $result->number = $counter + $this->startCount;
279
            $confidence = 0;
280 281 282
            if ($firstRank > 0) {
                $confidence = $result->rank / $firstRank;
            } else {
283
                $confidence = 0;
284 285 286
            }

            if ($confidence > 0.65) {
287
                $result->color = "#FF4000";
288
            } elseif ($confidence > 0.4) {
289
                $result->color = "#FF0080";
290
            } elseif ($confidence > 0.2) {
291
                $result->color = "#C000C0";
292
            } else {
293
                $result->color = "#000000";
294 295
            }

296 297
        }

298
        if (LaravelLocalization::getCurrentLocale() === "en") {
299 300
            $this->ads = [];
        }
301

302
        if ($this->validated) {
303 304
            $this->ads = [];
            $this->maps = false;
305
        }
306 307

        if (count($this->results) <= 0) {
308
            $this->errors[] = trans('metaGer.results.failed');
309
        }
310

311
        if ($this->canCache() && isset($this->next) && count($this->next) > 0 && count($this->results) > 0) {
312
            $page = $this->page + 1;
313
            $this->next = [
314
                'page' => $page,
315
                'startForwards' => $this->results[count($this->results) - 1]->number,
316
                'engines' => $this->next,
317 318
            ];
            Cache::put(md5(serialize($this->next)), serialize($this->next), 60);
319 320
        } else {
            $this->next = [];
321 322
        }

323
    }
324

325 326
    private function addLangCodes($results)
    {
327 328 329 330 331
        # Wenn es keine Ergebnisse gibt, brauchen wir uns gar nicht erst zu bemühen
        if (sizeof($results) === 0) {
            return $results;
        }

332 333 334 335 336
        # Bei der Spracheinstellung "all" wird nicht gefiltert
        if ($this->getLang() === "all") {
            return $results;
        } else {
            # Ansonsten müssen wir jedem Result einen Sprachcode hinzufügen
337
            $id = 0;
338 339 340 341 342
            $langStrings = [];
            foreach ($results as $result) {
                # Wir geben jedem Ergebnis eine ID um später die Sprachcodes zuordnen zu können
                $result->id = $id;

Dominik Hebeler's avatar
Dominik Hebeler committed
343
                $langStrings["result_" . $id] = utf8_encode($result->getLangString());
344 345 346 347 348 349 350 351

                $id++;
            }
            # Wir schreiben die Strings in eine temporäre JSON-Datei,
            # Da das Array unter umständen zu groß ist für eine direkte Übergabe an das Skript
            $filename = "/tmp/" . getmypid();
            file_put_contents($filename, json_encode($langStrings));
            $langDetectorPath = app_path() . "/Models/lang.pl";
352 353
            $lang = exec("echo '$filename' | $langDetectorPath");
            $lang = json_decode($lang, true);
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

            # Wir haben nun die Sprachcodes der einzelnen Ergebnisse.
            # Diese müssen wir nur noch korrekt zuordnen, dann sind wir fertig.
            foreach ($lang as $key => $langCode) {
                # Prefix vom Key entfernen:
                $id = intval(str_replace("result_", "", $key));
                foreach ($this->results as $result) {
                    if ($result->id === $id) {
                        $result->langCode = $langCode;
                        break;
                    }
                }
            }
            return $results;
        }
    }

Phil Höfer's avatar
Phil Höfer committed
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    public function combineResults($engines)
    {
        foreach ($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) {
                    $this->results[] = $result;
                }
            }
            foreach ($engine->ads as $ad) {
                $this->ads[] = $ad;
            }
        }
    }

391 392
    public function parseAdgoal($results)
    {
393
        $publicKey = getenv('adgoal_public');
394
        $privateKey = getenv('adgoal_private');
395
        if ($publicKey === false) {
396 397 398
            return $results;
        }
        $tldList = "";
399 400
        try {
            foreach ($results as $result) {
401
                $link = $result->anzeigeLink;
402
                if (strpos($link, "http") !== 0) {
403 404 405 406 407 408 409 410 411 412
                    $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");

413
            # Query
414 415
            $query = urlencode($this->q);

416
            $link = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
417 418 419
            $answer = json_decode(file_get_contents($link));

            # Nun müssen wir nur noch die Links für die Advertiser ändern:
420
            foreach ($answer as $el) {
421
                $hoster = $el[0];
422
                $hash = $el[1];
423

424
                foreach ($results as $result) {
Dominik Hebeler's avatar
Dominik Hebeler committed
425
                    if ($hoster === $result->tld && !$result->partnershop) {
426 427
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
428
                        if ($result->image !== "") {
429
                            $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
430
                        } else {
431
                            $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
432 433
                        }

434 435 436
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
                        $targetUrl = $result->anzeigeLink;
437
                        if (strpos($targetUrl, "http") !== 0) {
438
                            $targetUrl = "http://" . $targetUrl;
439 440
                        }

441 442 443
                        $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;
444 445 446 447
                        $result->partnershop = true;
                    }
                }
            }
448
        } catch (\ErrorException $e) {
449 450 451 452 453
            return $results;
        }

        return $results;
    }
454

Dominik Hebeler's avatar
Dominik Hebeler committed
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    public function humanVerification($results){
        # Let's check if we need to implement a redirect for human verification
        if($this->verificationCount > 10){
            foreach($results as $result){
                $link = $result->link;
                $day = Carbon::now()->day;
                $pw = md5($this->verificationId . $day . $link . env("PROXY_PASSWORD"));
                $url = route('humanverification', ['mm' => $this->verificationId, 'pw' => $pw, "url" => urlencode(base64_encode($link))]);
                $result->link = $url;
            }
            return $results;
        }else{
            return $results;
        }
    }

Phil Höfer's avatar
Phil Höfer committed
471 472 473 474 475 476
    public function authorize($key)
    {
        $postdata = http_build_query(array(
            'dummy' => rand(),
        ));
        $opts = array('http' => array(
477 478
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
Phil Höfer's avatar
Phil Höfer committed
479 480 481 482 483 484 485
            'content' => $postdata,
        ),
        );

        $context = stream_context_create($opts);

        try {
486
            $link = "https://key.metager3.de/" . urlencode($key) . "/request-permission/api-access";
Phil Höfer's avatar
Phil Höfer committed
487 488 489 490 491 492 493 494 495 496 497 498
            $result = json_decode(file_get_contents($link, false, $context));
            if ($result->{'api-access'} == true) {
                return true;
            } else {
                return false;
            }

        } catch (\ErrorException $e) {
            return false;
        }
    }

499 500
    public function createQuicktips()
    {
501 502 503 504 505
        # Die quicktips werden als job erstellt und zur Abarbeitung freigegeben
        $quicktips = new \App\Models\Quicktips\Quicktips($this->q, $this->lang, $this->getTime(), $this->getHashCode());
        return $quicktips;
    }

Karl's avatar
Karl committed
506 507 508 509
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

510 511
    public function createSearchEngines(Request $request)
    {
512
        # Wenn es kein Suchwort gibt
Dominik Hebeler's avatar
Dominik Hebeler committed
513
        if (!$request->filled("eingabe") || $this->q === "") {
514
            return;
515
        }
516

517 518
        $xml = simplexml_load_file($this->sumaFile);
        $sumas = $xml->xpath("suma");
519
        $enabledSearchengines = [];
520 521
        $overtureEnabled = false;
        $sumaCount = 0;
522

523
        $isCustomSearch = $this->startsWith($this->fokus, 'focus_');
524

525
        # Im Falle einer Custom-Suche ohne mindestens einer selektierter Suchmaschine wird eine Web-Suche durchgeführt
526
        if ($isCustomSearch && !$this->atLeastOneSearchengineSelected($request)) {
527 528 529
            $isCustomSearch = false;
            $this->fokus = 'web';
        }
530

Karl's avatar
Karl committed
531
        /* Erstellt die Liste der eingestellten Sumas
532 533 534
         * Der einzige Unterschied bei angepasstem Suchfokus ist,
         * dass nicht nach den Typen einer Suma,
         * sondern den im Request mitgegebenen Typen entschieden wird.
Karl's avatar
Karl committed
535 536 537 538 539 540
         * 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
         */
541
        foreach ($sumas as $suma) {
542
            if (($this->sumaIsSelected($suma, $request, $isCustomSearch)
543
                || (!$this->isBildersuche()
544
                    && $this->sumaIsAdsuche($suma, $overtureEnabled)))
545 546 547
                && (!$this->sumaIsDisabled($suma))) {
                if ($this->sumaIsOverture($suma)) {
                    $overtureEnabled = true;
548
                }
549 550
                if ($this->sumaIsNotAdsuche($suma)) {
                    $sumaCount += 1;
551
                }
552
                $enabledSearchengines[] = $suma;
553 554 555 556
            }
        }

        # Sonderregelung für alle Suchmaschinen, die zu den Minisuchern gehören. Diese können alle gemeinsam über einen Link abgefragt werden
557
        $subcollections = [];
558 559

        $tmp = [];
560 561 562 563
        // Es gibt den Schalter "minism=on" Dieser soll bewirken, dass alle Minisucher angeschaltet werden.
        // Wenn also "minism=on" ist, dann durchsuchen wir statt den tatsächlich angeschalteten Suchmaschinen,
        // alle Suchmaschinen nach "minismCollection"
        if ($request->input("minism", "off") === "on") {
Dominik Hebeler's avatar
Dominik Hebeler committed
564 565 566
            // Wir laden alle Minisucher
            foreach ($sumas as $engine) {
                if (isset($engine["minismCollection"])) {
567
                    $subcollections[] = $engine["minismCollection"]->__toString();
Dominik Hebeler's avatar
Dominik Hebeler committed
568 569
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
570 571 572 573 574 575
            # Nur noch alle eventuell angeschalteten Minisucher deaktivieren
            foreach ($enabledSearchengines as $index => $engine) {
                if (!isset($engine["minismCollection"])) {
                    $tmp[] = $engine;
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
576 577 578 579
        } else {
            // Wir schalten eine Teilmenge, oder aber gar keine an
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['minismCollection'])) {
580
                    $subcollections[] = $engine['minismCollection']->__toString();
Dominik Hebeler's avatar
Dominik Hebeler committed
581 582
                } else {
                    $tmp[] = $engine;
Dominik Hebeler's avatar
Dominik Hebeler committed
583
                }
584
            }
585 586
        }
        $enabledSearchengines = $tmp;
587 588
        if (sizeof($subcollections) > 0) {
            $enabledSearchengines[] = $this->loadMiniSucher($xml, $subcollections);
589
        }
590
        if ($sumaCount <= 0) {
591
            $this->errors[] = trans('metaGer.settings.noneSelected');
592
        }
593
        $engines = [];
594
        # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob überhaupt eine der Suchmaschinen eine Sitesearch unterstützt
595
        $siteSearchFailed = $this->checkCanNotSitesearch($enabledSearchengines);
596 597

        $typeslist = [];
598
        $counter = 0;
599

600 601
        if ($this->requestIsCached($request)) {
            $engines = $this->getCachedEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
602
            # We need to edit some Options of the Cached Search Engines
Phil Höfer's avatar
Phil Höfer committed
603
            foreach ($engines as $engine) {
Dominik Hebeler's avatar
Dominik Hebeler committed
604 605
                $engine->setResultHash($this->getHashCode());
            }
606
        } else {
607
            $engines = $this->actuallyCreateSearchEngines($enabledSearchengines, $siteSearchFailed);
608
        }
609

610
        # Wir starten alle Suchen
611 612
        foreach ($engines as $engine) {
            $engine->startSearch($this);
613
        }
614

615 616 617 618 619
        /* Wir warten auf die Antwort der Suchmaschinen
         * Die Verbindung steht zu diesem Zeitpunkt und auch unsere Requests wurden schon gesendet.
         * Wir zählen die Suchmaschinen, die durch den Cache beantwortet wurden:
         * $enginesToLoad zählt einerseits die Suchmaschinen auf die wir warten und andererseits
         * welche Suchmaschinen nicht rechtzeitig geantwortet haben.
620 621
         */

622
        $enginesToLoad = [];
623
        $canBreak = false;
624 625 626 627 628
        foreach ($engines as $engine) {
            if ($engine->cached) {
                if ($overtureEnabled && ($engine->name === "overture" || $engine->name === "overtureAds")) {
                    $canBreak = true;
                }
629 630
            } else {
                $enginesToLoad[$engine->name] = false;
631 632 633 634 635 636 637 638
            }
        }

        $this->waitForResults($enginesToLoad, $overtureEnabled, $canBreak);

        $this->retrieveResults($engines);
    }

639 640
    # Spezielle Suchen und Sumas

641
    public function sumaIsSelected($suma, $request, $custom)
642
    {
643
        if ($custom) {
Dominik Hebeler's avatar
Dominik Hebeler committed
644
            if ($request->filled("engine_" . $suma["name"])) {
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
                return true;
            }
        } else {
            $types = explode(",", $suma["type"]);
            if (in_array($this->fokus, $types)) {
                return true;
            }
        }
        return false;
    }

    public function actuallyCreateSearchEngines($enabledSearchengines, $siteSearchFailed)
    {
        $engines = [];
        foreach ($enabledSearchengines as $engine) {

            # Wenn diese Suchmaschine gar nicht eingeschaltet sein soll
            if (!$siteSearchFailed
                && strlen($this->site) > 0
                && (!isset($engine['hasSiteSearch'])
                    || $engine['hasSiteSearch']->__toString() === "0")) {
                continue;
            }

Dominik Hebeler's avatar
Dominik Hebeler committed
669 670 671
            if (!isset($engine["package"])) {
                die(var_dump($engine));
            }
672 673 674 675 676
            # Setze Pfad zu Parser
            $path = "App\Models\parserSkripte\\" . ucfirst($engine["package"]->__toString());

            # Prüfe ob Parser vorhanden
            if (!file_exists(app_path() . "/Models/parserSkripte/" . ucfirst($engine["package"]->__toString()) . ".php")) {
677
                Log::error("Konnte " . $engine["name"] . " nicht abfragen, da kein Parser existiert");
678
                $this->errors[] = trans('metaGer.engines.noParser', ['engine' => $engine["name"]]);
679 680 681 682 683 684 685 686
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
                $tmp = new $path($engine, $this);
            } catch (\ErrorException $e) {
687
                Log::error("Konnte " . $engine["name"] . " nicht abfragen. " . var_dump($e));
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
                continue;
            }

            # 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);
            }

            # Wenn die neu erstellte Engine eingeschaltet ist, wird sie der Liste hinzugefügt
            if ($tmp->isEnabled()) {
                $engines[] = $tmp;
            }
        }
        return $engines;
    }

    public function isBildersuche()
    {
706
        return $this->fokus === "bilder";
707 708 709 710
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
711
        $sumaName = $suma["name"]->__toString();
712
        return
713 714
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
Karl Hasselbring's avatar
Karl Hasselbring committed
715
            || (!$overtureEnabled && $sumaName === "overtureAds");
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    }

    public function sumaIsDisabled($suma)
    {
        return
        isset($suma['disabled'])
        && $suma['disabled']->__toString() === "1";
    }

    public function sumaIsOverture($suma)
    {
        return
        $suma["name"]->__toString() === "overture"
        || $suma["name"]->__toString() === "overtureAds";
    }

    public function sumaIsNotAdsuche($suma)
    {
        return
        $suma["name"]->__toString() !== "qualigo"
        && $suma["name"]->__toString() !== "similar_product_ads"
        && $suma["name"]->__toString() !== "overtureAds";
    }

    public function requestIsCached($request)
    {
        return
Dominik Hebeler's avatar
Dominik Hebeler committed
743
        $request->filled('next')
744 745 746 747 748 749
        && Cache::has($request->input('next'))
        && unserialize(Cache::get($request->input('next')))['page'] > 1;
    }

    public function getCachedEngines($request)
    {
750
        $next = unserialize(Cache::get($request->input('next')));
751
        $this->page = $next['page'];
752
        $engines = $next['engines'];
753 754 755 756 757 758 759 760 761 762 763
        if (isset($next['startForwards'])) {
            $this->startForwards = $next['startForwards'];
        }
        if (isset($next['startBackwards'])) {
            $this->startBackwards = $next['startBackwards'];
        }
        return $engines;
    }

    public function loadMiniSucher($xml, $subcollections)
    {
764
        $minisucherEngine = $xml->xpath('suma[@name="minism"]')[0];
765
        $minisucherEngine["subcollections"] = implode(", ", $subcollections);
766
        $subcollectionsString = urlencode("(" . implode(" OR ", $subcollections) . ")");
767
        $minisucherEngine["formData"] = str_replace("<<SUBCOLLECTIONS>>", $subcollectionsString, $minisucherEngine["formData"]);
768 769 770 771
        $minisucherEngine["formData"] = str_replace("<<COUNT>>", sizeof($subcollections) * 10, $minisucherEngine["formData"]);
        return $minisucherEngine;
    }

772
    # Passt den Suchfokus an, falls für einen Fokus genau alle vorhandenen Sumas eingeschaltet sind
773 774
    public function adjustFocus($sumas, $enabledSearchengines)
    {
775 776
        # Findet für alle Foki die enthaltenen Sumas
        $foki = []; # [fokus][suma] => [suma]
777
        foreach ($sumas as $suma) {
778
            if ((!$this->sumaIsDisabled($suma)) && (!isset($suma['userSelectable']) || $suma['userSelectable']->__toString() === "1")) {
779
                if (isset($suma['type'])) {
780 781 782
                    # Wenn foki für diese Suchmaschine angegeben sind
                    $focuses = explode(",", $suma['type']->__toString());
                    foreach ($focuses as $foc) {
783 784 785 786 787
                        if (isset($suma['minismCollection'])) {
                            $foki[$foc][] = "minism";
                        } else {
                            $foki[$foc][] = $suma['name']->__toString();
                        }
788
                    }
789
                } else {
790
                    # Wenn keine foki für diese Suchmaschine angegeben sind
791 792 793 794 795
                    if (isset($suma['minismCollection'])) {
                        $foki["andere"][] = "minism";
                    } else {
                        $foki["andere"][] = $suma['name']->__toString();
                    }
796 797 798 799
                }
            }
        }

800
        # Findet die Namen der aktuell eingeschalteten Sumas
801
        $realEngNames = [];
802
        foreach ($enabledSearchengines as $realEng) {
803
            $nam = $realEng["name"]->__toString();
Karl Hasselbring's avatar
Karl Hasselbring committed
804
            if ($nam !== "qualigo" && $nam !== "overtureAds") {
805 806 807
                $realEngNames[] = $nam;
            }
        }
808

809
        # 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.
810
        foreach ($foki as $fok => $engines) {
811
            $isFokus = true;
812
            $fokiEngNames = [];
813
            foreach ($engines as $eng) {
814 815
                $fokiEngNames[] = $eng;
            }
816
            # Jede eingeschaltete Engine ist für diesen Fokus geeignet
817
            foreach ($fokiEngNames as $fen) {
818 819
                # Bei Bildersuchen ist uns egal, ob alle Suchmaschinen aus dem Suchfokus eingeschaltet sind, da wir sie eh als Bildersuche anzeigen müssen
                if (!in_array($fen, $realEngNames) && $fok !== "bilder") {
820 821 822
                    $isFokus = false;
                }
            }
823
            # Jede im Fokus erwartete Engine ist auch eingeschaltet
824 825
            foreach ($realEngNames as $ren) {
                if (!in_array($ren, $fokiEngNames)) {
826 827 828
                    $isFokus = false;
                }
            }
829
            # Wenn die Listen identisch sind, setze den Fokus um
830
            if ($isFokus) {
831 832 833
                $this->fokus = $fok;
            }
        }
834
    }
835

836 837 838 839 840 841 842
    public function checkCanNotSitesearch($enabledSearchengines)
    {
        if (strlen($this->site) > 0) {
            $enginesWithSite = 0;
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1") {
                    $enginesWithSite++;
843
                }
844 845
            }
            if ($enginesWithSite === 0) {
846
                $this->errors[] = trans('metaGer.sitesearch.failed', ['site' => $this->site, 'searchLink' => $this->generateSearchLink("web", false)]);
847 848
                return true;
            } else {
849
                $this->warnings[] = trans('metaGer.sitesearch.success', ['site' => $this->site]);
850
                return false;
851 852
            }
        }
853
        return false;
854 855 856 857
    }

    public function waitForResults($enginesToLoad, $overtureEnabled, $canBreak)
    {
858

Phil Höfer's avatar
Phil Höfer committed
859
        $timeStart = microtime(true);
860
        $results = null;
861
        while (true) {
862 863 864
            $results = Redis::hgetall('search.' . $this->getHashCode());

            $ready = true;
Phil Höfer's avatar
Phil Höfer committed
865
            // When every
866
            $connected = true;
Phil Höfer's avatar
Phil Höfer committed
867 868
            foreach ($results as $key => $value) {
                if ($value === "waiting" || $value === "connected") {
869
                    $ready = false;
870
                }
Phil Höfer's avatar
Phil Höfer committed
871
                if ($value === "waiting") {
872
                    $connected = false;
873
                }
874
            }
875

876 877
            // If $ready is false at this point, we're waiting for more searchengines
            // But we have to check for the timeout, too
Phil Höfer's avatar
Phil Höfer committed
878 879 880 881
            if (!$connected) {
                $timeStart = microtime(true);
            }

882 883 884 885
            $time = (microtime(true) - $timeStart) * 1000;
            // We will apply the timeout only if it's not Yahoo we're waiting for since they are one the most
            // important search engines.
            $canTimeout = !((isset($results["overture"]) && $results["overture"] === "waiting") || (isset($results["overtureAds"]) && $results["overtureAds"] === "waiting"));
Phil Höfer's avatar
Phil Höfer committed
886 887 888
            if ($time > $this->time && $canTimeout) {
                $ready = true;
            }
889

Phil Höfer's avatar
Phil Höfer committed
890