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

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

class MetaGer
{
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    # 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 = [];
    protected $stopWords       = [];
    protected $phrases         = [];
    protected $engines         = [];
    protected $results         = [];
    protected $ads             = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
32
    protected $products        = [];
33
34
35
    protected $warnings        = [];
    protected $errors          = [];
    protected $addedHosts      = [];
36
    protected $startCount      = 0;
37
    protected $canCache        = false;
38
39
40
41
42
43
44
45
46
    # Daten über die Abfrage
    protected $ip;
    protected $language;
    protected $agent;
    # Konfigurationseinstellungen:
    protected $sumaFile;
    protected $mobile;
    protected $resultCount;
    protected $sprueche;
47
    protected $domainsBlacklisted = [];
48
    protected $urlsBlacklisted    = [];
49
50
51
    protected $url;
    protected $languageDetect;

52
53
    public function __construct()
    {
54
        # Timer starten
55
        $this->starttime = microtime(true);
56
57

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

67
        # Parser Skripte einhängen
68
69
70
71
        $dir = app_path() . "/Models/parserSkripte/";
        foreach (scandir($dir) as $filename) {
            $path = $dir . $filename;
            if (is_file($path)) {
72
                require_once $path;
73
74
75
            }
        }

76
        # Cachebarkeit testen
77
78
79
80
81
82
        try {
            Cache::has('test');
            $this->canCache = true;
        } catch (ConnectionException $e) {
            $this->canCache = false;
        }
83
    }
84

85
    # Erstellt aus den gesammelten Ergebnissen den View
86
87
88
    public function createView()
    {
        $viewResults = [];
89
        # Wir extrahieren alle notwendigen Variablen und geben Sie an unseren View:
90
        foreach ($this->results as $result) {
91
92
93
94
95
96
            $viewResults[] = get_object_vars($result);
        }

        # Wir müssen natürlich noch den Log für die durchgeführte Suche schreiben:
        $this->createLogs();

97
98
        if ($this->fokus === "bilder") {
            switch ($this->out) {
99
100
101
102
103
104
105
106
                case 'results':
                    return view('metager3bilderresults')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
                        ->with('metager', $this)
107
                        ->with('browser', (new Agent())->browser());
108
109
110
111
112
113
114
115
                default:
                    return view('metager3bilder')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
                        ->with('metager', $this)
116
                        ->with('browser', (new Agent())->browser());
117
            }
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
        } 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)
                        ->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)
                        ->with('metager', $this)
                        ->with('suspendheader', "yes")
                        ->with('browser', (new Agent())->browser());
                    break;
                default:
                    return view('metager3')
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
                        ->with('metager', $this)
                        ->with('browser', (new Agent())->browser());
                    break;
            }
151
152
153
        }
    }

Phil Höfer's avatar
Phil Höfer committed
154
    public function prepareResults()
155
    {
Phil Höfer's avatar
Phil Höfer committed
156
        $engines = $this->engines;
157

Phil Höfer's avatar
Phil Höfer committed
158
159
        // combine
        $combinedResults = $this->combineResults($engines);
160
161
162
163

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

Phil Höfer's avatar
Phil Höfer committed
164
165
166
167
168
169
        // sort
        //$sortedResults = $this->sortResults($engines);
        // filter
        // augment (boost&adgoal)
        // authorize
        // misc (WiP)
170
171
        uasort($this->results, function ($a, $b) {
            if ($a->getRank() == $b->getRank()) {
172
                return 0;
173
174
            }

175
176
            return ($a->getRank() < $b->getRank()) ? 1 : -1;
        });
177

178
179
        # Validate Results
        $newResults = [];
180
181
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
182
                $newResults[] = $result;
183
184
            }

185
186
187
        }
        $this->results = $newResults;

188
189
190
191
192
193
        # Boost implementation
        $this->results = $this->parseBoost($this->results);

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

194
        $counter   = 0;
195
        $firstRank = 0;
196

197
        if (isset($this->startForwards)) {
198
            $this->startCount = $this->startForwards;
199
        } elseif (isset($this->startBackwards)) {
200
            $this->startCount = $this->startBackwards - count($this->results) - 1;
201
        } else {
202
203
204
            $this->startCount = 0;
        }

