MetaGer.php 53.4 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
241
242
        #Amazon Affiliate (MetaGers tag ist: metager04-21)
        $this->results = $this->parseAmazon($this->results);

243
        $counter   = 0;
244
        $firstRank = 0;
245

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

254
255
        foreach ($this->results as $result) {
            if ($counter === 0) {
256
                $firstRank = $result->rank;
257
258
            }

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

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

278
279
        }

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

        if (count($this->results) <= 0) {
291
            $this->errors[] = trans('metaGer.results.failed');
292
        }
293

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

306
    }
307

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

315
316
317
318
319
320
321
322
323
324
325
        # 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
326
                $langStrings["result_" . $id] = utf8_encode($result->getLangString());
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353

                $id++;
            }
            # Wir schreiben die Strings in eine temporäre JSON-Datei,
            # Da das Array unter umständen zu groß ist für eine direkte Übergabe an das Skript
            $filename = "/tmp/" . getmypid();
            file_put_contents($filename, json_encode($langStrings));
            $langDetectorPath = app_path() . "/Models/lang.pl";
            $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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    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;
            }
        }

    }

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

400
            # Query
401
402
            $query = urlencode($this->q);

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

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

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

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

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

        return $results;
    }
441
442
443
444
445
446
447
448
449
450
    
    public function parseAmazon($results)
    {
        $amazonTag = "metager04-21";
        
        foreach ($results as $result) {
            $link = $result->anzeigeLink;
            if (strpos($link, "http") !== 0) {
                $link = "http://" . $link;
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
451
            $info = parse_url($link);
452
453
            if(isset($info["host"])){
                $host = $info['host'];
Dominik Hebeler's avatar
Dominik Hebeler committed
454
                $newurl = $link;
455
456
457
                if(strpos($host, "amazon") !== FALSE){
                    # This is Probably an Amazon Link. We'll add our tag as get parameter
                    if(isset($info["query"])){
Dominik Hebeler's avatar
Dominik Hebeler committed
458
                        $newurl .= "&tag=metager04-21";
459
                    }else{
Dominik Hebeler's avatar
Dominik Hebeler committed
460
                        $newurl .= "?tag=metager04-21";
461
                    }
462
463
                    $result->link = $newurl;
                    $result->partnershop = true;
464
465
466
467
468
                }
            }
        }
        return $results;
    }
469

Phil Höfer's avatar
Phil Höfer committed
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
    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
498
499
500
501
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

502
503
    public function createSearchEngines(Request $request)
    {
504
        # Wenn es kein Suchwort gibt
505
        if (!$request->has("eingabe") || $this->q === "") {
506
            return;
507
        }
508

509
        $xml                  = simplexml_load_file($this->sumaFile);
510
        $sumas                = $xml->xpath("suma");
511
        $enabledSearchengines = [];
512
        $overtureEnabled      = false;
513
514
        $sumaCount            = 0;

Karl's avatar
Karl committed
515
        /* Erstellt die Liste der eingestellten Sumas
516
517
518
         * 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
519
520
521
522
523
524
         * 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
         */
525
        foreach ($sumas as $suma) {
526
            if (($this->sumaIsSelected($suma, $request)
527
                || (!$this->isBildersuche()
528
                    && $this->sumaIsAdsuche($suma, $overtureEnabled)))
529
530
531
                && (!$this->sumaIsDisabled($suma))) {
                if ($this->sumaIsOverture($suma)) {
                    $overtureEnabled = true;
532
                }
533
534
                if ($this->sumaIsNotAdsuche($suma)) {
                    $sumaCount += 1;
535
                }
536
                $enabledSearchengines[] = $suma;
537
538
539
540
            }
        }

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

        $tmp = [];
544
545
546
547
        // 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
548
549
550
            // Wir laden alle Minisucher
            foreach ($sumas as $engine) {
                if (isset($engine["minismCollection"])) {
551
                    $subcollections[] = $engine["minismCollection"]->__toString();
Dominik Hebeler's avatar
Dominik Hebeler committed
552
553
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
554
555
556
557
558
559
            # 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
560
561
562
563
        } else {
            // Wir schalten eine Teilmenge, oder aber gar keine an
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['minismCollection'])) {
564
                    $subcollections[] = $engine['minismCollection']->__toString();
Dominik Hebeler's avatar
Dominik Hebeler committed
565
566
                } else {
                    $tmp[] = $engine;
Dominik Hebeler's avatar
Dominik Hebeler committed
567
                }
568
            }
569
570
        }
        $enabledSearchengines = $tmp;
571
572
        if (sizeof($subcollections) > 0) {
            $enabledSearchengines[] = $this->loadMiniSucher($xml, $subcollections);
573
        }
574
        if ($sumaCount <= 0) {
575
            $this->errors[] = trans('metaGer.settings.noneSelected');
576
        }
577
        $engines = [];
578
        # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob überhaupt eine der Suchmaschinen eine Sitesearch unterstützt
579
        $siteSearchFailed = $this->checkCanNotSitesearch($enabledSearchengines);
