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

use App;
5
use Cache;
6
use Carbon;
7
use Illuminate\Http\Request;
Phil Höfer's avatar
Phil Höfer committed
8
use Illuminate\Support\Facades\Redis;
9
use Jenssegers\Agent\Agent;
Dominik Hebeler's avatar
Bugfix    
Dominik Hebeler committed
10
use LaravelLocalization;
11
use Log;
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
                        ->with('quicktips', $quicktipResults)
201
202
                        ->with('resultcount', count($this->results))
                        ->with('focus', $this->fokus);
203
204
                    break;
            }
205
206
207
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

297
298
        }

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

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

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

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

324
    }
325

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

333
334
335
336
337
        # Bei der Spracheinstellung "all" wird nicht gefiltert
        if ($this->getLang() === "all") {
            return $results;
        } else {
            # Ansonsten müssen wir jedem Result einen Sprachcode hinzufügen
338
            $id = 0;
339
340
341
342
343
            $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
344
                $langStrings["result_" . $id] = utf8_encode($result->getLangString());
345
346
347
348
349
350
351
352

                $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";
353
354
            $lang = exec("echo '$filename' | $langDetectorPath");
            $lang = json_decode($lang, true);
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371

            # 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    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;
            }
        }
    }

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

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

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

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

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

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

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

        return $results;
    }
455

456
457
    public function humanVerification($results)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
458
        # Let's check if we need to implement a redirect for human verification
459
460
        if ($this->verificationCount > 10) {
            foreach ($results as $result) {
Dominik Hebeler's avatar
Dominik Hebeler committed
461
462
463
464
465
466
467
                $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;
468
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
469
470
471
472
            return $results;
        }
    }

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

        $context = stream_context_create($opts);

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

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

501
502
    public function createQuicktips()
    {
503
504
505
506
507
        # 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
508
509
510
511
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

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

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

525
        $isCustomSearch = $this->startsWith($this->fokus, 'focus_');
526

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

Karl's avatar
Karl committed
533
        /* Erstellt die Liste der eingestellten Sumas
534
535
536
         * 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
537
538
539
540
541
542
         * 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
         */
543
        foreach ($sumas as $suma) {
544
            if (($this->sumaIsSelected($suma, $request, $isCustomSearch)
545
                || (!$this->isBildersuche()
546
                    && $this->sumaIsAdsuche($suma, $overtureEnabled)))
547
548
549
                && (!$this->sumaIsDisabled($suma))) {
                if ($this->sumaIsOverture($suma)) {
                    $overtureEnabled = true;
550
                }
551
552
                if ($this->sumaIsNotAdsuche($suma)) {
                    $sumaCount += 1;
553
                }
554
                $enabledSearchengines[] = $suma;
555
556
557
558
            }
        }

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

        $tmp = [];
562
563
564
565
        // 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
566
567
568
            // Wir laden alle Minisucher
            foreach ($sumas as $engine) {
                if (isset($engine["minismCollection"])) {
569
                    $subcollections[] = $engine["minismCollection"]->__toString();
Dominik Hebeler's avatar
Dominik Hebeler committed
570
571
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
572
573
574
575
576
577
            # 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
578
579
580
581
        } else {
            // Wir schalten eine Teilmenge, oder aber gar keine an
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['minismCollection'])) {
582
                    $subcollections[] = $engine['minismCollection']->__toString();
Dominik Hebeler's avatar
Dominik Hebeler committed
583
584
                } else {
                    $tmp[] = $engine;
Dominik Hebeler's avatar
Dominik Hebeler committed
585
                }
586
            }
587
588
        }
        $enabledSearchengines = $tmp;
589
590
        if (sizeof($subcollections) > 0) {
            $enabledSearchengines[] = $this->loadMiniSucher($xml, $subcollections);
591
        }
592
        if ($sumaCount <= 0) {
593
            $this->errors[] = trans('metaGer.settings.noneSelected');
594
        }
595
        $engines = [];
596
        # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob überhaupt eine der Suchmaschinen eine Sitesearch unterstützt
597
        $siteSearchFailed = $this->checkCanNotSitesearch($enabledSearchengines);
598
599

        $typeslist = [];
600
        $counter = 0;
601

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

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

617
618
619
620
621
        /* 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.
622
623
         */

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

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

        $this->retrieveResults($engines);
    }

641
642
    # Spezielle Suchen und Sumas

643
    public function sumaIsSelected($suma, $request, $custom)
644
    {
645
        if ($custom) {
Dominik Hebeler's avatar
Dominik Hebeler committed
646
            if ($request->filled("engine_" . $suma["name"])) {
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
                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
671
672
673
            if (!isset($engine["package"])) {
                die(var_dump($engine));
            }
674
675
676
677
678
            # 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")) {
679
                Log::error("Konnte " . $engine["name"] . " nicht abfragen, da kein Parser existiert");
680
                $this->errors[] = trans('metaGer.engines.noParser', ['engine' => $engine["name"]]);
681
682
683
684
685
686
687
688
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
                $tmp = new $path($engine, $this);
            } catch (\ErrorException $e) {
689
                Log::error("Konnte " . $engine["name"] . " nicht abfragen. " . var_dump($e));
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
                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()
    {
708
        return $this->fokus === "bilder";
709
710
711
712
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
713
        $sumaName = $suma["name"]->__toString();
714
        return
715
716
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
Karl Hasselbring's avatar
Karl Hasselbring committed
717
            || (!$overtureEnabled && $sumaName === "overtureAds");
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
743
744
    }

    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
745
        $request->filled('next')
746
747
748
749
750
751
        && Cache::has($request->input('next'))
        && unserialize(Cache::get($request->input('next')))['page'] > 1;
    }

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

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

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

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

811
        # 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.
812
        foreach ($foki as $fok => $engines) {
813
            $isFokus = true;
814
            $fokiEngNames = [];
815
            foreach ($engines as $eng) {
816
817
                $fokiEngNames[] = $eng;
            }
818
            # Jede eingeschaltete Engine ist für diesen Fokus geeignet
819
            foreach ($fokiEngNames as $fen) {
820
821
                # 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") {
822
823
824
                    $isFokus = false;
                }
            }
825
            # Jede im Fokus erwartete Engine ist auch eingeschaltet
826
827
            foreach ($realEngNames as $ren) {
                if (!in_array($ren, $fokiEngNames)) {
828
829
830
                    $isFokus = false;
                }
            }
831
            # Wenn die Listen identisch sind, setze den Fokus um
832
            if ($isFokus) {
833
834
835
                $this->fokus = $fok;
            }
        }
836
    }
837

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

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

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

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

878
879
            // 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
880
881
882
883
            if (!$connected) {
                $timeStart = microtime(true);
            }

884
885
886
887
            $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
888
889
890
            if ($time > $this->time && $canTimeout) {
                $ready = true;
            }
891

Phil Höfer's avatar
Phil Höfer committed
892
            if ($ready) {
893
894
895
896
                break;
            }
            usleep(50000);
        }
897
898

        # Wir haben nun so lange wie möglich gewartet. Wir registrieren nun noch die Suchmaschinen, die geanwortet haben.
899
        foreach ($results as $key => $value) {
900
901
902
            $enginesToLoad[$key] = true;
        }
        $this->enginesToLoad = $enginesToLoad;
903
    }
904

905
906
907
    public function retrieveResults($engines)
    {
        # Von geladenen Engines die Ergebnisse holen
908
909
910
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
911
                    $engine->retrieveResults($this);
912
                } catch (\ErrorException $e) {
913
914
915
916
                    Log::error($e);
                }
            }
        }
917

918
        # Nicht fertige Engines verwefen
919