MetaGer.php 35.4 KB
Newer Older
1 2 3 4 5 6
<?php
namespace App;

use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use App;
7 8
use Storage;
use Log;
9
use Config;
10
use Redis;
11 12 13 14 15
use App\lib\TextLanguageDetect\TextLanguageDetect;
use App\lib\TextLanguageDetect\LanguageDetect\TextLanguageDetectException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
#use \Illuminate\Pagination\Paginator;
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

class MetaGer
{
	# 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 = [];
32
    protected $phrases = [];
33 34
	protected $engines = [];
	protected $results = [];
35
    protected $ads = [];
36
	protected $warnings = [];
37
    protected $errors = [];
38
    protected $addedHosts = [];
39 40 41 42 43 44 45 46 47
	# Daten über die Abfrage
	protected $ip;
	protected $language;
	protected $agent;
	# Konfigurationseinstellungen:
	protected $sumaFile;
	protected $mobile;
	protected $resultCount;
	protected $sprueche;
48 49 50
    protected $domainsBlacklisted = [];
    protected $urlsBlacklisted = [];
    protected $url;
51
    protected $languageDetect;
52 53 54

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

        $this->languageDetect = new TextLanguageDetect();
        $this->languageDetect->setNameMode("2");
70 71
	}

72 73 74 75 76 77
    public function getHashCode ()
    {
        $string = url()->full();
        return md5($string);
    }

78 79 80 81 82 83 84 85
    public function rankAll ()
    {
        foreach( $this->engines as $engine )
        {
            $engine->rank($this);
        }
    }

86 87 88
	public function createView()
	{
		$viewResults = [];
89

90 91 92 93 94
        # Wir extrahieren alle notwendigen Variablen und geben Sie an unseren View:
        foreach($this->results as $result)
        {
            $viewResults[] = get_object_vars($result);
        }
95

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

Dominik Hebeler's avatar
Dominik Hebeler committed
99 100 101 102 103
        if( $this->fokus === "bilder" )
        {
            switch ($this->out) 
            {
                case 'results':
104 105 106 107 108 109 110
                    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);
Dominik Hebeler's avatar
Dominik Hebeler committed
111 112 113 114 115 116 117 118 119 120 121
                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);
            }
        }

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

153 154 155
    private function createLogs()
    {
        $redis = Redis::connection('redisLogs');
156
        try
157 158 159 160 161 162 163 164 165 166 167 168
        {
            $logEntry = "";
            $logEntry .= "[" . date(DATE_RFC822, mktime(date("H"),date("i"), date("s"), date("m"), date("d"), date("Y"))) . "]";
            $logEntry .= " From=" . $this->ip;
            $logEntry .= " pid=" . getmypid();
            $anonId= md5("MySeCrEtSeEdFoRmd5"
            .$this->request->header('Accept')
            .$this->request->header('Accept-Charset')
            .$this->request->header('Accept-Encoding')
            .$this->request->header('HTTP_LANGUAGE')
            .$this->request->header('User-Agent')
            .$this->request->header('Keep-Alive')
Dominik Hebeler's avatar
Dominik Hebeler committed
169 170
            .$this->request->header('X-Forwarded-For')
            .date("H")); # Wichtig!! Den Parameter um die aktuelle Stunde erweitern. Ansonsten wäre die anonId dauerhaft einem Nutzer zuzuordnen.
171 172 173 174 175 176 177 178 179 180
            $logEntry .= " anonId=$anonId";
            $logEntry .= " ref=" . $this->request->header('Referer');
            $useragent = $this->request->header('User-Agent');
            $useragent = str_replace("(", " ", $useragent);
            $useragent = str_replace(")", " ", $useragent);
            $useragent = str_replace(" ", "", $useragent);
            $logEntry .= " ua=" . $useragent;
            $logEntry .= " iter= mm= time=" . round((microtime(true)-$this->starttime), 2) . " serv=" . $this->fokus . " which= hits= stringSearch= QuickTips= SSS= check=";
            $logEntry .= " search=" . $this->eingabe;
            $redis->rpush('logs.search', $logEntry);
181 182 183
        }catch( \Exception $e)
        {
            return;
184 185 186
        }
    }

