MetaGer.php 59.9 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
    # Einstellungen für die Suche
17
18
    public $alteredQuery = "";
    public $alterationOverrideQuery = "";
19
20
21
22
23
24
25
    protected $fokus;
    protected $eingabe;
    protected $q;
    protected $page;
    protected $lang;
    protected $cache = "";
    protected $site;
26
    protected $time = 2000;
27
    protected $hostBlacklist = [];
28
    protected $domainBlacklist = [];
29
30
31
32
    private $urlBlacklist = [];
    protected $stopWords = [];
    protected $phrases = [];
    protected $engines = [];
33
    protected $totalResults = 0;
34
    protected $results = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
35
36
    protected $queryFilter = [];
    protected $parameterFilter = [];
37
    protected $ads = [];
38
    protected $infos = [];
39
40
41
    protected $warnings = [];
    protected $errors = [];
    protected $addedHosts = [];
42
    protected $availableFoki = [];
43
44
    protected $startCount = 0;
    protected $canCache = false;
45
    # Daten über die Abfrage$
46
    protected $ip;
Dominik Hebeler's avatar
Dominik Hebeler committed
47
    protected $useragent;
48
49
    protected $language;
    protected $agent;
50
    protected $apiKey = "";
Phil Höfer's avatar
Phil Höfer committed
51
    protected $apiAuthorized = false;
52
    protected $next = [];
53
54
55
56
57
    # Konfigurationseinstellungen:
    protected $sumaFile;
    protected $mobile;
    protected $resultCount;
    protected $sprueche;
58
    protected $newtab;
59
    protected $domainsBlacklisted = [];
60
    protected $urlsBlacklisted = [];
61
    protected $url;
62
    protected $fullUrl;
63
    protected $languageDetect;
Dominik Hebeler's avatar
Dominik Hebeler committed
64
65
    protected $verificationId;
    protected $verificationCount;
66
    protected $searchUid;
67
    protected $redisResultWaitingKey, $redisResultEngineList, $redisEngineResult, $redisCurrentResultList;
68

69
    public function __construct($hash = "")
70
    {
71
        # Timer starten
72
        $this->starttime = microtime(true);
73
        # Versuchen Blacklists einzulesen
74
        if (file_exists(config_path() . "/blacklistDomains.txt") && file_exists(config_path() . "/blacklistUrl.txt")) {
75
            $tmp = file_get_contents(config_path() . "/blacklistDomains.txt");
76
            $this->domainsBlacklisted = explode("\n", $tmp);
77
78
            $tmp = file_get_contents(config_path() . "/blacklistUrl.txt");
            $this->urlsBlacklisted = explode("\n", $tmp);
79
        } else {
80
            Log::warning("Achtung: Eine, oder mehrere Blacklist Dateien, konnten nicht geöffnet werden");
81
82
        }

83
        # Parser Skripte einhängen
84
85
86
87
        $dir = app_path() . "/Models/parserSkripte/";
        foreach (scandir($dir) as $filename) {
            $path = $dir . $filename;
            if (is_file($path)) {
88
                require_once $path;
89
90
91
            }
        }

92
        # Cachebarkeit testen
93
94
95
96
97
98
        try {
            Cache::has('test');
            $this->canCache = true;
        } catch (ConnectionException $e) {
            $this->canCache = false;
        }
99
100
101
102
103
        if ($hash === "") {
            $this->searchUid = md5(uniqid());
        } else {
            $this->searchUid = $hash;
        }
104
105
106
107
108
109
110
        $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.";
111
112
113
        # A list of all search results already delivered to the user (sorted of course)
        $this->redisCurrentResultList = $redisPrefix . "." . $this->searchUid . ".currentResults";

114
    }
115

116
    # Erstellt aus den gesammelten Ergebnissen den View
117
    public function createView($quicktipResults = [])
118
    {
119
120
        # 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
121

122
        foreach ($this->request->all() as $key => $value) {
123
124
            if (starts_with($key, 'engine_') && $value === 'on') {
                $focusPages[] = $key;
125
126
127
            }
        }

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

Phil Höfer's avatar
Phil Höfer committed
238
    public function prepareResults()
239
    {
Phil Höfer's avatar
Phil Höfer committed
240
241
        $engines = $this->engines;
        // combine
242
        $this->combineResults($engines);
Phil Höfer's avatar
Phil Höfer committed
243
        // misc (WiP)
244
        if ($this->fokus == "nachrichten") {
245
246
247
            $this->results = array_filter($this->results, function ($v, $k) {
                return !is_null($v->getRank());
            }, ARRAY_FILTER_USE_BOTH);
248
249
250
251
252
253
254
255
256
257
            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;
                }
258

259
260
261
                return ($a->getRank() < $b->getRank()) ? 1 : -1;
            });
        }
