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

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

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

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

        # Versuchen Blacklists einzulesen
59
60
        if (file_exists(config_path() . "/blacklistDomains.txt") && file_exists(config_path() . "/blacklistUrl.txt")) {
            $tmp                      = file_get_contents(config_path() . "/blacklistDomains.txt");
61
            $this->domainsBlacklisted = explode("\n", $tmp);
62
63
64
            $tmp                      = file_get_contents(config_path() . "/blacklistUrl.txt");
            $this->urlsBlacklisted    = explode("\n", $tmp);
        } else {
65
            Log::warning(trans('metaGer.blacklist.failed'));
66
67
        }

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

77
        # Spracherkennung starten
78
79
        $this->languageDetect = new TextLanguageDetect();
        $this->languageDetect->setNameMode("2");
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
100
101
            $viewResults[] = get_object_vars($result);
        }

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

102
103
        if ($this->fokus === "bilder") {
            switch ($this->out) {
104
105
106
107
108
109
110
111
                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)
112
                        ->with('browser', (new Agent())->browser());
113
114
115
116
117
118
119
120
                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)
121
                        ->with('browser', (new Agent())->browser());
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
151
152
153
154
155
        } 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;
            }
156
157
158
        }
    }

159
160
161
    public function combineResults()
    {
        foreach ($this->engines as $engine) {
162
163
164
165
166
167
            if (isset($engine->next)) {
                $this->next[] = $engine->next;
            }
            if (isset($engine->last)) {
                $this->last[] = $engine->last;
            }
168
169
            foreach ($engine->results as $result) {
                if ($result->valid) {
170
                    $this->results[] = $result;
171
                }
172
            }
173
            foreach ($engine->ads as $ad) {
174
175
                $this->ads[] = $ad;
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
176
177
178
            foreach ($engine->products as $product) {
                $this->products[] = $product;
            }
179
        }
180

181
182
        uasort($this->results, function ($a, $b) {
            if ($a->getRank() == $b->getRank()) {
183
                return 0;
184
185
            }

186
187
            return ($a->getRank() < $b->getRank()) ? 1 : -1;
        });
188

189
190
        # Validate Results
        $newResults = [];
191
192
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
193
                $newResults[] = $result;
194
195
            }

196
197
198
        }
        $this->results = $newResults;

199
200
201
202
203
204
        # Boost implementation
        $this->results = $this->parseBoost($this->results);

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

205
        $counter   = 0;
206
        $firstRank = 0;
207

208
        if (isset($this->startForwards)) {
209
            $this->startCount = $this->startForwards;
210
        } elseif (isset($this->startBackwards)) {
211
            $this->startCount = $this->startBackwards - count($this->results) - 1;
212
        } else {
213
214
215
            $this->startCount = 0;
        }

216
217
        foreach ($this->results as $result) {
            if ($counter === 0) {
218
                $firstRank = $result->rank;
219
220
            }

221
            $counter++;
222
            $result->number = $counter + $this->startCount;
223
224
225
226
            $confidence     = 0;
            if ($firstRank > 0) {
                $confidence = $result->rank / $firstRank;
            } else {
227
                $confidence = 0;
228
229
230
            }

            if ($confidence > 0.65) {
231
                $result->color = "#FF4000";
232
            } elseif ($confidence > 0.4) {
233
                $result->color = "#FF0080";
234
            } elseif ($confidence > 0.2) {
235
                $result->color = "#C000C0";
236
            } else {
237
                $result->color = "#000000";
238
239
            }

240
241
        }

242
        if (LaravelLocalization::getCurrentLocale() === "en") {
243
244
245
            $this->ads = [];
        }

246
        $this->validated = false;
247
        if (isset($this->password)) {
248
249
250
            # 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');
251
            $eingabe  = $this->eingabe;
252
            $password = md5($eingabe . $password);
253
254
            if ($this->password === $password) {
                $this->ads       = [];
255
                $this->products  = [];
256
257
258
                $this->validated = true;
            }
        }
