Searchengine.php 8.86 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

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

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

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

Dominik Hebeler's avatar
Dominik Hebeler committed
60
61
62
63
64
65
        if ($this->engine->{"request-header"}) {
            $this->headers = [];
            foreach ($this->headers as $key => $value) {
                $this->headers[$key] = $value;
            }
        }
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
        # Parse enabled Parameter-Filter
        foreach ($metager->getParameterFilter() as $filterName => $filter) {
79
80
            $inputParameter = $filter->value;

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

89
        $this->getString = $this->generateGetString($q);
Karl Hasselbring's avatar
Karl Hasselbring committed
90
        $this->updateHash();
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
    public function getNext(MetaGer $metager, $result)
Dominik Hebeler's avatar
Dominik Hebeler committed
98
    {}
99

Karl's avatar
Karl committed
100
    # Prüft, ob die Suche bereits gecached ist, ansonsted wird sie als Job dispatched
101
102
    public function startSearch(\App\MetaGer $metager)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
103
        if ($this->canCache && Cache::has($this->hash)) {
104
            $this->cached = true;
105
            $this->retrieveResults($metager);
106
        } else {
107
108
109
110
111
            // 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
112

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

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

            $mission = json_encode($mission);

136
137
138
            // 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
139
            Redis::rpush(\App\MetaGer::FETCHQUEUE_KEY, $mission);
140
141
142
143
144
            // 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);
            }
145
146
147
        }
    }

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

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

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

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

Dominik Hebeler's avatar
Dominik Hebeler committed
173
        $body = null;
174

Dominik Hebeler's avatar
Dominik Hebeler committed
175
        if (Cache::has($this->hash)) {
176
            $body = Cache::get($this->hash);
Dominik Hebeler's avatar
Dominik Hebeler committed
177
178
179
180
        }
        /*
        if ($this->canCache && $this->cacheDuration > 0 && Cache::has($this->hash)) {
        $body = Cache::get($this->hash);
181
        } elseif ($redis->hexists($metager->getRedisEngineResult() . $this->name, "response")) {
Dominik Hebeler's avatar
Dominik Hebeler committed
182
183
184
        $body = $redis->hget($metager->getRedisEngineResult() . $this->name, "response");
        if ($this->canCache && $this->cacheDuration > 0) {
        Cache::put($this->hash, $body, $this->cacheDuration);
185
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
186
187
        }*/
        if ($body !== null) {
188
            $this->loadResults($body);
189
            $this->getNext($metager, $body);
190
191
192
193
194
195
196
            $this->loaded = true;
            return true;
        } else {
            return false;
        }
    }

Karl's avatar
Karl committed
197
    # Erstellt den für die Get-Anfrage genutzten String
198
    protected function generateGetString($query)
199
200
201
202
    {
        $getString = "";

        # Skript:
203
204
        if (!empty($this->engine->path)) {
            $getString .= $this->engine->path;
205
206
207
208
        } else {
            $getString .= "/";
        }

209
210
211
212
        $getString .= "?";
        $parameter = [];
        foreach ($this->engine->{"get-parameter"} as $key => $value) {
            $parameter[] = $this->urlEncode($key) . "=" . $this->urlEncode($value);
213
        }
214
        $getString .= implode("&", $parameter);
215

216
217
        # Append the Query String
        $getString .= "&" . $this->engine->{"query-parameter"} . "=" . $this->urlEncode($query);
218

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

221
222
223
        return $getString;
    }

Karl's avatar
Karl committed
224
    # Wandelt einen String nach aktuell gesetztem inputEncoding dieser Searchengine in URL-Format um
225
226
227
228
229
230
231
232
    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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

    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 [];
    }
250
}