MetaGer.php 35.9 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
    public function parseBoost($results)
    {
292
293
294
295
296
297
298
299
300
301
302
303
        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;
304
305
306
    }
    public function parseAdgoal($results)
    {
307
        $publicKey  = getenv('adgoal_public');
308
        $privateKey = getenv('adgoal_private');
309
        if ($publicKey === false) {
310
311
312
            return $results;
        }
        $tldList = "";
313
314
        try {
            foreach ($results as $result) {
315
                $link = $result->anzeigeLink;
316
                if (strpos($link, "http") !== 0) {
317
318
319
320
321
322
323
324
325
326
                    $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");

327
            # Query
328
329
            $query = urlencode($this->q);

330
            $link   = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query;
331
332
333
            $answer = json_decode(file_get_contents($link));

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

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

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

                        $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;
358
359
360
361
                        $result->partnershop = true;
                    }
                }
            }
362
        } catch (\ErrorException $e) {
363
364
365
366
367
            return $results;
        }

        return $results;
    }
368

369
370
    public function createSearchEngines(Request $request)
    {
371

372
        if (!$request->has("eingabe")) {
373
            return;
374
        }
375

376
377
        # Überprüfe, welche Sumas eingeschaltet sind
        $xml                  = simplexml_load_file($this->sumaFile);
378
        $enabledSearchengines = [];
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
        $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;
396
                        }
397
                        if ($suma["name"]->__toString() !== "qualigo" && $suma["name"]->__toString() !== "similar_product_ads" && $suma["name"]->__toString() !== "overtureAds") {
398
                            $countSumas += 1;
399
400
                        }

401
402
403
404
                        $enabledSearchengines[] = $suma;
                    }
                }
            }
405
406
407
408
409
410
411
412
413
414
415
416
417
418
        } 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;
419
                        }
420
                        if ($suma["name"]->__toString() !== "qualigo" && $suma["name"]->__toString() !== "similar_product_ads" && $suma["name"]->__toString() !== "overtureAds") {
421
                            $countSumas += 1;
422
423
                        }

424
425
426
427
428
429
430
431
                        $enabledSearchengines[] = $suma;
                    }
                }
            }
        }

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

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

        #die(var_dump($enabledSearchengines));

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

458
        $siteSearchFailed = false;
459
        if (strlen($this->site) > 0) {
460
461
            # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob eine der Suchmaschinen überhaupt eine Sitesearch unterstützt:
            $enginesWithSite = 0;
462
463
            foreach ($enabledSearchengines as $engine) {
                if (isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1") {
464
465
466
                    $enginesWithSite++;
                }
            }
467
468
            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.";
469
                $siteSearchFailed = true;
470
            } else {
471
472
473
474
475
476
                $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 = [];
477
        $counter   = 0;
478

479
480
481
        foreach ($enabledSearchengines as $engine) {

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

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

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

            $time = microtime();

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

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

507
508
            if ($tmp->isEnabled()) {
                $engines[]                 = $tmp;
509
510
                $this->sockets[$tmp->name] = $tmp->fp;
            }
511

512
        }
513

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

        # Es werden auch die Namen der aktuell aktiven Suchmaschinen abgespeichert.
        $realEngNames = [];
533
        foreach ($enabledSearchengines as $realEng) {
534
            $nam = $realEng["name"]->__toString();
535
            if ($nam !== "qualigo" && $nam !== "overtureAds") {
536
537
538
539
                $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.
540
541
        foreach ($foki as $fok => $engs) {
            $isFokus      = true;
542
            $fokiEngNames = [];
543
            foreach ($engs as $eng) {
544
545
                $fokiEngNames[] = $eng;
            }
546
547
            foreach ($fokiEngNames as $fen) {
                if (!in_array($fen, $realEngNames)) {
548
549
550
                    $isFokus = false;
                }
            }
551
552
            foreach ($realEngNames as $ren) {
                if (!in_array($ren, $fokiEngNames)) {
553
554
555
                    $isFokus = false;
                }
            }
556
            if ($isFokus) {
557
558
559
560
561
562
563
564
565
                $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.
566
567
568

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

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

            # Abbruchbedingung
590
591
            if ($time < 500) {
                if (($enginesToLoad === 0 || $loadedEngines >= $enginesToLoad) && $canBreak) {
592
                    break;
593
594
595
596
                }

            } elseif ($time >= 500 && $time < $this->time) {
                if (($enginesToLoad === 0 || ($loadedEngines / ($enginesToLoad * 1.0)) >= 0.8) && $canBreak) {
597
                    break;
598
599
600
                }

            } else {
601
602
603
604
605
                break;
            }
            usleep(50000);
        }

606
        #exit;
607
608
609
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
                try {
610
                    $engine->retrieveResults();
611
                } catch (\ErrorException $e) {
612
                    Log::error($e);
613

614
615
616
                }
            }
        }
617

618
        # und verwerfen den Rest:
619
620
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
621
                $engine->shutdown();
622
623
            }

624
625
626
        }

        $this->engines = $engines;
