Searchengine.php 10.5 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;
Dominik Hebeler's avatar
Dominik Hebeler committed
10
use Request;
11

12
abstract class Searchengine
13
{
14
    use DispatchesJobs;
15

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

    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

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

37 38
    private $headers; # Headers to add

Karl's avatar
Karl committed
39
    public $fp; # Wird für Artefakte benötigt
Dominik Hebeler's avatar
Dominik Hebeler committed
40 41 42
    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
43
    public $connection_time = 0; # Wird eventuell für Artefakte benötigt
44

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

Karl's avatar
Karl committed
50
        # Cache Standarddauer 60
Dominik Hebeler's avatar
Dominik Hebeler committed
51
        $this->cacheDuration = 60;
52
        if (isset($engine->{"cache-duration"}) && $engine->{"cache-duration"} !== -1) {
Dominik Hebeler's avatar
Dominik Hebeler committed
53
            $this->cacheDuration = $engine->{"cache-duration"};
54
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
55

Dominik Hebeler's avatar
Dominik Hebeler committed
56
        $this->useragent = $metager->getUserAgent();
Dominik Hebeler's avatar
Dominik Hebeler committed
57
        $this->ip = $metager->getIp();
58
        $this->startTime = microtime();
59 60 61 62 63
        # 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;
        }
64

65
        $this->headers = $this->engine->{"request-header"};
66

67 68 69 70
        # Suchstring generieren
        $q = $metager->getQ();
        $filters = $metager->getSumaFile()->filter;
        foreach ($metager->getQueryFilter() as $queryFilter => $filter) {
Dominik Hebeler's avatar
Dominik Hebeler committed
71
            $filterOptions = $filters->{"query-filter"}->$queryFilter;
72 73 74
            $filterOptionsEngine = $filterOptions->sumas->{$this->name};
            $query = $filterOptionsEngine->prefix . $filter . $filterOptionsEngine->suffix;
            $q = $query . " " . $q;
75
        }
76

Dominik Hebeler's avatar
Dominik Hebeler committed
77 78 79 80 81 82 83 84 85 86 87
        # Parse enabled Parameter-Filter
        foreach ($metager->getParameterFilter() as $filterName => $filter) {
            $inputParameter = Request::input($filter->{"get-parameter"}, "");
            if (empty($inputParameter) || empty($filter->sumas->{$name}->values->{$inputParameter})) {
                continue;
            }
            $engineParameterKey = $filter->sumas->{$name}->{"get-parameter"};
            $engineParameterValue = $filter->sumas->{$name}->values->{$inputParameter};
            $this->engine->{"get-parameter"}->{$engineParameterKey} = $engineParameterValue;
        }

88 89
        $this->getString = $this->generateGetString($q);
        $this->hash = md5($this->engine->host . $this->getString . $this->engine->port . $this->name);
90
        $this->resultHash = $metager->getHashCode();
Dominik Hebeler's avatar
Dominik Hebeler committed
91
        $this->canCache = $metager->canCache();
92 93 94 95
    }

    abstract public function loadResults($result);

96
    # Standardimplementierung der getNext Funktion, damit diese immer verwendet werden kann
97 98
    public function getNext(MetaGer $metager, $result)
    {
99 100 101

    }

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

Dominik Hebeler's avatar
Dominik Hebeler committed
106
        if ($this->canCache && Cache::has($this->hash)) {
107
            $this->cached = true;
108
            $this->retrieveResults($metager);
109
        } else {
110 111 112 113 114 115 116
            // 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
117

118
            $url = "";
119
            if ($this->engine->port === 443) {
120
                $url = "https://";
Dominik Hebeler's avatar
Dominik Hebeler committed
121
            } else {
122 123
                $url = "http://";
            }
124 125 126
            $url .= $this->engine->host;
            if ($this->engine->port !== 80 && $this->engine->port !== 443) {
                $url .= ":" . $this->engine->port;
Dominik Hebeler's avatar
Dominik Hebeler committed
127 128
            }
            $url .= $this->getString;
Dominik Hebeler's avatar
Dominik Hebeler committed
129
            $url = base64_encode($url);
130

Dominik Hebeler's avatar
Dominik Hebeler committed
131
            $mission = $this->resultHash . ";" . $url . ";" . $metager->getTime();
132 133 134 135 136
            // 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);

137
            /**
Dominik Hebeler's avatar
Dominik Hebeler committed
138 139 140 141 142 143 144 145 146 147 148
             * 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.
             **/
149 150 151 152 153
            $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
154
            // So if it's empty, then we have currently no searcher running and
155
            // of course need to spawn a new one.
Dominik Hebeler's avatar
Dominik Hebeler committed
156
            if (sizeof($searcherData) === 0) {
157
                $needSearcher = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
158
            } else {
159 160 161 162 163
                // 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
164 165
                // First calculate the median of all Times
                $median = 0;
Dominik Hebeler's avatar
Dominik Hebeler committed
166
                foreach ($searcherData as $pid => $data) {
Dominik Hebeler's avatar
Dominik Hebeler committed
167 168 169 170
                    $data = explode(";", $data);
                    $median += floatval($data[1]);
                }
                $median /= sizeof($searcherData);
Dominik Hebeler's avatar
Dominik Hebeler committed
171
                if ($median < .1) {
Dominik Hebeler's avatar
Dominik Hebeler committed
172 173
                    $needSearcher = true;
                }
174
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
175
            if ($needSearcher && Redis::get($this->name) !== "locked") {
Dominik Hebeler's avatar
Dominik Hebeler committed
176
                Redis::set($this->name, "locked");
177
                $this->dispatch(new Searcher($this->name, $this->username, $this->password, $this->headers));
178
            }
179 180 181
        }
    }

