MetaGer.php 67.6 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
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

108
109
110
111
112
        if(file_exists(config_path() . "/blacklistDescriptionUrl.txt")){
            $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
153
            if (starts_with($key, 'engine_') && $value === 'on') {
                $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)
175
                        ->with('browser', (new Agent())->browser());
176
                default:
177
                    return view('resultpages.resultpage_images')
178
179
180
181
182
                        ->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
183
                        ->with('apiAuthorized', $this->apiAuthorized)
184
                        ->with('metager', $this)
185
                        ->with('browser', (new Agent())->browser())
186
                        ->with('quicktips', $quicktipResults)
187
188
                        ->with('focus', $this->fokus)
                        ->with('resultcount', count($this->results));
189
            }
190
191
192
        } else {
            switch ($this->out) {
                case 'results':
193
                    return view('resultpages.results')
194
195
196
197
198
                        ->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
199
                        ->with('apiAuthorized', $this->apiAuthorized)
200
                        ->with('metager', $this)
Dominik Hebeler's avatar
Dominik Hebeler committed
201
202
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
203
204
                    break;
                case 'results-with-style':
205
                    return view('resultpages.resultpage')
206
207
208
209
210
                        ->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
211
                        ->with('apiAuthorized', $this->apiAuthorized)
212
213
                        ->with('metager', $this)
                        ->with('suspendheader', "yes")
Dominik Hebeler's avatar
Dominik Hebeler committed
214
215
                        ->with('browser', (new Agent())->browser())
                        ->with('fokus', $this->fokus);
216
                    break;
Davide Aprea's avatar
Davide Aprea committed
217
                
218
                case 'api':
Dominik Hebeler's avatar
Dominik Hebeler committed
219
                    return view('resultpages.metager3resultsatom10', ['eingabe' => $this->eingabe, 'resultcount' => sizeof($viewResults), 'key' => $this->apiKey, 'metager' => $this]);
220
                    break;
221
                case 'atom10':
Dominik Hebeler's avatar
Dominik Hebeler committed
222
                    return view('resultpages.metager3resultsatom10', ['eingabe' => $this->eingabe, 'resultcount' => sizeof($viewResults), 'key' => $this->apiKey, 'metager' => $this]);
Davide Aprea's avatar
Davide Aprea committed
223
                    break;
224
                case 'result-count':
225
226
                    # Wir geben die Ergebniszahl und die benötigte Zeit zurück:
                    return sizeof($viewResults) . ";" . round((microtime(true) - $this->starttime), 2);
227
                    break;
228
                default:
229
                    return view('resultpages.resultpage')
230
                        ->with('eingabe', $this->eingabe)
231
                        ->with('focusPages', $focusPages)
232
233
234
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
Phil Höfer's avatar
Phil Höfer committed
235
                        ->with('apiAuthorized', $this->apiAuthorized)
236
                        ->with('metager', $this)
237
                        ->with('browser', (new Agent())->browser())
238
                        ->with('quicktips', $quicktipResults)
239
240
                        ->with('resultcount', count($this->results))
                        ->with('focus', $this->fokus);
241
242
                    break;
            }
243
244
245
        }
    }

246
    public function prepareResults(&$timings = null)
247
    {
Phil Höfer's avatar
Phil Höfer committed
248
249
        $engines = $this->engines;
        // combine
250
        $this->combineResults($engines);
251
        if (!empty($timings)) {
252
253
            $timings["prepareResults"]["combined results"] = microtime(true) - $timings["starttime"];
        }
Phil Höfer's avatar
Phil Höfer committed
254
        // misc (WiP)
255
        if ($this->fokus == "nachrichten") {
256
257
258
            $this->results = array_filter($this->results, function ($v, $k) {
                return !is_null($v->getRank());
            }, ARRAY_FILTER_USE_BOTH);
259
260
261
262
263
264
265
266
267
268
            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;
                }
269

270
271
272
                return ($a->getRank() < $b->getRank()) ? 1 : -1;
            });
        }
273
        if (!empty($timings)) {
274
275
            $timings["prepareResults"]["sorted results"] = microtime(true) - $timings["starttime"];
        }
276
277
        # Validate Results
        $newResults = [];
278
279
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
280
                $newResults[] = $result;
281
            }
282
283
        }
        $this->results = $newResults;
284
        if (!empty($timings)) {
285
286
            $timings["prepareResults"]["validated results"] = microtime(true) - $timings["starttime"];
        }
287
        
Davide Aprea's avatar
Davide Aprea committed
288
        $this->duplicationCheck();