627
628
629
630
631
632
633
634
635
636
637
638
    }

    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);
        }
639
        $this->url = $request->url();
640
        # Zunächst überprüfen wir die eingegebenen Einstellungen:
641
642
        # FOKUS
        $this->fokus = trans('fokiNames.'
643
644
            . $request->input('focus', 'web'));
        if (strpos($this->fokus, ".")) {
645
646
647
648
            $this->fokus = trans('fokiNames.web');
        }

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

        # Sucheingabe:
        $this->eingabe = trim($request->input('eingabe', ''));
660
        if (strlen($this->eingabe) === 0) {
661
662
663
664
665
666
667
668
            $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:
669
        if (isset($_SERVER['HTTP_LANGUAGE'])) {
670
            $this->language = $_SERVER['HTTP_LANGUAGE'];
671
        } else {
672
673
674
675
676
677
            $this->language = "";
        }
        # Category
        $this->category = $request->input('category', '');
        # Request Times:
        $this->time = $request->input('time', 1000);
678

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

        #Sprüche
        $this->sprueche = $request->input('sprueche', 'off');
691
        if ($this->sprueche === "off") {
692
            $this->sprueche = true;
693
        } else {
694
            $this->sprueche = false;
695
696
        }

697
698
699
700
        # Ergebnisse pro Seite:
        $this->resultCount = $request->input('resultCount', '20');

        # Manchmal müssen wir Parameter anpassen um den Sucheinstellungen gerecht zu werden:
701
702
703
        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.";
704
        }
705
706
        if ($this->time <= 500 || $this->time > 20000) {
            $this->time = 1000;
707
        }
708
709
710
711
712
713
714
715
716
        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);
717
        }
718
719
        if (App::isLocale("en")) {
            $this->sprueche = "off";
720
        }
721
722
        if ($this->resultCount <= 0 || $this->resultCount > 200) {
            $this->resultCount = 1000;
723
        }
724
725
726
727
728
729
        if ($request->has('onenewspageAll') || $request->has('onenewspageGermanyAll')) {
            $this->time  = 5000;
            $this->cache = "cache";
        }
        if ($request->has('tab')) {
            if ($request->input('tab') === "off") {
730
                $this->tab = "_blank";
731
            } else {
732
733
                $this->tab = "_self";
            }
734
        } else {
735
736
            $this->tab = "_blank";
        }
737
        if ($request->has('password')) {
738
            $this->password = $request->input('password');
739
740
741
        }

        if ($request->has('quicktips')) {
742
            $this->quicktips = false;
743
        } else {
744
            $this->quicktips = true;
745
        }
746
747

        $this->out = $request->input('out', "html");
748
        if ($this->out !== "html" && $this->out !== "json" && $this->out !== "results" && $this->out !== "results-with-style") {
749
            $this->out = "html";
750
751
        }

752
        $this->request = $request;
753
754
755
756
757
758
759
760
761
762
    }

    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')) {
763
764
            $this->site = $request->input('site');
        }
765
766
767
768
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
        # 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   = "";
811
        $tmp = $this->q;
812
813
        while (preg_match("/(.*)\"(.+)\"(.*)/si", $tmp, $match)) {
            $tmp             = $match[1] . $match[3];
814
            $this->phrases[] = strtolower($match[2]);
815
816
        }
        foreach ($this->phrases as $phrase) {
817
818
819
            $p .= "\"$phrase\", ";
        }
        $p = rtrim($p, ", ");
