MetaGer.php 52.6 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;
11
use Predis\Connection\ConnectionException;
12
13
14

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

57
58
    public function __construct()
    {
59
        # Timer starten
60
        $this->starttime = microtime(true);
61
62

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

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

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

90
    # Erstellt aus den gesammelten Ergebnissen den View
91
92
93
    public function createView()
    {
        $viewResults = [];
94
        # Wir extrahieren alle notwendigen Variablen und geben Sie an unseren View:
95
        foreach ($this->results as $result) {
96
97
98
99
            $viewResults[] = get_object_vars($result);
        }
        # Wir müssen natürlich noch den Log für die durchgeführte Suche schreiben:
        $this->createLogs();
100
101
        if ($this->fokus === "bilder") {
            switch ($this->out) {
102
103
104
105
106
107
108
                case 'results':
                    return view('metager3bilderresults')
                        ->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
109
                        ->with('apiAuthorized', $this->apiAuthorized)
110
                        ->with('metager', $this)
111
                        ->with('browser', (new Agent())->browser());
112
113
114
115
116
117
118
                default:
                    return view('metager3bilder')
                        ->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
119
                        ->with('apiAuthorized', $this->apiAuthorized)
120
                        ->with('metager', $this)
121
                        ->with('browser', (new Agent())->browser());
122
            }
123
124
125
126
127
128
129
130
131
        } else {
            switch ($this->out) {
                case 'results':
                    return view('metager3results')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
132
                        ->with('apiAuthorized', $this->apiAuthorized)
133
134
135
136
137
138
139
140
141
142
                        ->with('metager', $this)
                        ->with('browser', (new Agent())->browser());
                    break;
                case 'results-with-style':
                    return view('metager3')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
143
                        ->with('apiAuthorized', $this->apiAuthorized)
144
145
146
147
                        ->with('metager', $this)
                        ->with('suspendheader', "yes")
                        ->with('browser', (new Agent())->browser());
                    break;
Phil Höfer's avatar
Phil Höfer committed
148
149
                case 'rich':
                    return view('metager3rich')
150
                        ->with('results', $viewResults)
Phil Höfer's avatar
Phil Höfer committed
151
152
153
154
                        ->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)
Phil Höfer's avatar
Phil Höfer committed
156
157
158
                        ->with('metager', $this)
                        ->with('browser', (new Agent())->browser());
                    break;
159
160
161
162
                case 'rss20':
                    return view('metager3resultsrss20')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
Phil Höfer's avatar
Phil Höfer committed
163
                        ->with('apiAuthorized', $this->apiAuthorized)
164
165
166
                        ->with('metager', $this)
                        ->with('resultcount', sizeof($viewResults));
                    break;
Aria Givi's avatar
Aria Givi committed
167
                case 'atom10':
Phil Höfer's avatar
Phil Höfer committed
168
                    return response()->view('metager3resultsatom10', ['results' => $viewResults,'eingabe' => $this->eingabe,'metager' => $this,'resultcount' => sizeof($viewResults)])
Phil Höfer's avatar
Phil Höfer committed
169
			->header('Content-Type', 'application/xml');
Aria Givi's avatar
Aria Givi committed
170
                    break;
171
                case 'result-count':
172
173
                    # Wir geben die Ergebniszahl und die benötigte Zeit zurück:
                    return sizeof($viewResults) . ";" . round((microtime(true) - $this->starttime), 2);
174
                    break;
175
176
177
178
179
180
                default:
                    return view('metager3')
                        ->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
181
                        ->with('apiAuthorized', $this->apiAuthorized)
182
183
184
185
                        ->with('metager', $this)
                        ->with('browser', (new Agent())->browser());
                    break;
            }
186
187
188
        }
    }

Phil Höfer's avatar
Phil Höfer committed
189
    public function prepareResults()
190
    {
Phil Höfer's avatar
Phil Höfer committed
191
        $engines = $this->engines;
192

Phil Höfer's avatar
Phil Höfer committed
193
194
        // combine
        $combinedResults = $this->combineResults($engines);
195
196
197
198

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

Phil Höfer's avatar
Phil Höfer committed
199
200
201
202
203
        // sort
        //$sortedResults = $this->sortResults($engines);
        // filter
        // augment (boost&adgoal)
        // authorize
Phil Höfer's avatar
Phil Höfer committed
204
205
206
        if ($this->apiKey) {
            $this->apiAuthorized = $this->authorize($this->apiKey);
        }
Phil Höfer's avatar
Phil Höfer committed
207
        // misc (WiP)
208
        if ($this->fokus == "nachrichten") {
209
210
211
            $this->results = array_filter($this->results, function ($v, $k) {
                return !is_null($v->getRank());
            }, ARRAY_FILTER_USE_BOTH);
212
213
214
215
216
217
218
219
220
221
            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;
                }
222

223
224
225
                return ($a->getRank() < $b->getRank()) ? 1 : -1;
            });
        }
