MetaGer.php 68.1 KB
Newer Older
1
<?php
Karl Hasselbring's avatar
Karl Hasselbring committed
2

3
4
5
namespace App;

use App;
6
use Cache;
7
use Carbon;
Davide's avatar
Davide committed
8
use Cookie;
9
use Illuminate\Http\Request;
10
use Illuminate\Support\Facades\Redis;
11
use Jenssegers\Agent\Agent;
Dominik Hebeler's avatar
Bugfix    
Dominik Hebeler committed
12
use LaravelLocalization;
13
use Log;
14
use Monospice\LaravelRedisSentinel\RedisSentinel;
15
use Predis\Connection\ConnectionException;
16
17
18

class MetaGer
{
Dominik Hebeler's avatar
Dominik Hebeler committed
19
20
    const FETCHQUEUE_KEY = "fetcher.queue";

21
    # Einstellungen für die Suche
22
23
    public $alteredQuery = "";
    public $alterationOverrideQuery = "";
24
    protected $fokus;
Dominik Hebeler's avatar
update    
Dominik Hebeler committed
25
    protected $test;
26
27
28
29
30
31
    protected $eingabe;
    protected $q;
    protected $page;
    protected $lang;
    protected $cache = "";
    protected $site;
32
    protected $time = 2000;
33
    protected $hostBlacklist = [];
34
    protected $domainBlacklist = [];
35
36
37
38
    private $urlBlacklist = [];
    protected $stopWords = [];
    protected $phrases = [];
    protected $engines = [];
39
    protected $totalResults = 0;
40
    protected $results = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
41
42
    protected $queryFilter = [];
    protected $parameterFilter = [];
43
    protected $ads = [];
44
    protected $infos = [];
45
46
47
    protected $warnings = [];
    protected $errors = [];
    protected $addedHosts = [];
48
    protected $availableFoki = [];
49
50
    protected $startCount = 0;
    protected $canCache = false;
51
    protected $javascript = false;
52
    # Daten über die Abfrage$
53
    protected $ip;
Dominik Hebeler's avatar
Dominik Hebeler committed
54
    protected $useragent;
55
56
    protected $language;
    protected $agent;
57
    protected $apiKey = "";
Phil Höfer's avatar
Phil Höfer committed
58
    protected $apiAuthorized = false;
59
    protected $next = [];
60
61
62
63
64
    # Konfigurationseinstellungen:
    protected $sumaFile;
    protected $mobile;
    protected $resultCount;
    protected $sprueche;
65
    protected $newtab;
66
    protected $domainsBlacklisted = [];
67
    protected $adDomainsBlacklisted = [];
68
    protected $urlsBlacklisted = [];
69
    protected $adUrlsBlacklisted = [];
70
    protected $blacklistDescriptionUrl = [];
71
    protected $url;
72
    protected $fullUrl;
Aria's avatar
Aria committed
73
    protected $enabledSearchengines = [];
74
    protected $languageDetect;
Dominik Hebeler's avatar
Dominik Hebeler committed
75
76
    protected $verificationId;
    protected $verificationCount;
77
    protected $searchUid;
78
79
80
81
    protected $redisResultWaitingKey;
    protected $redisResultEngineList;
    protected $redisEngineResult;
    protected $redisCurrentResultList;
Dominik Hebeler's avatar
Dominik Hebeler committed
82
    public $starttime;
Davide Aprea's avatar
Davide Aprea committed
83
    protected $dummy = false;
84

85
    public function __construct($hash = "")
86
    {
87
        # Timer starten
88
        $this->starttime = microtime(true);
89
        # Versuchen Blacklists einzulesen
90
        if (file_exists(config_path() . "/blacklistDomains.txt") && file_exists(config_path() . "/blacklistUrl.txt")) {
91
            $tmp = file_get_contents(config_path() . "/blacklistDomains.txt");
92
            $this->domainsBlacklisted = explode("\n", $tmp);
93
94
            $tmp = file_get_contents(config_path() . "/blacklistUrl.txt");
            $this->urlsBlacklisted = explode("\n", $tmp);
95
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
96

97
        # Versuchen Blacklists einzulesen
Dominik Hebeler's avatar
Dominik Hebeler committed
98
        if (file_exists(config_path() . "/adBlacklistDomains.txt")) {
99
100
            $tmp = file_get_contents(config_path() . "/adBlacklistDomains.txt");
            $this->adDomainsBlacklisted = explode("\n", $tmp);
Dominik Hebeler's avatar
Dominik Hebeler committed
101
102
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
103
        if (file_exists(config_path() . "/adBlacklistUrl.txt")) {
104
105
106
            $tmp = file_get_contents(config_path() . "/adBlacklistUrl.txt");
            $this->adUrlsBlacklisted = explode("\n", $tmp);
        }
107

Dominik Hebeler's avatar
Dominik Hebeler committed
108
        if (file_exists(config_path() . "/blacklistDescriptionUrl.txt")) {
109
110
111
112
            $tmp = file_get_contents(config_path() . "/blacklistDescriptionUrl.txt");
            $this->blacklistDescriptionUrl = explode("\n", $tmp);
        }

113
        # Parser Skripte einhängen
114
115
116
117
        $dir = app_path() . "/Models/parserSkripte/";
        foreach (scandir($dir) as $filename) {
            $path = $dir . $filename;
            if (is_file($path)) {
118
                require_once $path;
119
120
121
            }
        }

122
        # Cachebarkeit testen
123
124
125
126
127
128
        try {
            Cache::has('test');
            $this->canCache = true;
        } catch (ConnectionException $e) {
            $this->canCache = false;
        }
129
130
131
132
133
        if ($hash === "") {
            $this->searchUid = md5(uniqid());
        } else {
            $this->searchUid = $hash;
        }
134
135
136
137
138
139
140
        $redisPrefix = "search";
        # This is a list on which the MetaGer process can do a blocking pop to wait for new results
        $this->redisResultWaitingKey = $redisPrefix . "." . $this->searchUid . ".ready";
        # This is a list of searchengines which have delivered results for this search
        $this->redisResultEngineList = $redisPrefix . "." . $this->searchUid . ".engines";
        # This is the key where the results of the engine are stored as well as some statistical data
        $this->redisEngineResult = $redisPrefix . "." . $this->searchUid . ".results.";
141
142
        # A list of all search results already delivered to the user (sorted of course)
        $this->redisCurrentResultList = $redisPrefix . "." . $this->searchUid . ".currentResults";
143
    }
144

145
    # Erstellt aus den gesammelten Ergebnissen den View
146
    public function createView($quicktipResults = [])
147
    {
148
149
        # 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
150

151
        foreach ($this->request->all() as $key => $value) {
152
            if (stripos($key, 'engine_') === 0 && $value === 'on') {
153
                $focusPages[] = $key;
154
155
156
            }
        }

157
        $viewResults = [];
158
        # Wir extrahieren alle notwendigen Variablen und geben Sie an unseren View:
159
        foreach ($this->results as $result) {
160
161
162
163
            $viewResults[] = get_object_vars($result);
        }
        # Wir müssen natürlich noch den Log für die durchgeführte Suche schreiben:
        $this->createLogs();
164
165
        if ($this->fokus === "bilder") {
            switch ($this->out) {
166
                case 'results':
167
                    return view('resultpages.results_images')
168
169
170
171
172
                        ->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
173
                        ->with('apiAuthorized', $this->apiAuthorized)
174
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
175
                        ->with('imagesearch', true)
176
                        ->with('browser', (new Agent())->browser());
177
                default:
178
                    return view('resultpages.resultpage_images')
179
180
181
182
183
                        ->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
184
                        ->with('apiAuthorized', $this->apiAuthorized)
185
                        ->with('metager', $this)
186
                        ->with('browser', (new Agent())->browser())
187
                        ->with('quicktips', $quicktipResults)
188
                        ->with('focus', $this->fokus)
Dominik Hebeler's avatar
Dominik Hebeler committed
189
                        ->with('imagesearch', true)
190
                        ->with('resultcount', count($this->results));
191
            }
192
193
194
        } else {
            switch ($this->out) {
                case 'results':
195
                    return view('resultpages.results')
196
197
198
199
200
                        ->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
201
                        ->with('apiAuthorized', $this->apiAuthorized)
202
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
203
204
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
205
206
                    break;
                case 'results-with-style':
207
                    return view('resultpages.resultpage')
208
209
210
211
212
                        ->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
213
                        ->with('apiAuthorized', $this->apiAuthorized)
214
215
                        ->with('metager', $this)
                        ->with('suspendheader', "yes")
Dominik Hebeler's avatar
Dominik Hebeler committed
216
217
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
218
                    break;
Dominik Hebeler's avatar
Dominik Hebeler committed
219
220
221
222
223
224
225
226
227
                case 'rss20':
                    return view('resultpages.metager3resultsrss20')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('apiAuthorized', $this->apiAuthorized)
                        ->with('metager', $this)
                        ->with('resultcount', sizeof($viewResults))
                        ->with('fokus', $this->fokus);
                    break;
228
                case 'api':
Dominik Hebeler's avatar
Dominik Hebeler committed
229
                    return view('resultpages.metager3resultsatom10', ['eingabe' => $this->eingabe, 'resultcount' => sizeof($viewResults), 'key' => $this->apiKey, 'metager' => $this]);
230
                    break;
231
                case 'atom10':
Dominik Hebeler's avatar
Dominik Hebeler committed
232
                    return view('resultpages.metager3resultsatom10', ['eingabe' => $this->eingabe, 'resultcount' => sizeof($viewResults), 'key' => $this->apiKey, 'metager' => $this]);
Davide Aprea's avatar
Davide Aprea committed
233
                    break;
234
                case 'result-count':
235
236
                    # Wir geben die Ergebniszahl und die benötigte Zeit zurück:
                    return sizeof($viewResults) . ";" . round((microtime(true) - $this->starttime), 2);
237
                    break;
238
                default:
239
                    return view('resultpages.resultpage')
240
                        ->with('eingabe', $this->eingabe)
241
                        ->with('focusPages', $focusPages)
242
243
244
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
245
                        ->with('apiAuthorized', $this->apiAuthorized)
246
                        ->with('metager', $this)
247
                        ->with('browser', (new Agent())->browser())
248
                        ->with('quicktips', $quicktipResults)
249
250
                        ->with('resultcount', count($this->results))
                        ->with('focus', $this->fokus);
251
252
                    break;
            }
253
254
255
        }
    }

256
    public function prepareResults(&$timings = null)
257
    {
Phil Höfer's avatar
Phil Höfer committed
258
259
        $engines = $this->engines;
        // combine
260
        $this->combineResults($engines);
261
        if (!empty($timings)) {
262
263
            $timings["prepareResults"]["combined results"] = microtime(true) - $timings["starttime"];
        }
Phil Höfer's avatar
Phil Höfer committed
264
        // misc (WiP)
265
        if ($this->fokus == "nachrichten") {
266
267
268
            $this->results = array_filter($this->results, function ($v, $k) {
                return !is_null($v->getRank());
            }, ARRAY_FILTER_USE_BOTH);
269
270
271
272
273
274
275
276
277
278
            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;
                }
279

280
281
282
                return ($a->getRank() < $b->getRank()) ? 1 : -1;
            });
        }
283
        if (!empty($timings)) {
284
285
            $timings["prepareResults"]["sorted results"] = microtime(true) - $timings["starttime"];
        }
286
287
        # Validate Results
        $newResults = [];
288
289
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
290
                $newResults[] = $result;
291
            }