259
260

        if (count($this->results) <= 0) {
261
            $this->errors[] = trans('metaGer.results.failed');
262
        }
263

264
        if ($this->canCache() && isset($this->next) && count($this->next) > 0 && count($this->results) > 0) {
265
            $page       = $this->page + 1;
266
            $this->next = [
267
268
269
                'page'          => $page,
                'startForwards' => $this->results[count($this->results) - 1]->number,
                'engines'       => $this->next,
270
271
            ];
            Cache::put(md5(serialize($this->next)), serialize($this->next), 60);
272
273
        } else {
            $this->next = [];
274
275
        }

276
    }
277

278
279
    public function parseBoost($results)
    {
280
281
282
283
284
285
286
287
288
289
290
291
        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;
292
    }
293

294
295
    public function parseAdgoal($results)
    {
296
        $publicKey  = getenv('adgoal_public');
297
        $privateKey = getenv('adgoal_private');
298
        if ($publicKey === false) {
299
300
301
            return $results;
        }
        $tldList = "";
302
303
        try {
            foreach ($results as $result) {
304
                $link = $result->anzeigeLink;
305
                if (strpos($link, "http") !== 0) {
306
307
308
309
310
311
312
313
314
315
                    $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");

316
            # Query
317
318
            $query = urlencode($this->q);

319
            $link   = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
320
321
322
            $answer = json_decode(file_get_contents($link));

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

327
328
                foreach ($results as $result) {
                    if ($hoster === $result->tld) {
329
330
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
331
                        if ($result->image !== "") {
332
                            $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
333
                        } else {
334
                            $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
335
336
                        }

337
338
339
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
                        $targetUrl = $result->anzeigeLink;
340
                        if (strpos($targetUrl, "http") !== 0) {
341
                            $targetUrl = "http://" . $targetUrl;
342
343
344
345
346
                        }

                        $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;
347
348
349
350
                        $result->partnershop = true;
                    }
                }
            }
351
        } catch (\ErrorException $e) {
352
353
354
355
356
            return $results;
        }

        return $results;
    }
357

Karl's avatar
Karl committed
358
359
360
361
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

362
363
    public function createSearchEngines(Request $request)
    {
364
        # Wenn es kein Suchwort gibt
365
        if (!$request->has("eingabe")) {
366
            return;
367
        }
368

369
        $xml                  = simplexml_load_file($this->sumaFile);
370
        $sumas                = $xml->xpath("suma");
371
        $enabledSearchengines = [];
372
        $overtureEnabled      = false;
373
374
        $sumaCount            = 0;

Karl's avatar
Karl committed
375
        /* Erstellt die Liste der eingestellten Sumas
376
377
378
         * 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
379
380
381
382
383
384
         * 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
         */
385
        foreach ($sumas as $suma) {
386
387
388
389
390
391
            if ($this->sumaIsSelected($suma, $request)
                || ($this->isBildersuche()
                    && $this->sumaIsAdsuche($suma, $overtureEnabled))
                && (!$this->sumaIsDisabled($suma))) {
                if ($this->sumaIsOverture($suma)) {
                    $overtureEnabled = true;
392
                }
393
394
                if ($this->sumaIsNotAdsuche($suma)) {
                    $sumaCount += 1;
395
                }
396
                $enabledSearchengines[] = $suma;
397
398
399
400
401
            }
        }

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

        $tmp = [];
404
405
        foreach ($enabledSearchengines as $engine) {
            if (isset($engine['minismCollection'])) {
406
                $subcollections[] = $engine['minismCollection']->__toString();
407
            } else {
408
                $tmp[] = $engine;
409
410
            }

411
412
        }
        $enabledSearchengines = $tmp;
413
        if (sizeof($subcollections) > 0) {
414
            $enabledSearchengines[] = $this->loadMiniSucher($xml, $subcollections);
415
416
        }

417
        if ($sumaCount <= 0) {
418
            $this->errors[] = trans('metaGer.settings.noneSelected');
419
        }
420

421
        $engines = [];
422

423
        # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob überhaupt eine der Suchmaschinen eine Sitesearch unterstützt
424
        $siteSearchFailed = $this->checkCanNotSitesearch($enabledSearchengines);
425
426

        $typeslist = [];
427
        $counter   = 0;
428

429
430
        if ($this->requestIsCached($request)) {
            $engines = $this->getCachedEngines($request);
431
        } else {
432
            $engines = $this->actuallyCreateSearchEngines($enabledSearchengines, $siteSearchFailed);
433
        }
434

435
        # Wir starten alle Suchen
436
437
        foreach ($engines as $engine) {
            $engine->startSearch($this);
438
        }
439

440
441
        $this->adjustFocus($sumas, $enabledSearchengines);

442
443
444
445
446
        /* 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.
447
448
         */

449
        $enginesToLoad = [];
450
451
452
453
454
455
        $canBreak      = false;
        foreach ($engines as $engine) {
            if ($engine->cached) {
                if ($overtureEnabled && ($engine->name === "overture" || $engine->name === "overtureAds")) {
                    $canBreak = true;
                }
456
457
            } else {
                $enginesToLoad[$engine->name] = false;
458
459
460
461
462
463
464
465
            }
        }

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

        $this->retrieveResults($engines);
    }

466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
    # 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")) {
                Log::error(trans('metaGer.engines.noParser', ['engine' => $engine["name"]]));
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
                $tmp = new $path($engine, $this);
            } catch (\ErrorException $e) {
                Log::error(trans('metaGer.engines.cantQuery', ['engine' => $engine["name"], 'error' => var_dump($e)]));
                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()
    {
        return $this->fokus !== "bilder";
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
        return
        $suma["name"]->__toString() === "qualigo"
        || $suma["name"]->__toString() === "similar_product_ads"
        || (!$overtureEnabled
            && $suma["name"]->__toString() === "overtureAds")
        || $suma["name"]->__toString() == "rlvproduct";
    }

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

595
    # Passt den Suchfokus an, falls für einen Fokus genau alle vorhandenen Sumas eingeschaltet sind
596
597
    public function adjustFocus($sumas, $enabledSearchengines)
    {
598
599
        # Findet für alle Foki die enthaltenen Sumas
        $foki = []; # [fokus][suma] => [suma]
600
601
602
        foreach ($sumas as $suma) {
            if ((!isset($suma['disabled']) || $suma['disabled'] === "") && (!isset($suma['userSelectable']) || $suma['userSelectable']->__toString() === "1")) {
                if (isset($suma['type'])) {
603
604
605
                    # Wenn foki für diese Suchmaschine angegeben sind
                    $focuses = explode(",", $suma['type']->__toString());
                    foreach ($focuses as $foc) {
606
607
608
609
610
                        if (isset($suma['minismCollection'])) {
                            $foki[$foc][] = "minism";
                        } else {
                            $foki[$foc][] = $suma['name']->__toString();
                        }
611
                    }
612
                } else {
613
                    # Wenn keine foki für diese Suchmaschine angegeben sind
614
615
616
617
618
                    if (isset($suma['minismCollection'])) {
                        $foki["andere"][] = "minism";
                    } else {
                        $foki["andere"][] = $suma['name']->__toString();
                    }
619
620
621
622
                }
            }
        }

623
        # Findet die Namen der aktuell eingeschalteten Sumas
624
        $realEngNames = [];
625
        foreach ($enabledSearchengines as $realEng) {
626
            $nam = $realEng["name"]->__toString();
627
            if ($nam !== "qualigo" && $nam !== "overtureAds" && $nam !== "rlvproduct") {
628
629
630
                $realEngNames[] = $nam;
            }
        }
631

632
        # 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.
633
        foreach ($foki as $fok => $engines) {
634
            $isFokus      = true;
635
            $fokiEngNames = [];
636
            foreach ($engines as $eng) {
637
638
                $fokiEngNames[] = $eng;
            }
639
            # Jede eingeschaltete Engine ist für diesen Fokus geeignet
640
641
            foreach ($fokiEngNames as $fen) {
                if (!in_array($fen, $realEngNames)) {
642
643
644
                    $isFokus = false;
                }
            }
645
            # Jede im Fokus erwartete Engine ist auch eingeschaltet
646
647
            foreach ($realEngNames as $ren) {
                if (!in_array($ren, $fokiEngNames)) {
648
649
650
                    $isFokus = false;
                }
            }
651
            # Wenn die Listen identisch sind, setze den Fokus um
652
            if ($isFokus) {
653
654
655
                $this->fokus = $fok;
            }
        }
656
    }
657

658
659
660
661
662
663
664
    public function checkCanNotSitesearch($enabledSearchengines)
    {
        if (strlen($this->site) > 0) {
            $enginesWithSite = 0;
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1") {
                    $enginesWithSite++;
665
                }
666
667
            }
            if ($enginesWithSite === 0) {
668
                $this->errors[] = trans('metaGer.sitesearch.failed', ['site' => $this->site, 'searchLink' => $this->generateSearchLink("web", false)]);
669
670
                return true;
            } else {
671
                $this->warnings[] = trans('metaGer.sitesearch.success', ['site' => $this->site]);
672
                return false;
673
674
            }
        }