205
206
        foreach ($this->results as $result) {
            if ($counter === 0) {
207
                $firstRank = $result->rank;
208
209
            }

210
            $counter++;
211
            $result->number = $counter + $this->startCount;
212
213
214
215
            $confidence     = 0;
            if ($firstRank > 0) {
                $confidence = $result->rank / $firstRank;
            } else {
216
                $confidence = 0;
217
218
219
            }

            if ($confidence > 0.65) {
220
                $result->color = "#FF4000";
221
            } elseif ($confidence > 0.4) {
222
                $result->color = "#FF0080";
223
            } elseif ($confidence > 0.2) {
224
                $result->color = "#C000C0";
225
            } else {
226
                $result->color = "#000000";
227
228
            }

229
230
        }

231
        if (LaravelLocalization::getCurrentLocale() === "en") {
232
233
234
            $this->ads = [];
        }

235
        $this->validated = false;
236
        if (isset($this->password)) {
237
238
239
            # Wir bieten einen bezahlten API-Zugriff an, bei dem dementsprechend die Werbung ausgeblendet wurde:
            # Aktuell ist es nur die Uni-Mainz. Deshalb überprüfen wir auch nur diese.
            $password = getenv('mainz');
240
            $eingabe  = $this->eingabe;
241
            $password = md5($eingabe . $password);
242
243
            if ($this->password === $password) {
                $this->ads       = [];
244
                $this->products  = [];
245
246
247
                $this->validated = true;
            }
        }
248
249

        if (count($this->results) <= 0) {
250
            $this->errors[] = trans('metaGer.results.failed');
251
        }
252

253
        if ($this->canCache() && isset($this->next) && count($this->next) > 0 && count($this->results) > 0) {
254
            $page       = $this->page + 1;
255
            $this->next = [
256
257
258
                'page'          => $page,
                'startForwards' => $this->results[count($this->results) - 1]->number,
                'engines'       => $this->next,
259
260
            ];
            Cache::put(md5(serialize($this->next)), serialize($this->next), 60);
261
262
        } else {
            $this->next = [];
263
264
        }

265
    }
266

267
268
    private function addLangCodes($results)
    {
269
270
271
272
273
        # Wenn es keine Ergebnisse gibt, brauchen wir uns gar nicht erst zu bemühen
        if (sizeof($results) === 0) {
            return $results;
        }

274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
        # 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;

                $langStrings["result_" . $id] = utf8_encode($result->getLangString());

                $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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    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;
            }
        }

    }

337
338
    public function parseBoost($results)
    {
339
340
341
342
343
344
345
346
347
348
349
350
        foreach ($results as $result) {
            if (preg_match('/^(http[s]?\:\/\/)?(www.)?amazon\.de/', $result->anzeigeLink)) {
                if (preg_match('/\?/', $result->anzeigeLink)) {
                    $result->link .= '&tag=boostmg01-21';
                } else {
                    $result->link .= '?tag=boostmg01-21';
                }
                $result->partnershop = true;

            }
        }
        return $results;
351
    }
352

