MetaGer.php 52.7 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
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
134
135
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
136
137
138
139
140
141
142
143
                    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
144
                        ->with('apiAuthorized', $this->apiAuthorized)
145
146
                        ->with('metager', $this)
                        ->with('suspendheader', "yes")
Dominik Hebeler's avatar
Dominik Hebeler committed
147
148
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
149
                    break;
Phil Höfer's avatar
Phil Höfer committed
150
151
                case 'rich':
                    return view('metager3rich')
152
                        ->with('results', $viewResults)
Phil Höfer's avatar
Phil Höfer committed
153
154
155
156
                        ->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
157
                        ->with('apiAuthorized', $this->apiAuthorized)
Phil Höfer's avatar
Phil Höfer committed
158
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
159
160
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
Phil Höfer's avatar
Phil Höfer committed
161
                    break;
162
163
164
165
                case 'rss20':
                    return view('metager3resultsrss20')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
Phil Höfer's avatar
Phil Höfer committed
166
                        ->with('apiAuthorized', $this->apiAuthorized)
167
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
168
169
                        ->with('resultcount', sizeof($viewResults))
                        ->with('fokus', $this->fokus);
170
                    break;
Aria Givi's avatar
Aria Givi committed
171
                case 'atom10':
Phil Höfer's avatar
Phil Höfer committed
172
                    return response()->view('metager3resultsatom10', ['results' => $viewResults,'eingabe' => $this->eingabe,'metager' => $this,'resultcount' => sizeof($viewResults)])
Phil Höfer's avatar
Phil Höfer committed
173
			->header('Content-Type', 'application/xml');
Aria Givi's avatar
Aria Givi committed
174
                    break;
175
                case 'result-count':
176
177
                    # Wir geben die Ergebniszahl und die benötigte Zeit zurück:
                    return sizeof($viewResults) . ";" . round((microtime(true) - $this->starttime), 2);
178
                    break;
179
180
181
182
183
184
                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
185
                        ->with('apiAuthorized', $this->apiAuthorized)
186
187
188
189
                        ->with('metager', $this)
                        ->with('browser', (new Agent())->browser());
                    break;
            }
190
191
192
        }
    }

Phil Höfer's avatar
Phil Höfer committed
193
    public function prepareResults()
194
    {
Phil Höfer's avatar
Phil Höfer committed
195
        $engines = $this->engines;
196

Phil Höfer's avatar
Phil Höfer committed
197
198
        // combine
        $combinedResults = $this->combineResults($engines);
199
200
201
202

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

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

227
228
229
                return ($a->getRank() < $b->getRank()) ? 1 : -1;
            });
        }
230

231
232
        # Validate Results
        $newResults = [];
233
234
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
235
                $newResults[] = $result;
236
237
            }

238
239
240
        }
        $this->results = $newResults;

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

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

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

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

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

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

279
280
        }

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

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

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

307
    }
308

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

316
317
318
319
320
321
322
323
324
325
326
        # 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
327
                $langStrings["result_" . $id] = utf8_encode($result->getLangString());
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
354

                $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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    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;
            }
        }

    }

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

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

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

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

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

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

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

        return $results;
    }
442

Phil Höfer's avatar
Phil Höfer committed
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
    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
471
472
473
474
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

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

482
        $xml                  = simplexml_load_file($this->sumaFile);
483
        $sumas                = $xml->xpath("suma");
484
        $enabledSearchengines = [];
485
        $overtureEnabled      = false;
486
487
        $sumaCount            = 0;

488
        $isCustomSearch = $this->startsWith($this->fokus, 'focus_');
489

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

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

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

        $typeslist = [];
557
        $counter   = 0;
558

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

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

576
577
578
579
580
        /* 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.
581
582
         */

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

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

        $this->retrieveResults($engines);
    }

600
601
    # Spezielle Suchen und Sumas

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

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

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

    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];
727
        $minisucherEngine["subcollections"] = implode(", ", $subcollections);
728
729
730
731
732
733
        $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;
    }

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

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

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

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

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

Phil Höfer's avatar
Phil Höfer committed
821
822
        $timeStart = microtime(true);
        $results   = null;
823
        while (true) {
824
825
826
            $results = Redis::hgetall('search.' . $this->getHashCode());

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

838
839
            // 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
840
841
842
843
            if (!$connected) {
                $timeStart = microtime(true);
            }

844
845
846
847
            $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
848
849
850
            if ($time > $this->time && $canTimeout) {
                $ready = true;
            }
851

Phil Höfer's avatar
Phil Höfer committed
852
            if ($ready) {
853
854
855
856
                break;
            }
            usleep(50000);
        }
857
858

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

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

878
        # Nicht fertige Engines verwefen
879
880
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
881
                $engine->shutdown();
882
            }
883
884
885
        }

        $this->engines = $engines;
886
887
    }

888
889
890
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
891

892
893
    public function parseFormData(Request $request)
    {
894
        $this->request = $request;
895
        # Sichert, dass der request in UTF-8 formatiert ist
896
        if ($request->input('encoding', 'utf8') !== "utf8") {
897
898
899
900
901
902
903
            # 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);
        }
904
        $this->url = $request->url();
905
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
906
        # Fokus
907
        $this->fokus = $request->input('focus', 'web');
908
        # Suma-File
909
        if (App::isLocale("en")) {
910
            $this->sumaFile = config_path() . "/sumas.xml";
911
        } else {
912
913
            $this->sumaFile = config_path() . "/sumas.xml";
        }
914
        if (!file_exists($this->sumaFile)) {
915
            die(trans('metaGer.formdata.cantLoad'));
916
        }
917
        # Sucheingabe
918
        $this->eingabe = trim($request->input('eingabe', ''));
919
        $this->q       = mb_strtolower($this->eingabe, "UTF-8");
920
        # IP
921
        $this->ip = $request->ip();
922
923
924
925
        # 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);

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

944
        $this->agent  = new Agent();
945
        $this->mobile = $this->agent->isMobile();
946
        # Sprüche
947
948
        $this->sprueche = $request->input('sprueche', 'on');
        if ($this->sprueche === "on") {
949
            $this->sprueche = true;
950
        } else {
951
            $this->sprueche = false;
952
        }
Karl's avatar
Karl committed
953
        $this->maps = $request->input('maps', 'off');
954
        if ($this->maps === "on") {
955
956
957
958
            $this->maps = true;
        } else {
            $this->maps = false;
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
959
        $this->newtab = $request->input('newtab', 'on');
960
961
962
963
964
        if ($this->newtab === "on") {
            $this->newtab = "_blank";
        } else {
            $this->newtab = "_self";
        }
965
        # Theme
Phil Höfer's avatar
Phil Höfer committed
966
        $this->theme = preg_replace("/[^[:alnum:][:space:]]/u", '', $request->input('theme', 'default'));