226

227
228
        # Validate Results
        $newResults = [];
229
230
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
231
                $newResults[] = $result;
232
233
            }

234
235
236
        }
        $this->results = $newResults;

237
238
239
        #Adgoal Implementation
        $this->results = $this->parseAdgoal($this->results);

240
        $counter   = 0;
241
        $firstRank = 0;
242

243
        if (isset($this->startForwards)) {
244
            $this->startCount = $this->startForwards;
245
        } elseif (isset($this->startBackwards)) {
246
            $this->startCount = $this->startBackwards - count($this->results) - 1;
247
        } else {
248
249
250
            $this->startCount = 0;
        }

251
252
        foreach ($this->results as $result) {
            if ($counter === 0) {
253
                $firstRank = $result->rank;
254
255
            }

256
            $counter++;
257
            $result->number = $counter + $this->startCount;
258
259
260
261
            $confidence     = 0;
            if ($firstRank > 0) {
                $confidence = $result->rank / $firstRank;
            } else {
262
                $confidence = 0;
263
264
265
            }

            if ($confidence > 0.65) {
266
                $result->color = "#FF4000";
267
            } elseif ($confidence > 0.4) {
268
                $result->color = "#FF0080";
269
            } elseif ($confidence > 0.2) {
270
                $result->color = "#C000C0";
271
            } else {
272
                $result->color = "#000000";
273
274
            }

275
276
        }

277
        if (LaravelLocalization::getCurrentLocale() === "en") {
278
279
            $this->ads = [];
        }
280
281
        
        if ($this->validated) {
282
283
284
            $this->ads       = [];
            $this->products  = [];
            $this->maps      = false;
285
        }
286
287

        if (count($this->results) <= 0) {
288
            $this->errors[] = trans('metaGer.results.failed');
289
        }
290

291
        if ($this->canCache() && isset($this->next) && count($this->next) > 0 && count($this->results) > 0) {
292
            $page       = $this->page + 1;
293
            $this->next = [
294
295
296
                'page'          => $page,
                'startForwards' => $this->results[count($this->results) - 1]->number,
                'engines'       => $this->next,
297
298
            ];
            Cache::put(md5(serialize($this->next)), serialize($this->next), 60);
299
300
        } else {
            $this->next = [];
301
302
        }

303
    }
304

305
306
    private function addLangCodes($results)
    {
307
308
309
310
311
        # Wenn es keine Ergebnisse gibt, brauchen wir uns gar nicht erst zu bemühen
        if (sizeof($results) === 0) {
            return $results;
        }

312
313
314
315
316
317
318
319
320
321
322
        # Bei der Spracheinstellung "all" wird nicht gefiltert
        if ($this->getLang() === "all") {
            return $results;
        } else {
            # Ansonsten müssen wir jedem Result einen Sprachcode hinzufügen
            $id          = 0;
            $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
323
                $langStrings["result_" . $id] = utf8_encode($result->getLangString());
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

                $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";
            $lang             = exec("echo '$filename' | $langDetectorPath");
            $lang             = json_decode($lang, true);

            # 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
    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;
            }
            foreach ($engine->products as $product) {
                $this->products[] = $product;
            }
        }

    }

