Searchengine.php 9.6 KB
Newer Older
1 2
<?php

3
namespace App\Models;
4

5
use App\Jobs\Searcher;
6
use App\MetaGer;
7 8
use Cache;
use Illuminate\Foundation\Bus\DispatchesJobs;
9
use Illuminate\Support\Facades\Redis;
10

11
abstract class Searchengine
12
{
13
    use DispatchesJobs;
14

Karl's avatar
Karl committed
15 16
    public $getString = ""; # Der String für die Get-Anfrage
    public $engine; # Die ursprüngliche Engine XML
Dominik Hebeler's avatar
Dominik Hebeler committed
17 18
    public $results = []; # Die geladenen Ergebnisse
    public $ads = []; # Die geladenen Werbungen
Dominik Hebeler's avatar
Dominik Hebeler committed
19
    public $products = []; # Die geladenen Produkte
Dominik Hebeler's avatar
Dominik Hebeler committed
20 21
    public $loaded = false; # wahr, sobald die Ergebnisse geladen wurden
    public $cached = false;
Karl's avatar
Karl committed
22 23 24 25 26 27 28 29 30 31

    public $ip; # Die IP aus der metager
    public $uses; # Die Anzahl der Nutzungen dieser Suchmaschine
    public $homepage; # Die Homepage dieser Suchmaschine
    public $name; # Der Name dieser Suchmaschine
    public $disabled; # Ob diese Suchmaschine ausgeschaltet ist
    public $useragent; # Der HTTP Useragent
    public $startTime; # Die Zeit der Erstellung dieser Suchmaschine
    public $hash; # Der Hash-Wert dieser Suchmaschine

32
    private $username; # Username für HTTP-Auth (falls angegeben)
33 34
    private $password; # Passwort für HTTP-Auth (falls angegeben)

35 36
    private $headers; # Headers to add

Karl's avatar
Karl committed
37
    public $fp; # Wird für Artefakte benötigt
Dominik Hebeler's avatar
Dominik Hebeler committed
38 39 40
    public $socketNumber = null; # Wird für Artefakte benötigt
    public $counter = 0; # Wird eventuell für Artefakte benötigt
    public $write_time = 0; # Wird eventuell für Artefakte benötigt
Karl's avatar
Karl committed
41
    public $connection_time = 0; # Wird eventuell für Artefakte benötigt
42

43
    public function __construct($name, \stdClass $engine, MetaGer $metager)
44
    {
45 46
        $this->engine = $engine;
        $this->name = $name;
47

Karl's avatar
Karl committed
48
        # Cache Standarddauer 60
49 50 51
        if (!isset($this->cacheDuration)) {
            $this->cacheDuration = 60;
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
52
        $this->useragent = $metager->getUserAgent();
Dominik Hebeler's avatar
Dominik Hebeler committed
53
        $this->ip = $metager->getIp();
54
        $this->startTime = microtime();
55 56 57 58 59
        # check for http Auth
        if (!empty($this->engine->{"http-auth-credentials"}->username) && !empty($this->engine->{"http-auth-credentials"}->password)) {
            $this->username = $this->engine->{"http-auth-credentials"}->username;
            $this->password = $this->engine->{"http-auth-credentials"}->password;
        }
60

61
        $this->headers = $this->engine->{"request-header"};
62

63 64 65 66 67 68 69 70
        # Suchstring generieren
        $q = $metager->getQ();
        $filters = $metager->getSumaFile()->filter;
        foreach ($metager->getQueryFilter() as $queryFilter => $filter) {
            $filterOptions = $filters->$queryFilter;
            $filterOptionsEngine = $filterOptions->sumas->{$this->name};
            $query = $filterOptionsEngine->prefix . $filter . $filterOptionsEngine->suffix;
            $q = $query . " " . $q;
71
        }
72 73 74

        $this->getString = $this->generateGetString($q);
        $this->hash = md5($this->engine->host . $this->getString . $this->engine->port . $this->name);
75
        $this->resultHash = $metager->getHashCode();
Dominik Hebeler's avatar
Dominik Hebeler committed
76
        $this->canCache = $metager->canCache();
77 78 79 80
    }

    abstract public function loadResults($result);

81
    # Standardimplementierung der getNext Funktion, damit diese immer verwendet werden kann
82 83
    public function getNext(MetaGer $metager, $result)
    {
84 85 86

    }

Karl's avatar
Karl committed
87
    # Prüft, ob die Suche bereits gecached ist, ansonsted wird sie als Job dispatched
88 89
    public function startSearch(\App\MetaGer $metager)
    {
90

Dominik Hebeler's avatar
Dominik Hebeler committed
91
        if ($this->canCache && Cache::has($this->hash)) {
92
            $this->cached = true;
93
            $this->retrieveResults($metager);
94
        } else {
95 96 97 98 99 100 101
            // We will push the confirmation of the submission to the Result Hash
            Redis::hset('search.' . $this->resultHash, $this->name, "waiting");
            // We need to submit a action that one of our workers can understand
            // The missions are submitted to a redis queue in the following string format
            // <ResultHash>;<URL to fetch>
            // With <ResultHash> being the Hash Value where the fetcher will store the result.
            // and <URL to fetch> being the full URL to the searchengine
102

103
            $url = "";
104
            if ($this->engine->port === 443) {
105
                $url = "https://";
Dominik Hebeler's avatar
Dominik Hebeler committed
106
            } else {
107 108
                $url = "http://";
            }
109 110 111
            $url .= $this->engine->host;
            if ($this->engine->port !== 80 && $this->engine->port !== 443) {
                $url .= ":" . $this->engine->port;
Dominik Hebeler's avatar
Dominik Hebeler committed
112 113
            }
            $url .= $this->getString;
Dominik Hebeler's avatar
Dominik Hebeler committed
114
            $url = base64_encode($url);
115

Dominik Hebeler's avatar
Dominik Hebeler committed
116
            $mission = $this->resultHash . ";" . $url . ";" . $metager->getTime();
117 118 119 120 121
            // Submit this mission to the corresponding Redis Queue
            // Since each Searcher is dedicated to one specific search engine
            // each Searcher has it's own queue lying under the redis key <name>.queue
            Redis::rpush($this->name . ".queue", $mission);

122
            /**
Dominik Hebeler's avatar
Dominik Hebeler committed
123 124 125 126 127 128 129 130 131 132 133
             * We have Searcher processes running for MetaGer
             * Each Searcher is dedicated to one specific Searchengine and fetches it's results.
             * We can have multiple Searchers for each engine, if needed.
             * At this point we need to decide, whether we need to start a new Searcher process or
             * if we have enough of them running.
             * The information for that is provided through the redis system. Each running searcher
             * gives information how long it has waited to be given the last fetcher job.
             * The longer this time value is, the less frequent the search engine is used and the less
             * searcher of that type we need.
             * But if it's too low, i.e. 100ms, then the searcher is near to it's full workload and needs assistence.
             **/
134 135 136 137 138
            $needSearcher = false;
            $searcherData = Redis::hgetall($this->name . ".stats");

            // We now have an array of statistical data from the searchers
            // Each searcher has one entry in it.
Dominik Hebeler's avatar
Dominik Hebeler committed
139
            // So if it's empty, then we have currently no searcher running and
140
            // of course need to spawn a new one.
Dominik Hebeler's avatar
Dominik Hebeler committed
141
            if (sizeof($searcherData) === 0) {
142
                $needSearcher = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
143
            } else {
144 145 146 147 148
                // There we go:
                // There's at least one Fetcher running for this search engine.
                // Now we have to check if the current count is enough to fetch all the
                // searches or if it needs help.
                // Let's hardcode a minimum of 100ms between every search job.
Dominik Hebeler's avatar
Dominik Hebeler committed
149 150
                // First calculate the median of all Times
                $median = 0;
Dominik Hebeler's avatar
Dominik Hebeler committed
151
                foreach ($searcherData as $pid => $data) {
Dominik Hebeler's avatar
Dominik Hebeler committed
152 153 154 155
                    $data = explode(";", $data);
                    $median += floatval($data[1]);
                }
                $median /= sizeof($searcherData);
Dominik Hebeler's avatar
Dominik Hebeler committed
156
                if ($median < .1) {
Dominik Hebeler's avatar
Dominik Hebeler committed
157 158
                    $needSearcher = true;
                }
159
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
160
            if ($needSearcher && Redis::get($this->name) !== "locked") {
Dominik Hebeler's avatar
Dominik Hebeler committed
161
                Redis::set($this->name, "locked");
162
                $this->dispatch(new Searcher($this->name, $this->username, $this->password, $this->headers));
163
            }
164 165 166
        }
    }

Karl's avatar
Karl committed
167
    # Ruft die Ranking-Funktion aller Ergebnisse auf.
168
    public function rank($eingabe)
169 170
    {
        foreach ($this->results as $result) {
171
            $result->rank($eingabe);
172 173 174
        }
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
175 176
    public function setResultHash($hash)
    {
177 178 179
        $this->resultHash = $hash;
    }

Karl's avatar
Karl committed
180
    # Fragt die Ergebnisse von Redis ab und lädt Sie
181
    public function retrieveResults(MetaGer $metager)
182 183 184
    {
        if ($this->loaded) {
            return true;
185 186
        }

187
        $body = "";
Dominik Hebeler's avatar
Dominik Hebeler committed
188
        if ($this->canCache && $this->cacheDuration > 0 && Cache::has($this->hash)) {
189 190 191
            $body = Cache::get($this->hash);
        } elseif (Redis::hexists('search.' . $this->resultHash, $this->name)) {
            $body = Redis::hget('search.' . $this->resultHash, $this->name);
192
            Redis::hdel('search.' . $this->resultHash, $this->name);
Dominik Hebeler's avatar
Dominik Hebeler committed
193
            if ($this->canCache && $this->cacheDuration > 0) {
194 195 196
                Cache::put($this->hash, $body, $this->cacheDuration);
            }
        }
197
        if ($body !== "" && $body !== "connected" && $body !== "waiting") {
198
            $this->loadResults($body);
199
            $this->getNext($metager, $body);
200 201 202 203 204 205 206
            $this->loaded = true;
            return true;
        } else {
            return false;
        }
    }

Karl's avatar
Karl committed
207
    # Erstellt den für die Get-Anfrage genutzten String
208
    protected function generateGetString($query)
209 210 211 212
    {
        $getString = "";

        # Skript:
213 214
        if (!empty($this->engine->path)) {
            $getString .= $this->engine->path;
215 216 217 218
        } else {
            $getString .= "/";
        }

219 220 221 222
        $getString .= "?";
        $parameter = [];
        foreach ($this->engine->{"get-parameter"} as $key => $value) {
            $parameter[] = $this->urlEncode($key) . "=" . $this->urlEncode($value);
223
        }
224
        $getString .= implode("&", $parameter);
225

226 227 228 229
        # Append the Query String
        $getString .= "&" . $this->engine->{"query-parameter"} . "=" . $this->urlEncode($query);
/*
die(var_dump($getString));
230

231 232 233 234
# Affildata
if (strpos($getString, "<<AFFILDATA>>")) {
$getString = str_replace("<<AFFILDATA>>", $this->getOvertureAffilData($url), $getString);
}*/
235 236 237
        return $getString;
    }

Karl's avatar
Karl committed
238
    # Wandelt einen String nach aktuell gesetztem inputEncoding dieser Searchengine in URL-Format um
239 240 241 242 243 244 245 246 247
    protected function urlEncode($string)
    {
        if (isset($this->inputEncoding)) {
            return urlencode(mb_convert_encoding($string, $this->inputEncoding));
        } else {
            return urlencode($string);
        }
    }
}