MetaGer.php 20.7 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 10 11 12 13
use App\lib\TextLanguageDetect\TextLanguageDetect;
use App\lib\TextLanguageDetect\LanguageDetect\TextLanguageDetectException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
#use \Illuminate\Pagination\Paginator;
14 15 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 = [];
	protected $engines = [];
	protected $results = [];
32
    protected $ads = [];
33
	protected $warnings = [];
34
    protected $errors = [];
35
    protected $addedHosts = [];
36 37 38 39 40 41 42 43 44
	# Daten über die Abfrage
	protected $ip;
	protected $language;
	protected $agent;
	# Konfigurationseinstellungen:
	protected $sumaFile;
	protected $mobile;
	protected $resultCount;
	protected $sprueche;
45 46 47
    protected $domainsBlacklisted = [];
    protected $urlsBlacklisted = [];
    protected $url;
48
    protected $languageDetect;
49 50 51

	function __construct()
	{
52
        $this->time = microtime();   
53 54
        define('CRLF', "\r\n");
        define('BUFFER_LENGTH', 8192);
55 56 57 58 59 60 61 62 63 64 65
        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");
        }
66 67 68

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

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

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

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

        switch ($this->out) {
Dominik Hebeler's avatar
Dominik Hebeler committed
90 91
            case 'results':
                return view('metager3results')
92 93 94 95 96 97 98 99
                    ->with('results', $viewResults)
                    ->with('eingabe', $this->eingabe)
                    ->with('mobile', $this->mobile)
                    ->with('warnings', $this->warnings)
                    ->with('errors', $this->errors)
                    ->with('metager', $this);
                break;
            default:
Dominik Hebeler's avatar
Dominik Hebeler committed
100 101 102 103 104 105 106
                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);
107 108
                break;
        }
109 110
	}

111 112 113 114 115 116 117 118 119 120 121
    public function removeInvalids ()
    {
        $results = [];
        foreach($this->results as $result)
        {
            if($result->isValid($this))
                $results[] = $result;
        }
        #$this->results = $results;
    }