375
376
    public function parseAdgoal($results)
    {
377
        $publicKey  = getenv('adgoal_public');
378
        $privateKey = getenv('adgoal_private');
379
        if ($publicKey === false) {
380
381
382
            return $results;
        }
        $tldList = "";
383
384
        try {
            foreach ($results as $result) {
385
                $link = $result->anzeigeLink;
386
                if (strpos($link, "http") !== 0) {
387
388
389
390
391
392
393
394
395
396
                    $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");

397
            # Query
398
399
            $query = urlencode($this->q);

400
            $link   = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
401
402
403
            $answer = json_decode(file_get_contents($link));

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

408
409
                foreach ($results as $result) {
                    if ($hoster === $result->tld) {
410
411
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
412
                        if ($result->image !== "") {
413
                            $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
414
                        } else {
415
                            $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
416
417
                        }

418
419
420
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
                        $targetUrl = $result->anzeigeLink;
421
                        if (strpos($targetUrl, "http") !== 0) {
422
                            $targetUrl = "http://" . $targetUrl;
423
424
425
426
427
                        }

                        $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;
428
429
430
431
                        $result->partnershop = true;
                    }
                }
            }
432
        } catch (\ErrorException $e) {
433
434
435
436
437
            return $results;
        }

        return $results;
    }
438

Phil Höfer's avatar
Phil Höfer committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    public function authorize($key)
    {
        $postdata = http_build_query(array(
            'dummy' => rand(),
        ));
        $opts = array('http' => array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata,
        ),
        );

        $context = stream_context_create($opts);

        try {
            $link   = "https://key.metager3.de/" . urlencode($key) . "/request-permission/api-access";
            $result = json_decode(file_get_contents($link, false, $context));
            if ($result->{'api-access'} == true) {
                return true;
            } else {
                return false;
            }

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

Karl's avatar
Karl committed
467
468
469
470
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

471
472
    public function createSearchEngines(Request $request)
    {
473
        # Wenn es kein Suchwort gibt
474
        if (!$request->has("eingabe") || $this->q === "") {
475
            return;
476
        }
477

478
        $xml                  = simplexml_load_file($this->sumaFile);
479
        $sumas                = $xml->xpath("suma");
480
        $enabledSearchengines = [];
481
        $overtureEnabled      = false;
482
483
        $sumaCount            = 0;

484
        $isCustomSearch = $this->startsWith($this->fokus, 'focus_');
485

Karl's avatar
Karl committed
486
        /* Erstellt die Liste der eingestellten Sumas
487
488
489
         * 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
490
491
492
493
494
495
         * 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
         */
496
        foreach ($sumas as $suma) {
497
            if (($this->sumaIsSelected($suma, $request, $isCustomSearch)
498
                || (!$this->isBildersuche()
499
                    && $this->sumaIsAdsuche($suma, $overtureEnabled)))
500
501
502
                && (!$this->sumaIsDisabled($suma))) {
                if ($this->sumaIsOverture($suma)) {
                    $overtureEnabled = true;
503
                }
504
505
                if ($this->sumaIsNotAdsuche($suma)) {
                    $sumaCount += 1;
506
                }
507
                $enabledSearchengines[] = $suma;
508
509
510
511
            }
        }

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

        $tmp = [];
515
516
517
518
        // 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
519
520
521
            // Wir laden alle Minisucher
            foreach ($sumas as $engine) {
                if (isset($engine["minismCollection"])) {
522
                    $subcollections[] = $engine["minismCollection"]->__toString();
Dominik Hebeler's avatar
Dominik Hebeler committed
523
524
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
525
526
527
528
529
530
            # 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
531
532
533
534
        } else {
            // Wir schalten eine Teilmenge, oder aber gar keine an
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['minismCollection'])) {
535
                    $subcollections[] = $engine['minismCollection']->__toString();
Dominik Hebeler's avatar
Dominik Hebeler committed
536
537
                } else {
                    $tmp[] = $engine;
Dominik Hebeler's avatar
Dominik Hebeler committed
538
                }
539
            }
540
541
        }
        $enabledSearchengines = $tmp;
542
543
        if (sizeof($subcollections) > 0) {
            $enabledSearchengines[] = $this->loadMiniSucher($xml, $subcollections);
544
        }
545
        if ($sumaCount <= 0) {
546
            $this->errors[] = trans('metaGer.settings.noneSelected');
547
        }
548
        $engines = [];
549
        # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob überhaupt eine der Suchmaschinen eine Sitesearch unterstützt
550
        $siteSearchFailed = $this->checkCanNotSitesearch($enabledSearchengines);
551
552

        $typeslist = [];
553
        $counter   = 0;
554

555
556
        if ($this->requestIsCached($request)) {
            $engines = $this->getCachedEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
557
            # We need to edit some Options of the Cached Search Engines
Phil Höfer's avatar
Phil Höfer committed
558
            foreach ($engines as $engine) {
Dominik Hebeler's avatar
Dominik Hebeler committed
559
560
                $engine->setResultHash($this->getHashCode());
            }
561
        } else {
562
            $engines = $this->actuallyCreateSearchEngines($enabledSearchengines, $siteSearchFailed);
563
        }
564

565
        # Wir starten alle Suchen
566
567
        foreach ($engines as $engine) {
            $engine->startSearch($this);
568
        }
569
570
        // Derzeit deaktiviert, da es die eigene Suche gibt
        // $this->adjustFocus($sumas, $enabledSearchengines);
571

572
573
574
575
576
        /* 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.
577
578
         */

579
        $enginesToLoad = [];
580
581
582
583
584
585
        $canBreak      = false;
        foreach ($engines as $engine) {
            if ($engine->cached) {
                if ($overtureEnabled && ($engine->name === "overture" || $engine->name === "overtureAds")) {
                    $canBreak = true;
                }
586
587
            } else {
                $enginesToLoad[$engine->name] = false;
588
589
590
591
592
593
594
595
            }
        }

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

        $this->retrieveResults($engines);
    }

