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

use App;
5
use App\lib\TextLanguageDetect\TextLanguageDetect;
6
use Illuminate\Http\Request;
7 8
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
9
use Jenssegers\Agent\Agent;
Dominik Hebeler's avatar
Bugfix  
Dominik Hebeler committed
10
use LaravelLocalization;
11 12
use Log;
use Redis;
13 14 15

class MetaGer
{
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    # Einstellungen für die Suche
    protected $fokus;
    protected $eingabe;
    protected $q;
    protected $category;
    protected $time;
    protected $page;
    protected $lang;
    protected $cache = "";
    protected $site;
    protected $hostBlacklist   = [];
    protected $domainBlacklist = [];
    protected $stopWords       = [];
    protected $phrases         = [];
    protected $engines         = [];
    protected $results         = [];
    protected $ads             = [];
    protected $warnings        = [];
    protected $errors          = [];
    protected $addedHosts      = [];
    # Daten über die Abfrage
    protected $ip;
    protected $language;
    protected $agent;
    # Konfigurationseinstellungen:
    protected $sumaFile;
    protected $mobile;
    protected $resultCount;
    protected $sprueche;
45
    protected $domainsBlacklisted = [];
46
    protected $urlsBlacklisted    = [];
47 48 49
    protected $url;
    protected $languageDetect;

50 51 52 53
    public function __construct()
    {
        $this->starttime = microtime(true);
        if (file_exists(config_path() . "/blacklistDomains.txt") && file_exists(config_path() . "/blacklistUrl.txt")) {
54
            # Blacklists einlesen:
55
            $tmp                      = file_get_contents(config_path() . "/blacklistDomains.txt");
56
            $this->domainsBlacklisted = explode("\n", $tmp);
57 58 59
            $tmp                      = file_get_contents(config_path() . "/blacklistUrl.txt");
            $this->urlsBlacklisted    = explode("\n", $tmp);
        } else {
60 61 62 63 64
            Log::warning("Achtung: Eine, oder mehrere Blacklist Dateien, konnten nicht geöffnet werden");
        }

        $this->languageDetect = new TextLanguageDetect();
        $this->languageDetect->setNameMode("2");
65
    }
66

67
    public function getHashCode()
68 69 70 71 72
    {
        $string = url()->full();
        return md5($string);
    }

73
    public function rankAll()
74
    {
75
        foreach ($this->engines as $engine) {
76 77 78
            $engine->rank($this);
        }
    }
79

80 81 82
    public function createView()
    {
        $viewResults = [];
83

84
        # Wir extrahieren alle notwendigen Variablen und geben Sie an unseren View:
85
        foreach ($this->results as $result) {
86 87 88 89 90 91
            $viewResults[] = get_object_vars($result);
        }

        # Wir müssen natürlich noch den Log für die durchgeführte Suche schreiben:
        $this->createLogs();

92 93
        if ($this->fokus === "bilder") {
            switch ($this->out) {
94 95 96 97 98 99 100 101
                case 'results':
                    return view('metager3bilderresults')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
                        ->with('metager', $this)
102
                        ->with('browser', (new Agent())->browser());
103 104 105 106 107 108 109 110
                default:
                    return view('metager3bilder')
                        ->with('results', $viewResults)
                        ->with('eingabe', $this->eingabe)
                        ->with('mobile', $this->mobile)
                        ->with('warnings', $this->warnings)
                        ->with('errors', $this->errors)
                        ->with('metager', $this)
111
                        ->with('browser', (new Agent())->browser());
112 113 114 115 116 117 118 119 120 121 122 123
            }
        }

        switch ($this->out) {
            case 'results':
                return view('metager3results')
                    ->with('results', $viewResults)
                    ->with('eingabe', $this->eingabe)
                    ->with('mobile', $this->mobile)
                    ->with('warnings', $this->warnings)
                    ->with('errors', $this->errors)
                    ->with('metager', $this)
124
                    ->with('browser', (new Agent())->browser());
125 126 127 128 129 130 131 132 133 134
                break;
            case 'results-with-style':
                return view('metager3')
                    ->with('results', $viewResults)
                    ->with('eingabe', $this->eingabe)
                    ->with('mobile', $this->mobile)
                    ->with('warnings', $this->warnings)
                    ->with('errors', $this->errors)
                    ->with('metager', $this)
                    ->with('suspendheader', "yes")
135
                    ->with('browser', (new Agent())->browser());
136 137 138 139 140 141 142 143
                break;
            default:
                return view('metager3')
                    ->with('eingabe', $this->eingabe)
                    ->with('mobile', $this->mobile)
                    ->with('warnings', $this->warnings)
                    ->with('errors', $this->errors)
                    ->with('metager', $this)
144
                    ->with('browser', (new Agent())->browser());
145 146
                break;
        }
147
    }
148

149 150 151 152 153 154
    private function createLogs()
    {
        $redis = Redis::connection('redisLogs');
        try
        {
            $logEntry = "";
155
            $logEntry .= "[" . date(DATE_RFC822, mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"))) . "]";
156 157 158 159 160 161
            $logEntry .= " pid=" . getmypid();
            $logEntry .= " ref=" . $this->request->header('Referer');
            $useragent = $this->request->header('User-Agent');
            $useragent = str_replace("(", " ", $useragent);
            $useragent = str_replace(")", " ", $useragent);
            $useragent = str_replace(" ", "", $useragent);
162
            $logEntry .= " time=" . round((microtime(true) - $this->starttime), 2) . " serv=" . $this->fokus;
163 164
            $logEntry .= " search=" . $this->eingabe;
            $redis->rpush('logs.search', $logEntry);
165
        } catch (\Exception $e) {
166 167 168 169
            return;
        }
    }

170
    public function removeInvalids()
171 172
    {
        $results = [];
173 174
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
175
                $results[] = $result;
176 177
            }

178 179 180
        }
        #$this->results = $results;
    }