Dominik Hebeler's avatar
Dominik Hebeler committed
289
        if (!empty($timings)) {
290
291
            $timings["prepareResults"]["duplications checked"] = microtime(true) - $timings["starttime"];
        }
292
293
294
295
        # Validate Advertisements
        $newResults = [];
        foreach ($this->ads as $ad) {
            if (($ad->strippedHost !== "" && (in_array($ad->strippedHost, $this->adDomainsBlacklisted) ||
296
297
                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
298
            ) {
299
300
301
302
303
                continue;
            }
            $newResults[] = $ad;
        }
        $this->ads = $newResults;
304
        if (!empty($timings)) {
305
306
            $timings["prepareResults"]["validated ads"] = microtime(true) - $timings["starttime"];
        }
307
        #Adgoal Implementation
308
309
310
        if (empty($this->adgoalLoaded)) {
            $this->adgoalLoaded = false;
        }
311
312
313
314
315

        if (!empty($this->jskey)) {
            $js = Redis::connection('cache')->lpop("js" . $this->jskey);
            if ($js !== null && boolval($js)) {
                $this->javascript = true;
316
            }
317
        }
318

Dominik Hebeler's avatar
Dominik Hebeler committed
319
        # Human Verification
320
321
        $this->humanVerification($this->results);
        $this->humanVerification($this->ads);
322
        if (!empty($timings)) {
323
324
            $timings["prepareResults"]["human verification"] = microtime(true) - $timings["starttime"];
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
325

326
        $counter = 0;
327
        $firstRank = 0;
328

329
        if (count($this->results) <= 0) {
330
331
332
333
334
335
            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');
            }
336
        }
337

338
        if ($this->canCache() && isset($this->next) && count($this->next) > 0 && count($this->results) > 0) {
339
            $page = $this->page + 1;
340
            $this->next = [
341
342
                'page' => $page,
                'engines' => $this->next,
343
            ];
344
            Cache::put($this->getSearchUid(), serialize($this->next), 60 * 60);
345
            if (!empty($timings)) {
346
347
                $timings["prepareResults"]["filled cache"] = microtime(true) - $timings["starttime"];
            }
348
349
        } else {
            $this->next = [];
350
        }
351
    }
352

Phil Höfer's avatar
Phil Höfer committed
353
354
355
356
357
358
359
360
361
362
363
    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) {
364
                    $this->results[] = clone $result;
Phil Höfer's avatar
Phil Höfer committed
365
366
367
                }
            }
            foreach ($engine->ads as $ad) {
368
                $this->ads[] = clone $ad;
Phil Höfer's avatar
Phil Höfer committed
369
370
371
372
            }
        }
    }