187 188 189 190 191 192 193 194 195 196 197
    public function removeInvalids ()
    {
        $results = [];
        foreach($this->results as $result)
        {
            if($result->isValid($this))
                $results[] = $result;
        }
        #$this->results = $results;
    }

198 199 200 201
	public function combineResults ()
	{
		foreach($this->engines as $engine)
		{
202 203 204 205 206 207 208 209 210
            foreach($engine->results as $result)
            {
                if($result->valid)
                    $this->results[] = $result;
            }
            foreach($engine->ads as $ad)
            {
                $this->ads[] = $ad;
            }
211
		}
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
        uasort($this->results, function($a, $b){
            if($a->getRank() == $b->getRank())
                return 0;
            return ($a->getRank() < $b->getRank()) ? 1 : -1;
        });
        # Validate Results
        $newResults = [];
        foreach($this->results as $result)
        {
            if($result->isValid($this))
                $newResults[] = $result;
        }
        $this->results = $newResults;

        $counter = 0;
        $firstRank = 0;
        foreach($this->results as $result)
        {
            if($counter === 0)
                $firstRank = $result->rank;
            $counter++;
            $result->number = $counter;
            $confidence = 0;
            if($firstRank > 0)
                $confidence = $result->rank/$firstRank;
            else
                $confidence = 0;
            if($confidence > 0.65)
                $result->color = "#FF4000";
            elseif($confidence > 0.4)
                $result->color = "#FF0080";
            elseif($confidence > 0.2)
                $result->color = "#C000C0";
            else
                $result->color = "#000000";
        }

        //Get current page form url e.g. &page=6
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
        $offset= $currentPage-1;

        //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();

Dominik Hebeler's avatar
Dominik Hebeler committed
262 263 264
        # Für diese 20 Links folgt nun unsere Adgoal Implementation.
        $currentPageSearchResults = $this->parseAdgoal($currentPageSearchResults);

265 266 267 268 269
        //Create our paginator and pass it to the view
        $paginatedSearchResults= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
        $paginatedSearchResults->setPath('/meta/meta.ger3');
        foreach($this->request->all() as $key => $value)
        {
Dominik Hebeler's avatar
Bugfix  
Dominik Hebeler committed
270
            if( $key === "out" )
271
                continue;
272 273 274 275
            $paginatedSearchResults->addQuery($key, $value);
        }

        $this->results = $paginatedSearchResults;
276

277
        $this->validated = false;
278 279 280 281 282 283 284 285 286 287
        if( isset($this->password) )
        {
            # 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');
            $eingabe = $this->eingabe;
            $password = md5($eingabe . $password);
            if( $this->password === $password )
            {
                $this->ads = [];
288
                $this->validated = true;
289 290
            }
        }
291 292
	}

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

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

            $link = "https://api.smartredirect.de/api_v2/CheckForAffiliateUniversalsearchMetager.php?p=" . $publicKey . "&k=" . $hash . "&tld=" . $tldList . "&q=" . $query; 
            $answer = json_decode(file_get_contents($link));
Dominik Hebeler's avatar
Dominik Hebeler committed
323

Dominik Hebeler's avatar
Dominik Hebeler committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339

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

                foreach($results as $result)
                {
                    if( $hoster === $result->tld )
                    {
                        # Hier ist ein Advertiser:
                        # Das Logo hinzufügen:
                        $result->image = "https://img.smartredirect.de/logos_v2/120x60/" . $hash . ".gif";
                        # Den Link hinzufügen:
                        $publicKey = $publicKey;
Dominik Hebeler's avatar
Dominik Hebeler committed
340
                        $targetUrl = $result->anzeigeLink;
Dominik Hebeler's avatar
Dominik Hebeler committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
                        if(strpos($targetUrl, "http") !== 0)
                            $targetUrl = "http://" . $targetUrl;
                        $hash = md5($targetUrl . $privateKey);
                        $newLink = "https://api.smartredirect.de/api_v2/ClickGate.php?p=" . $publicKey . "&k=" . $hash . "&url=" . urlencode($targetUrl) . "&q=" . $query;
                        $result->link = $newLink;
                    }
                }
            }
        }catch(\ErrorException $e)
        {
            return $results;
        }

        return $results;
    }