580
581

        $typeslist = [];
582
        $counter   = 0;
583

584
585
        if ($this->requestIsCached($request)) {
            $engines = $this->getCachedEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
586
            # We need to edit some Options of the Cached Search Engines
Phil Höfer's avatar
Phil Höfer committed
587
            foreach ($engines as $engine) {
Dominik Hebeler's avatar
Dominik Hebeler committed
588
589
                $engine->setResultHash($this->getHashCode());
            }
590
        } else {
591
            $engines = $this->actuallyCreateSearchEngines($enabledSearchengines, $siteSearchFailed);
592
        }
593

594
        # Wir starten alle Suchen
595
596
        foreach ($engines as $engine) {
            $engine->startSearch($this);
597
        }
598
599
        // Derzeit deaktiviert, da es die eigene Suche gibt
        // $this->adjustFocus($sumas, $enabledSearchengines);
600

601
602
603
604
605
        /* 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.
606
607
         */

608
        $enginesToLoad = [];
609
610
611
612
613
614
        $canBreak      = false;
        foreach ($engines as $engine) {
            if ($engine->cached) {
                if ($overtureEnabled && ($engine->name === "overture" || $engine->name === "overtureAds")) {
                    $canBreak = true;
                }
615
616
            } else {
                $enginesToLoad[$engine->name] = false;
617
618
619
620
621
622
623
624
            }
        }

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

        $this->retrieveResults($engines);
    }

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

Dominik Hebeler's avatar
Dominik Hebeler committed
655
656
657
            if (!isset($engine["package"])) {
                die(var_dump($engine));
            }
658
659
660
661
662
            # 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")) {
663
                Log::error("Konnte " . $engine["name"] . " nicht abfragen, da kein Parser existiert");
664
                $this->errors[] = trans('metaGer.engines.noParser', ['engine' => $engine["name"]]);
665
666
667
668
669
670
671
672
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
                $tmp = new $path($engine, $this);
            } catch (\ErrorException $e) {
673
                Log::error("Konnte " . $engine["name"] . " nicht abfragen. " . var_dump($e));
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
                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()
    {
692
        return $this->fokus === "bilder";
693
694
695
696
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
697
        $sumaName = $suma["name"]->__toString();
698
        return
699
700
701
702
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
            || (!$overtureEnabled && $sumaName === "overtureAds")
            || $sumaName == "rlvproduct";
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
    }

    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];
752
        $minisucherEngine["subcollections"] = implode(", ", $subcollections);
753
754
755
756
757
758
        $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;
    }

759
    # Passt den Suchfokus an, falls für einen Fokus genau alle vorhandenen Sumas eingeschaltet sind
760
761
    public function adjustFocus($sumas, $enabledSearchengines)
    {
762
763
        # Findet für alle Foki die enthaltenen Sumas
        $foki = []; # [fokus][suma] => [suma]
764
        foreach ($sumas as $suma) {
765
            if ((!$this->sumaIsDisabled($suma)) && (!isset($suma['userSelectable']) || $suma['userSelectable']->__toString() === "1")) {
766
                if (isset($suma['type'])) {
767
768
769
                    # Wenn foki für diese Suchmaschine angegeben sind
                    $focuses = explode(",", $suma['type']->__toString());
                    foreach ($focuses as $foc) {
770
771
772
773
774
                        if (isset($suma['minismCollection'])) {
                            $foki[$foc][] = "minism";
                        } else {
                            $foki[$foc][] = $suma['name']->__toString();
                        }
775
                    }
776
                } else {
777
                    # Wenn keine foki für diese Suchmaschine angegeben sind
778
779
780
781
782
                    if (isset($suma['minismCollection'])) {
                        $foki["andere"][] = "minism";
                    } else {
                        $foki["andere"][] = $suma['name']->__toString();
                    }
783
784
785
786
                }
            }
        }

787
        # Findet die Namen der aktuell eingeschalteten Sumas
788
        $realEngNames = [];
789
        foreach ($enabledSearchengines as $realEng) {
790
            $nam = $realEng["name"]->__toString();
791
            if ($nam !== "qualigo" && $nam !== "overtureAds" && $nam !== "rlvproduct") {
792
793
794
                $realEngNames[] = $nam;
            }
        }
795

796
        # 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.
797
        foreach ($foki as $fok => $engines) {
798
            $isFokus      = true;
799
            $fokiEngNames = [];
800
            foreach ($engines as $eng) {
801
802
                $fokiEngNames[] = $eng;
            }
803
            # Jede eingeschaltete Engine ist für diesen Fokus geeignet
804
            foreach ($fokiEngNames as $fen) {
805
806
                # 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") {
807
808
809
                    $isFokus = false;
                }
            }
810
            # Jede im Fokus erwartete Engine ist auch eingeschaltet
811
812
            foreach ($realEngNames as $ren) {
                if (!in_array($ren, $fokiEngNames)) {
813
814
815
                    $isFokus = false;
                }
            }
816
            # Wenn die Listen identisch sind, setze den Fokus um
817
            if ($isFokus) {
818
819
820
                $this->fokus = $fok;
            }
        }