820
        if (sizeof($this->phrases) > 0) {
821
            $this->warnings[] = "Sie führen eine Phrasensuche durch: $p";
822
        }
823

824
825
826
    }

    public function getFokus()
827
828
829
830
    {
        return $this->fokus;
    }

831
    public function getIp()
832
833
834
835
    {
        return $this->ip;
    }

836
    public function getEingabe()
837
838
839
840
    {
        return $this->eingabe;
    }

841
    public function getQ()
842
    {
843
        return $this->q;
844
845
    }

846
    public function getUrl()
847
848
849
    {
        return $this->url;
    }
850
    public function getTime()
851
852
853
854
    {
        return $this->time;
    }

855
    public function getLanguage()
856
857
858
859
    {
        return $this->language;
    }

860
    public function getLang()
861
862
863
864
    {
        return $this->lang;
    }

865
    public function getSprueche()
866
867
868
869
    {
        return $this->sprueche;
    }

870
    public function getCategory()
871
872
873
874
    {
        return $this->category;
    }

875
    public function getPhrases()
876
877
878
879
    {
        return $this->phrases;
    }

880
    public function getSumaFile()
881
882
883
884
    {
        return $this->sumaFile;
    }

885
    public function getUserHostBlacklist()
886
887
888
889
    {
        return $this->hostBlacklist;
    }

890
    public function getUserDomainBlacklist()
891
892
893
894
    {
        return $this->domainBlacklist;
    }

895
    public function getDomainBlacklist()
896
897
898
899
    {
        return $this->domainsBlacklisted;
    }

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

        if (strpos($link, "https://") === 0) {
940
            $link = substr($link, 8);
941
942
943
        }

        if (strpos($link, "www.") === 0) {
944
            $link = substr($link, 4);
945
946
        }

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

            return true;
        }
    }

    public function generateSearchLink($fokus, $results = true)
    {
960
        $requestData          = $this->request->except('page');
961
        $requestData['focus'] = $fokus;
962
        if ($results) {
963
            $requestData['out'] = "results";
964
        } else {
965
            $requestData['out'] = "";
966
967
        }

968
969
970
971
972
973
974
975
976
977
978
979
980
        $link = action('MetaGerSearch@search', $requestData);
        return $link;
    }

    public function generateQuicktipLink()
    {
        $link = action('MetaGerSearch@quicktips');

        return $link;
    }

    public function generateSiteSearchLink($host)
    {
981
982
        $host        = urlencode($host);
        $requestData = $this->request->except(['page', 'out']);
983
984
        $requestData['eingabe'] .= " site:$host";
        $requestData['focus'] = "web";
985
        $link                 = action('MetaGerSearch@search', $requestData);
986
987
988
        return $link;
    }

989
    public function generateRemovedHostLink($host)
990
    {
991
992
        $host        = urlencode($host);
        $requestData = $this->request->except(['page', 'out']);
993
994
995
996
997
        $requestData['eingabe'] .= " -host:$host";
        $link = action('MetaGerSearch@search', $requestData);
        return $link;
    }

998
    public function generateRemovedDomainLink($domain)
999
    {
1000
1001
        $domain      = urlencode($domain);
        $requestData = $this->request->except(['page', 'out']);
1002
1003
1004
1005
1006
        $requestData['eingabe'] .= " -domain:$domain";
        $link = action('MetaGerSearch@search', $requestData);
        return $link;
    }

1007
    public function getTab()
1008
1009
1010
    {
        return $this->tab;
    }
1011
    public function getResults()
1012
1013
1014
1015
1016
    {
        return $this->results;
    }
    public function popAd()
    {
1017
        if (count($this->ads) > 0) {
1018
            return get_object_vars(array_shift($this->ads));
1019
        } else {
1020
            return null;
1021
1022
        }

1023
1024
1025
    }
    public function getImageProxyLink($link)
    {
1026
        $requestData        = [];
1027
        $requestData["url"] = $link;
1028
        $link               = action('Pictureproxy@get', $requestData);
1029
1030
        return