181

182 183 184 185 186
    public function combineResults()
    {
        foreach ($this->engines as $engine) {
            foreach ($engine->results as $result) {
                if ($result->valid) {
187
                    $this->results[] = $result;
188 189
                }

190
            }
191
            foreach ($engine->ads as $ad) {
192 193
                $this->ads[] = $ad;
            }
194 195 196
        }
        uasort($this->results, function ($a, $b) {
            if ($a->getRank() == $b->getRank()) {
197
                return 0;
198 199
            }

200 201 202 203
            return ($a->getRank() < $b->getRank()) ? 1 : -1;
        });
        # Validate Results
        $newResults = [];
204 205
        foreach ($this->results as $result) {
            if ($result->isValid($this)) {
206
                $newResults[] = $result;
207 208
            }

209 210 211
        }
        $this->results = $newResults;

212
        $counter   = 0;
213
        $firstRank = 0;
214 215
        foreach ($this->results as $result) {
            if ($counter === 0) {
216
                $firstRank = $result->rank;
217 218
            }

219 220
            $counter++;
            $result->number = $counter;
221 222 223 224
            $confidence     = 0;
            if ($firstRank > 0) {
                $confidence = $result->rank / $firstRank;
            } else {
225
                $confidence = 0;
226 227 228
            }

            if ($confidence > 0.65) {
229
                $result->color = "#FF4000";
230
            } elseif ($confidence > 0.4) {
231
                $result->color = "#FF0080";
232
            } elseif ($confidence > 0.2) {
233
                $result->color = "#C000C0";
234
            } else {
235
                $result->color = "#000000";
236 237
            }

238 239 240 241
        }

        //Get current page form url e.g. &page=6
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
242
        $offset      = $currentPage - 1;
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

        //Create a new Laravel collection from the array data
        $collection = new Collection($this->results);

        //Define how many items we want to be visible in each page
        $perPage = $this->resultCount;

        //Slice the collection to get the items to display in current page
        $currentPageSearchResults = $collection->slice($offset * $perPage, $perPage)->all();

        # Für diese 20 Links folgt nun unsere Boost-Implementation.
        $currentPageSearchResults = $this->parseBoost($currentPageSearchResults);

        # Für diese 20 Links folgt nun unsere Adgoal- Implementation.
        $currentPageSearchResults = $this->parseAdgoal($currentPageSearchResults);

        //Create our paginator and pass it to the view
260
        $paginatedSearchResults = new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
261
        $paginatedSearchResults->setPath('/meta/meta.ger3');
262 263
        foreach ($this->request->all() as $key => $value) {
            if ($key === "out") {
264
                continue;
265 266
            }

267 268 269 270 271
            $paginatedSearchResults->addQuery($key, $value);
        }

        $this->results = $paginatedSearchResults;

272
        if (LaravelLocalization::getCurrentLocale() === "en") {
273 274 275
            $this->ads = [];
        }

276
        $this->validated = false;
277
        if (isset($this->password)) {
278 279 280
            # Wir bieten einen bezahlten API-Zugriff an, bei dem dementsprechend die Werbung ausgeblendet wurde:
            # Aktuell ist es nur die Uni-Mainz. Deshalb überprüfen wir auch nur diese.
            $password = getenv('mainz');
281
            $eingabe  = $this->eingabe;
282
            $password = md5($eingabe . $password);
283 284
            if ($this->password === $password) {
                $this->ads       = [];
285 286 287
                $this->validated = true;
            }
        }
288 289 290 291

        if (count($this->results) <= 0) {
            $this->errors[] = "Leider konnten wir zu Ihrer Sucheingabe keine passenden Ergebnisse finden. Sie können aber versuchen diese anzupassen.";
        }
292
    }