821
    }
822

823
824
825
826
827
828
829
    public function checkCanNotSitesearch($enabledSearchengines)
    {
        if (strlen($this->site) > 0) {
            $enginesWithSite = 0;
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1") {
                    $enginesWithSite++;
830
                }
831
832
            }
            if ($enginesWithSite === 0) {
833
                $this->errors[] = trans('metaGer.sitesearch.failed', ['site' => $this->site, 'searchLink' => $this->generateSearchLink("web", false)]);
834
835
                return true;
            } else {
836
                $this->warnings[] = trans('metaGer.sitesearch.success', ['site' => $this->site]);
837
                return false;
838
839
            }
        }
840
        return false;
841
842
843
844
    }

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

Phil Höfer's avatar
Phil Höfer committed
846
847
        $timeStart = microtime(true);
        $results   = null;
848
        while (true) {
849
850
851
            $results = Redis::hgetall('search.' . $this->getHashCode());

            $ready = true;
Phil Höfer's avatar
Phil Höfer committed
852
            // When every
853
            $connected = true;
Phil Höfer's avatar
Phil Höfer committed
854
855
            foreach ($results as $key => $value) {
                if ($value === "waiting" || $value === "connected") {
856
                    $ready = false;
857
                }
Phil Höfer's avatar
Phil Höfer committed
858
                if ($value === "waiting") {
859
                    $connected = false;
860
                }
861
            }
862

863
864
            // 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
865
866
867
868
            if (!$connected) {
                $timeStart = microtime(true);
            }

869
870
871
872
            $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
873
874
875
            if ($time > $this->time && $canTimeout) {
                $ready = true;
            }
876

Phil Höfer's avatar
Phil Höfer committed
877
            if ($ready) {
878
879
880
881
                break;
            }
            usleep(50000);
        }
882
883

        # Wir haben nun so lange wie möglich gewartet. Wir registrieren nun noch die Suchmaschinen, die geanwortet haben.
884
        foreach ($results as $key => $value) {
885
886
887
            $enginesToLoad[$key] = true;
        }
        $this->enginesToLoad = $enginesToLoad;
888
    }
889

890
891
892
    public function retrieveResults($engines)
    {
        # Von geladenen Engines die Ergebnisse holen
893
894
895
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
896
                    $engine->retrieveResults($this);
897
                } catch (\ErrorException $e) {
898
899
900
901
                    Log::error($e);
                }
            }
        }
902

903
        # Nicht fertige Engines verwefen
904
905
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
906
                $engine->shutdown();
907
            }
908
909
910
        }

        $this->engines = $engines;
911
912
    }

913
914
915
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
916

917
918
    public function parseFormData(Request $request)
    {
919
        $this->request = $request;
920
        # Sichert, dass der request in UTF-8 formatiert ist
921
        if ($request->input('encoding', 'utf8') !== "utf8") {
922
923
924
925
926
927
928
            # 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);
        }
929
        $this->url = $request->url();
930
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
931
        # Fokus
932
        $this->fokus = $request->input('focus', 'web');
933
        # Suma-File
934
        if (App::isLocale("en")) {
935
            $this->sumaFile = config_path() . "/sumas.xml";
936
        } else {
937
938
            $this->sumaFile = config_path() . "/sumas.xml";
        }
939
        if (!file_exists($this->sumaFile)) {
940
            die(trans('metaGer.formdata.cantLoad'));
941
        }
942
        # Sucheingabe
943
        $this->eingabe = trim($request->input('eingabe', ''));
944
        $this->q       = mb_strtolower($this->eingabe, "UTF-8");
945
        # IP
946
        $this->ip = $request->ip();
947
948
949
950
        # 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);

951
        # Language
952
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
953
            $this->language = $_SERVER['HTTP_LANGUAGE'];
954
        } else {
955
956
957
958
            $this->language = "";
        }
        # Category
        $this->category = $request->input('category', '');
959
        # Request Times
960
        $this->time = $request->input('time', 1500);
961
        # Page
962
        $this->page = 1;
963
964
        # Lang
        $this->lang = $request->input('lang', 'all');
965
966
        if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
            $this->lang = "all";
967
        }
968

969
        $this->agent  = new Agent();
970
        $this->mobile = $this->agent->isMobile();
971
        # Sprüche
972
973
        $this->sprueche = $request->input('sprueche', 'on');
        if ($this->sprueche === "on") {
974
            $this->sprueche = true;
975
        } else {
976
            $this->sprueche = false;
977
        }
Karl's avatar
Karl committed
978
        $this->maps = $request->input('maps', 'off');
979
        if ($this->maps === "on") {
980
981
982
983
            $this->maps = true;
        } else {
            $this->maps = false;
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
984
        $this->newtab = $request->input('newtab', 'on');
985
986
987
988
989
        if ($this->newtab === "on") {
            $this->newtab = "_blank";
        } else {
            $this->newtab = "_self";
        }
990
        # Theme