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

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

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

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

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

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

111
    }
112

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

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

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

Phil Höfer's avatar
Phil Höfer committed
235
    public function prepareResults()
236
    {
Phil Höfer's avatar
Phil Höfer committed
237
        $engines = $this->engines;
238

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

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

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

268 269 270
        }
        $this->results = $newResults;

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

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

280
        $counter = 0;
281
        $firstRank = 0;
282

283
        if (isset($this->startForwards)) {
284
            $this->startCount = $this->startForwards;
285
        } elseif (isset($this->startBackwards)) {
286
            $this->startCount = $this->startBackwards - count($this->results) - 1;
287
        } else {
288 289 290
            $this->startCount = 0;
        }

291
        if (count($this->results) <= 0) {
292 293 294 295 296 297
            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');
            }
298
        }
299

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

312
    }
313

Phil Höfer's avatar
Phil Höfer committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    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;
            }
        }
    }

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

359
            # Query
360 361
            $query = urlencode($this->q);

362
            $link = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
363 364 365
            $answer = json_decode(file_get_contents($link));

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

370
                foreach ($results as $result) {
371
                    if ($result->new && $hoster === $result->tld && !$result->partnershop) {
372 373
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
374
                        if ($result->image !== "") {
375
                            $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
376
                        } else {
377
                            $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
378 379
                        }

380 381 382
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
                        $targetUrl = $result->anzeigeLink;
383
                        if (strpos($targetUrl, "http") !== 0) {
384
                            $targetUrl = "http://" . $targetUrl;
385 386
                        }

387 388 389
                        $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;
390 391 392 393
                        $result->partnershop = true;
                    }
                }
            }
394
        } catch (\ErrorException $e) {
395 396 397 398 399
            return $results;
        }

        return $results;
    }
400

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