293

294 295
    public function parseBoost($results)
    {
296 297 298 299 300 301 302 303 304 305 306 307
        foreach ($results as $result) {
            if (preg_match('/^(http[s]?\:\/\/)?(www.)?amazon\.de/', $result->anzeigeLink)) {
                if (preg_match('/\?/', $result->anzeigeLink)) {
                    $result->link .= '&tag=boostmg01-21';
                } else {
                    $result->link .= '?tag=boostmg01-21';
                }
                $result->partnershop = true;

            }
        }
        return $results;
308 309 310
    }
    public function parseAdgoal($results)
    {
311
        $publicKey  = getenv('adgoal_public');
312
        $privateKey = getenv('adgoal_private');
313
        if ($publicKey === false) {
314 315 316
            return $results;
        }
        $tldList = "";
317 318
        try {
            foreach ($results as $result) {
319
                $link = $result->anzeigeLink;
320
                if (strpos($link, "http") !== 0) {
321 322 323 324 325 326 327 328 329 330
                    $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");

331
            # Query
332 333
            $query = urlencode($this->q);

334
            $link   = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
335 336 337
            $answer = json_decode(file_get_contents($link));

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

342 343
                foreach ($results as $result) {
                    if ($hoster === $result->tld) {
344 345
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
346
                        if ($result->image !== "") {
347
                            $result->logo = "https://img.smartredirect.de/logos_v2/60x30/" . $hash . ".gif";
348
                        } else {
349
                            $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
350 351
                        }

352 353 354
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
                        $targetUrl = $result->anzeigeLink;
355
                        if (strpos($targetUrl, "http") !== 0) {
356
                            $targetUrl = "http://" . $targetUrl;
357 358 359 360 361
                        }

                        $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;
362 363 364 365
                        $result->partnershop = true;
                    }
                }
            }
366
        } catch (\ErrorException $e) {
367 368 369 370 371
            return $results;
        }

        return $results;
    }
372

373 374
    public function createSearchEngines(Request $request)
    {
375

376
        if (!$request->has("eingabe")) {
377
            return;
378
        }
379

380 381
        # Überprüfe, welche Sumas eingeschaltet sind
        $xml                  = simplexml_load_file($this->sumaFile);
382
        $enabledSearchengines = [];
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
        $overtureEnabled      = false;
        $countSumas           = 0;
        $sumas                = $xml->xpath("suma");
        if ($this->fokus === "angepasst") {
            foreach ($sumas as $suma) {
                if ($request->has($suma["name"])
                    || ($this->fokus !== "bilder"
                        && ($suma["name"]->__toString() === "qualigo"
                            || $suma["name"]->__toString() === "similar_product_ads"
                            || (!$overtureEnabled && $suma["name"]->__toString() === "overtureAds")
                        )
                    )
                ) {

                    if (!(isset($suma['disabled']) && $suma['disabled']->__toString() === "1")) {
                        if ($suma["name"]->__toString() === "overture" || $suma["name"]->__toString() === "overtureAds") {
                            $overtureEnabled = true;
400
                        }
401
                        if ($suma["name"]->__toString() !== "qualigo" && $suma["name"]->__toString() !== "similar_product_ads" && $suma["name"]->__toString() !== "overtureAds") {
402
                            $countSumas += 1;
403 404
                        }

405 406 407 408
                        $enabledSearchengines[] = $suma;
                    }
                }
            }
409 410 411 412 413 414 415 416 417 418 419 420 421 422
        } else {
            foreach ($sumas as $suma) {
                $types = explode(",", $suma["type"]);
                if (in_array($this->fokus, $types)
                    || ($this->fokus !== "bilder"
                        && ($suma["name"]->__toString() === "qualigo"
                            || $suma["name"]->__toString() === "similar_product_ads"
                            || (!$overtureEnabled && $suma["name"]->__toString() === "overtureAds")
                        )
                    )
                ) {
                    if (!(isset($suma['disabled']) && $suma['disabled']->__toString() === "1")) {
                        if ($suma["name"]->__toString() === "overture" || $suma["name"]->__toString() === "overtureAds") {
                            $overtureEnabled = true;
423
                        }
424
                        if ($suma["name"]->__toString() !== "qualigo" && $suma["name"]->__toString() !== "similar_product_ads" && $suma["name"]->__toString() !== "overtureAds") {
425
                            $countSumas += 1;
426 427
                        }

428 429 430 431 432 433 434 435
                        $enabledSearchengines[] = $suma;
                    }
                }
            }
        }

        # Sonderregelung für alle Suchmaschinen, die zu den Minisuchern gehören. Diese können alle gemeinsam über einen Link abgefragt werden
        $subcollections = [];
436 437 438
        $tmp            = [];
        foreach ($enabledSearchengines as $engine) {
            if (isset($engine['minismCollection'])) {
439
                $subcollections[] = $engine['minismCollection']->__toString();
440
            } else {
441
                $tmp[] = $engine;
442 443
            }

444 445
        }
        $enabledSearchengines = $tmp;
446 447 448 449
        if (sizeof($subcollections) > 0) {
            $count                        = sizeof($subcollections) * 10;
            $minisucherEngine             = $xml->xpath('suma[@name="minism"]')[0];
            $subcollections               = urlencode("(" . implode(" OR ", $subcollections) . ")");
450 451
            $minisucherEngine["formData"] = str_replace("<<SUBCOLLECTIONS>>", $subcollections, $minisucherEngine["formData"]);
            $minisucherEngine["formData"] = str_replace("<<COUNT>>", $count, $minisucherEngine["formData"]);
452
            $enabledSearchengines[]       = $minisucherEngine;
453 454 455 456
        }

        #die(var_dump($enabledSearchengines));

457
        if ($countSumas <= 0) {
458 459
            $this->errors[] = "Achtung: Sie haben in ihren Einstellungen keine Suchmaschine ausgewählt.";
        }
460
        $engines = [];
461

462
        $siteSearchFailed = false;
463
        if (strlen($this->site) > 0) {
464 465
            # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob eine der Suchmaschinen überhaupt eine Sitesearch unterstützt:
            $enginesWithSite = 0;
466 467
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1") {
468 469 470
                    $enginesWithSite++;
                }
            }
471 472
            if ($enginesWithSite === 0) {
                $this->errors[]   = "Sie wollten eine Sitesearch auf " . $this->site . " durchführen. Leider unterstützen die eingestellten Suchmaschinen diese nicht. Sie können <a href=\"" . $this->generateSearchLink("web", false) . "\">hier</a> die Sitesearch im Web-Fokus durchführen. Es werden ihnen Ergebnisse ohne Sitesearch angezeigt.";
473
                $siteSearchFailed = true;
474
            } else {
475 476 477 478 479 480
                $this->warnings[] = "Sie führen eine Sitesearch durch. Es werden nur Ergebnisse von der Seite: <a href=\"http://" . $this->site . "\" target=\"_blank\">\"" . $this->site . "\"</a> angezeigt.";
            }

        }

        $typeslist = [];