353
354
    public function parseAdgoal($results)
    {
355
        $publicKey  = getenv('adgoal_public');
356
        $privateKey = getenv('adgoal_private');
357
        if ($publicKey === false) {
358
359
360
            return $results;
        }
        $tldList = "";
361
362
        try {
            foreach ($results as $result) {
363
                $link = $result->anzeigeLink;
364
                if (strpos($link, "http") !== 0) {
365
366
367
368
369
370
371
372
373
374
                    $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");

375
            # Query
376
377
            $query = urlencode($this->q);

378
            $link   = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
379
380
381
            $answer = json_decode(file_get_contents($link));

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

386
387
                foreach ($results as $result) {
                    if ($hoster === $result->tld) {
388
389
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
390
                        if ($result->image !== "") {
391
                            $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
392
                        } else {
393
                            $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
394
395
                        }

396
397
398
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
                        $targetUrl = $result->anzeigeLink;
399
                        if (strpos($targetUrl, "http") !== 0) {
400
                            $targetUrl = "http://" . $targetUrl;
401
402
403
404
405
                        }

                        $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;
406
407
408
409
                        $result->partnershop = true;
                    }
                }
            }
410
        } catch (\ErrorException $e) {
411
412
413
414
415
            return $results;
        }

        return $results;
    }
416

Karl's avatar
Karl committed
417
418
419
420
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

421
422
    public function createSearchEngines(Request $request)
    {
423
        # Wenn es kein Suchwort gibt
424
        if (!$request->has("eingabe")) {
425
            return;
426
        }
427

428
        $xml                  = simplexml_load_file($this->sumaFile);
429
        $sumas                = $xml->xpath("suma");
430
        $enabledSearchengines = [];
431
        $overtureEnabled      = false;
432
433
        $sumaCount            = 0;

Karl's avatar
Karl committed
434
        /* Erstellt die Liste der eingestellten Sumas
435
436
437
         * 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
438
439
440
441
442
443
         * 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
         */
444
        foreach ($sumas as $suma) {
445
            if (($this->sumaIsSelected($suma, $request)
446
                || (!$this->isBildersuche()
447
                    && $this->sumaIsAdsuche($suma, $overtureEnabled)))
448
449
450
                && (!$this->sumaIsDisabled($suma))) {
                if ($this->sumaIsOverture($suma)) {
                    $overtureEnabled = true;
451
                }
452
453
                if ($this->sumaIsNotAdsuche($suma)) {
                    $sumaCount += 1;
454
                }
455
                $enabledSearchengines[] = $suma;
456
457
458
459
460
            }
        }

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

        $tmp = [];
463
464
        foreach ($enabledSearchengines as $engine) {
            if (isset($engine['minismCollection'])) {
465
                $subcollections[] = $engine['minismCollection']->__toString();
466
            } else {
467
                $tmp[] = $engine;
468
469
            }

470
471
        }
        $enabledSearchengines = $tmp;
472
        if (sizeof($subcollections) > 0) {
473
            $enabledSearchengines[] = $this->loadMiniSucher($xml, $subcollections);
474
475
        }

476
        if ($sumaCount <= 0) {
477
            $this->errors[] = trans('metaGer.settings.noneSelected');
478
        }
479

480
        $engines = [];
481

482
        # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob überhaupt eine der Suchmaschinen eine Sitesearch unterstützt
483
        $siteSearchFailed = $this->checkCanNotSitesearch($enabledSearchengines);
484
485

        $typeslist = [];
486
        $counter   = 0;
487

488
489
        if ($this->requestIsCached($request)) {
            $engines = $this->getCachedEngines($request);
490
        } else {
491
            $engines = $this->actuallyCreateSearchEngines($enabledSearchengines, $siteSearchFailed);
492
        }
493

494
        # Wir starten alle Suchen
495
496
        foreach ($engines as $engine) {
            $engine->startSearch($this);
497
        }
498

499
500
        $this->adjustFocus($sumas, $enabledSearchengines);

501
502
503
504
505
        /* 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.
506
507
         */

508
        $enginesToLoad = [];
509
510
511
512
513
514
        $canBreak      = false;
        foreach ($engines as $engine) {
            if ($engine->cached) {
                if ($overtureEnabled && ($engine->name === "overture" || $engine->name === "overtureAds")) {
                    $canBreak = true;
                }
515
516
            } else {
                $enginesToLoad[$engine->name] = false;
517
518
519
520
521
522
523
524
            }
        }

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

        $this->retrieveResults($engines);
    }

525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    # Spezielle Suchen und Sumas

    public function sumaIsSelected($suma, $request)
    {
        if ($this->fokus === "angepasst") {
            if ($request->has($suma["name"])) {
                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;
            }

            # 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")) {
560
                Log::error("Konnte " . $engine["name"] . " nicht abfragen, da kein Parser existiert");
561
                $this->errors[] = trans('metaGer.engines.noParser', ['engine' => $engine["name"]]);
562
563
564
565
566
567
568
569
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
                $tmp = new $path($engine, $this);
            } catch (\ErrorException $e) {
570
                Log::error("Konnte " . $engine["name"] . " nicht abfragen. " . var_dump($e));
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
                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()
    {
589
        return $this->fokus === "bilder";
590
591
592
593
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
594
        $sumaName = $suma["name"]->__toString();
595
        return
596
597
598
599
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
            || (!$overtureEnabled && $sumaName === "overtureAds")
            || $sumaName == "rlvproduct";
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    }

    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];
        $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;
    }

655
    # Passt den Suchfokus an, falls für einen Fokus genau alle vorhandenen Sumas eingeschaltet sind
656
657
    public function adjustFocus($sumas, $enabledSearchengines)
    {
658
659
        # Findet für alle Foki die enthaltenen Sumas
        $foki = []; # [fokus][suma] => [suma]
660
        foreach ($sumas as $suma) {
661
            if ((!$this->sumaIsDisabled($suma)) && (!isset($suma['userSelectable']) || $suma['userSelectable']->__toString() === "1")) {
662
                if (isset($suma['type'])) {
663
664
665
                    # Wenn foki für diese Suchmaschine angegeben sind
                    $focuses = explode(",", $suma['type']->__toString());
                    foreach ($focuses as $foc) {
666
667
668
669
670
                        if (isset($suma['minismCollection'])) {
                            $foki[$foc][] = "minism";
                        } else {
                            $foki[$foc][] = $suma['name']->__toString();
                        }
671
                    }
672
                } else {
673
                    # Wenn keine foki für diese Suchmaschine angegeben sind
674
675
676
677
678
                    if (isset($suma['minismCollection'])) {
                        $foki["andere"][] = "minism";
                    } else {
                        $foki["andere"][] = $suma['name']->__toString();
                    }
679
680
681
682
                }
            }
        }

683
        # Findet die Namen der aktuell eingeschalteten Sumas
684
        $realEngNames = [];
685
        foreach ($enabledSearchengines as $realEng) {
686
            $nam = $realEng["name"]->__toString();
687
            if ($nam !== "qualigo" && $nam !== "overtureAds" && $nam !== "rlvproduct") {
688
689
690
                $realEngNames[] = $nam;
            }
        }
691

692
        # 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.
693
        foreach ($foki as $fok => $engines) {
694
            $isFokus      = true;
695
            $fokiEngNames = [];
696
            foreach ($engines as $eng) {
697
698
                $fokiEngNames[] = $eng;
            }
699
            # Jede eingeschaltete Engine ist für diesen Fokus geeignet
700
            foreach ($fokiEngNames as $fen) {
701
702
                # 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") {
703
704
705
                    $isFokus = false;
                }
            }
706
            # Jede im Fokus erwartete Engine ist auch eingeschaltet
707
708
            foreach ($realEngNames as $ren) {
                if (!in_array($ren, $fokiEngNames)) {
709
710
711
                    $isFokus = false;
                }
            }
712
            # Wenn die Listen identisch sind, setze den Fokus um
713
            if ($isFokus) {
714
715
716
                $this->fokus = $fok;
            }
        }
717
    }