292
293
        }
        $this->results = $newResults;
294
        if (!empty($timings)) {
295
296
            $timings["prepareResults"]["validated results"] = microtime(true) - $timings["starttime"];
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
297

Davide Aprea's avatar
Davide Aprea committed
298
        $this->duplicationCheck();
Dominik Hebeler's avatar
Dominik Hebeler committed
299
        if (!empty($timings)) {
300
301
            $timings["prepareResults"]["duplications checked"] = microtime(true) - $timings["starttime"];
        }
302
303
304
305
        # Validate Advertisements
        $newResults = [];
        foreach ($this->ads as $ad) {
            if (($ad->strippedHost !== "" && (in_array($ad->strippedHost, $this->adDomainsBlacklisted) ||
Dominik Hebeler's avatar
Dominik Hebeler committed
306
307
                    in_array($ad->strippedLink, $this->adUrlsBlacklisted))) || ($ad->strippedHostAnzeige !== "" && (in_array($ad->strippedHostAnzeige, $this->adDomainsBlacklisted) ||
                    in_array($ad->strippedLinkAnzeige, $this->adUrlsBlacklisted)))
Karl Hasselbring's avatar
Karl Hasselbring committed
308
            ) {
309
310
311
312
313
                continue;
            }
            $newResults[] = $ad;
        }
        $this->ads = $newResults;
314
        if (!empty($timings)) {
315
316
            $timings["prepareResults"]["validated ads"] = microtime(true) - $timings["starttime"];
        }
317
        #Adgoal Implementation
318
319
320
        if (empty($this->adgoalLoaded)) {
            $this->adgoalLoaded = false;
        }
321
322

        if (!empty($this->jskey)) {
323
            $js = Redis::connection(config('cache.stores.redis.connection'))->lpop("js" . $this->jskey);
324
325
            if ($js !== null && boolval($js)) {
                $this->javascript = true;
326
            }
327
        }
328

Dominik Hebeler's avatar
Dominik Hebeler committed
329
        # Human Verification
330
331
        $this->humanVerification($this->results);
        $this->humanVerification($this->ads);
332
        if (!empty($timings)) {
333
334
            $timings["prepareResults"]["human verification"] = microtime(true) - $timings["starttime"];
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
335

336
        $counter = 0;
337
        $firstRank = 0;
338

339
        if (count($this->results) <= 0) {
340
341
342
343
344
345
            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');
            }
346
        }
347

348
        if ($this->canCache() && isset($this->next) && count($this->next) > 0 && count($this->results) > 0) {
349
            $page = $this->page + 1;
350
            $this->next = [
351
352
                'page' => $page,
                'engines' => $this->next,
353
            ];
354
            Cache::put($this->getSearchUid(), serialize($this->next), 60 * 60);
355
            if (!empty($timings)) {
356
357
                $timings["prepareResults"]["filled cache"] = microtime(true) - $timings["starttime"];
            }
358
359
        } else {
            $this->next = [];
360
        }
361
    }