481
        $counter   = 0;
482

483 484 485
        foreach ($enabledSearchengines as $engine) {

            if (!$siteSearchFailed && strlen($this->site) > 0 && (!isset($engine['hasSiteSearch']) || $engine['hasSiteSearch']->__toString() === "0")) {
486

487 488 489 490 491
                continue;
            }
            # Wenn diese Suchmaschine gar nicht eingeschaltet sein soll
            $path = "App\Models\parserSkripte\\" . ucfirst($engine["package"]->__toString());

492
            if (!file_exists(app_path() . "/Models/parserSkripte/" . ucfirst($engine["package"]->__toString()) . ".php")) {
493 494 495 496 497 498 499 500 501
                Log::error("Konnte " . $engine["name"] . " nicht abfragen, da kein Parser existiert");
                continue;
            }

            $time = microtime();

            try
            {
                $tmp = new $path($engine, $this);
502
            } catch (\ErrorException $e) {
503 504 505 506
                Log::error("Konnte " . $engine["name"] . " nicht abfragen." . var_dump($e));
                continue;
            }

507 508
            if ($tmp->enabled && isset($this->debug)) {
                $this->warnings[] = $tmp->service . "   Connection_Time: " . $tmp->connection_time . "    Write_Time: " . $tmp->write_time . " Insgesamt:" . ((microtime() - $time) / 1000);
509 510
            }

511 512
            if ($tmp->isEnabled()) {
                $engines[]                 = $tmp;
513 514
                $this->sockets[$tmp->name] = $tmp->fp;
            }
515

516
        }