122 123 124 125
	public function combineResults ()
	{
		foreach($this->engines as $engine)
		{
126 127 128 129 130 131 132 133 134
            foreach($engine->results as $result)
            {
                if($result->valid)
                    $this->results[] = $result;
            }
            foreach($engine->ads as $ad)
            {
                $this->ads[] = $ad;
            }
135
		}
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        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();

        //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)
        {
191 192
            if( $key = "out" )
                continue;
193 194 195 196
            $paginatedSearchResults->addQuery($key, $value);
        }

        $this->results = $paginatedSearchResults;
197 198 199 200
	}

	public function createSearchEngines (Request $request)
	{
201 202 203

        #die(SocketRocket::get("tls", "dominik-pfennig.de", "", 443));

204 205 206 207 208 209 210 211 212

		# Überprüfe, welche Sumas eingeschaltet sind
        $xml = simplexml_load_file($this->sumaFile);
        $enabledSearchengines = [];
        $overtureEnabled = FALSE;
        
        if($this->fokus === "angepasst")
        {
            $sumas = $xml->xpath("suma");
213 214 215 216 217 218 219 220 221
            /**$maxSumas = 30;
            $count = 0;
            foreach($sumas as $suma)
            {
                if($maxSumas === $count)
                    break;
                $enabledSearchengines[] = $suma;
                $count++;
            }**/
222 223 224
            foreach($sumas as $suma)
            {
                if($request->has($suma["service"]) 
225 226 227 228 229 230
                	|| ( $this->fokus !== "bilder" 
                		&& ($suma["name"]->__toString() === "qualigo" 
                			|| $suma["name"]->__toString() === "similar_product_ads" 
                			|| ( !$overtureEnabled && $suma["name"]->__toString() === "overtureAds" )
                			)
                		)
231
                    #|| 1 === 1  #Todo: entfernen
232
                	){
233 234 235 236 237 238 239

                	if(!(isset($suma['disabled']) && $suma['disabled']->__toString() === "1"))
                    {
                        if($suma["name"]->__toString() === "overture")
                        {
                            $overtureEnabled = TRUE;
                        }
240

241 242
                        $enabledSearchengines[] = $suma;
                    }
243 244 245 246 247 248 249
                }
            }
        }else{
            $sumas = $xml->xpath("suma");
            foreach($sumas as $suma){
                $types = explode(",",$suma["type"]);
                if(in_array($this->fokus, $types) 
250 251 252 253 254 255
                	|| ( $this->fokus !== "bilder" 
                		&& ($suma["name"]->__toString() === "qualigo" 
                			|| $suma["name"]->__toString() === "similar_product_ads" 
                			|| ( !$overtureEnabled && $suma["name"]->__toString() === "overtureAds" )
                			)
                		)
256
                	){
257 258 259 260 261 262 263 264
                    if(!(isset($suma['disabled']) && $suma['disabled']->__toString() === "1"))
                    {
                        if($suma["name"]->__toString() === "overture")
                        {
                            $overtureEnabled = TRUE;
                        }
                        $enabledSearchengines[] = $suma;
                    }
265 266 267
                }
            }
        }
268

269 270 271 272 273
        if( ( $this->fokus !== "bilder" && sizeof($enabledSearchengines) <= 3 ) || ( $this->fokus === "bilder" && sizeof($enabledSearchengines) === 0) )
        {
            $this->errors[] = "Achtung: Sie haben in ihren Einstellungen keine Suchmaschine ausgewählt.";
        }

274 275
		$engines = [];
		foreach($enabledSearchengines as $engine){
276

277 278 279 280 281 282
            if(strlen($this->site) > 0 && (!isset($engine["hasSiteSearch"]) || $engine["hasSiteSearch"]->__toString() !== "1"))
            {
                continue;
            }
            # Wenn diese Suchmaschine gar nicht eingeschaltet sein soll

283 284
            $path = "App\Models\parserSkripte\\" . ucfirst($engine["package"]->__toString());

285
            $time = microtime();
286 287
            $tmp = new $path($engine, $this);

288 289 290 291 292
            if($tmp->enabled && isset($this->debug))
            {
                $this->warnings[] = $tmp->service . "   Connection_Time: " . $tmp->connection_time . "    Write_Time: " . $tmp->write_time . " Insgesamt:" . ((microtime()-$time)/1000);
            }

293
            if($tmp->isEnabled())
294 295
            {
                $engines[] = $tmp;
296
                $this->sockets[$tmp->name] = $tmp->fp;
297
            }
298
		}
299 300 301 302 303 304 305 306

        # 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.
        usleep(500000);
        # Jetzt lesen wir alles aus, was da ist und verwerfen den Rest:
307 308
        foreach($engines as $engine)
        {
309
            $engine->retrieveResults();
310
        }
311 312


313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        $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);
		}
328
        $this->url = $request->url();
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
		# 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")){
            $this->sumaFile = config_path() . "/sumasEn.xml";
        }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:
        if( isset($_SERVER['HTTP_FROM']) )
        {
            $this->ip = $_SERVER['HTTP_FROM'];
        }else
        {
            $this->ip = "127.0.0.1";
        }
        # Language:
        if( isset($_SERVER['HTTP_LANGUAGE']) )
        {
            $this->language = $_SERVER['HTTP_LANGUAGE'];
        }else
        {
            $this->language = "";
        }
        # Category
        $this->category = $request->input('category', '');
        # Request Times:
        $this->time = $request->input('time', 1);
        # Page
        $this->page = $request->input('page', 1);
        # Lang
        $this->lang = $request->input('lang', 'all');
