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

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

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

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

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

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

92
    # Erstellt aus den gesammelten Ergebnissen den View
93
    public function createView($quicktipResults = [])
94
    {
95
96
        # Hiermit werden die evtl. ausgewählten SuMas extrahiert, damit die Input-Boxen richtig gesetzt werden können
        $focusPages = [];
Aria Givi's avatar
Aria Givi committed
97

98
        foreach ($this->request->all() as $key => $value) {
99
100
            if (starts_with($key, 'engine_') && $value === 'on') {
                $focusPages[] = $key;
101
102
103
            }
        }

104
        $viewResults = [];
105
        # Wir extrahieren alle notwendigen Variablen und geben Sie an unseren View:
106
        foreach ($this->results as $result) {
107
108
109
110
            $viewResults[] = get_object_vars($result);
        }
        # Wir müssen natürlich noch den Log für die durchgeführte Suche schreiben:
        $this->createLogs();
111
112
        if ($this->fokus === "bilder") {
            switch ($this->out) {
113
                case 'results':
114
                    return view('resultpages.results_images')
115
116
117
118
119
                        ->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
120
                        ->with('apiAuthorized', $this->apiAuthorized)
121
                        ->with('metager', $this)
122
                        ->with('browser', (new Agent())->browser());
123
                default:
124
                    return view('resultpages.resultpage_images')
125
126
127
128
129
                        ->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
130
                        ->with('apiAuthorized', $this->apiAuthorized)
131
                        ->with('metager', $this)
132
133
134
135
                        ->with('browser', (new Agent())->browser())
                        ->with('quicktips', $quicktipResults)
                        ->with('focus', $this->fokus)
                        ->with('resultcount', count($this->results));
136
            }
137
138
139
        } else {
            switch ($this->out) {
                case 'results':
140
                    return view('resultpages.results')
141
142
143
144
145
                        ->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
146
                        ->with('apiAuthorized', $this->apiAuthorized)
147
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
148
149
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
150
151
                    break;
                case 'results-with-style':
152
                    return view('resultpages.resultpage')
153
154
155
156
157
                        ->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
158
                        ->with('apiAuthorized', $this->apiAuthorized)
159
160
                        ->with('metager', $this)
                        ->with('suspendheader', "yes")
Dominik Hebeler's avatar
Dominik Hebeler committed
161
162
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
163
                    break;
Phil Höfer's avatar
Phil Höfer committed
164
                case 'rich':
165
                    return view('resultpages.metager3rich')
166
                        ->with('results', $viewResults)
Phil Höfer's avatar
Phil Höfer committed
167
168
169
170
                        ->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
171
                        ->with('apiAuthorized', $this->apiAuthorized)
Phil Höfer's avatar
Phil Höfer committed
172
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
173
174
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
Phil Höfer's avatar
Phil Höfer committed
175
                    break;
176
                case 'rss20':
177
                    return view('resultpages.metager3resultsrss20')
178
179
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
Phil Höfer's avatar
Phil Höfer committed
180
                        ->with('apiAuthorized', $this->apiAuthorized)
181
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
182
183
                        ->with('resultcount', sizeof($viewResults))
                        ->with('fokus', $this->fokus);
184
                    break;
185
186
187
                case 'api':
                    return response()->view('resultpages.metager3resultsatom10', ['results' => $viewResults, 'eingabe' => $this->eingabe, 'metager' => $this, 'resultcount' => sizeof($viewResults), 'apiAuthorized' => $this->apiAuthorized])->header('Content-Type', 'application/xml');
                    break;
Aria Givi's avatar
Aria Givi committed
188
                case 'atom10':
189
                    return response()->view('resultpages.metager3resultsatom10', ['results' => $viewResults, 'eingabe' => $this->eingabe, 'metager' => $this, 'resultcount' => sizeof($viewResults), 'apiAuthorized' => true])
190
                        ->header('Content-Type', 'application/xml');
Aria Givi's avatar
Aria Givi committed
191
                    break;
192
                case 'result-count':
193
194
                    # Wir geben die Ergebniszahl und die benötigte Zeit zurück:
                    return sizeof($viewResults) . ";" . round((microtime(true) - $this->starttime), 2);
195
                    break;
196
                default:
197
                    return view('resultpages.resultpage')
198
                        ->with('eingabe', $this->eingabe)
199
                        ->with('focusPages', $focusPages)
200
201
202
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
203
                        ->with('apiAuthorized', $this->apiAuthorized)
204
                        ->with('metager', $this)
205
                        ->with('browser', (new Agent())->browser())
206
                        ->with('quicktips', $quicktipResults)
207
208
                        ->with('resultcount', count($this->results))
                        ->with('focus', $this->fokus);
209
210
                    break;
            }
211
212
213
        }
    }