517

518 519
        # Jetzt werden noch alle Kategorien der Settings durchgegangen und die jeweils enthaltenen namen der Suchmaschinen gespeichert.
        $foki = [];
520 521 522
        foreach ($sumas as $suma) {
            if ((!isset($suma['disabled']) || $suma['disabled'] === "") && (!isset($suma['userSelectable']) || $suma['userSelectable']->__toString() === "1")) {
                if (isset($suma['type'])) {
523
                    $f = explode(",", $suma['type']->__toString());
524 525
                    foreach ($f as $tmp) {
                        $name                                    = $suma['name']->__toString();
526 527
                        $foki[$tmp][$suma['name']->__toString()] = $name;
                    }
528 529
                } else {
                    $name                                        = $suma['name']->__toString();
530 531 532 533 534 535 536
                    $foki["andere"][$suma['name']->__toString()] = $name;
                }
            }
        }

        # Es werden auch die Namen der aktuell aktiven Suchmaschinen abgespeichert.
        $realEngNames = [];
537
        foreach ($enabledSearchengines as $realEng) {
538
            $nam = $realEng["name"]->__toString();
539
            if ($nam !== "qualigo" && $nam !== "overtureAds") {
540 541 542 543
                $realEngNames[] = $nam;
            }
        }
        # Anschließend werden diese beiden Listen verglichen (jeweils eine der Fokuslisten für jeden Fokus), um herauszufinden ob sie vielleicht identisch sind. Ist dies der Fall, so hat der Nutzer anscheinend Suchmaschinen eines kompletten Fokus eingestellt. Der Fokus wird dementsprechend angepasst.
544 545
        foreach ($foki as $fok => $engs) {
            $isFokus      = true;
546
            $fokiEngNames = [];
547
            foreach ($engs as $eng) {
548 549
                $fokiEngNames[] = $eng;
            }
550 551
            foreach ($fokiEngNames as $fen) {
                if (!in_array($fen, $realEngNames)) {
552 553 554
                    $isFokus = false;
                }
            }
555 556
            foreach ($realEngNames as $ren) {
                if (!in_array($ren, $fokiEngNames)) {
557 558 559
                    $isFokus = false;
                }
            }
560
            if ($isFokus) {
561 562 563 564 565 566 567 568 569
                $this->fokus = $fok;
            }
        }

        # Nun passiert ein elementarer Schritt.
        # Wir warten auf die Antwort der Suchmaschinen, da wir vorher nicht weiter machen können.
        # aber natürlich nicht ewig.
        # Die Verbindung steht zu diesem Zeitpunkt und auch unsere Request wurde schon gesendet.
        # Wir geben der Suchmaschine nun bis zu 500ms Zeit zu antworten.