718

719
720
721
722
723
724
725
    public function checkCanNotSitesearch($enabledSearchengines)
    {
        if (strlen($this->site) > 0) {
            $enginesWithSite = 0;
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1") {
                    $enginesWithSite++;
726
                }
727
728
            }
            if ($enginesWithSite === 0) {
729
                $this->errors[] = trans('metaGer.sitesearch.failed', ['site' => $this->site, 'searchLink' => $this->generateSearchLink("web", false)]);
730
731
                return true;
            } else {
732
                $this->warnings[] = trans('metaGer.sitesearch.success', ['site' => $this->site]);
733
                return false;
734
735
            }
        }
736
        return false;
737
738
739
740
    }

    public function waitForResults($enginesToLoad, $overtureEnabled, $canBreak)
    {
741
        $loadedEngines = 0;
742
        $timeStart     = microtime(true);
743
744
745
746

        # Auf wie viele Suchmaschinen warten wir?
        $engineCount = count($enginesToLoad);

747
748
        while (true) {
            $time          = (microtime(true) - $timeStart) * 1000;
749
            $loadedEngines = intval(Redis::hlen('search.' . $this->getHashCode()));
750
            if ($overtureEnabled && (Redis::hexists('search.' . $this->getHashCode(), 'overture') || Redis::hexists('search.' . $this->getHashCode(), 'overtureAds'))) {
751
                $canBreak = true;
752
            }
753
754

            # Abbruchbedingung
755
            if ($time < 500) {
756
                if (($engineCount === 0 || $loadedEngines >= $engineCount) && $canBreak) {
757
                    break;
758
759
760
                }

            } elseif ($time >= 500 && $time < $this->time) {
761
                if (($engineCount === 0 || ($loadedEngines / ($engineCount * 1.0)) >= 0.8) && $canBreak) {
762
                    break;
763
764
765
                }

            } else {
766
767
768
769
                break;
            }
            usleep(50000);
        }
770
771
772
773
774
775
776

        # Wir haben nun so lange wie möglich gewartet. Wir registrieren nun noch die Suchmaschinen, die geanwortet haben.
        $answered = Redis::hgetall('search.' . $this->getHashCode());
        foreach ($answered as $key => $value) {
            $enginesToLoad[$key] = true;
        }
        $this->enginesToLoad = $enginesToLoad;
777
    }