675
676
677
678
    }

    public function waitForResults($enginesToLoad, $overtureEnabled, $canBreak)
    {
679
        $loadedEngines = 0;
680
        $timeStart     = microtime(true);
681
682
683
684

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

685
686
        while (true) {
            $time          = (microtime(true) - $timeStart) * 1000;
687
            $loadedEngines = intval(Redis::hlen('search.' . $this->getHashCode()));
688
            if ($overtureEnabled && (Redis::hexists('search.' . $this->getHashCode(), 'overture') || Redis::hexists('search.' . $this->getHashCode(), 'overtureAds'))) {
689
                $canBreak = true;
690
            }
691
692

            # Abbruchbedingung
693
            if ($time < 500) {
694
                if (($engineCount === 0 || $loadedEngines >= $engineCount) && $canBreak) {
695
                    break;
696
697
698
                }

            } elseif ($time >= 500 && $time < $this->time) {
699
                if (($engineCount === 0 || ($loadedEngines / ($engineCount * 1.0)) >= 0.8) && $canBreak) {
700
                    break;
701
702
703
                }

            } else {
704
705
706
707
                break;
            }
            usleep(50000);
        }
708
709
710
711
712
713
714

        # 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;
715
    }
716

717
718
719
    public function retrieveResults($engines)
    {
        # Von geladenen Engines die Ergebnisse holen
720
721
722
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
723
                    $engine->retrieveResults($this);
724
                } catch (\ErrorException $e) {
725
726
727
728
                    Log::error($e);
                }
            }
        }