357 358
	public function createSearchEngines (Request $request)
	{
359 360 361

        if( !$request->has("eingabe") )
            return;
362

363 364 365 366
		# Überprüfe, welche Sumas eingeschaltet sind
        $xml = simplexml_load_file($this->sumaFile);
        $enabledSearchengines = [];
        $overtureEnabled = FALSE;
367
        $countSumas = 0;
368
        $sumas = $xml->xpath("suma");
369 370 371 372
        if($this->fokus === "angepasst")
        {
            foreach($sumas as $suma)
            {
373
                if($request->has($suma["name"]) 
374 375 376 377 378 379
                	|| ( $this->fokus !== "bilder" 
                		&& ($suma["name"]->__toString() === "qualigo" 
                			|| $suma["name"]->__toString() === "similar_product_ads" 
                			|| ( !$overtureEnabled && $suma["name"]->__toString() === "overtureAds" )
                			)
                		)
380
                	){
381 382 383

                	if(!(isset($suma['disabled']) && $suma['disabled']->__toString() === "1"))
                    {
384
                        if($suma["name"]->__toString() === "overture" || $suma["name"]->__toString() === "overtureAds")
385 386 387
                        {
                            $overtureEnabled = TRUE;
                        }
388 389
                        if( $suma["name"]->__toString() !== "qualigo" && $suma["name"]->__toString() !== "similar_product_ads" && $suma["name"]->__toString() !== "overtureAds" )
                            $countSumas += 1;
390 391
                        $enabledSearchengines[] = $suma;
                    }
392 393 394 395 396 397
                }
            }
        }else{
            foreach($sumas as $suma){
                $types = explode(",",$suma["type"]);
                if(in_array($this->fokus, $types) 
398 399 400 401 402 403
                	|| ( $this->fokus !== "bilder" 
                		&& ($suma["name"]->__toString() === "qualigo" 
                			|| $suma["name"]->__toString() === "similar_product_ads" 
                			|| ( !$overtureEnabled && $suma["name"]->__toString() === "overtureAds" )
                			)
                		)
404
                	){
405 406
                    if(!(isset($suma['disabled']) && $suma['disabled']->__toString() === "1"))
                    {
407
                        if($suma["name"]->__toString() === "overture" || $suma["name"]->__toString() === "overtureAds")
408 409 410
                        {
                            $overtureEnabled = TRUE;
                        }
411 412
                        if( $suma["name"]->__toString() !== "qualigo" && $suma["name"]->__toString() !== "similar_product_ads" && $suma["name"]->__toString() !== "overtureAds" )
                            $countSumas += 1;
413 414
                        $enabledSearchengines[] = $suma;
                    }
415 416 417
                }
            }
        }
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

        # Sonderregelung für alle Suchmaschinen, die zu den Minisuchern gehören. Diese können alle gemeinsam über einen Link abgefragt werden
        $subcollections = [];
        $tmp = [];
        foreach($enabledSearchengines as $engine )
        {
            if( isset($engine['minismCollection']) )
                $subcollections[] = $engine['minismCollection']->__toString();
            else
                $tmp[] = $engine;
        }
        $enabledSearchengines = $tmp;
        if( sizeof($subcollections) > 0)
        {
            $count = sizeof($subcollections) * 10;
            $minisucherEngine = $xml->xpath('suma[@name="minism"]')[0];  
            $subcollections = urlencode("(" . implode(" OR ", $subcollections) . ")");
            $minisucherEngine["formData"] = str_replace("<<SUBCOLLECTIONS>>", $subcollections, $minisucherEngine["formData"]);
            $minisucherEngine["formData"] = str_replace("<<COUNT>>", $count, $minisucherEngine["formData"]);
            $enabledSearchengines[] = $minisucherEngine;
        }

        #die(var_dump($enabledSearchengines));

442
        if( $countSumas <= 0 )
443 444 445
        {
            $this->errors[] = "Achtung: Sie haben in ihren Einstellungen keine Suchmaschine ausgewählt.";
        }
446
		$engines = [];
447

448 449 450 451 452 453 454 455 456 457 458 459 460 461
        $siteSearchFailed = false;
        if( strlen($this->site) > 0 )
        {
            # Wenn eine Sitesearch durchgeführt werden soll, überprüfen wir ob eine der Suchmaschinen überhaupt eine Sitesearch unterstützt:
            $enginesWithSite = 0;
            foreach($enabledSearchengines as $engine)
            {
                if( isset($engine['hasSiteSearch']) && $engine['hasSiteSearch']->__toString() === "1" )
                {
                    $enginesWithSite++;
                }
            }
            if( $enginesWithSite === 0 )
            {
462
                $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.";
463 464 465 466 467
                $siteSearchFailed = true;
            }else
            {
                $this->warnings[] = "Sie führen eine Sitesearch durch. Es werden nur Ergebnisse von der Seite: \"" . $this->site . "\" angezeigt.";
            }
468

469 470 471 472
        }

        $typeslist = [];
        $counter = 0;
473

474
		foreach($enabledSearchengines as $engine){
475

476
            if( !$siteSearchFailed && strlen($this->site) > 0 && ( !isset($engine['hasSiteSearch']) || $engine['hasSiteSearch']->__toString() === "0")  )
477
            {
478
                
479 480
                continue;
            }
481
            # Wenn diese Suchmaschine gar nicht eingeschaltet sein soll
482 483
            $path = "App\Models\parserSkripte\\" . ucfirst($engine["package"]->__toString());

484
            $time = microtime();
485 486
            $tmp = new $path($engine, $this);

487 488 489 490 491
            if($tmp->enabled && isset($this->debug))
            {
                $this->warnings[] = $tmp->service . "   Connection_Time: " . $tmp->connection_time . "    Write_Time: " . $tmp->write_time . " Insgesamt:" . ((microtime()-$time)/1000);
            }

492
            if($tmp->isEnabled())
493 494
            {
                $engines[] = $tmp;
495
                $this->sockets[$tmp->name] = $tmp->fp;
496
            }
497

498
            # Alternativ
499
            # Hier wird direkt eine Liste der Fokustypen erstellt, die bei der Suche verwendet werden: [0] => [web, nachrichten]
500
            /*if($engine["name"] !== "overtureAds") {
501 502 503 504
                $type = explode(",", $engine["type"]);
                if(!$type[0] == "") {
                    $typeslist[$counter++] = $type;
                }
505
            }*/
506

507
		}
508

509
        # Alternativ
510
        # Jetzt wird geguckt, ob diese Liste überhaupt Typen enthält und für jeden Typen des ersten Eintrags (oder späteren falls dieser "" ist) wird geguckt, ob sich dieser Typ in allen folgenden Einträgen finden lässt. Diese Einträge sind nie "web", da diese Suche meist eh auch möglich ist und ohnehin wie die angepasste Suche funktioniert. Am Ende wird geguckt ob es einen Typen gab, der in allen Elementen enthalten ist. Dieser wird als Fokus gesetzt.
511
        /*if(!empty($typeslist)) {
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
            foreach($typeslist as $matchTypeSearch) {
                if(!empty($matchTypeSearch) && $matchTypeSearch[0] !== "") {
                    $toMatch = $matchTypeSearch;
                    break;
                }
            }
            $toMatch = $typeslist[0];
            array_shift($typeslist);
            $matchedType = "";
            foreach($toMatch as $matchType) {
                if($matchType !== "web" && $matchType !== "") {
                    $matched = true;
                    foreach($typeslist as $otherTypes) {
                        if(!in_array($matchType, $otherTypes)) {
                            $matched = false;
                        }
                    }
                    if($matched) {
                        $matchedType = $matchType;
                        break;
                    }
                }
            }
            if($matchedType !== "") {
                $this->fokus = $matchedType;
            }
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
        }*/

        # Jetzt werden noch alle Kategorien der Settings durchgegangen und die jeweils enthaltenen namen der Suchmaschinen gespeichert.
        $foki = [];
        foreach($sumas as $suma)
        {
            if( (!isset($suma['disabled']) || $suma['disabled'] === "") && ( !isset($suma['userSelectable']) || $suma['userSelectable']->__toString() === "1") )
            {
                if( isset($suma['type']) )
                {
                    $f = explode(",", $suma['type']->__toString());
                    foreach($f as $tmp)
                    {
                        $name = $suma['name']->__toString();
                        $foki[$tmp][$suma['name']->__toString()] = $name;
                    }
                }else
                {
                    $name = $suma['name']->__toString();
                    $foki["andere"][$suma['name']->__toString()] = $name;
                }
            }
        }

        # Es werden auch die Namen der aktuell aktiven Suchmaschinen abgespeichert.
        $realEngNames = [];
        foreach($enabledSearchengines as $realEng) {
            $nam = $realEng["name"]->__toString();
            if($nam !== "qualigo" && $nam !== "overtureAds") {
                $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.
        foreach($foki as $fok => $engs) {
            $isFokus = true;
            $fokiEngNames = [];
            foreach($engs as $eng) {
                $fokiEngNames[] = $eng;
            }
            foreach($fokiEngNames as $fen) {
                if(!in_array($fen, $realEngNames)) {
                    $isFokus = false;
                }
            }
            foreach($realEngNames as $ren) {
                if(!in_array($ren, $fokiEngNames)) {
                    $isFokus = false;
                }
            }
            if($isFokus) {
                $this->fokus = $fok;
            }
590 591
        }

592 593 594 595 596
        # 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.
597 598
        $enginesToLoad = count($engines);
        $loadedEngines = 0;
599 600
        $timeStart = microtime(true);

601 602
        while( true )
        {
603 604 605 606 607 608 609
            $time = (microtime(true) - $timeStart) * 1000;
            $loadedEngines = intval(Redis::hlen('search.' . $this->getHashCode()));
            $canBreak = true;
            if( $overtureEnabled && !Redis::hexists('search.' . $this->getHashCode(), 'overture') && !Redis::hexists('search.' . $this->getHashCode(), 'overtureAds'))
                $canBreak = false;


610 611 612
            # Abbruchbedingung
            if($time < 500)
            {
613
                if(($enginesToLoad === 0 || $loadedEngines >= $enginesToLoad) && $canBreak)
614 615 616
                    break;
            }elseif( $time >= 500 && $time < $this->time)
            {
617
                if( ($enginesToLoad === 0 || ($loadedEngines / ($enginesToLoad * 1.0)) >= 0.8) && $canBreak )
618 619 620 621 622
                    break;
            }else
            {
                break;
            }
623 624 625 626 627 628 629
            usleep(50000);
        }

        
        foreach($engines as $engine)
        {
            if(!$engine->loaded)
630
            {
631 632 633 634 635 636 637
                try{
                    $engine->retrieveResults();
                } catch(\ErrorException $e)
                {
                    Log::error($e);
                    
                }
638 639
            }
        }
640 641
        
        # und verwerfen den Rest:
642
        foreach( $engines as $engine )
643
        {
644 645
            if( !$engine->loaded )
                $engine->shutdown();
646
        }
647

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
        $this->engines = $engines;
	}

	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);
		}