362

Phil Höfer's avatar
Phil Höfer committed
363
364
365
366
367
368
369
370
371
372
373
    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) {
374
                    $this->results[] = clone $result;
Phil Höfer's avatar
Phil Höfer committed
375
376
377
                }
            }
            foreach ($engine->ads as $ad) {
378
                $this->ads[] = clone $ad;
Phil Höfer's avatar
Phil Höfer committed
379
380
381
382
            }
        }
    }

Davide Aprea's avatar
Davide Aprea committed
383
384
385
    public function duplicationCheck()
    {
        $arr = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
386
        for ($i = 0; $i < count($this->results); $i++) {
Davide Aprea's avatar
Davide Aprea committed
387
388
389
390
391
            $link = $this->results[$i]->link;

            if (strpos($link, "http://") === 0) {
                $link = substr($link, 7);
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
392

Davide Aprea's avatar
Davide Aprea committed
393
394
395
            if (strpos($link, "https://") === 0) {
                $link = substr($link, 8);
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
396

Davide Aprea's avatar
Davide Aprea committed
397
398
399
            if (strpos($link, "www.") === 0) {
                $link = substr($link, 4);
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
400

Davide Aprea's avatar
Davide Aprea committed
401
402
            $link = trim($link, "/");

Dominik Hebeler's avatar
Dominik Hebeler committed
403
            if (isset($arr[$link])) {
Davide Aprea's avatar
Davide Aprea committed
404
405
                $arr[$link]->gefVon[] = $this->results[$i]->gefVon[0];
                $arr[$link]->gefVonLink[] = $this->results[$i]->gefVonLink[0];
406
407

                // The duplicate might already be an adgoal partnershop
Dominik Hebeler's avatar
Dominik Hebeler committed
408
                if ($this->results[$i]->partnershop) {
409
410
411
412
413
414
415
                    # Den Link hinzufügen:
                    $arr[$link]->logo = $this->results[$i]->logo;
                    $arr[$link]->image = $this->results[$i]->image;
                    $arr[$link]->link = $this->results[$i]->link;
                    $arr[$link]->partnershop = $this->results[$i]->partnershop;
                }

Davide Aprea's avatar
Davide Aprea committed
416
417
                array_splice($this->results, $i, 1);
                $i--;
Dominik Hebeler's avatar
Dominik Hebeler committed
418
                if ($arr[$link]->new === true || $this->results[$i]->new === true) {
Dominik Hebeler's avatar
Dominik Hebeler committed
419
                    $arr[$link]->changed = true;
Davide Aprea's avatar
Davide Aprea committed
420
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
421
            } else {
Davide Aprea's avatar
Davide Aprea committed
422
423
424
425
426
                $arr[$link] = &$this->results[$i];
            }
        }
    }

427
428
429
430
431
    /**
     * @param \App\Models\Admitad[] $admitads
     * @param Boolean $wait Wait for Results?
     * @return Boolean whether or not all Admitad Objects are finished
     */
Dominik Hebeler's avatar
Dominik Hebeler committed
432
433
    public function parseAffiliates(&$affiliates)
    {
434
435
        $wait = false;
        $finished = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
436
        if (!$this->javascript) {
437
438
            $wait = true;
        }
439
440
441
        foreach ($affiliates as $affiliate) {
            $affiliate->fetchAffiliates($wait);
            $affiliate->parseAffiliates($this->results);
Dominik Hebeler's avatar
Dominik Hebeler committed
442
            if (!$affiliate->finished) {
443
444
445
446
                $finished = false;
            }
        }
        return $finished;
447
    }
448

449
    public function humanVerification(&$results)
450
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
451
        # Let's check if we need to implement a redirect for human verification
452
453
        if ($this->verificationCount > 10) {
            foreach ($results as $result) {
Dominik Hebeler's avatar
Dominik Hebeler committed
454
455
                $link = $result->link;
                $day = Carbon::now()->day;
456
                $pw = md5($this->verificationId . $day . $link . config("metager.metager.proxy.password"));
457
                $url = route('humanverification', ['mm' => $this->verificationId, 'pw' => $pw, "url" => urlencode(str_replace("/", "<<SLASH>>", base64_encode($link)))]);
458
                $proxyPw = md5($this->verificationId . $day . $result->proxyLink . config("metager.metager.proxy.password"));
459
                $proxyUrl = route('humanverification', ['mm' => $this->verificationId, 'pw' => $proxyPw, "url" => urlencode(str_replace("/", "<<SLASH>>", base64_encode($result->proxyLink)))]);
Dominik Hebeler's avatar
Dominik Hebeler committed
460
                $result->link = $url;
461
                $result->proxyLink = $proxyUrl;
Dominik Hebeler's avatar
Dominik Hebeler committed
462
463
464
465
            }
        }
    }

Phil Höfer's avatar
Phil Höfer committed
466
467
    public function authorize($key)
    {
468
        return app('App\Models\Key')->requestPermission();
Phil Höfer's avatar
Phil Höfer committed
469
470
    }

Karl's avatar
Karl committed
471
472
473
474
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

Dominik Hebeler's avatar
Dominik Hebeler committed
475
    public function createSearchEngines(Request $request, &$timings)
476
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
477
478
479
480
        if (!empty($timings)) {
            $timings["createSearchEngines"]["start"] = microtime(true) - $timings["starttime"];
        }

481
        # Wenn es kein Suchwort gibt
Dominik Hebeler's avatar
Dominik Hebeler committed
482
        if (!$request->filled("eingabe") || $this->q === "") {
483
            return;
484
        }
485

Dominik Hebeler's avatar
Dominik Hebeler committed
486
        $this->enabledSearchengines = [];
487
        $overtureEnabled = false;
488

489
490
491
        # Check if selected focus is valid
        if (empty($this->sumaFile->foki->{$this->fokus})) {
            $this->fokus = "web";
492
        }
493

Karl Hasselbring's avatar
Karl Hasselbring committed
494
        $sumaNames = $this->sumaFile->foki->{$this->fokus}->sumas;
495

Karl Hasselbring's avatar
Karl Hasselbring committed
496
497
498
        $sumas = [];
        foreach ($sumaNames as $sumaName) {
            $sumas[$sumaName] = $this->sumaFile->sumas->{$sumaName};
499
500
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
501
502
503
504
        if (!empty($timings)) {
            $timings["createSearchEngines"]["created engine array"] = microtime(true) - $timings["starttime"];
        }

Karl Hasselbring's avatar
Karl Hasselbring committed
505
506
        $this->removeAdsFromListIfAdfree($sumas);

Dominik Hebeler's avatar
Dominik Hebeler committed
507
508
509
510
        if (!empty($timings)) {
            $timings["createSearchEngines"]["removed ads"] = microtime(true) - $timings["starttime"];
        }

Karl Hasselbring's avatar
Karl Hasselbring committed
511
        foreach ($sumas as $sumaName => $suma) {
512
            # Check if this engine is disabled and can't be used
Karl Hasselbring's avatar
Karl Hasselbring committed
513
514
515
516
517
518
519
            $disabled = empty($suma->disabled) ? false : $suma->disabled;
            $autoDisabled = empty($suma->{"auto-disabled"}) ? false : $suma->{"auto-disabled"};
            if (
                $disabled || $autoDisabled
                || \Cookie::get($this->getFokus() . "_engine_" . $sumaName) === "off"
            ) {
                continue;
520
            }
Karl Hasselbring's avatar
Karl Hasselbring committed
521

522
            $valid = true;
Karl Hasselbring's avatar
Karl Hasselbring committed
523
524
525
526

            # Check if this engine can use potentially defined query-filter
            foreach ($this->queryFilter as $filterName => $filter) {
                if (empty($this->sumaFile->filter->{"query-filter"}->$filterName->sumas->$sumaName)) {
527
528
                    $valid = false;
                    break;
Dominik Hebeler's avatar
Dominik Hebeler committed
529
530
                }
            }
Karl Hasselbring's avatar
Karl Hasselbring committed
531
532

            # Check if this engine can use potentially defined parameter-filter
Dominik Hebeler's avatar
Dominik Hebeler committed
533
534
            if ($valid) {
                foreach ($this->parameterFilter as $filterName => $filter) {
535
                    # We need to check if the searchengine supports the parameter value, too
Karl Hasselbring's avatar
Karl Hasselbring committed
536
                    if (empty($filter->sumas->$sumaName) || empty($filter->sumas->{$sumaName}->values->{$filter->value})) {
Dominik Hebeler's avatar
Dominik Hebeler committed
537
538
539
540
541
                        $valid = false;
                        break;
                    }
                }
            }
Karl Hasselbring's avatar
Karl Hasselbring committed
542

543
            # Check if this engine should only be active when filter is used
Karl Hasselbring's avatar
Karl Hasselbring committed
544
            if ($suma->{"filter-opt-in"}) {
545
546
547
                # This search engine should only be used when a parameter filter of it is used
                $validTmp = false;
                foreach ($this->parameterFilter as $filterName => $filter) {
Karl Hasselbring's avatar
Karl Hasselbring committed
548
                    if (!empty($filter->sumas->{$sumaName})) {
549
550
551
552
553
554
555
556
                        $validTmp = true;
                        break;
                    }
                }
                if (!$validTmp) {
                    $valid = false;
                }
            }
Karl Hasselbring's avatar
Karl Hasselbring committed
557
558

            # If the suma is still valid, we can add it
559
            if ($valid) {
Karl Hasselbring's avatar
Karl Hasselbring committed
560
                $this->enabledSearchengines[$sumaName] = $suma;
561
            }
562
        }
563

Dominik Hebeler's avatar
Dominik Hebeler committed
564
565
566
567
        if (!empty($timings)) {
            $timings["createSearchEngines"]["filtered invalid engines"] = microtime(true) - $timings["starttime"];
        }

Karl Hasselbring's avatar
Karl Hasselbring committed
568
569
        # Include Yahoo Ads if Yahoo is not enabled as a searchengine
        if (!$this->apiAuthorized && $this->fokus != "bilder" && empty($this->enabledSearchengines["yahoo"]) && isset($this->sumaFile->sumas->{"yahoo-ads"})) {
570
571
572
            $this->enabledSearchengines["yahoo-ads"] = $this->sumaFile->sumas->{"yahoo-ads"};
        }

573
574
        # Special case if search engines are disabled
        # Since bing is normally only active if a filter is set but it should be active, too if yahoo is disabled
Davide Aprea's avatar
Davide Aprea committed
575
        if ($this->getFokus() === "web" && empty($this->enabledSearchengines["yahoo"]) && \Cookie::get("web_engine_bing") !== "off"  && isset($this->sumaFile->sumas->{"bing"})) {
576
577
578
            $this->enabledSearchengines["bing"] = $this->sumaFile->sumas->{"bing"};
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
579
        if (sizeof($this->enabledSearchengines) === 0) {
580
581
            $filter = "";
            foreach ($this->queryFilter as $queryFilter => $filterPhrase) {
Dominik Hebeler's avatar
Dominik Hebeler committed
582
                $filter .= trans($this->sumaFile->filter->{"query-filter"}->{$queryFilter}->name) . ",";
583
584
            }
            $filter = rtrim($filter, ",");
Karl Hasselbring's avatar
Karl Hasselbring committed
585
586
            $error = trans('metaGer.engines.noSpecialSearch', [
                'fokus' => trans($this->sumaFile->foki->{$this->fokus}->{"display-name"}),
587
                'filter' => $filter,
Karl Hasselbring's avatar
Karl Hasselbring committed
588
            ]);
589
            $this->errors[] = $error;
590
        }
591
        $this->setEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
592
593
594
        if (!empty($timings)) {
            $timings["createSearchEngines"]["saved engines"] = microtime(true) - $timings["starttime"];
        }
595
    }
596

Karl Hasselbring's avatar
Karl Hasselbring committed
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
    private function removeAdsFromListIfAdfree(&$sumas)
    {
        if ($this->apiAuthorized) {
            foreach ($sumas as $sumaName => $suma) {
                $ads = $suma->ads ?? false;
                if ($ads) {
                    unset($sumas[$sumaName]);

                    $adBackups = $suma->{"ad-backups"} ?? [];
                    $adBackupName = $adBackups->{$this->fokus} ?? null;
                    if (isset($adBackupName)) {
                        $this->sumaFile->sumas->{$adBackupName}->{"filter-opt-in"} = false;
                    }
                }
            }
        }
    }

615
616
    public function setEngines(Request $request, $enabledSearchengines = [])
    {
617
        if ($this->requestIsCached($request)) {
618
            # If this is a page other than 1 the request is "cached"
619
            $engines = $this->getCachedEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
620
            # We need to edit some Options of the Cached Search Engines
Phil Höfer's avatar
Phil Höfer committed
621
            foreach ($engines as $engine) {
622
                $engine->setResultHash($this->getSearchUid());
Dominik Hebeler's avatar
Dominik Hebeler committed
623
            }
624
            $this->engines = $engines;
625
        } else {
626
627
628
            if (sizeof($enabledSearchengines) > 0) {
                $this->enabledSearchengines = $enabledSearchengines;
            }
629
            $this->actuallyCreateSearchEngines($this->enabledSearchengines);
630
        }
631
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
632

Dominik Hebeler's avatar
Dominik Hebeler committed
633
    public function startSearch(&$timings)
634
    {
635
636
637
638
639
        if (!empty($timings)) {
            $timings["startSearch"]["start"] = microtime(true) - $timings["starttime"];
        }

        # Check all engines for Cached responses
Dominik Hebeler's avatar
Dominik Hebeler committed
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
        $this->checkCache();

        if (!empty($timings)) {
            $timings["startSearch"]["cache checked"] = microtime(true) - $timings["starttime"];
        }

        # Wir starten alle Suchen
        foreach ($this->engines as $engine) {
            $engine->startSearch($this, $timings);
        }
        if (!empty($timings)) {
            $timings["startSearch"]["searches started"] = microtime(true) - $timings["starttime"];
        }
    }

    public function checkCache()
    {
657
658
        if ($this->canCache()) {
            foreach ($this->engines as $engine) {
Dominik Hebeler's avatar
Dominik Hebeler committed
659
                if (Cache::has($engine->hash)) {
660
                    $engine->cached = true;
661
                    $engine->retrieveResults($this, Cache::get($engine->hash));
662
663
664
                }
            }
        }
665
666
    }

667
668
    # Spezielle Suchen und Sumas

669
    public function sumaIsSelected($suma, $request, $custom)
670
    {
671
        if ($custom) {
672
            if ($request->filled("engine_" . strtolower($suma["name"]))) {
673
674
675
676
677
678
679
680
681
682
683
                return true;
            }
        } else {
            $types = explode(",", $suma["type"]);
            if (in_array($this->fokus, $types)) {
                return true;
            }
        }
        return false;
    }

684
    public function actuallyCreateSearchEngines($enabledSearchengines)
685
686
    {
        $engines = [];
687
688
        foreach ($enabledSearchengines as $engineName => $engine) {
            if (!isset($engine->{"parser-class"})) {
Dominik Hebeler's avatar
Dominik Hebeler committed
689
690
                die(var_dump($engine));
            }
691
            # Setze Pfad zu Parser
692
            $path = "App\\Models\\parserSkripte\\" . $engine->{"parser-class"};
693
694

            # Prüfe ob Parser vorhanden
695
696
697
            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"}]);
698
699
700
701
702
703
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
704
                $tmp = new $path($engineName, $engine, $this);
705
            } catch (\ErrorException $e) {
706
                Log::error("Konnte " . $engine->{"display-name"} . " nicht abfragen. " . $e);
707
708
709
                continue;
            }

710
            $engines[] = $tmp;
711
        }
712
        $this->engines = $engines;
713
714
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
715
716
717
718
719
720
721
    public function getAvailableParameterFilter()
    {
        $parameterFilter = $this->sumaFile->filter->{"parameter-filter"};

        $availableFilter = [];

        foreach ($parameterFilter as $filterName => $filter) {
722
            $values = clone $filter->values;
Dominik Hebeler's avatar
Dominik Hebeler committed
723
724
725
            # Check if any of the enabled search engines provide this filter
            foreach ($this->enabledSearchengines as $engineName => $engine) {
                if (!empty($filter->sumas->$engineName)) {
726
727
                    if (empty($availableFilter[$filterName])) {
                        $availableFilter[$filterName] = $filter;
728
729
                        foreach ($availableFilter[$filterName]->values as $key => $value) {
                            if ($key !== "nofilter") {
730
731
732
                                unset($availableFilter[$filterName]->values->{$key});
                            }
                        }
733
734
                    }
                    if (empty($availableFilter[$filterName]->values)) {
735
                        $availableFilter[$filterName]->values = new \stdClass();
736
737
                    }
                    foreach ($filter->sumas->{$engineName}->values as $key => $value) {
738
                        $availableFilter[$filterName]->values->{$key} = $values->$key;
739
                    }
Dominik Hebeler's avatar
Dominik Hebeler committed
740
741
                }
            }
742
743
            # We will also add the filter from the opt-in search engines (the searchengines that are only used when a filter of it is too)
            foreach ($this->sumaFile->foki->{$this->fokus}->sumas as $suma) {
744
                if ($this->sumaFile->sumas->{$suma}->{"filter-opt-in"} && \Cookie::get($this->getFokus() . "_engine_" . $suma) !== "off") {
745
                    if (!empty($filter->sumas->{$suma})) {
746
747
                        # If the searchengine is disabled this filter shouldn't be available
                        if ((!empty($this->sumaFile->sumas->{$suma}->disabled) && $this->sumaFile->sumas->{$suma}->disabled === true)
Karl Hasselbring's avatar
Karl Hasselbring committed
748
749
                            || (!empty($this->sumaFile->sumas->{$suma}->{"auto-disabled"}) && $this->sumaFile->sumas->{$suma}->{"auto-disabled"} === true)
                        ) {
750
751
                            continue;
                        }
752
753
                        if (empty($availableFilter[$filterName])) {
                            $availableFilter[$filterName] = $filter;
754
755
                            foreach ($availableFilter[$filterName]->values as $key => $value) {
                                if ($key !== "nofilter") {
756
757
758
                                    unset($availableFilter[$filterName]->values->{$key});
                                }
                            }
759
760
                        }
                        if (empty($availableFilter[$filterName]->values)) {
761
                            $availableFilter[$filterName]->values = new \stdClass();
762
763
                        }
                        foreach ($filter->sumas->{$suma}->values as $key => $value) {
764
                            $availableFilter[$filterName]->values->{$key} = $values->$key;
765
                        }
766
767
768
                    }
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
769
770
        }

771
772
773
774
        # Set the current values for the filters
        foreach ($availableFilter as $filterName => $filter) {
            if (\Request::filled($filter->{"get-parameter"})) {
                $filter->value = \Request::input($filter->{"get-parameter"});
775
            } elseif (\Cookie::get($this->getFokus() . "_setting_" . $filter->{"get-parameter"}) !== null) {
776
777
778
779
                $filter->value = \Cookie::get($this->getFokus() . "_setting_" . $filter->{"get-parameter"});
            }
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
780
781
782
        return $availableFilter;
    }

783
784
    public function isBildersuche()
    {
785
        return $this->fokus === "bilder";
786
787
788
789
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
790
        $sumaName = $suma["name"]->__toString();
791
        return
792
793
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
Karl Hasselbring's avatar
Karl Hasselbring committed
794
            || (!$overtureEnabled && $sumaName === "overtureAds");
795
796
797
798
799
    }

    public function sumaIsDisabled($suma)
    {
        return
Dominik Hebeler's avatar
Dominik Hebeler committed
800
801
            isset($suma['disabled'])
            && $suma['disabled']->__toString() === "1";
802
803
804
805
806
    }

    public function sumaIsOverture($suma)
    {
        return
Dominik Hebeler's avatar
Dominik Hebeler committed
807
808
            $suma["name"]->__toString() === "overture"
            || $suma["name"]->__toString() === "overtureAds";
809
810
811
812
813
    }

    public function sumaIsNotAdsuche($suma)
    {
        return
Dominik Hebeler's avatar
Dominik Hebeler committed
814
815
816
            $suma["name"]->__toString() !== "qualigo"
            && $suma["name"]->__toString() !== "similar_product_ads"
            && $suma["name"]->__toString() !== "overtureAds";
817
818
819
820
821
    }

    public function requestIsCached($request)
    {
        return
Dominik Hebeler's avatar
Dominik Hebeler committed
822
823
824
            $request->filled('next')
            && Cache::has($request->input('next'))
            && unserialize(Cache::get($request->input('next')))['page'] > 1;
825
826
827
828
    }

    public function getCachedEngines($request)
    {
829
        $next = unserialize(Cache::get($request->input('next')));
830
        $this->page = $next['page'];
831
        $engines = $next['engines'];
832
833
834
        return $engines;
    }

835
    public function waitForMainResults()
836
    {
837
        $engines = $this->engines;
838
        $enginesToWaitFor = [];
839
840
841
        $mainEngines = $this->sumaFile->foki->{$this->fokus}->main;
        foreach ($mainEngines as $mainEngine) {
            foreach ($engines as $engine) {
842
                if ($engine->name === $mainEngine) {
843
                    $enginesToWaitFor[] = $engine->hash;
844
                }
845
846
            }
        }
847

848
849
850
851
852
        # If no main engines are enabled by the user we will wait for all results
        if (sizeof($enginesToWaitFor) === 0) {
            foreach ($engines as $engine) {
                $enginesToWaitFor[] = $engine->hash;
            }