Davide Aprea's avatar
Davide Aprea committed
373
374
375
    public function duplicationCheck()
    {
        $arr = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
376
        for ($i = 0; $i < count($this->results); $i++) {
Davide Aprea's avatar
Davide Aprea committed
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
            $link = $this->results[$i]->link;

            if (strpos($link, "http://") === 0) {
                $link = substr($link, 7);
            }
    
            if (strpos($link, "https://") === 0) {
                $link = substr($link, 8);
            }
    
            if (strpos($link, "www.") === 0) {
                $link = substr($link, 4);
            }
    
            $link = trim($link, "/");
            $hash = md5($link);

Dominik Hebeler's avatar
Dominik Hebeler committed
394
            if (isset($arr[$link])) {
Davide Aprea's avatar
Davide Aprea committed
395
396
                $arr[$link]->gefVon[] = $this->results[$i]->gefVon[0];
                $arr[$link]->gefVonLink[] = $this->results[$i]->gefVonLink[0];
397
398
399
400
401
402
403
404
405
406

                // The duplicate might already be an adgoal partnershop
                if($this->results[$i]->partnershop){
                    # 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
407
408
                array_splice($this->results, $i, 1);
                $i--;
Dominik Hebeler's avatar
Dominik Hebeler committed
409
                if ($arr[$link]->new === true || $this->results[$i]->new === true) {
410
                    $arr[$link]->changed = true; 
Davide Aprea's avatar
Davide Aprea committed
411
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
412
            } else {
Davide Aprea's avatar
Davide Aprea committed
413
414
415
416
417
                $arr[$link] = &$this->results[$i];
            }
        }
    }

418
419
420
421
422
    /**
     * @param \App\Models\Admitad[] $admitads
     * @param Boolean $wait Wait for Results?
     * @return Boolean whether or not all Admitad Objects are finished
     */
423
    public function parseAffiliates(&$affiliates){
424
425
426
427
428
        $wait = false;
        $finished = true;
        if(!$this->javascript){
            $wait = true;
        }
429
430
431
432
        foreach ($affiliates as $affiliate) {
            $affiliate->fetchAffiliates($wait);
            $affiliate->parseAffiliates($this->results);
            if(!$affiliate->finished){
433
434
435
436
                $finished = false;
            }
        }
        return $finished;
437
    }
438

439
    public function humanVerification(&$results)
440
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
441
        # Let's check if we need to implement a redirect for human verification
442
443
        if ($this->verificationCount > 10) {
            foreach ($results as $result) {
Dominik Hebeler's avatar
Dominik Hebeler committed
444
445
446
                $link = $result->link;
                $day = Carbon::now()->day;
                $pw = md5($this->verificationId . $day . $link . env("PROXY_PASSWORD"));
447
448
449
                $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
450
                $result->link = $url;
451
                $result->proxyLink = $proxyUrl;
Dominik Hebeler's avatar
Dominik Hebeler committed
452
453
454
455
            }
        }
    }

Phil Höfer's avatar
Phil Höfer committed
456
457
    public function authorize($key)
    {
458
        return app('App\Models\Key')->requestPermission();
Phil Höfer's avatar
Phil Höfer committed
459
460
    }

Karl's avatar
Karl committed
461
462
463
464
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

Dominik Hebeler's avatar
Dominik Hebeler committed
465
    public function createSearchEngines(Request $request, &$timings)
466
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
467
468
469
470
        if (!empty($timings)) {
            $timings["createSearchEngines"]["start"] = microtime(true) - $timings["starttime"];
        }

471
        # Wenn es kein Suchwort gibt
Dominik Hebeler's avatar
Dominik Hebeler committed
472
        if (!$request->filled("eingabe") || $this->q === "") {
473
            return;
474
        }
475

Dominik Hebeler's avatar
Dominik Hebeler committed
476
        $this->enabledSearchengines = [];
477
        $overtureEnabled = false;
478

479
480
481
        # Check if selected focus is valid
        if (empty($this->sumaFile->foki->{$this->fokus})) {
            $this->fokus = "web";
482
        }
483

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

Karl Hasselbring's avatar
Karl Hasselbring committed
486
487
488
        $sumas = [];
        foreach ($sumaNames as $sumaName) {
            $sumas[$sumaName] = $this->sumaFile->sumas->{$sumaName};
489
490
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
491
492
493
494
        if (!empty($timings)) {
            $timings["createSearchEngines"]["created engine array"] = microtime(true) - $timings["starttime"];
        }

Karl Hasselbring's avatar
Karl Hasselbring committed
495
496
        $this->removeAdsFromListIfAdfree($sumas);

Dominik Hebeler's avatar
Dominik Hebeler committed
497
498
499
500
        if (!empty($timings)) {
            $timings["createSearchEngines"]["removed ads"] = microtime(true) - $timings["starttime"];
        }

Karl Hasselbring's avatar
Karl Hasselbring committed
501
        foreach ($sumas as $sumaName => $suma) {
502
            # Check if this engine is disabled and can't be used
Karl Hasselbring's avatar
Karl Hasselbring committed
503
504
505
506
507
508
509
            $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;
510
            }
Karl Hasselbring's avatar
Karl Hasselbring committed
511

512
            $valid = true;
Karl Hasselbring's avatar
Karl Hasselbring committed
513
514
515
516

            # 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)) {
517
518
                    $valid = false;
                    break;
Dominik Hebeler's avatar
Dominik Hebeler committed
519
520
                }
            }
Karl Hasselbring's avatar
Karl Hasselbring committed
521
522

            # Check if this engine can use potentially defined parameter-filter
Dominik Hebeler's avatar
Dominik Hebeler committed
523
524
            if ($valid) {
                foreach ($this->parameterFilter as $filterName => $filter) {
525
                    # We need to check if the searchengine supports the parameter value, too
Karl Hasselbring's avatar
Karl Hasselbring committed
526
                    if (empty($filter->sumas->$sumaName) || empty($filter->sumas->{$sumaName}->values->{$filter->value})) {
Dominik Hebeler's avatar
Dominik Hebeler committed
527
528
529
530
531
                        $valid = false;
                        break;
                    }
                }
            }
Karl Hasselbring's avatar
Karl Hasselbring committed
532

533
            # Check if this engine should only be active when filter is used
Karl Hasselbring's avatar
Karl Hasselbring committed
534
            if ($suma->{"filter-opt-in"}) {
535
536
537
                # 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
538
                    if (!empty($filter->sumas->{$sumaName})) {
539
540
541
542
543
544
545
546
                        $validTmp = true;
                        break;
                    }
                }
                if (!$validTmp) {
                    $valid = false;
                }
            }