663
        $this->url = $request->url();
664 665 666 667 668 669 670 671 672 673 674
		# Zunächst überprüfen wir die eingegebenen Einstellungen:
        # FOKUS
        $this->fokus = trans('fokiNames.'
        	. $request->input('focus', 'web'));
        if(strpos($this->fokus,"."))
        {
            $this->fokus = trans('fokiNames.web');
        }

        # SUMA-FILE
        if(App::isLocale("en")){
675
            $this->sumaFile = config_path() . "/sumas.xml";
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        }else{
            $this->sumaFile = config_path() . "/sumas.xml";
        }
        if(!file_exists($this->sumaFile))
        {
            die("Suma-File konnte nicht gefunden werden");
        }

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

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

695 696 697 698 699 700 701 702 703 704 705
        # Language:
        if( isset($_SERVER['HTTP_LANGUAGE']) )
        {
            $this->language = $_SERVER['HTTP_LANGUAGE'];
        }else
        {
            $this->language = "";
        }
        # Category
        $this->category = $request->input('category', '');
        # Request Times:
706 707
        $this->time = $request->input('time', 1000);
       
708 709 710 711
        # Page
        $this->page = $request->input('page', 1);
        # Lang
        $this->lang = $request->input('lang', 'all');
712
        if ( $this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all" )
713 714 715 716 717
        {
        	$this->lang = "all";
        }
        $this->agent = new Agent();
        $this->mobile = $this->agent->isMobile();
Dominik Hebeler's avatar
Dominik Hebeler committed
718

719
        #Sprüche
720 721 722 723 724
        $this->sprueche = $request->input('sprueche', 'off');
        if($this->sprueche === "off" )
            $this->sprueche = true;
        else
            $this->sprueche = false;
725 726 727 728 729 730
        # Ergebnisse pro Seite:
        $this->resultCount = $request->input('resultCount', '20');

        # Manchmal müssen wir Parameter anpassen um den Sucheinstellungen gerecht zu werden:
        if( $request->has('dart') )
        {
731
        	$this->time = 10000;
732 733
        	$this->warnings[] = "Hinweis: Sie haben Dart-Europe aktiviert. Die Suche kann deshalb länger dauern und die maximale Suchzeit wurde auf 10 Sekunden hochgesetzt.";
        }
734
        if( $this->time <= 500 || $this->time > 20000 )
735
        {
736
        	$this->time = 1000;
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
        }
        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);
        }
        if( $request->has('ebay') )
        {
753
        	$this->time = 2000;
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
        	$this->warnings[] = "Hinweis: Sie haben Ebay aktiviert. Die Suche kann deshalb länger dauern und die maximale Suchzeit wurde auf 2 Sekunden hochgesetzt.";
        }
        if( App::isLocale("en") )
        {
        	$this->sprueche = "off";
        }
        if($this->resultCount <= 0 || $this->resultCount > 200 )
        {
        	$this->resultCount = 1000;
        }
        if( $request->has('onenewspageAll') || $request->has('onenewspageGermanyAll') )
        {
        	$this->time = 5000;
        	$this->cache = "cache";
        }
