MetaGerSearch.php 12.6 KB
Newer Older
Dominik Hebeler's avatar
Dominik Hebeler committed
1
2
3
4
<?php

namespace App\Http\Controllers;

5
use App;
6
use App\MetaGer;
7
use Cache;
8
use Illuminate\Http\Request;
9
use LaravelLocalization;
10
use Log;
11
use View;
Dominik Hebeler's avatar
Dominik Hebeler committed
12
13
14

class MetaGerSearch extends Controller
{
Dominik Hebeler's avatar
Dominik Hebeler committed
15
16

    public function search(Request $request, MetaGer $metager, $timing = false)
17
    {
18
19
20
        if ($request->filled("chrome-plugin")) {
            return redirect(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), "/plugin"));
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
21
22
23
24
        $timings = null;
        if ($timing) {
            $timings = ['starttime' => microtime(true)];
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
25
        $time = microtime(true);
26
        $spamEntries = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
27
        $spamEntry = null;
28
29
30
31
        if (file_exists(config_path('spam.txt'))) {
            $spamEntries = file(config_path('spam.txt'));
        }

32
        $focus = $request->input("focus", "web");
33

34
35
36
37
38
        if ($focus === "maps") {
            $searchinput = $request->input('eingabe', '');
            return redirect()->to('https://maps.metager.de/map/' . $searchinput . '/1240908.5493525574,6638783.2192695495,6');
        }

39
40
41
42
43
44
        # If there is no query parameter we redirect to the startpage
        $eingabe = $request->input('eingabe', '');
        if (empty(trim($eingabe))) {
            return redirect(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), '/'));
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
45
46
47
48
49
50
51
52
53
54
55
        foreach ($spamEntries as $index => $entry) {
            $entry = trim($entry);
            if (empty($entry)) {
                continue;
            }
            if (preg_match("/" . $entry . "/si", $eingabe)) {
                $spamEntry = $entry;
                break;
            }
        }

56
57
        # Mit gelieferte Formulardaten parsen und abspeichern:
        $metager->parseFormData($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
58
59
60
        if (!empty($timings)) {
            $timings["parseFormData"] = microtime(true) - $time;
        }
61

62
63
        # Nach Spezialsuchen überprüfen:
        $metager->checkSpecialSearches($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
64
65
66
        if (!empty($timings)) {
            $timings["checkSpecialSearches"] = microtime(true) - $time;
        }
67

Dominik Hebeler's avatar
Dominik Hebeler committed
68
69
        # Search query can be empty after parsing the formdata
        # we will cancel the search in that case and show an error to the user
70
        if (empty($metager->getQ())) {
71
72
            return $metager->createView();
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
73

Dominik Hebeler's avatar
Dominik Hebeler committed
74
75
76
77
        if ($spamEntry !== null && Cache::has('spam.' . $metager->getFokus() . "." . md5($spamEntry))) {
            $responseContent = Cache::get('spam.' . $metager->getFokus() . "." . md5($spamEntry));
            $responseContent = preg_replace('/(name="eingabe"\s+value=")[^"]+/', "$1$eingabe", $responseContent);
            return response($responseContent);
78
79
        }

80
        # Suche für alle zu verwendenden Suchmaschinen als Job erstellen,
81
        # auf Ergebnisse warten und die Ergebnisse laden
Dominik Hebeler's avatar
Dominik Hebeler committed
82
        $metager->createSearchEngines($request, $timings);
83

Dominik Hebeler's avatar
Dominik Hebeler committed
84
        $metager->startSearch($timings);
85
86

        $metager->waitForMainResults();
Dominik Hebeler's avatar
Dominik Hebeler committed
87
88
89
        if (!empty($timings)) {
            $timings["waitForMainResults"] = microtime(true) - $time;
        }
90
91

        $metager->retrieveResults();
Dominik Hebeler's avatar
Dominik Hebeler committed
92
93
94
        if (!empty($timings)) {
            $timings["retrieveResults"] = microtime(true) - $time;
        }
95

96
97
        # Alle Ergebnisse vor der Zusammenführung ranken:
        $metager->rankAll();
Dominik Hebeler's avatar
Dominik Hebeler committed
98
99
100
        if (!empty($timings)) {
            $timings["rankAll"] = microtime(true) - $time;
        }
101

102
        # Ergebnisse der Suchmaschinen kombinieren:
Phil Höfer's avatar
Phil Höfer committed
103
        $metager->prepareResults();
Dominik Hebeler's avatar
Dominik Hebeler committed
104
105
106
        if (!empty($timings)) {
            $timings["prepareResults"] = microtime(true) - $time;
        }
107

Dominik Hebeler's avatar
Dominik Hebeler committed
108
109
110
111
112
113
114
115
        $finished = true;
        foreach ($metager->getEngines() as $engine) {
            if ($engine->loaded) {
                $engine->setNew(false);
                $engine->markNew();
            }
        }

116
        try {
117
118
119
120
121
122
123
124
125
126
            Cache::put("loader_" . $metager->getSearchUid(), [
                "metager" => [
                    "apiAuthorized" => $metager->isApiAuthorized(),
                ],
                "adgoal" => [
                    "loaded" => $metager->isAdgoalLoaded(),
                    "adgoalHash" => $metager->getAdgoalHash(),
                ],
                "engines" => $metager->getEngines(),
            ], 60 * 60);
127
128
129
        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
130
131
132
        if (!empty($timings)) {
            $timings["Filled resultloader Cache"] = microtime(true) - $time;
        }
133

134
        # Die Ausgabe erstellen:
135
        $resultpage = $metager->createView();
Dominik Hebeler's avatar
Dominik Hebeler committed
136
        if ($spamEntry !== null) {
137
138
139
140
141
            try {
                Cache::put('spam.' . $metager->getFokus() . "." . md5($spamEntry), $resultpage->render(), 604800);
            } catch (\Exception $e) {
                Log::error($e->getMessage());
            }
142
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
143

Dominik Hebeler's avatar
Dominik Hebeler committed
144
145
146
147
148
149
150
151
        if (!empty($timings)) {
            $timings["createView"] = microtime(true) - $time;
        }

        if ($timings) {
            dd($timings);
        }

Dominik Hebeler's avatar
Dominik Hebeler committed
152
        $registry = \Prometheus\CollectorRegistry::getDefault();
153
154
        $counter = $registry->getOrRegisterCounter('metager', 'result_counter', 'counts total number of returned results', []);
        $counter->incBy(sizeof($metager->getResults()));
Dominik Hebeler's avatar
Dominik Hebeler committed
155
156
        $counter = $registry->getOrRegisterCounter('metager', 'query_counter', 'counts total number of search queries', []);
        $counter->inc();
157

158
159
160
161
162
163
164
        // Splitting the response return into multiple parts.
        // This might speed up page view time for users with slow network
        $responseArray = str_split($resultpage->render(), 1024);
        foreach ($responseArray as $responsePart) {
            echo ($responsePart);
            flush();
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
165
166
        $requestTime = microtime(true) - $time;
        \App\PrometheusExporter::Duration($requestTime, "request_time");
Dominik Hebeler's avatar
Dominik Hebeler committed
167
168
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
169
170
171
172
173
174
175
176
    public function searchTimings(Request $request, MetaGer $metager)
    {
        $request->merge([
            'eingabe' => "Hannover",
        ]);
        return $this->search($request, $metager, true);
    }

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    public function loadMore(Request $request)
    {
        /**
         * There are three forms of requests to the resultpage
         * 1. Initial Request: Loads the fastest searchengines and sends them to the user
         * 2. Load more results (with JS): Loads new search engines that answered after the initial request was send
         * 3. Load more results (without JS): Loads new search engines that answered within 1s timeout
         */
        if ($request->filled('loadMore') && $request->filled('script') && $request->input('script') === "yes") {
            return $this->loadMoreJS($request);
        }

    }

    private function loadMoreJS(Request $request)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
193
        $request->request->add(["javascript" => true]);
194
195
196
        # Create a MetaGer Instance with the supplied hash
        $hash = $request->input('loadMore', '');

197
198
199
200
201
202
        # Parser Skripte einhängen
        $dir = app_path() . "/Models/parserSkripte/";
        foreach (scandir($dir) as $filename) {
            $path = $dir . $filename;
            if (is_file($path)) {
                require_once $path;
203
            }
204
        }
205

206
207
        $cached = Cache::get($hash);
        if ($cached === null) {
208
209
            return response()->json(['finished' => true]);
        }
210

211
212
213
214
        $engines = $cached["engines"];
        $adgoal = $cached["adgoal"];
        $mg = $cached["metager"];

Dominik Hebeler's avatar
Dominik Hebeler committed
215
        $metager = new MetaGer(substr($hash, strpos($hash, "loader_") + 7));
216
217
218
        $metager->setApiAuthorized($mg["apiAuthorized"]);
        $metager->setAdgoalLoaded($adgoal["loaded"]);
        $metager->setAdgoalHash($adgoal["adgoalHash"]);
219
220
221
222
223
224

        $metager->parseFormData($request);
        # Nach Spezialsuchen überprüfen:
        $metager->checkSpecialSearches($request);
        $metager->restoreEngines($engines);

Dominik Hebeler's avatar
Dominik Hebeler committed
225
226
227
        # Checks Cache for engine Results
        $metager->checkCache();

228
        $metager->retrieveResults();
229

230
231
232
233
234
235
        $metager->rankAll();
        $metager->prepareResults();

        $result = [
            'finished' => true,
            'newResults' => [],
236
            'changedResults' => [],
237
238
239
        ];
        $result["nextSearchLink"] = $metager->nextSearchLink();

240
        $newResults = 0;
241
        foreach ($metager->getResults() as $index => $resultTmp) {
242
            if ($resultTmp->new || $resultTmp->adgoalChanged) {
243
244
245
                if ($metager->getFokus() !== "bilder") {
                    $view = View::make('layouts.result', ['index' => $index, 'result' => $resultTmp, 'metager' => $metager]);
                    $html = $view->render();
246
247
248
249
250
                    if (!$resultTmp->new && $resultTmp->adgoalChanged) {
                        $result['changedResults'][$index] = $html;
                    } else {
                        $result['newResults'][$index] = $html;
                    }
251
252
253
254
                    $result["imagesearch"] = false;
                } else {
                    $view = View::make('layouts.image_result', ['index' => $index, 'result' => $resultTmp, 'metager' => $metager]);
                    $html = $view->render();
255
256
257
258
259
                    if (!$resultTmp->new && $resultTmp->adgoalChanged) {
                        $result['changedResults'][$index] = $html;
                    } else {
                        $result['newResults'][$index] = $html;
                    }
260
                    $result["imagesearch"] = true;
261
                }
262
                $newResults++;
263
264
            }
        }
265

Dominik Hebeler's avatar
Dominik Hebeler committed
266
        $finished = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
267
        $enginesLoaded = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
268
269
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
Dominik Hebeler's avatar
Dominik Hebeler committed
270
                $enginesLoaded[$engine->name] = false;
Dominik Hebeler's avatar
Dominik Hebeler committed
271
272
                $finished = false;
            } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
273
                $enginesLoaded[$engine->name] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
274
275
276
277
                $engine->setNew(false);
                $engine->markNew();
            }
        }
278

279
        if (!$metager->isAdgoalLoaded()) {
280
            $finished = false;
281
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
282
283

        $result["finished"] = $finished;
Dominik Hebeler's avatar
Dominik Hebeler committed
284
        $result["engines"] = $enginesLoaded;
Dominik Hebeler's avatar
Dominik Hebeler committed
285

286
        if ($newResults > 0) {
287
288
289
290
            $registry = \Prometheus\CollectorRegistry::getDefault();
            $counter = $registry->getOrRegisterCounter('metager', 'result_counter', 'counts total number of returned results', []);
            $counter->incBy($newResults);
        }
291
        // Update new Engines
292
293
294
295
296
297
298
299
300
301
        Cache::put("loader_" . $metager->getSearchUid(), [
            "metager" => [
                "apiAuthorized" => $metager->isApiAuthorized(),
            ],
            "adgoal" => [
                "loaded" => $metager->isAdgoalLoaded(),
                "adgoalHash" => $metager->getAdgoalHash(),
            ],
            "engines" => $metager->getEngines(),
        ], 1 * 60);
302
303
304
        return response()->json($result);
    }

305
306
307
308
309
310
311
312
    public function botProtection($redirect)
    {
        $hash = md5(date('YmdHi'));
        return view('botProtection')
            ->with('hash', $hash)
            ->with('r', $redirect);
    }

313
314
    public function get($url)
    {
315
        $ctx = stream_context_create(array('http' => array('timeout' => 2)));
316
        return file_get_contents($url, false, $ctx);
317
    }
318
319
320
321
322
323

    private function startsWith($haystack, $needle)
    {
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }
324
325
326

    public function tips(Request $request)
    {
327
328
329
330
331
332
        $tipserver = '';
        if (env('APP_ENV') === "development") {
            $tipserver = "https://dev.quicktips.metager.de/1.1/tips.xml";
        } else {
            $tipserver = "https://quicktips.metager.de/1.1/tips.xml";
        }
333
334
335
        if (LaravelLocalization::getCurrentLocale() == "en") {
            $tipserver .= "?locale=en";
        }
336
        $tips_text = file_get_contents($tipserver);
337
        $tips = [];
338
        try {
Dominik Hebeler's avatar
Dominik Hebeler committed
339
            $tips_xml = \simplexml_load_string($tips_text);
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354

            $tips_xml->registerXPathNamespace('mg', 'http://metager.de/tips/');
            $tips_xml = $tips_xml->xpath('mg:tip');
            foreach ($tips_xml as $tip_xml) {
                $tips[] = $tip_xml->__toString();
            }
        } catch (\Exception $e) {
            Log::error("A problem occurred loading tips from the tip server.");
            Log::error($e->getMessage());
            abort(500);
        }
        return view('tips')
            ->with('title', trans('tips.title'))
            ->with('tips', $tips);
    }
355

356
    public function quicktips(Request $request)
357
    {
358
        $search = $request->input('search', '');
359
        $quotes = $request->input('quotes', 'on');
360
        if (empty($search)) {
Dominik Hebeler's avatar
Dominik Hebeler committed
361
            abort(404);
362
363
        }

364
        $quicktips = new \App\Models\Quicktips\Quicktips($search, $quotes);
Dominik Hebeler's avatar
Dominik Hebeler committed
365
366
367
        return view('quicktips')
            ->with('quicktips', $quicktips->getResults())
            ->with('search', $search);
368
    }
369
}