570 571 572

        # Wir zählen die Suchmaschinen, die durch den Cache beantwortet wurden:
        $enginesToLoad = 0;
573 574 575
        $canBreak      = false;
        foreach ($engines as $engine) {
            if ($engine->cached) {
576
                $enginesToLoad--;
577
                if ($overtureEnabled && ($engine->name === "overture" || $engine->name === "overtureAds")) {
578
                    $canBreak = true;
579 580
                }

581 582 583
            }
        }
        $enginesToLoad += count($engines);
584
        $loadedEngines = 0;
585 586 587
        $timeStart     = microtime(true);
        while (true) {
            $time          = (microtime(true) - $timeStart) * 1000;
588
            $loadedEngines = intval(Redis::hlen('search.' . $this->getHashCode()));
589
            if ($overtureEnabled && (Redis::hexists('search.' . $this->getHashCode(), 'overture') || Redis::hexists('search.' . $this->getHashCode(), 'overtureAds'))) {
590
                $canBreak = true;
591
            }
592 593

            # Abbruchbedingung
594 595
            if ($time < 500) {
                if (($enginesToLoad === 0 || $loadedEngines >= $enginesToLoad) && $canBreak) {
596
                    break;
597 598 599 600
                }

            } elseif ($time >= 500 && $time < $this->time) {
                if (($enginesToLoad === 0 || ($loadedEngines / ($enginesToLoad * 1.0)) >= 0.8) && $canBreak) {
601
                    break;
602 603 604
                }

            } else {
605 606 607 608 609
                break;
            }
            usleep(50000);
        }

610
        #exit;
611 612 613
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
614
                    $engine->retrieveResults();
615
                } catch (\ErrorException $e) {
616
                    Log::error($e);
617

618 619 620
                }
            }
        }
621

622
        # und verwerfen den Rest:
623 624
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
625
                $engine->shutdown();
626 627
            }

628 629 630
        }

        $this->engines = $engines;
631 632 633 634 635 636 637 638 639 640 641 642
    }

    public function parseFormData(Request $request)
    {
        if ($request->input('encoding', '') !== "utf8") {
            # 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);
        }
643
        $this->url = $request->url();
644
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
645 646
        # FOKUS
        $this->fokus = trans('fokiNames.'
647 648
            . $request->input('focus', 'web'));
        if (strpos($this->fokus, ".")) {
649 650 651 652
            $this->fokus = trans('fokiNames.web');
        }

        # SUMA-FILE
653
        if (App::isLocale("en")) {
654
            $this->sumaFile = config_path() . "/sumas.xml";
655
        } else {
656 657
            $this->sumaFile = config_path() . "/sumas.xml";
        }
658
        if (!file_exists($this->sumaFile)) {
659 660 661 662 663
            die("Suma-File konnte nicht gefunden werden");
        }

        # Sucheingabe:
        $this->eingabe = trim($request->input('eingabe', ''));
664
        if (strlen($this->eingabe) === 0) {
665 666 667 668 669 670 671 672
            $this->warnings[] = 'Achtung: Sie haben keinen Suchbegriff eingegeben. Sie können ihre Suchbegriffe oben eingeben und es erneut versuchen.';
        }
        $this->q = $this->eingabe;

        # IP:
        $this->ip = $request->ip();

        # Language:
673
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
674
            $this->language = $_SERVER['HTTP_LANGUAGE'];
675
        } else {
676 677 678 679 680 681
            $this->language = "";
        }
        # Category
        $this->category = $request->input('category', '');
        # Request Times:
        $this->time = $request->input('time', 1000);
682

683 684 685 686
        # Page
        $this->page = $request->input('page', 1);
        # Lang
        $this->lang = $request->input('lang', 'all');
687 688
        if ($this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all") {
            $this->lang = "all";
689
        }
690
        $this->agent  = new Agent();
691 692 693 694
        $this->mobile = $this->agent->isMobile();

        #Sprüche
        $this->sprueche = $request->input('sprueche', 'off');
695
        if ($this->sprueche === "off") {
696
            $this->sprueche = true;
697
        } else {
698
            $this->sprueche = false;
699 700
        }