778

779
780
781
    public function retrieveResults($engines)
    {
        # Von geladenen Engines die Ergebnisse holen
782
783
784
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
785
                    $engine->retrieveResults($this);
786
                } catch (\ErrorException $e) {
787
788
789
790
                    Log::error($e);
                }
            }
        }
791

792
        # Nicht fertige Engines verwefen
793
794
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
795
                $engine->shutdown();
796
            }
797
798
799
        }

        $this->engines = $engines;
800
801
    }

802
803
804
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
805

806
807
    public function parseFormData(Request $request)
    {
808
        # Sichert, dass der request in UTF-8 formatiert ist
809
810
811
812
813
814
815
816
        if ($request->input('encoding', '') !== "utf8") {
            # 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);
        }
817
        $this->url = $request->url();
818
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
819
        # Fokus
820
        $this->fokus = $request->input('focus', 'web');
821
        # Suma-File
822
        if (App::isLocale("en")) {
823
            $this->sumaFile = config_path() . "/sumas.xml";
824
        } else {
825
826
            $this->sumaFile = config_path() . "/sumas.xml";
        }
827
        if (!file_exists($this->sumaFile)) {
828
            die(trans('metaGer.formdata.cantLoad'));
829
        }
830
        # Sucheingabe
831
        $this->eingabe = trim($request->input('eingabe', ''));
832
        if (strlen($this->eingabe) === 0) {
833
            $this->warnings[] = trans('metaGer.formdata.noSearch');
834
835
        }
        $this->q = $this->eingabe;
836
        # IP
837
        $this->ip = $request->ip();
838
        # Language
839
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
840
            $this->language = $_SERVER['HTTP_LANGUAGE'];
841
        } else {
842
843
844
845
            $this->language = "";
        }
        # Category
        $this->category = $request->input('category', '');
846
        # Request Times
847
848
        $this->time = $request->input('time', 1000);
        # Page
849
        $this->page = 1;
850
851
        # Lang
        $this->lang = $request->input('lang', 'all');
852
853
        if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
            $this->lang = "all";
854
        }
855
        $this->agent  = new Agent();
856
        $this->mobile = $this->agent->isMobile();
857
        # Sprüche
858
        $this->sprueche = $request->input('sprueche', 'off');
859
        if ($this->sprueche === "off") {
860
            $this->sprueche = true;
861
        } else {
862
            $this->sprueche = false;
863
        }
864
        # Theme
Phil Höfer's avatar
Phil Höfer committed
865
        $this->theme = preg_replace("/[^[:alnum:][:space:]]/u", '', $request->input('theme', 'default'));
866
867
868
        # Ergebnisse pro Seite:
        $this->resultCount = $request->input('resultCount', '20');
        # Manchmal müssen wir Parameter anpassen um den Sucheinstellungen gerecht zu werden:
869
870
        if ($request->has('dart')) {
            $this->time       = 10000;
871
            $this->warnings[] = trans('metaGer.formdata.dartEurope');
872
        }
873
874
        if ($this->time <= 500 || $this->time > 20000) {
            $this->time = 1000;
875
        }
876
877
878
879
880
881
882
883
884
        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);
885
        }
886
887
        if (App::isLocale("en")) {
            $this->sprueche = "off";
888
        }