769 770
        if( $request->has('tab'))
        {
771
            if($request->input('tab') === "off")
772 773 774 775 776 777 778 779 780 781
            {
                $this->tab = "_blank";
            }else
            {
                $this->tab = "_self";
            }
        }else
        {
            $this->tab = "_blank";
        }
782 783 784 785 786 787 788
        if( $request->has('password') )
            $this->password = $request->input('password');
        if( $request->has('quicktips') )
            $this->quicktips = false;
        else
            $this->quicktips = true;

789 790 791 792
        $this->out = $request->input('out', "html");
        if($this->out !== "html" && $this->out !== "json" && $this->out !== "results" && $this->out !== "results-with-style")
            $this->out = "html";
        $this->request = $request;
793 794 795 796 797 798 799 800 801 802
	}

	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];
		}
803 804 805 806
        if( $request->has('site') )
        {
            $this->site = $request->input('site');
        }
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
		# 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
861 862 863 864 865
        $p = "";
        $tmp = $this->q;
		while(preg_match("/(.*)\"(.+)\"(.*)/si", $tmp, $match)){
            $tmp = $match[1] . $match[3];
            $this->phrases[] = strtolower($match[2]);
866
		}
867 868 869 870 871 872 873
        foreach($this->phrases as $phrase)
        {
            $p .= "\"$phrase\", ";
        }
        $p = rtrim($p, ", ");
        if(sizeof($this->phrases) > 0)
            $this->warnings[] = "Sie führen eine Phrasensuche durch: $p";