262

263
264
        # Validate Results
        $newResults = [];
265
266
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
267
                $newResults[] = $result;
268
269
            }

270
271
272
        }
        $this->results = $newResults;

273
        #Adgoal Implementation
274
275
276
        if (!$this->apiAuthorized) {
            $this->results = $this->parseAdgoal($this->results);
        }
277

Dominik Hebeler's avatar
Dominik Hebeler committed
278
279
        # Human Verification
        $this->results = $this->humanVerification($this->results);
280
        $this->ads = $this->humanVerification($this->ads);
Dominik Hebeler's avatar
Dominik Hebeler committed
281

282
        $counter = 0;
283
        $firstRank = 0;
284

285
        if (count($this->results) <= 0) {
286
287
288
289
290
291
            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');
            }
292
        }
293

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

305
    }
306

Phil Höfer's avatar
Phil Höfer committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
    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;
            }
        }
    }

327
328
    public function parseAdgoal($results)
    {
329
        $publicKey = getenv('adgoal_public');
330
        $privateKey = getenv('adgoal_private');
331
        if ($publicKey === false) {
332
333
334
            return $results;
        }
        $tldList = "";
335
336
        try {
            foreach ($results as $result) {
337
338
339
                if (!$result->new) {
                    continue;
                }
340
                $link = $result->anzeigeLink;
341
                if (strpos($link, "http") !== 0) {
342
343
344
345
346
347
348
349
350
351
                    $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");

352
            # Query
353
354
            $query = urlencode($this->q);

355
            $link = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
356
357
358
            $answer = json_decode(file_get_contents($link));

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

363
                foreach ($results as $result) {
364
                    if ($result->new && $hoster === $result->tld && !$result->partnershop) {
365
366
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
367
                        if ($result->image !== "") {
368
                            $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
369
                        } else {
370
                            $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
371
372
                        }

373
374
375
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
                        $targetUrl = $result->anzeigeLink;
376
                        if (strpos($targetUrl, "http") !== 0) {
377
                            $targetUrl = "http://" . $targetUrl;
378
379
                        }

380
381
382
                        $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;
383
384
385
386
                        $result->partnershop = true;
                    }
                }
            }
387
        } catch (\ErrorException $e) {
388
389
390
391
392
            return $results;
        }

        return $results;
    }
393

394
395
    public function humanVerification($results)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
396
        # Let's check if we need to implement a redirect for human verification
397
398
        if ($this->verificationCount > 10) {
            foreach ($results as $result) {
Dominik Hebeler's avatar
Dominik Hebeler committed
399
400
401
                $link = $result->link;
                $day = Carbon::now()->day;
                $pw = md5($this->verificationId . $day . $link . env("PROXY_PASSWORD"));
402
403
404
                $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
405
                $result->link = $url;
406
                $result->proxyLink = $proxyUrl;
Dominik Hebeler's avatar
Dominik Hebeler committed
407
408
            }
            return $results;
409
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
410
411
412
413
            return $results;
        }
    }