889
890
        if ($this->resultCount <= 0 || $this->resultCount > 200) {
            $this->resultCount = 1000;
891
        }
892
893
894
895
896
897
        if ($request->has('onenewspageAll') || $request->has('onenewspageGermanyAll')) {
            $this->time  = 5000;
            $this->cache = "cache";
        }
        if ($request->has('tab')) {
            if ($request->input('tab') === "off") {
898
                $this->tab = "_blank";
899
            } else {
900
901
                $this->tab = "_self";
            }
902
        } else {
903
904
            $this->tab = "_blank";
        }
905
        if ($request->has('password')) {
906
            $this->password = $request->input('password');
907
908
        }
        if ($request->has('quicktips')) {
909
            $this->quicktips = false;
910
        } else {
911
            $this->quicktips = true;
912
        }
913
        $this->out = $request->input('out', "html");
914
        # Standard output format html
915
        if ($this->out !== "html" && $this->out !== "json" && $this->out !== "results" && $this->out !== "results-with-style") {
916
            $this->out = "html";
917
        }
918
        $this->request = $request;
919
920
921
922
    }

    public function checkSpecialSearches(Request $request)
    {
923
924
925
926
927
        if ($request->has('site')) {
            $site = $request->input('site');
        } else {
            $site = "";
        }
928
929
930
931
        $this->searchCheckSitesearch($site);
        $this->searchCheckHostBlacklist();
        $this->searchCheckDomainBlacklist();
        $this->searchCheckPhrase();
Karl's avatar
Karl committed
932
        $this->searchCheckStopwords();
933
934
    }

935
    public function searchCheckSitesearch($site)
936
    {
937
        if (preg_match("/(.*)\bsite:(\S+)(.*)/si", $this->q, $match)) {
938
939
940
            $this->site = $match[2];
            $this->q    = $match[1] . $match[3];
        }
941
942
        if ($site !== "") {
            $this->site = $site;
943
        }
944
    }
945

946
    public function searchCheckHostBlacklist()
947
    {
948
        while (preg_match("/(.*)(^|\s)-host:(\S+)(.*)/si", $this->q, $match)) {
949
            $this->hostBlacklist[] = $match[3];
950
            $this->q               = $match[1] . $match[4];
951
952
953
954
955
956
957
        }
        if (sizeof($this->hostBlacklist) > 0) {
            $hostString = "";
            foreach ($this->hostBlacklist as $host) {
                $hostString .= $host . ", ";
            }
            $hostString       = rtrim($hostString, ", ");
958
            $this->warnings[] = trans('metaGer.formdata.hostBlacklist', ['host' => $hostString]);
959
        }
960
    }
961

962
    public function searchCheckDomainBlacklist()
963
    {
964
        while (preg_match("/(.*)(^|\s)-domain:(\S+)(.*)/si", $this->q, $match)) {
965
            $this->domainBlacklist[] = $match[3];
966
            $this->q                 = $match[1] . $match[4];
967
968
969
970
971
972
973
        }
        if (sizeof($this->domainBlacklist) > 0) {
            $domainString = "";
            foreach ($this->domainBlacklist as $domain) {
                $domainString .= $domain . ", ";
            }
            $domainString     = rtrim($domainString, ", ");
974
            $this->warnings[] = trans('metaGer.formdata.domainBlacklist', ['domain' => $domainString]);
975
        }
976
    }
977

978
    public function searchCheckStopwords()
979
    {
980
        while (preg_match("/(.*)(^|\s)-(\S+)(.*)/si", $this->q, $match)) {
981
            $this->stopWords[] = $match[3];
982
            $this->q           = $match[1] . $match[4];
983
984
985
986
987
988
989
        }
        if (sizeof($this->stopWords) > 0) {
            $stopwordsString = "";
            foreach ($this->stopWords as $stopword) {
                $stopwordsString .= $stopword . ", ";
            }
            $stopwordsString  = rtrim($stopwordsString, ", ");
990
            $this->warnings[] = trans('metaGer.formdata.stopwords', ['stopwords' => $stopwordsString]);
991
        }
992
    }
993

994
    public function searchCheckPhrase()
995
    {
996
        $p   = "";
997
        $tmp = $this->q;