Phil Höfer's avatar
Phil Höfer committed
421 422 423 424 425 426
    public function authorize($key)
    {
        $postdata = http_build_query(array(
            'dummy' => rand(),
        ));
        $opts = array('http' => array(
427 428
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
Phil Höfer's avatar
Phil Höfer committed
429 430 431 432 433 434 435
            'content' => $postdata,
        ),
        );

        $context = stream_context_create($opts);

        try {
436
            $link = "https://key.metager3.de/" . urlencode($key) . "/request-permission/api-access";
Phil Höfer's avatar
Phil Höfer committed
437 438 439 440 441 442 443 444 445 446 447 448
            $result = json_decode(file_get_contents($link, false, $context));
            if ($result->{'api-access'} == true) {
                return true;
            } else {
                return false;
            }

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

449 450
    public function createQuicktips()
    {
451
        # Die quicktips werden als job erstellt und zur Abarbeitung freigegeben
452
        $quicktips = new \App\Models\Quicktips\Quicktips($this->q, $this->lang, $this->getTime());
453 454 455
        return $quicktips;
    }

Karl's avatar
Karl committed
456 457 458 459
    /*
     * Die Erstellung der Suchmaschinen bis die Ergebnisse da sind mit Unterfunktionen
     */

460 461
    public function createSearchEngines(Request $request)
    {
462
        # Wenn es kein Suchwort gibt
Dominik Hebeler's avatar
Dominik Hebeler committed
463
        if (!$request->filled("eingabe") || $this->q === "") {
464
            return;
465
        }
466

Dominik Hebeler's avatar
Dominik Hebeler committed
467
        $this->enabledSearchengines = [];
468
        $overtureEnabled = false;
469

470 471 472
        # Check if selected focus is valid
        if (empty($this->sumaFile->foki->{$this->fokus})) {
            $this->fokus = "web";
473
        }
474 475
        foreach ($this->sumaFile->foki->{$this->fokus}->sumas as $suma) {
            # Check if this engine is disabled and can't be used
476
            $disabled = empty($this->sumaFile->sumas->{$suma}->disabled) ? false : $this->sumaFile->sumas->{$suma}->disabled;
477 478
            $autoDisabled = empty($this->sumaFile->sumas->{$suma}->{"auto-disabled"}) ? false : $this->sumaFile->sumas->{$suma}->{"auto-disabled"};
            if ($disabled || $autoDisabled) {
479
                continue;
480 481
            }

482 483 484
            # 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
485
                if (empty($this->sumaFile->filter->{"query-filter"}->$queryFilter->sumas->$suma)) {
486 487
                    $valid = false;
                    break;
Dominik Hebeler's avatar
Dominik Hebeler committed
488 489
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
490 491 492
            # Check if this engine can use eventually defined parameter-filter
            if ($valid) {
                foreach ($this->parameterFilter as $filterName => $filter) {
493 494 495
                    # We need to check if the searchengine supports the parameter value, too
                    $value = $request->input($filter->{"get-parameter"}, "");
                    if (empty($filter->sumas->$suma) || empty($filter->sumas->{$suma}->values->{$value})) {
Dominik Hebeler's avatar
Dominik Hebeler committed
496 497 498 499 500
                        $valid = false;
                        break;
                    }
                }
            }
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
            # 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;
                }

            }
516 517
            # If it can we add it
            if ($valid) {
Dominik Hebeler's avatar
Dominik Hebeler committed
518
                $this->enabledSearchengines[$suma] = $this->sumaFile->sumas->{$suma};
519
            }
520

521
        }
522

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

Dominik Hebeler's avatar
Dominik Hebeler committed
528
        if (sizeof($this->enabledSearchengines) === 0) {
529 530
            $filter = "";
            foreach ($this->queryFilter as $queryFilter => $filterPhrase) {
Dominik Hebeler's avatar
Dominik Hebeler committed
531
                $filter .= trans($this->sumaFile->filter->{"query-filter"}->{$queryFilter}->name) . ",";
532 533 534 535 536
            }
            $filter = rtrim($filter, ",");
            $error = trans('metaGer.engines.noSpecialSearch', ['fokus' => trans($this->sumaFile->foki->{$this->fokus}->{"display-name"}),
                'filter' => $filter]);
            $this->errors[] = $error;
537
        }
538
        $engines = [];
539
        $typeslist = [];
540
        $counter = 0;
541

542
        if ($this->requestIsCached($request)) {
543
            # If this is a page other than 1 the request is "cached"
544
            $engines = $this->getCachedEngines($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
545
            # We need to edit some Options of the Cached Search Engines
Phil Höfer's avatar
Phil Höfer committed
546
            foreach ($engines as $engine) {
Dominik Hebeler's avatar
Dominik Hebeler committed
547 548
                $engine->setResultHash($this->getHashCode());
            }
549
        } else {
550
            $this->actuallyCreateSearchEngines($this->enabledSearchengines);
551
        }
552
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
553

554 555
    public function startSearch()
    {
556
        # Wir starten alle Suchen
557
        foreach ($this->engines as $engine) {
558
            $engine->startSearch($this);
559
        }
560 561
    }

562 563
    # Spezielle Suchen und Sumas

564
    public function sumaIsSelected($suma, $request, $custom)
565
    {
566
        if ($custom) {
567
            if ($request->filled("engine_" . strtolower($suma["name"]))) {
568 569 570 571 572 573 574 575 576 577 578
                return true;
            }
        } else {
            $types = explode(",", $suma["type"]);
            if (in_array($this->fokus, $types)) {
                return true;
            }
        }
        return false;
    }

579
    public function actuallyCreateSearchEngines($enabledSearchengines)
580 581
    {
        $engines = [];
582
        foreach ($enabledSearchengines as $engineName => $engine) {
583

584
            if (!isset($engine->{"parser-class"})) {
Dominik Hebeler's avatar
Dominik Hebeler committed
585 586
                die(var_dump($engine));
            }
587
            # Setze Pfad zu Parser
588
            $path = "App\\Models\\parserSkripte\\" . $engine->{"parser-class"};
589 590

            # Prüfe ob Parser vorhanden
591 592 593
            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"}]);
594 595 596 597 598 599
                continue;
            }

            # Es wird versucht die Suchengine zu erstellen
            $time = microtime();
            try {
600
                $tmp = new $path($engineName, $engine, $this);
601
            } catch (\ErrorException $e) {
602
                Log::error("Konnte " . $engine->{"display-name"} . " nicht abfragen. " . var_dump($e));
603 604 605
                continue;
            }

606
            $engines[] = $tmp;
607
        }
608
        $this->engines = $engines;
609 610
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
611 612 613 614 615 616 617 618 619 620 621 622 623
    public function getAvailableParameterFilter()
    {
        $parameterFilter = $this->sumaFile->filter->{"parameter-filter"};

        $availableFilter = [];

        foreach ($parameterFilter as $filterName => $filter) {
            # Check if any of the enabled search engines provide this filter
            foreach ($this->enabledSearchengines as $engineName => $engine) {
                if (!empty($filter->sumas->$engineName)) {
                    $availableFilter[$filterName] = $filter;
                }
            }
624 625 626 627
            # 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) {
                if ($this->sumaFile->sumas->{$suma}->{"filter-opt-in"}) {
                    if (!empty($filter->sumas->{$suma})) {
628 629 630 631 632
                        # 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;
                        }
633 634 635 636
                        $availableFilter[$filterName] = $filter;
                    }
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
637 638 639 640 641
        }

        return $availableFilter;
    }

642 643
    public function isBildersuche()
    {
644
        return $this->fokus === "bilder";
645 646 647 648
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
649
        $sumaName = $suma["name"]->__toString();
650
        return
651 652
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
Karl Hasselbring's avatar
Karl Hasselbring committed
653
            || (!$overtureEnabled && $sumaName === "overtureAds");
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
    }

    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
681
        $request->filled('next')
682 683 684 685 686 687
        && Cache::has($request->input('next'))
        && unserialize(Cache::get($request->input('next')))['page'] > 1;
    }

    public function getCachedEngines($request)
    {
688
        $next = unserialize(Cache::get($request->input('next')));
689
        $this->page = $next['page'];
690
        $engines = $next['engines'];
691 692 693 694 695 696 697 698 699
        if (isset($next['startForwards'])) {
            $this->startForwards = $next['startForwards'];
        }
        if (isset($next['startBackwards'])) {
            $this->startBackwards = $next['startBackwards'];
        }
        return $engines;
    }

700
    public function waitForMainResults()
701
    {
702
        $engines = $this->engines;
703 704 705 706
        $enginesToWaitFor = [];
        foreach ($engines as $engine) {
            if ($engine->cached || !isset($engine->engine->main) || !$engine->engine->main) {
                continue;
707
            }
708
            $enginesToWaitFor[] = $engine;
709
        }
710

Phil Höfer's avatar
Phil Höfer committed
711
        $timeStart = microtime(true);
712
        $answered = [];
713
        $results = null;
714 715 716 717 718 719 720 721 722 723 724
        while (sizeof($enginesToWaitFor) > 0) {
            $newEngine = Redis::blpop($this->redisResultWaitingKey, 5);
            if ($newEngine === null || sizeof($newEngine) !== 2) {
                continue;
            } else {
                $newEngine = $newEngine[1];
                foreach ($enginesToWaitFor as $index => $engine) {
                    if ($engine->name === $newEngine) {
                        unset($enginesToWaitFor[$index]);
                        break;
                    }
725
                }
726
                $answered[] = $newEngine;
727
            }
728
            if ((microtime(true) - $timeStart) >= 2) {
729 730
                break;
            }
731
        }
732 733 734 735 736 737 738 739 740 741 742 743

        # Now we can add an entry to Redis which defines the starting time and how many engines should answer this request
        $redis = Redis::connection(env('REDIS_RESULT_CONNECTION'));
        $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));
        foreach ($answered as $engine) {
            $pipeline->hset($this->getRedisEngineResult() . $engine, "delivered", "1");
        }
        $pipeline->execute();

744
    }
