Searchengine.php 10.3 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
Dominik Hebeler's avatar
Dominik Hebeler committed
18
19
    public $results = []; # Die geladenen Ergebnisse
    public $ads = []; # Die geladenen Werbungen
Dominik Hebeler's avatar
Dominik Hebeler committed
20
    public $products = []; # Die geladenen Produkte
Dominik Hebeler's avatar
Dominik Hebeler committed
21
22
    public $loaded = false; # wahr, sobald die Ergebnisse geladen wurden
    public $cached = false;
Karl's avatar
Karl committed
23
24
25
26
27
28
29
30
31
32

    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

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

36
37
    private $headers; # Headers to add

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

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

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

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

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

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

Dominik Hebeler's avatar
Dominik Hebeler committed
76
77
78
79
80
81
82
83
84
85
86
        # 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;
        }

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

    abstract public function loadResults($result);

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

    }

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

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

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

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

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

Karl's avatar
Karl committed
181
    # Ruft die Ranking-Funktion aller Ergebnisse auf.
182
    public function rank($eingabe)
183
184
    {
        foreach ($this->results as $result) {
185
            $result->rank($eingabe);
186
187
188
        }
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
189
190
    public function setResultHash($hash)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
191
192
193
        $this->resultHash = $hash;
    }

Karl's avatar
Karl committed
194
    # Fragt die Ergebnisse von Redis ab und lädt Sie
195
    public function retrieveResults(MetaGer $metager)
196
197
198
    {
        if ($this->loaded) {
            return true;
199
200
        }

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

Karl's avatar
Karl committed
221
    # Erstellt den für die Get-Anfrage genutzten String
222
    protected function generateGetString($query)
223
224
225
226
    {
        $getString = "";

        # Skript:
227
228
        if (!empty($this->engine->path)) {
            $getString .= $this->engine->path;
229
230
231
232
        } else {
            $getString .= "/";
        }

233
234
235
236
        $getString .= "?";
        $parameter = [];
        foreach ($this->engine->{"get-parameter"} as $key => $value) {
            $parameter[] = $this->urlEncode($key) . "=" . $this->urlEncode($value);
237
        }
238
        $getString .= implode("&", $parameter);
239

240
241
242
243
        # Append the Query String
        $getString .= "&" . $this->engine->{"query-parameter"} . "=" . $this->urlEncode($query);
/*
die(var_dump($getString));
244

245
246
247
248
# Affildata
if (strpos($getString, "<<AFFILDATA>>")) {
$getString = str_replace("<<AFFILDATA>>", $this->getOvertureAffilData($url), $getString);
}*/
249
250
251
        return $getString;
    }

Karl's avatar
Karl committed
252
    # Wandelt einen String nach aktuell gesetztem inputEncoding dieser Searchengine in URL-Format um
253
254
255
256
257
258
259
260
261
    protected function urlEncode($string)
    {
        if (isset($this->inputEncoding)) {
            return urlencode(mb_convert_encoding($string, $this->inputEncoding));
        } else {
            return urlencode($string);
        }
    }
}