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

3
namespace App\Models;
4

5
use App\MetaGer;
6
use Cache;
7
use Illuminate\Support\Facades\Redis;
8

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

    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

29
    private $username; # Username für HTTP-Auth (falls angegeben)
30
31
    private $password; # Passwort für HTTP-Auth (falls angegeben)

32
33
    private $headers; # Headers to add

Karl's avatar
Karl committed
34
    public $fp; # Wird für Artefakte benötigt
Dominik Hebeler's avatar
Dominik Hebeler committed
35
36
37
    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
38
    public $connection_time = 0; # Wird eventuell für Artefakte benötigt
Dominik Hebeler's avatar
Dominik Hebeler committed
39
    public $cacheDuration = 60; # Wie lange soll das Ergebnis im Cache bleiben (Minuten)
40
    public $new = true; # Important for loading results by JS
41

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

47
        if (isset($engine->{"cache-duration"}) && $engine->{"cache-duration"} !== -1) {
Dominik Hebeler's avatar
Dominik Hebeler committed
48
            $this->cacheDuration = $engine->{"cache-duration"};
49
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
50
        $this->cacheDuration = max($this->cacheDuration, 5);
Dominik Hebeler's avatar
Dominik Hebeler committed
51

Dominik Hebeler's avatar
Dominik Hebeler committed
52
        $this->useragent = $metager->getUserAgent();
Dominik Hebeler's avatar
Dominik Hebeler committed
53
        $this->ip = $metager->getIp();
Dominik Hebeler's avatar
Dominik Hebeler committed
54
        $this->startTime = microtime(true);
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

Dominik Hebeler's avatar
Dominik Hebeler committed
61
62
63
64
65
66
        if ($this->engine->{"request-header"}) {
            $this->headers = [];
            foreach ($this->headers as $key => $value) {
                $this->headers[$key] = $value;
            }
        }
67

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

Dominik Hebeler's avatar
Dominik Hebeler committed
78
79
        # Parse enabled Parameter-Filter
        foreach ($metager->getParameterFilter() as $filterName => $filter) {
80
81
            $inputParameter = $filter->value;

Dominik Hebeler's avatar
Dominik Hebeler committed
82
83
84
85
86
87
88
89
            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;
        }

90
        $this->getString = $this->generateGetString($q);
Karl Hasselbring's avatar
Karl Hasselbring committed
91
        $this->updateHash();
Dominik Hebeler's avatar
Dominik Hebeler committed
92
        $this->canCache = $metager->canCache();
93
94
95
96
    }

    abstract public function loadResults($result);

97
    # Standardimplementierung der getNext Funktion, damit diese immer verwendet werden kann
98
    public function getNext(MetaGer $metager, $result)
Dominik Hebeler's avatar
Dominik Hebeler committed
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)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
104
        if ($this->canCache && Cache::has($this->hash)) {
105
            $this->cached = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
106
            $this->retrieveResults($metager, true);
107
        } else {
108
109
110
111
112
            // 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
113

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

Dominik Hebeler's avatar
Dominik Hebeler committed
126
127
128
129
130
131
132
133
134
135
136
            $mission = [
                "resulthash" => $this->hash,
                "url" => $url,
                "username" => $this->username,
                "password" => $this->password,
                "headers" => $this->headers,
                "cacheDuration" => $this->cacheDuration,
            ];

            $mission = json_encode($mission);

137
138
139
            // 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
Dominik Hebeler's avatar
Dominik Hebeler committed
140
            Redis::rpush(\App\MetaGer::FETCHQUEUE_KEY, $mission);
141
142
143
144
145
            // The request is not cached and will be submitted to the searchengine
            // We need to check if the number of requests to this engine are limited
            if (!empty($this->engine->{"monthly-requests"})) {
                Redis::incr("monthlyRequests:" . $this->name);
            }
146
147
148
        }
    }

Karl's avatar
Karl committed
149
    # Ruft die Ranking-Funktion aller Ergebnisse auf.
150
    public function rank($eingabe)
151
152
    {
        foreach ($this->results as $result) {
153
            $result->rank($eingabe);
154
155
156
        }
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
157
158
    public function setResultHash($hash)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
159
160
161
        $this->resultHash = $hash;
    }

Karl Hasselbring's avatar
Karl Hasselbring committed
162
163
164
165
166
    public function updateHash()
    {
        $this->hash = md5($this->engine->host . $this->getString . $this->engine->port . $this->name);
    }

Karl's avatar
Karl committed
167
    # Fragt die Ergebnisse von Redis ab und lädt Sie
168
    public function retrieveResults(MetaGer $metager)
169
170
171
    {
        if ($this->loaded) {
            return true;
172
173
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
174
175
176
177
178
179
180
181
        $body = null;
        if ($this->cached) {
            $body = Cache::get($this->hash);
            if ($body === "no-result") {
                $body = "";
            }
        } else {
            $body = Redis::get($this->hash);
182
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
183

Dominik Hebeler's avatar
Dominik Hebeler committed
184
        if ($body !== null) {
185
            $this->loadResults($body);
186
            $this->getNext($metager, $body);
187
            $this->markNew();
188
189
190
191
192
193
194
            $this->loaded = true;
            return true;
        } else {
            return false;
        }
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
195
    public function markNew()
196
197
198
199
200
201
    {
        foreach ($this->results as $result) {
            $result->new = $this->new;
        }
    }

Karl's avatar
Karl committed
202
    # Erstellt den für die Get-Anfrage genutzten String
203
    protected function generateGetString($query)
204
205
206
207
    {
        $getString = "";

        # Skript:
208
209
        if (!empty($this->engine->path)) {
            $getString .= $this->engine->path;
210
211
212
213
        } else {
            $getString .= "/";
        }

214
215
216
217
        $getString .= "?";
        $parameter = [];
        foreach ($this->engine->{"get-parameter"} as $key => $value) {
            $parameter[] = $this->urlEncode($key) . "=" . $this->urlEncode($value);
218
        }
219
        $getString .= implode("&", $parameter);
220

221
222
        # Append the Query String
        $getString .= "&" . $this->engine->{"query-parameter"} . "=" . $this->urlEncode($query);
223

Karl Hasselbring's avatar
Karl Hasselbring committed
224
225
        $getString .= $this->getDynamicParamsString();

226
227
228
        return $getString;
    }

Karl's avatar
Karl committed
229
    # Wandelt einen String nach aktuell gesetztem inputEncoding dieser Searchengine in URL-Format um
230
231
232
233
234
235
236
237
    protected function urlEncode($string)
    {
        if (isset($this->inputEncoding)) {
            return urlencode(mb_convert_encoding($string, $this->inputEncoding));
        } else {
            return urlencode($string);
        }
    }
Karl Hasselbring's avatar
Karl Hasselbring committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254

    private function getDynamicParamsString()
    {
        $paramString = "";

        $params = $this->getDynamicParams();
        foreach ($params as $key => $value) {
            $paramString .= sprintf("&%s=%s", urlencode($key), urlencode($value));
        }

        return $paramString;
    }

    protected function getDynamicParams()
    {
        return [];
    }
255
256
257
258
259

    public function setNew($new)
    {
        $this->new = $new;
    }
260
}