874
	}
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890

    public function getFokus ()
    {
        return $this->fokus;
    }

    public function getIp ()
    {
        return $this->ip;
    }

    public function getEingabe ()
    {
        return $this->eingabe;
    }

891 892 893 894 895
    public function getQ ()
    {
            return $this->q;
    }

896 897 898 899 900 901 902 903 904 905 906 907 908 909
    public function getUrl ()
    {
        return $this->url;
    }
    public function getTime ()
    {
        return $this->time;
    }

    public function getLanguage ()
    {
        return $this->language;
    }

910 911 912 913 914 915 916 917 918 919
    public function getLang ()
    {
        return $this->lang;
    }

    public function getSprueche ()
    {
        return $this->sprueche;
    }

920 921 922 923
    public function getCategory ()
    {
        return $this->category;
    }
924

925 926 927 928 929
    public function getPhrases ()
    {
        return $this->phrases;
    }

930 931 932 933
    public function getSumaFile ()
    {
        return $this->sumaFile;
    }
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961

    public function getUserHostBlacklist ()
    {
        return $this->hostBlacklist;
    }

    public function getUserDomainBlacklist ()
    {
        return $this->domainBlacklist;
    }

    public function getDomainBlacklist ()
    {
        return $this->domainsBlacklisted;
    }

    public function getUrlBlacklist ()
    {
        return $this->urlsBlacklisted;
    }
    public function getLanguageDetect ()
    {
        return $this->languageDetect;
    }
    public function getStopWords ()
    {
        return $this->stopWords;
    }