Phil Höfer's avatar
Phil Höfer committed
214
    public function prepareResults()
215
    {
Phil Höfer's avatar
Phil Höfer committed
216
        $engines = $this->engines;
217

Phil Höfer's avatar
Phil Höfer committed
218
219
        // combine
        $combinedResults = $this->combineResults($engines);
220
221
222
223

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

Phil Höfer's avatar
Phil Höfer committed
224
225
226
227
228
        // sort
        //$sortedResults = $this->sortResults($engines);
        // filter
        // augment (boost&adgoal)
        // authorize
Phil Höfer's avatar
Phil Höfer committed
229
230
231
        if ($this->apiKey) {
            $this->apiAuthorized = $this->authorize($this->apiKey);
        }
Phil Höfer's avatar
Phil Höfer committed
232
        // misc (WiP)
233
        if ($this->fokus == "nachrichten") {
234
235
236
            $this->results = array_filter($this->results, function ($v, $k) {
                return !is_null($v->getRank());
            }, ARRAY_FILTER_USE_BOTH);
237
238
239
240
241
242
243
244
245
246
            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;
                }
247

248
249
250
                return ($a->getRank() < $b->getRank()) ? 1 : -1;
            });
        }
251

252
253
        # Validate Results
        $newResults = [];
254
255
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
256
                $newResults[] = $result;
257
258
            }

259
260
261
        }
        $this->results = $newResults;

262
        #Adgoal Implementation
263
264
265
        if (!$this->apiAuthorized) {
            $this->results = $this->parseAdgoal($this->results);
        }
266

Dominik Hebeler's avatar
Dominik Hebeler committed
267
268
        # Human Verification
        $this->results = $this->humanVerification($this->results);
269
        $this->ads = $this->humanVerification($this->ads);
Dominik Hebeler's avatar
Dominik Hebeler committed
270

271
        $counter = 0;
272
        $firstRank = 0;
273

274
        if (isset($this->startForwards)) {
275
            $this->startCount = $this->startForwards;
276
        } elseif (isset($this->startBackwards)) {
277
            $this->startCount = $this->startBackwards - count($this->results) - 1;
278
        } else {
279
280
281
            $this->startCount = 0;
        }

282
283
        foreach ($this->results as $result) {
            if ($counter === 0) {
284
                $firstRank = $result->rank;
285
286
            }

287
            $counter++;
288
            $result->number = $counter + $this->startCount;
289
            $confidence = 0;
290
291
292
            if ($firstRank > 0) {
                $confidence = $result->rank / $firstRank;
            } else {
293
                $confidence = 0;
294
295
296
            }

            if ($confidence > 0.65) {
297
                $result->color = "#FF4000";
298
            } elseif ($confidence > 0.4) {
299
                $result->color = "#FF0080";
300
            } elseif ($confidence > 0.2) {
301
                $result->color = "#C000C0";
302
            } else {
303
                $result->color = "#000000";
304
305
            }

306
307
        }

308
        if ($this->validated) {
309
            $this->ads = [];
310
        }
311
312

        if (count($this->results) <= 0) {
313
314
315
316
317
318
            if (strlen($this->site) > 0) {
                $no_sitesearch_query = str_replace(urlencode("site:" . $this->site), "", $this->fullUrl);
                $this->errors[] = trans('metaGer.results.failedSitesearch', ['altSearch' => $no_sitesearch_query]);
            } else {
                $this->errors[] = trans('metaGer.results.failed');
            }
319
        }
320

321
        if ($this->canCache() && isset($this->next) && count($this->next) > 0 && count($this->results) > 0) {
322
            $page = $this->page + 1;
323
            $this->next = [
324
                'page' => $page,
325
                'startForwards' => $this->results[count($this->results) - 1]->number,
326
                'engines' => $this->next,
327
328
            ];
            Cache::put(md5(serialize($this->next)), serialize($this->next), 60);
329
330
        } else {
            $this->next = [];
331
332
        }

333
    }
334