701 702 703 704
        # Ergebnisse pro Seite:
        $this->resultCount = $request->input('resultCount', '20');

        # Manchmal müssen wir Parameter anpassen um den Sucheinstellungen gerecht zu werden:
705 706 707
        if ($request->has('dart')) {
            $this->time       = 10000;
            $this->warnings[] = "Hinweis: Sie haben Dart-Europe aktiviert. Die Suche kann deshalb länger dauern und die maximale Suchzeit wurde auf 10 Sekunden hochgesetzt.";
708
        }
709 710
        if ($this->time <= 500 || $this->time > 20000) {
            $this->time = 1000;
711
        }
712 713 714 715 716 717 718 719 720
        if ($request->has('minism') && ($request->has('fportal') || $request->has('harvest'))) {
            $input    = $request->all();
            $newInput = [];
            foreach ($input as $key => $value) {
                if ($key !== "fportal" && $key !== "harvest") {
                    $newInput[$key] = $value;
                }
            }
            $request->replace($newInput);
721
        }
722 723
        if (App::isLocale("en")) {
            $this->sprueche = "off";
724
        }
725 726
        if ($this->resultCount <= 0 || $this->resultCount > 200) {
            $this->resultCount = 1000;
727
        }
728 729 730 731 732 733
        if ($request->has('onenewspageAll') || $request->has('onenewspageGermanyAll')) {
            $this->time  = 5000;
            $this->cache = "cache";
        }
        if ($request->has('tab')) {
            if ($request->input('tab') === "off") {
734
                $this->tab = "_blank";
735
            } else {
736 737
                $this->tab = "_self";
            }
738
        } else {
739 740
            $this->tab = "_blank";
        }
741
        if ($request->has('password')) {
742
            $this->password = $request->input('password');
743 744 745
        }

        if ($request->has('quicktips')) {
746
            $this->quicktips = false;
747
        } else {
748
            $this->quicktips = true;
749
        }
750 751

        $this->out = $request->input('out', "html");
752
        if ($this->out !== "html" && $this->out !== "json" && $this->out !== "results" && $this->out !== "results-with-style") {
753
            $this->out = "html";
754 755
        }

756
        $this->request = $request;
757 758 759 760 761 762 763 764 765 766
    }

    public function checkSpecialSearches(Request $request)
    {
        # Site Search:
        if (preg_match("/(.*)\bsite:(\S+)(.*)/si", $this->q, $match)) {
            $this->site = $match[2];
            $this->q    = $match[1] . $match[3];
        }
        if ($request->has('site')) {
767 768
            $this->site = $request->input('site');
        }
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        # Wenn die Suchanfrage um das Schlüsselwort "-host:*" ergänzt ist, sollen bestimmte Hosts nicht eingeblendet werden
        # Wir prüfen, ob das hier der Fall ist:
        while (preg_match("/(.*)(^|\s)-host:(\S+)(.*)/si", $this->q, $match)) {
            $this->hostBlacklist[] = $match[3];
            $this->q               = $match[1] . $match[4];
        }
        if (sizeof($this->hostBlacklist) > 0) {
            $hostString = "";
            foreach ($this->hostBlacklist as $host) {
                $hostString .= $host . ", ";
            }
            $hostString       = rtrim($hostString, ", ");
            $this->warnings[] = "Ergebnisse von folgenden Hosts werden nicht angezeigt: \"" . $hostString . "\"";
        }
        # Wenn die Suchanfrage um das Schlüsselwort "-domain:*" ergänzt ist, sollen bestimmte Domains nicht eingeblendet werden
        # Wir prüfen, ob das hier der Fall ist:
        while (preg_match("/(.*)(^|\s)-domain:(\S+)(.*)/si", $this->q, $match)) {
            $this->domainBlacklist[] = $match[3];
            $this->q                 = $match[1] . $match[4];
        }
        if (sizeof($this->domainBlacklist) > 0) {
            $domainString = "";
            foreach ($this->domainBlacklist as $domain) {
                $domainString .= $domain . ", ";
            }
            $domainString     = rtrim($domainString, ", ");
            $this->warnings[] = "Ergebnisse von folgenden Domains werden nicht angezeigt: \"" . $domainString . "\"";
        }

        # Alle mit "-" gepräfixten Worte sollen aus der Suche ausgeschlossen werden.
        # Wir prüfen, ob das hier der Fall ist:
        while (preg_match("/(.*)(^|\s)-(\S+)(.*)/si", $this->q, $match)) {
            $this->stopWords[] = $match[3];
            $this->q           = $match[1] . $match[4];
        }
        if (sizeof($this->stopWords) > 0) {
            $stopwordsString = "";
            foreach ($this->stopWords as $stopword) {
                $stopwordsString .= $stopword . ", ";
            }
            $stopwordsString  = rtrim($stopwordsString, ", ");
            $this->warnings[] = "Sie machen eine Ausschlusssuche. Ergebnisse mit folgenden Wörtern werden nicht angezeigt: \"" . $stopwordsString . "\"";
        }

        # Meldung über eine Phrasensuche
        $p   = "";
815
        $tmp = $this->q;
816 817
        while (preg_match("/(.*)\"(.+)\"(.*)/si", $tmp, $match)) {
            $tmp             = $match[1] . $match[3];
818
            $this->phrases[] = strtolower($match[2]);
819 820
        }
        foreach ($this->phrases as $phrase) {
821 822 823
            $p .= "\"$phrase\", ";
        }
        $p = rtrim($p, ", ");
824
        if (sizeof($this->phrases) > 0) {
825
            $this->warnings[] = "Sie führen eine Phrasensuche durch: $p";
826
        }
827

828 829 830
    }

    public function getFokus()