596
597
    # Spezielle Suchen und Sumas

598
    public function sumaIsSelected($suma, $request, $custom)
599
    {
600
601
        if ($custom) {
            if ($request->has("engine_" . $suma["name"])) {
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
                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
626
627
628
            if (!isset($engine["package"])) {
                die(var_dump($engine));
            }
629
630
631
632
633
            # 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")) {
634
                Log::error("Konnte " . $engine["name"] . " nicht abfragen, da kein Parser existiert");
635
                $this->errors[] = trans('metaGer.engines.noParser', ['engine' => $engine["name"]]);
636
637
638
639
640
641
642
643
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
                $tmp = new $path($engine, $this);
            } catch (\ErrorException $e) {
644
                Log::error("Konnte " . $engine["name"] . " nicht abfragen. " . var_dump($e));
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
                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()
    {
663
        return $this->fokus === "bilder";
664
665
666
667
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
668
        $sumaName = $suma["name"]->__toString();
669
        return
670
671
672
673
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
            || (!$overtureEnabled && $sumaName === "overtureAds")
            || $sumaName == "rlvproduct";
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
    }

    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
        $request->has('next')
        && Cache::has($request->input('next'))
        && unserialize(Cache::get($request->input('next')))['page'] > 1;
    }

    public function getCachedEngines($request)
    {
        $next       = unserialize(Cache::get($request->input('next')));
        $this->page = $next['page'];
        $engines    = $next['engines'];
        if (isset($next['startForwards'])) {
            $this->startForwards = $next['startForwards'];
        }
        if (isset($next['startBackwards'])) {
            $this->startBackwards = $next['startBackwards'];
        }
        return $engines;
    }

    public function loadMiniSucher($xml, $subcollections)
    {
        $minisucherEngine             = $xml->xpath('suma[@name="minism"]')[0];
723
        $minisucherEngine["subcollections"] = implode(", ", $subcollections);
724
725
726
727
728
729
        $subcollections               = urlencode("(" . implode(" OR ", $subcollections) . ")");
        $minisucherEngine["formData"] = str_replace("<<SUBCOLLECTIONS>>", $subcollections, $minisucherEngine["formData"]);
        $minisucherEngine["formData"] = str_replace("<<COUNT>>", sizeof($subcollections) * 10, $minisucherEngine["formData"]);
        return $minisucherEngine;
    }

730
    # Passt den Suchfokus an, falls für einen Fokus genau alle vorhandenen Sumas eingeschaltet sind
731
732
    public function adjustFocus($sumas, $enabledSearchengines)
    {
733
734
        # Findet für alle Foki die enthaltenen Sumas
        $foki = []; # [fokus][suma] => [suma]
735
        foreach ($sumas as $suma) {
736
            if ((!$this->sumaIsDisabled($suma)) && (!isset($suma['userSelectable']) || $suma['userSelectable']->__toString() === "1")) {
737
                if (isset($suma['type'])) {
738
739
740
                    # Wenn foki für diese Suchmaschine angegeben sind
                    $focuses = explode(",", $suma['type']->__toString());
                    foreach ($focuses as $foc) {
741
742
743
744
745
                        if (isset($suma['minismCollection'])) {
                            $foki[$foc][] = "minism";
                        } else {
                            $foki[$foc][] = $suma['name']->__toString();
                        }
746
                    }
747
                } else {
748
                    # Wenn keine foki für diese Suchmaschine angegeben sind
749
750
751
752
753
                    if (isset($suma['minismCollection'])) {
                        $foki["andere"][] = "minism";
                    } else {
                        $foki["andere"][] = $suma['name']->__toString();
                    }
754
755
756
757
                }
            }
        }

758
        # Findet die Namen der aktuell eingeschalteten Sumas
759
        $realEngNames = [];
760
        foreach ($enabledSearchengines as $realEng) {
761
            $nam = $realEng["name"]->__toString();
762
            if ($nam !== "qualigo" && $nam !== "overtureAds" && $nam !== "rlvproduct") {
763
764
765
                $realEngNames[] = $nam;
            }
        }
766

767
        # 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.
768
        foreach ($foki as $fok => $engines) {
769
            $isFokus      = true;
770
            $fokiEngNames = [];
771
            foreach ($engines as $eng) {
772
773
                $fokiEngNames[] = $eng;
            }
774
            # Jede eingeschaltete Engine ist für diesen Fokus geeignet
775
            foreach ($fokiEngNames as $fen) {
776
777
                # 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") {
778
779
780
                    $isFokus = false;
                }
            }
781
            # Jede im Fokus erwartete Engine ist auch eingeschaltet
782
783
            foreach ($realEngNames as $ren) {
                if (!in_array($ren, $fokiEngNames)) {
784
785
786
                    $isFokus = false;
                }
            }
787
            # Wenn die Listen identisch sind, setze den Fokus um
788
            if ($isFokus) {
789
790
791
                $this->fokus = $fok;
            }
        }
792
    }
793

794
795
796
797
798
799
800
    public function checkCanNotSitesearch($enabledSearchengines)
    {
        if (strlen($this->site) > 0) {
            $enginesWithSite = 0;
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1") {
                    $enginesWithSite++;
801
                }
802
803
            }
            if ($enginesWithSite === 0) {
804
                $this->errors[] = trans('metaGer.sitesearch.failed', ['site' => $this->site, 'searchLink' => $this->generateSearchLink("web", false)]);
805
806
                return true;
            } else {
807
                $this->warnings[] = trans('metaGer.sitesearch.success', ['site' => $this->site]);
808
                return false;
809
810
            }
        }