335
336
    private function addLangCodes($results)
    {
337
338
339
340
341
        # Wenn es keine Ergebnisse gibt, brauchen wir uns gar nicht erst zu bemühen
        if (sizeof($results) === 0) {
            return $results;
        }

342
343
344
345
346
        # Bei der Spracheinstellung "all" wird nicht gefiltert
        if ($this->getLang() === "all") {
            return $results;
        } else {
            # Ansonsten müssen wir jedem Result einen Sprachcode hinzufügen
347
            $id = 0;
348
349
350
351
352
            $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
353
                $langStrings["result_" . $id] = utf8_encode($result->getLangString());
354
355
356
357
358
359
360
361

                $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";
362
363
            $lang = exec("echo '$filename' | $langDetectorPath");
            $lang = json_decode($lang, true);
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380

            # 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
    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;
            }
        }
    }

401
402
    public function parseAdgoal($results)
    {
403
        $publicKey = getenv('adgoal_public');
404
        $privateKey = getenv('adgoal_private');
405
        if ($publicKey === false) {
406
407
408
            return $results;
        }
        $tldList = "";
409
410
        try {
            foreach ($results as $result) {
411
                $link = $result->anzeigeLink;
412
                if (strpos($link, "http") !== 0) {
413
414
415
416
417
418
419
420
421
422
                    $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");

423
            # Query
424
425
            $query = urlencode($this->q);

426
            $link = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
427
428
429
            $answer = json_decode(file_get_contents($link));

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

434
                foreach ($results as $result) {
Dominik Hebeler's avatar
Dominik Hebeler committed
435
                    if ($hoster === $result->tld && !$result->partnershop) {
436
437
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
438
                        if ($result->image !== "") {
439
                            $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
440
                        } else {
441
                            $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
442
443
                        }

444
445
446
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
                        $targetUrl = $result->anzeigeLink;
447
                        if (strpos($targetUrl, "http") !== 0) {
448
                            $targetUrl = "http://" . $targetUrl;
449
450
                        }

451
452
453
                        $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;
454
455
456
457
                        $result->partnershop = true;
                    }
                }
            }
458
        } catch (\ErrorException $e) {
459
460
461
462
463
            return $results;
        }

        return $results;
    }
464

465
466
    public function humanVerification($results)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
467
        # Let's check if we need to implement a redirect for human verification
468
469
        if ($this->verificationCount > 10) {
            foreach ($results as $result) {
Dominik Hebeler's avatar
Dominik Hebeler committed
470
471
472
                $link = $result->link;
                $day = Carbon::now()->day;
                $pw = md5($this->verificationId . $day . $link . env("PROXY_PASSWORD"));
473
474
475
                $url = route('humanverification', ['mm' => $this->verificationId, 'pw' => $pw, "url" => urlencode(str_replace("/", "<<SLASH>>", base64_encode($link)))]);
                $proxyPw = md5($this->verificationId . $day . $result->proxyLink . env("PROXY_PASSWORD"));
                $proxyUrl = route('humanverification', ['mm' => $this->verificationId, 'pw' => $proxyPw, "url" => urlencode(str_replace("/", "<<SLASH>>", base64_encode($result->proxyLink)))]);
Dominik Hebeler's avatar
Dominik Hebeler committed
476
                $result->link = $url;
477
                $result->proxyLink = $proxyUrl;
Dominik Hebeler's avatar
Dominik Hebeler committed
478
479
            }
            return $results;
480
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
481
482
483
484
            return $results;
        }
    }