Phil Höfer's avatar
Phil Höfer committed
414
415
416
417
418
419
    public function authorize($key)
    {
        $postdata = http_build_query(array(
            'dummy' => rand(),
        ));
        $opts = array('http' => array(
420
421
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
Phil Höfer's avatar
Phil Höfer committed
422
423
424
425
426
427
428
            'content' => $postdata,
        ),
        );

        $context = stream_context_create($opts);

        try {
429
            $link = "https://key.metager3.de/" . urlencode($key) . "/request-permission/api-access";
Phil Höfer's avatar
Phil Höfer committed
430
431
432
433
434
435
436
437
438
439
440
441
            $result = json_decode(file_get_contents($link, false, $context));
            if ($result->{'api-access'} == true) {
                return true;
            } else {
                return false;
            }

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

442
443
    public function createQuicktips()
    {
444
        # Die quicktips werden als job erstellt und zur Abarbeitung freigegeben
445
        $quicktips = new \App\Models\Quicktips\Quicktips($this->q, LaravelLocalization::getCurrentLocale(), $this->getTime());
446
447
448
        return $quicktips;
    }

Karl's avatar
Karl committed
449
450
451
452
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

453
454
    public function createSearchEngines(Request $request)
    {
455
        # Wenn es kein Suchwort gibt
Dominik Hebeler's avatar
Dominik Hebeler committed
456
        if (!$request->filled("eingabe") || $this->q === "") {
457
            return;
458
        }
459

Dominik Hebeler's avatar
Dominik Hebeler committed
460
        $this->enabledSearchengines = [];
461
        $overtureEnabled = false;
462

463
464
465
        # Check if selected focus is valid
        if (empty($this->sumaFile->foki->{$this->fokus})) {
            $this->fokus = "web";
466
        }
467
468
469
470
471
472
473
474
475
476
477
478
479
480

        $sumaList = $this->sumaFile->foki->{$this->fokus}->sumas;

        # If the user is authorized to use adfree search we won't activate yahoo or yahoo-ads
        if ($this->apiAuthorized && ($key = array_search("yahoo", $sumaList)) !== false) {
            unset($sumaList[$key]);
            if ($this->fokus === "web") {
                $this->sumaFile->sumas->{"bing"}->{"filter-opt-in"} = false;
            }
        } elseif ($this->apiAuthorized && ($key = array_search("yahoo-ads", $sumaList)) !== false) {
            unset($sumaList[$key]);
        }

        foreach ($sumaList as $suma) {
481
            # Check if this engine is disabled and can't be used
482
            $disabled = empty($this->sumaFile->sumas->{$suma}->disabled) ? false : $this->sumaFile->sumas->{$suma}->disabled;
483
            $autoDisabled = empty($this->sumaFile->sumas->{$suma}->{"auto-disabled"}) ? false : $this->sumaFile->sumas->{$suma}->{"auto-disabled"};
484
485
486
            if ($disabled || $autoDisabled
                || \Cookie::get($this->getFokus() . "_engine_" . $suma) === "off") { # Check if the user has disabled this engine
            continue;
487
            }
488
489
490
            # Check if this engine can use eventually defined query-filter
            $valid = true;
            foreach ($this->queryFilter as $queryFilter => $filter) {
Dominik Hebeler's avatar
Dominik Hebeler committed
491
                if (empty($this->sumaFile->filter->{"query-filter"}->$queryFilter->sumas->$suma)) {
492
493
                    $valid = false;
                    break;
Dominik Hebeler's avatar
Dominik Hebeler committed
494
495
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
496
497
498
            # Check if this engine can use eventually defined parameter-filter
            if ($valid) {
                foreach ($this->parameterFilter as $filterName => $filter) {
499
                    # We need to check if the searchengine supports the parameter value, too
500
                    if (empty($filter->sumas->$suma) || empty($filter->sumas->{$suma}->values->{$filter->value})) {
Dominik Hebeler's avatar
Dominik Hebeler committed
501
502
503
504
505
                        $valid = false;
                        break;
                    }
                }
            }
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
            # Check if this engine should only be active when filter is used
            if ($this->sumaFile->sumas->{$suma}->{"filter-opt-in"}) {
                # This search engine should only be used when a parameter filter of it is used
                $validTmp = false;
                foreach ($this->parameterFilter as $filterName => $filter) {
                    if (!empty($filter->sumas->{$suma})) {
                        $validTmp = true;
                        break;
                    }
                }
                if (!$validTmp) {
                    $valid = false;
                }

            }
521
522
            # If it can we add it
            if ($valid) {
Dominik Hebeler's avatar
Dominik Hebeler committed
523
                $this->enabledSearchengines[$suma] = $this->sumaFile->sumas->{$suma};
524
            }
525

526
        }
527
        # Implements Yahoo Ads if Yahoo is not enabled as a searchengine
528
        if (!$this->apiAuthorized && empty($this->enabledSearchengines["yahoo"]) && $this->fokus != "bilder" && !empty($this->sumaFile->sumas->{"yahoo-ads"})) {
529
530
531
            $this->enabledSearchengines["yahoo-ads"] = $this->sumaFile->sumas->{"yahoo-ads"};
        }

532
533
534
535
536
537
        # 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
        if ($this->getFokus() === "web" && empty($this->enabledSearchengines["yahoo"]) && \Cookie::get("web_engine_bing") !== "off") {
            $this->enabledSearchengines["bing"] = $this->sumaFile->sumas->{"bing"};
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
538
        if (sizeof($this->enabledSearchengines) === 0) {
539
540
            $filter = "";
            foreach ($this->queryFilter as $queryFilter => $filterPhrase) {
Dominik Hebeler's avatar
Dominik Hebeler committed
541
                $filter .= trans($this->sumaFile->filter->{"query-filter"}->{$queryFilter}->name) . ",";
542
543
544
545
546
            }
            $filter = rtrim($filter, ",");
            $error = trans('metaGer.engines.noSpecialSearch', ['fokus' => trans($this->sumaFile->foki->{$this->fokus}->{"display-name"}),
                'filter' => $filter]);
            $this->errors[] = $error;
547
        }
548
        $engines = [];
549
        $typeslist = [];
550
        $counter = 0;
551
552
        $this->setEngines($request);
    }
553

554
555
    public function setEngines(Request $request, $enabledSearchengines = [])
    {
556
        if ($this->requestIsCached($request)) {
557
            # If this is a page other than 1 the request is "cached"
558
            $engines = $this->getCachedEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
559
            # We need to edit some Options of the Cached Search Engines
Phil Höfer's avatar
Phil Höfer committed
560
            foreach ($engines as $engine) {
561
                $engine->setResultHash($this->getSearchUid());
Dominik Hebeler's avatar
Dominik Hebeler committed
562
            }
563
            $this->engines = $engines;
564
        } else {
565
566
567
            if (sizeof($enabledSearchengines) > 0) {
                $this->enabledSearchengines = $enabledSearchengines;
            }
568
            $this->actuallyCreateSearchEngines($this->enabledSearchengines);
569
        }
570
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
571

572
573
    public function startSearch()
    {
574
        # Wir starten alle Suchen
575
        foreach ($this->engines as $engine) {
576
            $engine->startSearch($this);
577
        }
578
579
    }

580
581
    # Spezielle Suchen und Sumas

582
    public function sumaIsSelected($suma, $request, $custom)
583
    {
584
        if ($custom) {
585
            if ($request->filled("engine_" . strtolower($suma["name"]))) {
586
587
588
589
590
591
592
593
594
595
596
                return true;
            }
        } else {
            $types = explode(",", $suma["type"]);
            if (in_array($this->fokus, $types)) {
                return true;
            }
        }
        return false;
    }

597
    public function actuallyCreateSearchEngines($enabledSearchengines)
598
599
    {
        $engines = [];
600
        foreach ($enabledSearchengines as $engineName => $engine) {
601

602
            if (!isset($engine->{"parser-class"})) {
Dominik Hebeler's avatar
Dominik Hebeler committed
603
604
                die(var_dump($engine));
            }
605
            # Setze Pfad zu Parser
606
            $path = "App\\Models\\parserSkripte\\" . $engine->{"parser-class"};
607
608

            # Prüfe ob Parser vorhanden
609
610
611
            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"}]);
612
613
614
615
616
617
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
618
                $tmp = new $path($engineName, $engine, $this);
619
            } catch (\ErrorException $e) {
620
                Log::error("Konnte " . $engine->{"display-name"} . " nicht abfragen. " . var_dump($e));
621
622
623
                continue;
            }

624
            $engines[] = $tmp;
625
        }
626
        $this->engines = $engines;
627
628
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
629
630
631
632
633
634
635
    public function getAvailableParameterFilter()
    {
        $parameterFilter = $this->sumaFile->filter->{"parameter-filter"};

        $availableFilter = [];

        foreach ($parameterFilter as $filterName => $filter) {
636
            $values = $filter->values;
Dominik Hebeler's avatar
Dominik Hebeler committed
637
638
639
            # Check if any of the enabled search engines provide this filter
            foreach ($this->enabledSearchengines as $engineName => $engine) {
                if (!empty($filter->sumas->$engineName)) {
640
641
642
643
644
645
646
647
648
649
                    if (empty($availableFilter[$filterName])) {
                        $availableFilter[$filterName] = $filter;
                        unset($availableFilter[$filterName]->values);
                    }
                    if (empty($availableFilter[$filterName]->values)) {
                        $availableFilter[$filterName]->values = (object) ["" => $values->{""}];
                    }
                    foreach ($filter->sumas->{$engineName}->values as $key => $value) {
                        $availableFilter[$filterName]->values->$key = $values->$key;
                    }
Dominik Hebeler's avatar
Dominik Hebeler committed
650
651
                }
            }
652
653
            # 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) {
654
                if ($this->sumaFile->sumas->{$suma}->{"filter-opt-in"} && \Cookie::get($this->getFokus() . "_engine_" . $suma) !== "off") {
655
                    if (!empty($filter->sumas->{$suma})) {
656
657
658
659
660
                        # If the searchengine is disabled this filter shouldn't be available
                        if ((!empty($this->sumaFile->sumas->{$suma}->disabled) && $this->sumaFile->sumas->{$suma}->disabled === true)
                            || (!empty($this->sumaFile->sumas->{$suma}->{"auto-disabled"}) && $this->sumaFile->sumas->{$suma}->{"auto-disabled"} === true)) {
                            continue;
                        }
661
662
663
664
665
666
667
668
669
670
                        if (empty($availableFilter[$filterName])) {
                            $availableFilter[$filterName] = $filter;
                            unset($availableFilter[$filterName]->values);
                        }
                        if (empty($availableFilter[$filterName]->values)) {
                            $availableFilter[$filterName]->values = (object) ["" => $values->{""}];
                        }
                        foreach ($filter->sumas->{$suma}->values as $key => $value) {
                            $availableFilter[$filterName]->values->$key = $values->$key;
                        }
671
672
673
                    }
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
674
675
        }

676
677
678
679
680
681
682
683
684
        # 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"});
            } else if (\Cookie::get($this->getFokus() . "_setting_" . $filter->{"get-parameter"}) !== null) {
                $filter->value = \Cookie::get($this->getFokus() . "_setting_" . $filter->{"get-parameter"});
            }
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
685
686
687
        return $availableFilter;
    }

688
689
    public function isBildersuche()
    {
690
        return $this->fokus === "bilder";
691
692
693
694
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
695
        $sumaName = $suma["name"]->__toString();
696
        return
697
698
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
Karl Hasselbring's avatar
Karl Hasselbring committed
699
            || (!$overtureEnabled && $sumaName === "overtureAds");
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
    }

    public function sumaIsDisabled($suma)
    {
        return
        isset($suma['disabled'])
        && $suma['disabled']->__toString() === "1";
    }

    public function sumaIsOverture($suma)
    {
        return
        $suma["name"]->__toString() === "overture"
        || $suma["name"]->__toString() === "overtureAds";
    }

    public function sumaIsNotAdsuche($suma)
    {
        return
        $suma["name"]->__toString() !== "qualigo"
        && $suma["name"]->__toString() !== "similar_product_ads"
        && $suma["name"]->__toString() !== "overtureAds";
    }

    public function requestIsCached($request)
    {
        return
Dominik Hebeler's avatar
Dominik Hebeler committed
727
        $request->filled('next')
728
729
730
731
732
733
        && Cache::has($request->input('next'))
        && unserialize(Cache::get($request->input('next')))['page'] > 1;
    }

    public function getCachedEngines($request)
    {
734
        $next = unserialize(Cache::get($request->input('next')));
735
        $this->page = $next['page'];
736
        $engines = $next['engines'];
737
738
739
        return $engines;
    }

740
    public function waitForMainResults()
741
    {
742
        $redis = Redis::connection(env('REDIS_RESULT_CONNECTION'));
743
        $engines = $this->engines;
744
        $enginesToWaitFor = [];
745
746
747
748
749
750
        $mainEngines = $this->sumaFile->foki->{$this->fokus}->main;
        foreach ($mainEngines as $mainEngine) {
            foreach ($engines as $engine) {
                if (!$engine->cached && $engine->name === $mainEngine) {
                    $enginesToWaitFor[] = $engine;
                }
751
752
            }
        }
753

Phil Höfer's avatar
Phil Höfer committed
754
        $timeStart = microtime(true);
755
        $answered = [];
756
        $results = null;
757
758
759
760
761
762
763
764
765

        # If there is no main searchengine to wait for or if the only main engine is yahoo-ads we will define a timeout of 1s
        $forceTimeout = null;
        if (sizeof($enginesToWaitFor) === 0 || (sizeof($enginesToWaitFor) === 1 && $enginesToWaitFor[0]->name === "yahoo-ads")) {
            $forceTimeout = 1;
        }

        while (sizeof($enginesToWaitFor) > 0 || ($forceTimeout !== null && (microtime(true) - $timeStart) < $forceTimeout)) {
            $newEngine = $redis->blpop($this->redisResultWaitingKey, 1);
766
767
768
769
770
771
772
773
774
            if ($newEngine === null || sizeof($newEngine) !== 2) {
                continue;
            } else {
                $newEngine = $newEngine[1];
                foreach ($enginesToWaitFor as $index => $engine) {
                    if ($engine->name === $newEngine) {
                        unset($enginesToWaitFor[$index]);
                        break;
                    }
775
                }
776
                $answered[] = $newEngine;
777
            }
778
            if ((microtime(true) - $timeStart) >= 2) {
779
780
                break;
            }
781
        }
782
783

        # Now we can add an entry to Redis which defines the starting time and how many engines should answer this request
784

785
786
787
788
        $pipeline = $redis->pipeline();
        $pipeline->hset($this->getRedisEngineResult() . "status", "startTime", $timeStart);
        $pipeline->hset($this->getRedisEngineResult() . "status", "engineCount", sizeof($engines));
        $pipeline->hset($this->getRedisEngineResult() . "status", "engineDelivered", sizeof($answered));
789
790
791
792
793
794
795
        # Add the cached engines as answered
        foreach ($engines as $engine) {
            if ($engine->cached) {
                $pipeline->hincrby($this->getRedisEngineResult() . "status", "engineDelivered", 1);
                $pipeline->hincrby($this->getRedisEngineResult() . "status", "engineAnswered", 1);
            }
        }
796
797
798
799
800
        foreach ($answered as $engine) {
            $pipeline->hset($this->getRedisEngineResult() . $engine, "delivered", "1");
        }
        $pipeline->execute();

801
    }
802

803
    public function retrieveResults()
804
    {
805
        $engines = $this->engines;
806
        # Von geladenen Engines die Ergebnisse holen
807
808
809
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
810
                    $engine->retrieveResults($this);
811
                } catch (\ErrorException $e) {
812
813
814
                    Log::error($e);
                }
            }
815
816
817
            if (!empty($engine->totalResults) && $engine->totalResults > $this->totalResults) {
                $this->totalResults = $engine->totalResults;
            }
818
819
820
821
            if (!empty($engine->alteredQuery) && !empty($engine->alterationOverrideQuery)) {
                $this->alteredQuery = $engine->alteredQuery;
                $this->alterationOverrideQuery = $engine->alterationOverrideQuery;
            }
822
        }
823
824
    }

825
826
827
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
828

829
830
    public function parseFormData(Request $request)
    {
831

832
        # Sichert, dass der request in UTF-8 formatiert ist
833
        if ($request->input('encoding', 'utf8') !== "utf8") {
834
835
836
837
838
839
840
            # 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);
        }
841
        $this->url = $request->url();
842
        $this->fullUrl = $request->fullUrl();
843
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
844
        # Fokus
845
        $this->fokus = $request->input('focus', 'web');
846
        # Suma-File
847
        if (App::isLocale("en")) {
848
            $this->sumaFile = config_path() . "/sumasEn.json";
849
        } else {
850
            $this->sumaFile = config_path() . "/sumas.json";
851
        }
852
        if (!file_exists($this->sumaFile)) {
853
            die(trans('metaGer.formdata.cantLoad'));
854
855
        } else {
            $this->sumaFile = json_decode(file_get_contents($this->sumaFile));
856
        }
857
        # Sucheingabe
858
        $this->eingabe = trim($request->input('eingabe', ''));
859
        $this->q = $this->eingabe;
860
        # IP
861
        $this->ip = $this->anonymizeIp($request->ip());
862

Dominik Hebeler's avatar
Dominik Hebeler committed
863
864
        $this->useragent = $request->header('User-Agent');

865
        # Language
866
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
867
            $this->language = $_SERVER['HTTP_LANGUAGE'];
868
        } else {
869
870
            $this->language = "";
        }
871

872
        # Page
873
        $this->page = 1;
874
875
        # Lang
        $this->lang = $request->input('lang', 'all');
876
877
        if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
            $this->lang = "all";
878
        }