745

746
    public function retrieveResults()
747
    {
748
        $engines = $this->engines;
749
        # Von geladenen Engines die Ergebnisse holen
750 751 752
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
753
                    $engine->retrieveResults($this);
754
                } catch (\ErrorException $e) {
755 756 757
                    Log::error($e);
                }
            }
758 759 760
            if (!empty($engine->totalResults) && $engine->totalResults > $this->totalResults) {
                $this->totalResults = $engine->totalResults;
            }
761
        }
762 763
    }

764 765 766
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
767

768 769
    public function parseFormData(Request $request)
    {
770

771
        # Sichert, dass der request in UTF-8 formatiert ist
772
        if ($request->input('encoding', 'utf8') !== "utf8") {
773 774 775 776 777 778 779
            # 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);
        }
780
        $this->url = $request->url();
781
        $this->fullUrl = $request->fullUrl();
782
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
783
        # Fokus
784
        $this->fokus = $request->input('focus', 'web');
785
        # Suma-File
786
        if (App::isLocale("en")) {
787
            $this->sumaFile = config_path() . "/sumasEn.json";
788
        } else {
789
            $this->sumaFile = config_path() . "/sumas.json";
790
        }
791
        if (!file_exists($this->sumaFile)) {
792
            die(trans('metaGer.formdata.cantLoad'));
793 794
        } else {
            $this->sumaFile = json_decode(file_get_contents($this->sumaFile));
795
        }
796
        # Sucheingabe
797
        $this->eingabe = trim($request->input('eingabe', ''));
798
        $this->q = $this->eingabe;
799
        # IP
800
        $this->ip = $request->ip();
801 802 803 804
        # Unser erster Schritt wird sein, IP-Adresse und USER-Agent zu anonymisieren, damit
        # nicht einmal wir selbst noch Zugriff auf die Daten haben:
        $this->ip = preg_replace("/(\d+)\.(\d+)\.\d+.\d+/s", "$1.$2.0.0", $this->ip);

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

807
        # Language
808
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
809
            $this->language = $_SERVER['HTTP_LANGUAGE'];
810
        } else {
811 812
            $this->language = "";
        }
813

814
        # Page
815
        $this->page = 1;
816 817
        # Lang
        $this->lang = $request->input('lang', 'all');
818 819
        if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
            $this->lang = "all";
820
        }
821

822
        $this->agent = new Agent();
823
        $this->mobile = $this->agent->isMobile();
824
        # Sprüche
825 826
        $this->sprueche = $request->input('sprueche', 'on');
        if ($this->sprueche === "on") {
827
            $this->sprueche = true;
828
        } else {
829
            $this->sprueche = false;
830
        }
831

832
        $this->newtab = $request->input('newtab', 'on');