831 832 833 834
    {
        return $this->fokus;
    }

835
    public function getIp()
836 837 838 839
    {
        return $this->ip;
    }

840
    public function getEingabe()
841 842 843 844
    {
        return $this->eingabe;
    }

845
    public function getQ()
846
    {
847
        return $this->q;
848 849
    }

850
    public function getUrl()
851 852 853
    {
        return $this->url;
    }
854
    public function getTime()
855 856 857 858
    {
        return $this->time;
    }

859
    public function getLanguage()
860 861 862 863
    {
        return $this->language;
    }

864
    public function getLang()
865 866 867 868
    {
        return $this->lang;
    }

869
    public function getSprueche()
870 871 872 873
    {
        return $this->sprueche;
    }

874
    public function getCategory()
875 876 877 878
    {
        return $this->category;
    }

879
    public function getPhrases()
880 881 882 883
    {
        return $this->phrases;
    }

884
    public function getSumaFile()
885 886 887 888
    {
        return $this->sumaFile;
    }

889
    public function getUserHostBlacklist()
890 891 892 893
    {
        return $this->hostBlacklist;
    }

894
    public function getUserDomainBlacklist()
895 896 897 898
    {
        return $this->domainBlacklist;
    }

899
    public function getDomainBlacklist()
900 901 902 903
    {
        return $this->domainsBlacklisted;
    }

904
    public function getUrlBlacklist()
905 906 907
    {
        return $this->urlsBlacklisted;
    }
908
    public function getLanguageDetect()
909 910 911
    {
        return $this->languageDetect;
    }
912
    public function getStopWords()
913 914 915 916 917
    {
        return $this->stopWords;
    }
    public function getHostCount($host)
    {
918
        if (isset($this->addedHosts[$host])) {
919
            return $this->addedHosts[$host];
920
        } else {
921 922 923 924 925 926
            return 0;
        }
    }
    public function addHostCount($host)
    {
        $hash = md5($host);
927
        if (isset($this->addedHosts[$hash])) {
928
            $this->addedHosts[$hash] += 1;
929
        } else {
930 931 932 933 934 935 936 937 938
            $this->addedHosts[$hash] = 1;
        }
    }
    public function getSite()
    {
        return $this->site;
    }
    public function addLink($link)
    {
939
        if (strpos($link, "http://") === 0) {
940
            $link = substr($link, 7);
941 942 943
        }

        if (strpos($link, "https://") === 0) {
944
            $link = substr($link, 8);
945 946 947
        }

        if (strpos($link, "www.") === 0) {
948
            $link = substr($link, 4);
949 950
        }

951 952
        $link = trim($link, "/");
        $hash = md5($link);
953
        if (isset($this->addedLinks[$hash])) {
954
            return false;
955
        } else {
956 957 958 959 960 961 962