Karl Hasselbring's avatar
Karl Hasselbring committed
547
548

            # If the suma is still valid, we can add it
549
            if ($valid) {
Karl Hasselbring's avatar
Karl Hasselbring committed
550
                $this->enabledSearchengines[$sumaName] = $suma;
551
            }
552
        }
553

Dominik Hebeler's avatar
Dominik Hebeler committed
554
555
556
557
        if (!empty($timings)) {
            $timings["createSearchEngines"]["filtered invalid engines"] = microtime(true) - $timings["starttime"];
        }

Karl Hasselbring's avatar
Karl Hasselbring committed
558
559
        # 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"})) {
560
561
562
            $this->enabledSearchengines["yahoo-ads"] = $this->sumaFile->sumas->{"yahoo-ads"};
        }

563
564
        # 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
565
        if ($this->getFokus() === "web" && empty($this->enabledSearchengines["yahoo"]) && \Cookie::get("web_engine_bing") !== "off"  && isset($this->sumaFile->sumas->{"bing"})) {
566
567
568
            $this->enabledSearchengines["bing"] = $this->sumaFile->sumas->{"bing"};
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
569
        if (sizeof($this->enabledSearchengines) === 0) {
570
571
            $filter = "";
            foreach ($this->queryFilter as $queryFilter => $filterPhrase) {
Dominik Hebeler's avatar
Dominik Hebeler committed
572
                $filter .= trans($this->sumaFile->filter->{"query-filter"}->{$queryFilter}->name) . ",";
573
574
            }
            $filter = rtrim($filter, ",");
Karl Hasselbring's avatar
Karl Hasselbring committed
575
576
            $error = trans('metaGer.engines.noSpecialSearch', [
                'fokus' => trans($this->sumaFile->foki->{$this->fokus}->{"display-name"}),
577
                'filter' => $filter,
Karl Hasselbring's avatar
Karl Hasselbring committed
578
            ]);
579
            $this->errors[] = $error;
580
        }
581
        $this->setEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
582
583
584
        if (!empty($timings)) {
            $timings["createSearchEngines"]["saved engines"] = microtime(true) - $timings["starttime"];
        }
585
    }
586

Karl Hasselbring's avatar
Karl Hasselbring committed
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
    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;
                    }
                }
            }
        }
    }