729

730
        # Nicht fertige Engines verwefen
731
732
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
733
                $engine->shutdown();
734
            }
735
736
737
        }

        $this->engines = $engines;
738
739
    }

740
741
742
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
743

744
745
    public function parseFormData(Request $request)
    {
746
        # Sichert, dass der request in UTF-8 formatiert ist
747
748
749
750
751
752
753
754
        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);
        }
755
        $this->url = $request->url();
756
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
757
        # Fokus
758
        $this->fokus = $request->input('focus', 'web');
759
        # Suma-File
760
        if (App::isLocale("en")) {
761
            $this->sumaFile = config_path() . "/sumas.xml";
762
        } else {
763
764
            $this->sumaFile = config_path() . "/sumas.xml";
        }
765
        if (!file_exists($this->sumaFile)) {
766
            die(trans('metaGer.formdata.cantLoad'));
767
        }
768
        # Sucheingabe
769
        $this->eingabe = trim($request->input('eingabe', ''));
770
        if (strlen($this->eingabe) === 0) {
771
            $this->warnings[] = trans('metaGer.formdata.noSearch');
772
773
        }
        $this->q = $this->eingabe;
774
        # IP
775
        $this->ip = $request->ip();
776
        # Language
777
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
778
            $this->language = $_SERVER['HTTP_LANGUAGE'];