811
        return false;
812
813
814
815
    }

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

Phil Höfer's avatar
Phil Höfer committed
817
818
        $timeStart = microtime(true);
        $results   = null;
819
        while (true) {
820
821
822
            $results = Redis::hgetall('search.' . $this->getHashCode());

            $ready = true;
Phil Höfer's avatar
Phil Höfer committed
823
            // When every
824
            $connected = true;
Phil Höfer's avatar
Phil Höfer committed
825
826
            foreach ($results as $key => $value) {
                if ($value === "waiting" || $value === "connected") {
827
                    $ready = false;
828
                }
Phil Höfer's avatar
Phil Höfer committed
829
                if ($value === "waiting") {
830
                    $connected = false;
831
                }
832
            }
833

834
835
            // 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
836
837
838
839
            if (!$connected) {
                $timeStart = microtime(true);
            }

840
841
842
843
            $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
844
845
846
            if ($time > $this->time && $canTimeout) {
                $ready = true;
            }
847

Phil Höfer's avatar
Phil Höfer committed
848
            if ($ready) {
849
850
851
852
                break;
            }
            usleep(50000);
        }
853
854

        # Wir haben nun so lange wie möglich gewartet. Wir registrieren nun noch die Suchmaschinen, die geanwortet haben.
855
        foreach ($results as $key => $value) {
856
857
858
            $enginesToLoad[$key] = true;
        }
        $this->enginesToLoad = $enginesToLoad;
859
    }
860

861
862
863
    public function retrieveResults($engines)
    {
        # Von geladenen Engines die Ergebnisse holen
864
865
866
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
867
                    $engine->retrieveResults($this);
868
                } catch (\ErrorException $e) {
869
870
871
872
                    Log::error($e);
                }
            }
        }
873

874
        # Nicht fertige Engines verwefen
875
876
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
877
                $engine->shutdown();
878
            }
879
880
881
        }

        $this->engines = $engines;
882
883
    }

884
885
886
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
887