Karl's avatar
Karl committed
182
    # Ruft die Ranking-Funktion aller Ergebnisse auf.
183
    public function rank($eingabe)
184 185
    {
        foreach ($this->results as $result) {
186
            $result->rank($eingabe);
187 188 189 190
            if (str_contains($this->engine->{"display-name"}, "Yahoo")) {
                #die(var_dump($result));
            }

191 192 193
        }
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
194 195
    public function setResultHash($hash)
    {
196 197 198
        $this->resultHash = $hash;
    }

Karl's avatar
Karl committed
199
    # Fragt die Ergebnisse von Redis ab und lädt Sie
200
    public function retrieveResults(MetaGer $metager)
201 202 203
    {
        if ($this->loaded) {
            return true;
204 205
        }

206
        $body = "";
207

Dominik Hebeler's avatar
Dominik Hebeler committed
208
        if ($this->canCache && $this->cacheDuration > 0 && Cache::has($this->hash)) {
209 210 211
            $body = Cache::get($this->hash);
        } elseif (Redis::hexists('search.' . $this->resultHash, $this->name)) {
            $body = Redis::hget('search.' . $this->resultHash, $this->name);
212
            Redis::hdel('search.' . $this->resultHash, $this->name);
Dominik Hebeler's avatar
Dominik Hebeler committed
213
            if ($this->canCache && $this->cacheDuration > 0) {
214 215 216
                Cache::put($this->hash, $body, $this->cacheDuration);
            }
        }
217
        if ($body !== "" && $body !== "connected" && $body !== "waiting") {
218
            $this->loadResults($body);
219
            $this->getNext($metager, $body);
220 221 222 223 224 225 226
            $this->loaded = true;
            return true;
        } else {
            return false;
        }
    }

Karl's avatar
Karl committed
227
    # Erstellt den für die Get-Anfrage genutzten String
228
    protected function generateGetString($query)
229 230 231 232
    {
        $getString = "";

        # Skript:
233 234
        if (!empty($this->engine->path)) {
            $getString .= $this->engine->path;
235 236 237 238
        } else {
            $getString .= "/";
        }

239 240 241 242
        $getString .= "?";
        $parameter = [];
        foreach ($this->engine->{"get-parameter"} as $key => $value) {
            $parameter[] = $this->urlEncode($key) . "=" . $this->urlEncode($value);
243
        }
244
        $getString .= implode("&", $parameter);
245

246 247 248 249
        # Append the Query String
        $getString .= "&" . $this->engine->{"query-parameter"} . "=" . $this->urlEncode($query);
/*
die(var_dump($getString));
250

251 252 253 254
# Affildata
if (strpos($getString, "<<AFFILDATA>>")) {
$getString = str_replace("<<AFFILDATA>>", $this->getOvertureAffilData($url), $getString);
}*/
255 256 257
        return $getString;
    }

Karl's avatar
Karl committed
258
    # Wandelt einen String nach aktuell gesetztem inputEncoding dieser Searchengine in URL-Format um
259 260 261 262 263 264 265 266 267
    protected function urlEncode($string)
    {
        if (isset($this->inputEncoding)) {
            return urlencode(mb_convert_encoding($string, $this->inputEncoding));
        } else {
            return urlencode($string);
        }
    }
}