779
        } else {
780
781
782
783
            $this->language = "";
        }
        # Category
        $this->category = $request->input('category', '');
784
        # Request Times
785
786
        $this->time = $request->input('time', 1000);
        # Page
787
        $this->page = 1;
788
789
        # Lang
        $this->lang = $request->input('lang', 'all');
790
791
        if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
            $this->lang = "all";
792
        }
793
        $this->agent  = new Agent();
794
        $this->mobile = $this->agent->isMobile();
795
        # Sprüche
796
        $this->sprueche = $request->input('sprueche', 'off');
797
        if ($this->sprueche === "off") {
798
            $this->sprueche = true;
799
        } else {
800
            $this->sprueche = false;
801
        }
802
803
        # Theme
        $this->theme = preg_replace("/[^[:alnum:][:space:]]/u", '', $request->input('theme', 'none'));
804
805
806
        # Ergebnisse pro Seite:
        $this->resultCount = $request->input('resultCount', '20');
        # Manchmal müssen wir Parameter anpassen um den Sucheinstellungen gerecht zu werden:
807
808
        if ($request->has('dart')) {
            $this->time       = 10000;
809
            $this->warnings[] = trans('metaGer.formdata.dartEurope');
810
        }
811
812
        if ($this->time <= 500 || $this->time > 20000) {
            $this->time = 1000;
813
        }
814
815
816
817
818
819
820
821
822
        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);
823
        }
824
825
        if (App::isLocale("en")) {
            $this->sprueche = "off";
826
        }
827
828
        if ($this->resultCount <= 0 || $this->resultCount > 200) {
            $this->resultCount = 1000;
829
        }
830
831
832
833
834
835
        if ($request->has('onenewspageAll') || $request->has('onenewspageGermanyAll')) {
            $this->time  = 5000;
            $this->cache = "cache";
        }
        if ($request->has('tab')) {
            if ($request->input('tab') === "off") {
836
                $this->tab = "_blank";
837
            } else {
838
839
                $this->tab = "_self";
            }
840
        } else {
841
842
            $this->tab = "_blank";
        }
843
        if ($request->has('password')) {
844
            $this->password = $request->input('password');
845
846
        }
        if ($request->has('quicktips')) {
847
            $this->quicktips = false;
848
        } else {
849
            $this->quicktips = true;
850
        }
851
        $this->out = $request->input('out', "html");
852
        # Standard output format html
853
        if ($this->out !== "html" && $this->out !== "json" && $this->out !== "results" && $this->out !== "results-with-style") {
854
            $this->out = "html";
855
        }
856
        $this->request = $request;
857
858
859
860
    }

    public function checkSpecialSearches(Request $request)
    {
861
862
863
864
865
866
867
868
869
        $this->searchCheckSitesearch($request);
        $this->searchCheckHostBlacklist();
        $this->searchCheckDomainBlacklist();
        $this->searchCheckStopwords();
        $this->searchCheckPhrase();
    }

    public function searchCheckSitesearch($request)
    {
870
871
872
873
874
        if (preg_match("/(.*)\bsite:(\S+)(.*)/si", $this->q, $match)) {
            $this->site = $match[2];
            $this->q    = $match[1] . $match[3];
        }
        if ($request->has('site')) {
875
876
            $this->site = $request->input('site');
        }
877
    }
878

879
880
    public function searchCheckHostBlacklist()
    {
881
882
883
884
885
886
887
888
889
890
        while (preg_match("/(.*)(^|\s)-host:(\S+)(.*)/si", $this->q, $match)) {
            $this->hostBlacklist[] = $match[3];
            $this->q               = $match[1] . $match[4];
        }
        if (sizeof($this->hostBlacklist) > 0) {
            $hostString = "";
            foreach ($this->hostBlacklist as $host) {
                $hostString .= $host . ", ";
            }
            $hostString       = rtrim($hostString, ", ");
891
            $this->warnings[] = trans('metaGer.formdata.hostBlacklist', ['host' => $hostString]);
892
        }
893
    }
