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
                        ->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

Dominik Hebeler's avatar
Dominik Hebeler committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
    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
472
473
474
475
476
477
    public function authorize($key)
    {
        $postdata = http_build_query(array(
            'dummy' => rand(),
        ));
        $opts = array('http' => array(
478
479
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
Phil Höfer's avatar
Phil Höfer committed
480
481
482
483
484
485
486
            'content' => $postdata,
        ),
        );

        $context = stream_context_create($opts);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $this->retrieveResults($engines);
    }

640
641
    # Spezielle Suchen und Sumas

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

917
        # Nicht fertige Engines verwefen
918
919
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
920
                $engine->shutdown();
921
            }
922
923
924
        }

        $this->engines = $engines;