605
606
    public function setEngines(Request $request, $enabledSearchengines = [])
    {
607
        if ($this->requestIsCached($request)) {
608
            # If this is a page other than 1 the request is "cached"
609
            $engines = $this->getCachedEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
610
            # We need to edit some Options of the Cached Search Engines
Phil Höfer's avatar
Phil Höfer committed
611
            foreach ($engines as $engine) {
612
                $engine->setResultHash($this->getSearchUid());
Dominik Hebeler's avatar
Dominik Hebeler committed
613
            }
614
            $this->engines = $engines;
615
        } else {
616
617
618
            if (sizeof($enabledSearchengines) > 0) {
                $this->enabledSearchengines = $enabledSearchengines;
            }
619
            $this->actuallyCreateSearchEngines($this->enabledSearchengines);
620
        }
621
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
622

Dominik Hebeler's avatar
Dominik Hebeler committed
623
    public function startSearch(&$timings)
624
    {
625
626
627
628
629
        if (!empty($timings)) {
            $timings["startSearch"]["start"] = microtime(true) - $timings["starttime"];
        }

        # Check all engines for Cached responses
Dominik Hebeler's avatar
Dominik Hebeler committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
        $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()
    {
647
648
649
650
651
        if ($this->canCache()) {
            $keys = [];
            foreach ($this->engines as $engine) {
                $keys[] = $engine->hash;
            }
652
653
654
655
            # Noch searchengines enabled
            if (empty($keys)) {
                return;
            }
656
657
658
659
660
661
662
663
            $cacheValues = Cache::many($keys);
            foreach ($this->engines as $engine) {
                if ($cacheValues[$engine->hash] !== null) {
                    $engine->cached = true;
                    $engine->retrieveResults($this, $cacheValues[$engine->hash]);
                }
            }
        }
664
665
    }

666
667
    # Spezielle Suchen und Sumas

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

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

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

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

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

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

        $availableFilter = [];

        foreach ($parameterFilter as $filterName => $filter) {
721
            $values = clone $filter->values;
Dominik Hebeler's avatar
Dominik Hebeler committed
722
723
724
            # Check if any of the enabled search engines provide this filter
            foreach ($this->enabledSearchengines as $engineName => $engine) {
                if (!empty($filter->sumas->$engineName)) {
725
726
                    if (empty($availableFilter[$filterName])) {
                        $availableFilter[$filterName] = $filter;
727
728
                        foreach ($availableFilter[$filterName]->values as $key => $value) {
                            if ($key !== "nofilter") {
729
730
731
                                unset($availableFilter[$filterName]->values->{$key});
                            }
                        }
732
733
                    }
                    if (empty($availableFilter[$filterName]->values)) {
734
                        $availableFilter[$filterName]->values = new \stdClass();
735
736
                    }
                    foreach ($filter->sumas->{$engineName}->values as $key => $value) {
737
                        $availableFilter[$filterName]->values->{$key} = $values->$key;
738
                    }
Dominik Hebeler's avatar
Dominik Hebeler committed
739
740
                }
            }
741
742
            # 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) {
743
                if ($this->sumaFile->sumas->{$suma}->{"filter-opt-in"} && \Cookie::get($this->getFokus() . "_engine_" . $suma) !== "off") {
744
                    if (!empty($filter->sumas->{$suma})) {
745
746
                        # 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
747
748
                            || (!empty($this->sumaFile->sumas->{$suma}->{"auto-disabled"}) && $this->sumaFile->sumas->{$suma}->{"auto-disabled"} === true)
                        ) {
749
750
                            continue;
                        }
751
752
                        if (empty($availableFilter[$filterName])) {
                            $availableFilter[$filterName] = $filter;
753
754
                            foreach ($availableFilter[$filterName]->values as $key => $value) {
                                if ($key !== "nofilter") {
755
756
757
                                    unset($availableFilter[$filterName]->values->{$key});
                                }
                            }
758
759
                        }
                        if (empty($availableFilter[$filterName]->values)) {
760
                            $availableFilter[$filterName]->values = new \stdClass();
761
762
                        }
                        foreach ($filter->sumas->{$suma}->values as $key => $value) {
763
                            $availableFilter[$filterName]->values->{$key} = $values->$key;
764
                        }
765
766
767
                    }
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
768
769
        }

770
771
772
773
        # 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"});
774
            } elseif (\Cookie::get($this->getFokus() . "_setting_" . $filter->{"get-parameter"}) !== null) {
775
776
777
778
                $filter->value = \Cookie::get($this->getFokus() . "_setting_" . $filter->{"get-parameter"});
            }
        }

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

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

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

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

    public function sumaIsOverture($suma)
    {
        return
806
807
        $suma["name"]->__toString() === "overture"
        || $suma["name"]->__toString() === "overtureAds";
808
809
810
811
812
    }

    public function sumaIsNotAdsuche($suma)
    {
        return
813
814
815
        $suma["name"]->__toString() !== "qualigo"
        && $suma["name"]->__toString() !== "similar_product_ads"
        && $suma["name"]->__toString() !== "overtureAds";
816
817
818
819
820
    }

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

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

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

847
848
849
850
851
        # 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;
            }
852
853
854
855
856
857
858
859
860
861
862
        } else {
            $newEnginesToWaitFor = [];
            // Don't wait for engines that are already loaded in Cache
            foreach ($enginesToWaitFor as $engineToWaitFor) {
                foreach ($engines as $engine) {
                    if ($engine->hash === $engineToWaitFor && !$engine->loaded) {
                        $newEnginesToWaitFor[] = $engineToWaitFor;
                    }
                }
            }
            $enginesToWaitFor = $newEnginesToWaitFor;
863
864
        }

Phil Höfer's avatar
Phil Höfer committed
865
        $timeStart = microtime(true);
866
        while (sizeof($enginesToWaitFor) > 0) {
867
            if ((microtime(true) - $timeStart) >= 2) {
868
                break;
869
870
871
872
873
            }
            $answer = Redis::brpop($enginesToWaitFor, 2);
            
            if ($answer === null) {
                continue;
874
875
            } else {
                Redis::lpush($answer[0], $answer[1]);
Dominik Hebeler's avatar
Dominik Hebeler committed
876
                Redis::expire($answer[0], 60);
877
878
879
880
881
882
883
884
885
886
887
            }
            foreach ($engines as $index => $engine) {
                if ($engine->hash === $answer[0]) {
                    $engine->retrieveResults($this, $answer[1]);
                    foreach ($enginesToWaitFor as $waitIndex => $engineToWaitFor) {
                        if ($engineToWaitFor === $answer[0]) {
                            unset($enginesToWaitFor[$waitIndex]);
                            break 2;
                        }
                    }
                }
888
            }
889
        }
890
    }
891

892