Phil Höfer's avatar
Phil Höfer committed
485
486
487
488
489
490
    public function authorize($key)
    {
        $postdata = http_build_query(array(
            'dummy' => rand(),
        ));
        $opts = array('http' => array(
491
492
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
Phil Höfer's avatar
Phil Höfer committed
493
494
495
496
497
498
499
            'content' => $postdata,
        ),
        );

        $context = stream_context_create($opts);

        try {
500
            $link = "https://key.metager3.de/" . urlencode($key) . "/request-permission/api-access";
Phil Höfer's avatar
Phil Höfer committed
501
502
503
504
505
506
507
508
509
510
511
512
            $result = json_decode(file_get_contents($link, false, $context));
            if ($result->{'api-access'} == true) {
                return true;
            } else {
                return false;
            }

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

513
514
    public function createQuicktips()
    {
515
516
517
518
519
        # Die quicktips werden als job erstellt und zur Abarbeitung freigegeben
        $quicktips = new \App\Models\Quicktips\Quicktips($this->q, $this->lang, $this->getTime(), $this->getHashCode());
        return $quicktips;
    }

Karl's avatar
Karl committed
520
521
522
523
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

524
525
    public function createSearchEngines(Request $request)
    {
526
        # Wenn es kein Suchwort gibt
Dominik Hebeler's avatar
Dominik Hebeler committed
527
        if (!$request->filled("eingabe") || $this->q === "") {
528
            return;
529
        }
530

531
        $enabledSearchengines = [];
532
        $overtureEnabled = false;
533

534
535
536
        # Check if selected focus is valid
        if (empty($this->sumaFile->foki->{$this->fokus})) {
            $this->fokus = "web";
537
538
        }

539
540
541
542
543
        foreach ($this->sumaFile->foki->{$this->fokus}->sumas as $suma) {
            # Check if this engine is disabled and can't be used
            $disabled = empty($suma->disabled) ? false : $suma->disabled;
            if ($disabled) {
                continue;
544
545
            }

546
547
548
549
550
551
            # Check if this engine can use eventually defined query-filter
            $valid = true;
            foreach ($this->queryFilter as $queryFilter => $filter) {
                if (empty($this->sumaFile->filter->$queryFilter->sumas->$suma)) {
                    $valid = false;
                    break;
Dominik Hebeler's avatar
Dominik Hebeler committed
552
553
                }
            }
554
555
556
            # If it can we add it
            if ($valid) {
                $enabledSearchengines[$suma] = $this->sumaFile->sumas->{$suma};
557
            }
558

559
        }
560
561
562
563
564
565
566
567
568
569

        if (sizeof($enabledSearchengines) === 0) {
            $filter = "";
            foreach ($this->queryFilter as $queryFilter => $filterPhrase) {
                $filter .= trans($this->sumaFile->filter->{$queryFilter}->name) . ",";
            }
            $filter = rtrim($filter, ",");
            $error = trans('metaGer.engines.noSpecialSearch', ['fokus' => trans($this->sumaFile->foki->{$this->fokus}->{"display-name"}),
                'filter' => $filter]);
            $this->errors[] = $error;
570
        }
571

572
        $engines = [];
573
574

        $typeslist = [];
575
        $counter = 0;
576

577
578
        if ($this->requestIsCached($request)) {
            $engines = $this->getCachedEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
579
            # We need to edit some Options of the Cached Search Engines
Phil Höfer's avatar
Phil Höfer committed
580
            foreach ($engines as $engine) {
Dominik Hebeler's avatar
Dominik Hebeler committed
581
582
                $engine->setResultHash($this->getHashCode());
            }
583
        } else {
584
            $engines = $this->actuallyCreateSearchEngines($enabledSearchengines);
585
        }
586
        # Wir starten alle Suchen
587
588
        foreach ($engines as $engine) {
            $engine->startSearch($this);
589
        }
590

591
592
593
594
595
        /* 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.
596
597
         */

598
        $enginesToLoad = [];
599
        $canBreak = false;
600
601
602
603
604
        foreach ($engines as $engine) {
            if ($engine->cached) {
                if ($overtureEnabled && ($engine->name === "overture" || $engine->name === "overtureAds")) {
                    $canBreak = true;
                }
605
606
            } else {
                $enginesToLoad[$engine->name] = false;
607
608
609
610
611
612
613
614
            }
        }

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

        $this->retrieveResults($engines);
    }

615
616
    # Spezielle Suchen und Sumas

617
    public function sumaIsSelected($suma, $request, $custom)
618
    {
619
        if ($custom) {
620
            if ($request->filled("engine_" . strtolower($suma["name"]))) {
621
622
623
624
625
626
627
628
629
630
631
                return true;
            }
        } else {
            $types = explode(",", $suma["type"]);
            if (in_array($this->fokus, $types)) {
                return true;
            }
        }
        return false;
    }

632
    public function actuallyCreateSearchEngines($enabledSearchengines)
633
634
    {
        $engines = [];
635
        foreach ($enabledSearchengines as $engineName => $engine) {
636

637
            if (!isset($engine->{"parser-class"})) {
Dominik Hebeler's avatar
Dominik Hebeler committed
638
639
                die(var_dump($engine));
            }
640
            # Setze Pfad zu Parser
641
            $path = "App\\Models\\parserSkripte\\" . $engine->{"parser-class"};
642
643

            # Prüfe ob Parser vorhanden
644
645
646
            if (!file_exists(app_path() . "/Models/parserSkripte/" . $engine->{"parser-class"} . ".php")) {
                Log::error("Konnte " . $engine->{"display-name"} . " nicht abfragen, da kein Parser existiert");
                $this->errors[] = trans('metaGer.engines.noParser', ['engine' => $engine->{"display-name"}]);
647
648
649
650
651
652
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
653
                $tmp = new $path($engineName, $engine, $this);
654
            } catch (\ErrorException $e) {
655
                Log::error("Konnte " . $engine->{"display-name"} . " nicht abfragen. " . var_dump($e));
656
657
658
                continue;
            }

659
            $engines[] = $tmp;
660
661
662
663
664
665
        }
        return $engines;
    }

    public function isBildersuche()
    {
666
        return $this->fokus === "bilder";
667
668
669
670
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
671
        $sumaName = $suma["name"]->__toString();
672
        return
673
674
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
Karl Hasselbring's avatar
Karl Hasselbring committed
675
            || (!$overtureEnabled && $sumaName === "overtureAds");
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
    }

    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
Dominik Hebeler's avatar
Dominik Hebeler committed
703
        $request->filled('next')
704
705
706
707
708
709
        && Cache::has($request->input('next'))
        && unserialize(Cache::get($request->input('next')))['page'] > 1;
    }

    public function getCachedEngines($request)
    {
710
        $next = unserialize(Cache::get($request->input('next')));
711
        $this->page = $next['page'];
712
        $engines = $next['engines'];
713
714
715
716
717
718
719
720
721
        if (isset($next['startForwards'])) {
            $this->startForwards = $next['startForwards'];
        }
        if (isset($next['startBackwards'])) {
            $this->startBackwards = $next['startBackwards'];
        }
        return $engines;
    }

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

750
        # Findet die Namen der aktuell eingeschalteten Sumas
751
        $realEngNames = [];
752
        foreach ($enabledSearchengines as $realEng) {
753
            $nam = $realEng["name"]->__toString();
Karl Hasselbring's avatar
Karl Hasselbring committed
754
            if ($nam !== "qualigo" && $nam !== "overtureAds") {
755
756
757
                $realEngNames[] = $nam;
            }
        }
758

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

786
787
    public function waitForResults($enginesToLoad, $overtureEnabled, $canBreak)
    {
788

Phil Höfer's avatar
Phil Höfer committed
789
        $timeStart = microtime(true);
790
        $results = null;
791
        while (true) {
792
793
794
            $results = Redis::hgetall('search.' . $this->getHashCode());

            $ready = true;
Phil Höfer's avatar
Phil Höfer committed
795
            // When every
796
            $connected = true;
Phil Höfer's avatar
Phil Höfer committed
797
798
            foreach ($results as $key => $value) {
                if ($value === "waiting" || $value === "connected") {
799
                    $ready = false;
800
                }
Phil Höfer's avatar
Phil Höfer committed
801
                if ($value === "waiting") {
802
                    $connected = false;
803
                }
804
            }
805

806
807
            // 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
808
809
810
811
            if (!$connected) {
                $timeStart = microtime(true);
            }

812
813
814
815
            $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
816
817
818
            if ($time > $this->time && $canTimeout) {
                $ready = true;
            }
819

Phil Höfer's avatar
Phil Höfer committed
820
            if ($ready) {
821
822
823
824
                break;
            }
            usleep(50000);
        }
825
826

        # Wir haben nun so lange wie möglich gewartet. Wir registrieren nun noch die Suchmaschinen, die geanwortet haben.
827
        foreach ($results as $key => $value) {
828
829
830
            $enginesToLoad[$key] = true;
        }
        $this->enginesToLoad = $enginesToLoad;
831
    }
832

833
834
835
    public function retrieveResults($engines)
    {
        # Von geladenen Engines die Ergebnisse holen
836
837
838
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
839
                    $engine->retrieveResults($this);
840
                } catch (\ErrorException $e) {
841
842
843
844
                    Log::error($e);
                }
            }
        }
845

846
        # Nicht fertige Engines verwefen
847
848
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
849
                $engine->shutdown();
850
            }
851
852
853
        }

        $this->engines = $engines;
854
855
    }

856
857
858
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
859

860
861
    public function parseFormData(Request $request)
    {
862

863
        # Sichert, dass der request in UTF-8 formatiert ist
864
        if ($request->input('encoding', 'utf8') !== "utf8") {
865
866
867
868
869
870
871
            # 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);
        }
872
        $this->url = $request->url();
873
        $this->fullUrl = $request->fullUrl();
874
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
875
        # Fokus
876
        $this->fokus = $request->input('focus', 'web');
877
        # Suma-File
878
        if (App::isLocale("en")) {
879
            $this->sumaFile = config_path() . "/sumasEn.json";
880
        } else {
881
            $this->sumaFile = config_path() . "/sumas.json";
882
        }
883
        if (!file_exists($this->sumaFile)) {
884
            die(trans('metaGer.formdata.cantLoad'));
885
886
        } else {
            $this->sumaFile = json_decode(file_get_contents($this->sumaFile));
887
        }
888
        # Sucheingabe
Dominik Hebeler's avatar