381
        if ( $this->lang !== "de" && $this->lang !== "en" && $this->lang !== "all" )
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
        {
        	$this->lang = "all";
        }
        $this->agent = new Agent();
        $this->mobile = $this->agent->isMobile();
        #Sprüche
        $this->sprueche = $request->input('sprueche', 'on');
        # 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') )
        {
        	$this->time = 10;
        	$this->warnings[] = "Hinweis: Sie haben Dart-Europe aktiviert. Die Suche kann deshalb länger dauern und die maximale Suchzeit wurde auf 10 Sekunden hochgesetzt.";
        }
        if( $this->time < 0 || $this->time > 20 )
        {
        	$this->time = 1;
        }
        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') )
        {
        	$this->time = 2;
        	$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";
        }
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
        if( $request->has('tab'))
        {
            if($request->input('tab') === "1")
            {
                $this->tab = "_blank";
            }else
            {
                $this->tab = "_self";
            }
        }else
        {
            $this->tab = "_blank";
        }
        $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;
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
	}

	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];
			$this->warnings[] = "Sie führen eine Sitesearch durch. Es werden nur Ergebnisse von der Seite: \"" . $this->site . "\" angezeigt.";
		}
		# 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
		if(preg_match("/\"(.+)\"/si", $this->q, $match)){
			$this->warnings[] = "Sie führen eine Phrasensuche durch: \"" . $match[1] . "\"";
		}
	}
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534

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

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

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

535 536 537 538 539 540 541 542
    public function getQ ()
    {
        if(strlen($this->site) > 0)
            return $this->q . " site:" . $this->site;
        else
            return $this->q;
    }

543 544 545 546 547 548 549 550 551 552 553 554 555 556
    public function getUrl ()
    {
        return $this->url;
    }
    public function getTime ()
    {
        return $this->time;
    }

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

557 558 559 560 561 562 563 564 565 566
    public function getLang ()
    {
        return $this->lang;
    }

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

567 568 569 570
    public function getCategory ()
    {
        return $this->category;
    }
571 572 573 574 575

    public function getSumaFile ()
    {
        return $this->sumaFile;
    }
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

    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;
    }
604
    public function getHostCount($host)
605 606 607 608 609 610 611 612 613
    {
        if(isset($this->addedHosts[$host]))
        {
            return $this->addedHosts[$host];
        }else
        {
            return 0;
        }
    }
614
    public function addHostCount($host)
615 616 617 618 619 620 621 622 623 624 625 626 627 628
    {
        $hash = md5($host);
        if(isset($this->addedHosts[$hash]))
        {
            $this->addedHosts[$hash] += 1;
        }else
        {
            $this->addedHosts[$hash] = 1;
        }
    }
    public function getSite()
    {
        return $this->site;
    }
629
    public function addLink($link)
630 631 632 633 634 635 636 637 638 639 640 641 642
    {
        $hash = md5($link);
        if(isset($this->addedLinks[$hash]))
        {
            return false;
        }else
        {
            $this->addedLinks[$hash] = 1;

            return true;
        }
    }

643
    public function generateSearchLink($fokus)
644
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
645 646 647 648
        $requestData = $this->request->except('page');
        $requestData['focus'] = $fokus;
        $requestData['out'] = "results";
        $link = action('MetaGerSearch@search', $requestData);
649 650 651 652 653 654 655 656 657 658
        return $link;
    }

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

        return $link;
    }

659
    public function generateSiteSearchLink($host)
660 661
    {
        $host = urlencode($host);
Dominik Hebeler's avatar
Dominik Hebeler committed
662 663 664 665
        $requestData = $this->request->except('page');
        $requestData['eingabe'] .= " site:$host";
        $requestData['focus'] = "web";
        $link = action('MetaGerSearch@search', $requestData);
666 667 668
        return $link;
    }

669
    public function generateRemovedHostLink ($host)
670 671
    {
        $host = urlencode($host);
Dominik Hebeler's avatar
Dominik Hebeler committed
672 673 674
        $requestData = $this->request->except('page');
        $requestData['eingabe'] .= " -host:$host";
        $link = action('MetaGerSearch@search', $requestData);
675 676 677
        return $link;
    }

678
    public function generateRemovedDomainLink ($domain)
679 680
    {
        $domain = urlencode($domain);
Dominik Hebeler's avatar
Dominik Hebeler committed
681 682 683
        $requestData = $this->request->except('page');
        $requestData['eingabe'] .= " -domain:$domain";
        $link = action('MetaGerSearch@search', $requestData);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
        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;
    }
702
}