MetaGer.php 56.3 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 210 211
                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
212
                case 'atom10':
213
                    return response()->view('resultpages.metager3resultsatom10', ['results' => $viewResults, 'eingabe' => $this->eingabe, 'metager' => $this, 'resultcount' => sizeof($viewResults), '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 484
            $autoDisabled = empty($this->sumaFile->sumas->{$suma}->{"auto-disabled"}) ? false : $this->sumaFile->sumas->{$suma}->{"auto-disabled"};
            if ($disabled || $autoDisabled) {
485
                continue;
486 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 500 501
                    # 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
502 503 504 505 506
                        $valid = false;
                        break;
                    }
                }
            }
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
            # 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;
                }

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

527
        }
528

529 530 531 532 533
        # 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
534
        if (sizeof($this->enabledSearchengines) === 0) {
535 536
            $filter = "";
            foreach ($this->queryFilter as $queryFilter => $filterPhrase) {
Dominik Hebeler's avatar
Dominik Hebeler committed
537
                $filter .= trans($this->sumaFile->filter->{"query-filter"}->{$queryFilter}->name) . ",";
538 539 540 541 542
            }
            $filter = rtrim($filter, ",");
            $error = trans('metaGer.engines.noSpecialSearch', ['fokus' => trans($this->sumaFile->foki->{$this->fokus}->{"display-name"}),
                'filter' => $filter]);
            $this->errors[] = $error;
543
        }
544
        $engines = [];
545
        $typeslist = [];
546
        $counter = 0;
547 548
        $this->setEngines($request);
    }
549

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

568 569
    public function startSearch()
    {
570
        # Wir starten alle Suchen
571
        foreach ($this->engines as $engine) {
572
            $engine->startSearch($this);
573
        }
574 575
    }

576 577
    # Spezielle Suchen und Sumas

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

593
    public function actuallyCreateSearchEngines($enabledSearchengines)
594 595
    {
        $engines = [];
596
        foreach ($enabledSearchengines as $engineName => $engine) {
597

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

            # Prüfe ob Parser vorhanden
605 606 607
            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"}]);
608 609 610 611 612 613
                continue;
            }

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

620
            $engines[] = $tmp;
621
        }
622
        $this->engines = $engines;
623 624
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
625 626 627 628 629 630 631 632 633 634 635 636 637
    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;
                }
            }
638 639 640 641
            # 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})) {
642 643 644 645 646
                        # 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;
                        }
647 648 649 650
                        $availableFilter[$filterName] = $filter;
                    }
                }
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
651 652 653 654 655
        }

        return $availableFilter;
    }

656 657
    public function isBildersuche()
    {
658
        return $this->fokus === "bilder";
659 660 661 662
    }

    public function sumaIsAdsuche($suma, $overtureEnabled)
    {
663
        $sumaName = $suma["name"]->__toString();
664
        return
665 666
            $sumaName === "qualigo"
            || $sumaName === "similar_product_ads"
Karl Hasselbring's avatar
Karl Hasselbring committed
667
            || (!$overtureEnabled && $sumaName === "overtureAds");
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    }

    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
695
        $request->filled('next')
696 697 698 699 700 701
        && Cache::has($request->input('next'))
        && unserialize(Cache::get($request->input('next')))['page'] > 1;
    }

    public function getCachedEngines($request)
    {
702
        $next = unserialize(Cache::get($request->input('next')));
703
        $this->page = $next['page'];
704
        $engines = $next['engines'];
705 706 707
        return $engines;
    }

708
    public function waitForMainResults()
709
    {
710
        $redis = Redis::connection(env('REDIS_RESULT_CONNECTION'));
711
        $engines = $this->engines;
712
        $enginesToWaitFor = [];
713 714 715 716 717 718
        $mainEngines = $this->sumaFile->foki->{$this->fokus}->main;
        foreach ($mainEngines as $mainEngine) {
            foreach ($engines as $engine) {
                if (!$engine->cached && $engine->name === $mainEngine) {
                    $enginesToWaitFor[] = $engine;
                }
719 720
            }
        }
721

Phil Höfer's avatar
Phil Höfer committed
722
        $timeStart = microtime(true);
723
        $answered = [];
724
        $results = null;
725 726 727 728 729 730 731 732 733

        # 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);
734 735 736 737 738 739 740 741 742
            if ($newEngine === null || sizeof($newEngine) !== 2) {
                continue;
            } else {
                $newEngine = $newEngine[1];
                foreach ($enginesToWaitFor as $index => $engine) {
                    if ($engine->name === $newEngine) {
                        unset($enginesToWaitFor[$index]);
                        break;
                    }
743
                }
744
                $answered[] = $newEngine;
745
            }
746
            if ((microtime(true) - $timeStart) >= 2) {
747 748
                break;
            }
749
        }
750 751

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

753 754 755 756
        $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));
757 758 759 760 761 762 763
        # 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);
            }
        }
764 765 766 767 768
        foreach ($answered as $engine) {
            $pipeline->hset($this->getRedisEngineResult() . $engine, "delivered", "1");
        }
        $pipeline->execute();

769
    }
770

771
    public function retrieveResults()
772
    {
773
        $engines = $this->engines;
774
        # Von geladenen Engines die Ergebnisse holen
775 776 777
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
778
                    $engine->retrieveResults($this);
779
                } catch (\ErrorException $e) {
780 781 782
                    Log::error($e);
                }
            }
783 784 785
            if (!empty($engine->totalResults) && $engine->totalResults > $this->totalResults) {
                $this->totalResults = $engine->totalResults;
            }
786 787 788 789
            if (!empty($engine->alteredQuery) && !empty($engine->alterationOverrideQuery)) {
                $this->alteredQuery = $engine->alteredQuery;
                $this->alterationOverrideQuery = $engine->alterationOverrideQuery;
            }
790
        }
791 792
    }

793 794 795
/*
 * Ende Suchmaschinenerstellung und Ergebniserhalt
 */
Karl's avatar
Karl committed
796

797 798
    public function parseFormData(Request $request)
    {
799

800
        # Sichert, dass der request in UTF-8 formatiert ist
801
        if ($request->input('encoding', 'utf8') !== "utf8") {
802 803 804 805 806 807 808
            # 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);
        }
809
        $this->url = $request->url();
810
        $this->fullUrl = $request->fullUrl();
811
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
812
        # Fokus
813
        $this->fokus = $request->input('focus', 'web');
814
        # Suma-File
815
        if (App::isLocale("en")) {
816
            $this->sumaFile = config_path() . "/sumasEn.json";
817
        } else {
818
            $this->sumaFile = config_path() . "/sumas.json";
819
        }
820
        if (!file_exists($this->sumaFile)) {
821
            die(trans('metaGer.formdata.cantLoad'));
822 823
        } else {
            $this->sumaFile = json_decode(file_get_contents($this->sumaFile));
824
        }
825
        # Sucheingabe
826
        $this->eingabe = trim($request->input('eingabe', ''));
827
        $this->q = $this->eingabe;
828
        # IP
829
        $this->ip = $this->anonymizeIp($request->ip());
830

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

833
        # Language
834
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
835
            $this->language = $_SERVER['HTTP_LANGUAGE'];
836
        } else {
837 838
            $this->language = "";
        }
839

840
        # Page
841
        $this->page = 1;
842 843
        # Lang
        $this->lang = $request->input('lang', 'all');
844 845
        if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
            $this->lang = "all";
846
        }