894

895
896
    public function searchCheckDomainBlacklist()
    {
897
898
899
900
901
902
903
904
905
906
        while (preg_match("/(.*)(^|\s)-domain:(\S+)(.*)/si", $this->q, $match)) {
            $this->domainBlacklist[] = $match[3];
            $this->q                 = $match[1] . $match[4];
        }
        if (sizeof($this->domainBlacklist) > 0) {
            $domainString = "";
            foreach ($this->domainBlacklist as $domain) {
                $domainString .= $domain . ", ";
            }
            $domainString     = rtrim($domainString, ", ");
907
            $this->warnings[] = trans('metaGer.formdata.domainBlacklist', ['domain' => $domainString]);
908
        }
909
    }
910

911
912
    public function searchCheckStopwords()
    {
913
914
915
916
917
918
919
920
921
922
        while (preg_match("/(.*)(^|\s)-(\S+)(.*)/si", $this->q, $match)) {
            $this->stopWords[] = $match[3];
            $this->q           = $match[1] . $match[4];
        }
        if (sizeof($this->stopWords) > 0) {
            $stopwordsString = "";
            foreach ($this->stopWords as $stopword) {
                $stopwordsString .= $stopword . ", ";
            }
            $stopwordsString  = rtrim($stopwordsString, ", ");
923
            $this->warnings[] = trans('metaGer.formdata.stopwords', ['stopwords' => $stopwordsString]);
924
        }
925
    }
926

927
928
    public function searchCheckPhrase()
    {
929
        $p   = "";
930
        $tmp = $this->q;
931
932
        while (preg_match("/(.*)\"(.+)\"(.*)/si", $tmp, $match)) {
            $tmp             = $match[1] . $match[3];
933
            $this->phrases[] = strtolower($match[2]);
934
935
        }
        foreach ($this->phrases as $phrase) {
936
937
938
            $p .= "\"$phrase\", ";
        }
        $p = rtrim($p, ", ");
939
        if (sizeof($this->phrases) > 0) {
940
            $this->warnings[] = trans('metaGer.formdata.phrase', ['phrase' => $p]);
941
942
943
        }
    }

944
    public function nextSearchLink()
945
    {
946
947
948
949
950
951
952
953
        if (isset($this->next) && isset($this->next['engines']) && count($this->next['engines']) > 0) {
            $requestData         = $this->request->except(['page', 'out']);
            $requestData['next'] = md5(serialize($this->next));
            $link                = action('MetaGerSearch@search', $requestData);
        } else {
            $link = "#";
        }
        return $link;
954
955
    }

956
    public function rankAll()
957
    {
958
959
960
        foreach ($this->engines as $engine) {
            $engine->rank($this);
        }
961
962
    }

963
# Hilfsfunktionen
964

Karl's avatar
Karl committed
965
966
967
968
969
970
971
972
973
974
975
    public function removeInvalids()
    {
        $results = [];
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
                $results[] = $result;
            }

        }
    }

976
    public function showQuicktips()
977
    {
978
        return $this->quicktips;
979
980
    }

981
    public function popAd()
982
    {
983
984
        if (count($this->ads) > 0) {
            return get_object_vars(array_shift($this->ads));
985
        } else {
986
            return null;
987
988
        }
    }
989

Dominik Hebeler's avatar
Dominik Hebeler committed
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
    public function hasProducts()
    {
        if (count($this->products) > 0) {
            return true;
        } else {
            return false;
        }
    }

    public function getProducts()
    {
        $return = [];
        foreach ($this->products as $product) {
            $return[] = get_object_vars($product);
        }
        return $return;
    }

1008
1009
1010
1011
    public function canCache()
    {
        return $this->canCache;
    }