962
    public function getHostCount($host)
963 964 965 966 967 968 969 970 971
    {
        if(isset($this->addedHosts[$host]))
        {
            return $this->addedHosts[$host];
        }else
        {
            return 0;
        }
    }
972
    public function addHostCount($host)
973 974 975 976 977 978 979 980 981 982 983 984 985 986
    {
        $hash = md5($host);
        if(isset($this->addedHosts[$hash]))
        {
            $this->addedHosts[$hash] += 1;
        }else
        {
            $this->addedHosts[$hash] = 1;
        }
    }
    public function getSite()
    {
        return $this->site;
    }
987
    public function addLink($link)
988 989 990 991 992 993 994 995 996 997 998 999 1000
    {
        $hash = md5($link);
        if(isset($this->addedLinks[$hash]))
        {
            return false;
        }else
        {
            $this->addedLinks[$hash] = 1;

            return true;
        }
    }

1001
    public function generateSearchLink($fokus, $results = true)
1002
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
1003 1004
        $requestData = $this->request->except('page');
        $requestData['focus'] = $fokus;
1005 1006
        if($results)
            $requestData['out'] = "results";
1007 1008
        else
            $requestData['out'] = "";
Dominik Hebeler's avatar
Dominik Hebeler committed
1009
        $link = action('MetaGerSearch@search', $requestData);
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
        return $link;
    }

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

        return $link;
    }

1020
    public function generateSiteSearchLink($host)
1021 1022
    {
        $host = urlencode($host);
1023
        $requestData = $this->request->except(['page','out']);
Dominik Hebeler's avatar
Dominik Hebeler committed
1024 1025 1026
        $requestData['eingabe'] .= " site:$host";
        $requestData['focus'] = "web";
        $link = action('MetaGerSearch@search', $requestData);
1027 1028 1029
        return $link;
    }

1030
    public function generateRemovedHostLink ($host)
1031 1032
    {
        $host = urlencode($host);
1033
        $requestData = $this->request->except(['page','out']);
Dominik Hebeler's avatar
Dominik Hebeler committed
1034 1035
        $requestData['eingabe'] .= " -host:$host";
        $link = action('MetaGerSearch@search', $requestData);
1036 1037 1038
        return $link;
    }

1039
    public function generateRemovedDomainLink ($domain)
1040 1041
    {
        $domain = urlencode($domain);
1042
        $requestData = $this->request->except(['page','out']);
Dominik Hebeler's avatar
Dominik Hebeler committed
1043 1044
        $requestData['eingabe'] .= " -domain:$domain";
        $link = action('MetaGerSearch@search', $requestData);
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
        return $link;
    }

    public function getTab ()
    {
        return $this->tab;
    }
    public function getResults ()
    {
        return $this->results;
    }
    public function popAd()
    {
        if(count($this->ads) > 0)
            return get_object_vars(array_shift($this->ads));
        else
            return null;
    }
1063 1064 1065 1066 1067 1068 1069
    public function getImageProxyLink($link)
    {
        $requestData = [];
        $requestData["url"] = $link;
        $link = action('Pictureproxy@get', $requestData);
        return $link;
    }
1070 1071 1072 1073
    public function showQuicktips ()
    {
        return $this->quicktips;
    }
1074
}