888
889
    public function parseFormData(Request $request)
    {
890
        $this->request = $request;
891
        # Sichert, dass der request in UTF-8 formatiert ist
892
        if ($request->input('encoding', 'utf8') !== "utf8") {
893
894
895
896
897
898
899
            # In früheren Versionen, als es den Encoding Parameter noch nicht gab, wurden die Daten in ISO-8859-1 übertragen
            $input = $request->all();
            foreach ($input as $key => $value) {
                $input[$key] = mb_convert_encoding("$value", "UTF-8", "ISO-8859-1");
            }
            $request->replace($input);
        }
900
        $this->url = $request->url();
901
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
902
        # Fokus
903
        $this->fokus = $request->input('focus', 'web');
904
        # Suma-File
905
        if (App::isLocale("en")) {
906
            $this->sumaFile = config_path() . "/sumas.xml";
907
        } else {
908
909
            $this->sumaFile = config_path() . "/sumas.xml";
        }
910
        if (!file_exists($this->sumaFile)) {
911
            die(trans('metaGer.formdata.cantLoad'));
912
        }
913
        # Sucheingabe
914
        $this->eingabe = trim($request->input('eingabe', ''));
915
        $this->q       = mb_strtolower($this->eingabe, "UTF-8");
916
        # IP
917
        $this->ip = $request->ip();
918
919
920
921
        # Unser erster Schritt wird sein, IP-Adresse und USER-Agent zu anonymisieren, damit
        # nicht einmal wir selbst noch Zugriff auf die Daten haben:
        $this->ip = preg_replace("/(\d+)\.(\d+)\.\d+.\d+/s", "$1.$2.0.0", $this->ip);

922
        # Language
923
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
924
            $this->language = $_SERVER['HTTP_LANGUAGE'];
925
        } else {
926
927
928
929
            $this->language = "";
        }
        # Category
        $this->category = $request->input('category', '');
930
        # Request Times
931
        $this->time = $request->input('time', 1500);
932
        # Page
933
        $this->page = 1;
934
935
        # Lang
        $this->lang = $request->input('lang', 'all');
936
937
        if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
            $this->lang = "all";
938
        }
939

940
        $this->agent  = new Agent();
941
        $this->mobile = $this->agent->isMobile();
942
        # Sprüche
943
944
        $this->sprueche = $request->input('sprueche', 'on');
        if ($this->sprueche === "on") {
945
            $this->sprueche = true;
946
        } else {
947
            $this->sprueche = false;
948
        }
Karl's avatar
Karl committed
949
        $this->maps = $request->input('maps', 'off');
950
        if ($this->maps === "on") {
951
952
953
954
            $this->maps = true;
        } else {
            $this->maps = false;
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
955
        $this->newtab = $request->input('newtab', 'on');
956
957
958
959
960
        if ($this->newtab === "on") {
            $this->newtab = "_blank";
        } else {
            $this->newtab = "_self";
        }
961
        # Theme
Phil Höfer's avatar
Phil Höfer committed
962
        $this->theme = preg_replace("/[^[:alnum:][:space:]]/u", '', $request->input('theme', 'default'));
963
964
965
        # Ergebnisse pro Seite:
        $this->resultCount = $request->input('resultCount', '20');
        # Manchmal müssen wir Parameter anpassen um den Sucheinstellungen gerecht zu werden:
966
967
        if ($request->has('dart')) {
            $this->time       = 10000;
968
            $this->warnings[] = trans('metaGer.formdata.dartEurope');
969
        }
970
971
        if ($this->time <= 500 || $this->time > 20000) {
            $this->time = 1000;
972
        }
973
974
975
976
977
978
979
980
981
        if ($request->has('minism') && ($request->has('fportal') || $request->has('harvest'))) {
            $input    = $request->all();
            $newInput = [];
            foreach ($input as $key => $value) {
                if ($key !== "fportal" && $key !== "harvest") {
                    $newInput[$key] = $value;
                }
            }
            $request->replace($newInput);
982
        }
983
984
        if (App::isLocale("en")) {
            $this->sprueche = "off";
985
        }
986
987
        if ($this->resultCount <= 0 || $this->resultCount > 200) {
            $this->resultCount = 1000;
988
        }
989
990
991
992
993
        if ($request->has('onenewspageAll') || $request->has('onenewspageGermanyAll')) {
            $this->time  = 5000;
            $this->cache = "cache";
        }
        if ($request->has('password')) {
994
            $this->password = $request->input('password');
995
996
        }
        if ($request->has('quicktips')) {
997
            $this->quicktips = false;
998
        } else {
999
            $this->quicktips = true;
1000
        }
Phil Höfer's avatar
Phil Höfer committed
1001
1002

        $this->apiKey =