MetaGer.php 57.2 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
        # Human Verification
        $this->results = $this->humanVerification($this->results);
261
        $this->ads = $this->humanVerification($this->ads);
Dominik Hebeler's avatar
Dominik Hebeler committed
262

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

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

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

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

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

298
299
        }

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

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

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

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

325
    }
326

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

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

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

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

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

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

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

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

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

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

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

        return $results;
    }
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
                $link = $result->link;
                $day = Carbon::now()->day;
                $pw = md5($this->verificationId . $day . $link . env("PROXY_PASSWORD"));
464
465
466
                $url = route('humanverification', ['mm' => $this->verificationId, 'pw' => $pw, "url" => urlencode(str_replace("/", "<<SLASH>>", base64_encode($link)))]);
                $proxyPw = md5($this->verificationId . $day . $result->proxyLink . env("PROXY_PASSWORD"));
                $proxyUrl = route('humanverification', ['mm' => $this->verificationId, 'pw' => $proxyPw, "url" => urlencode(str_replace("/", "<<SLASH>>", base64_encode($result->proxyLink)))]);
Dominik Hebeler's avatar
Dominik Hebeler committed
467
                $result->link = $url;
468
                $result->proxyLink = $proxyUrl;
Dominik Hebeler's avatar
Dominik Hebeler committed
469
470
            }
            return $results;
471
        }else{
Dominik Hebeler's avatar
Dominik Hebeler committed
472
473
474
475
            return $results;
        }
    }

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

        $context = stream_context_create($opts);

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

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

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

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

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

528
        $isCustomSearch = $this->startsWith($this->fokus, 'focus_');
529

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

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

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

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

        $typeslist = [];
603
        $counter = 0;
604

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

615
        # Wir starten alle Suchen
616
617
        foreach ($engines as $engine) {
            $engine->startSearch($this);
618
        }
619

620
621
622
623
624
        /* 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.
625
626
         */

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

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

        $this->retrieveResults($engines);
    }

644
645
    # Spezielle Suchen und Sumas

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Phil Höfer's avatar
Phil Höfer committed
895
            if ($ready) {
896
897
898
899
                break;
            }
            usleep(50000);
        }
900
901

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

908
909
910
    public function retrieveResults($engines)
    {
        # Von geladenen Engines die Ergebnisse holen
911
912
913
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
914
                    $engine->retrieveResults($this);
Dominik Hebeler's avatar