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

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

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

38
39
40
41
42
43
        # 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
44
45
46
47
48
49
50
51
52
53
54
        foreach ($spamEntries as $index => $entry) {
            $entry = trim($entry);
            if (empty($entry)) {
                continue;
            }
            if (preg_match("/" . $entry . "/si", $eingabe)) {
                $spamEntry = $entry;
                break;
            }
        }

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

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

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

Dominik Hebeler's avatar
Dominik Hebeler committed
73
74
75
76
        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);
77
78
        }

79
80
81
82
83
        $quicktips = $metager->createQuicktips();
        if (!empty($timings)) {
            $timings["createQuicktips"] = microtime(true) - $time;
        }

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

88
89
        $metager->startSearch($timings);

90
        # Versuchen die Ergebnisse der Quicktips zu laden
Davide Aprea's avatar
Davide Aprea committed
91
92
93
94
95
96
97
        if($quicktips !== null) {
            $quicktipResults = $quicktips->loadResults();
            if (!empty($timings)) {
                $timings["Loaded Quicktip Results"] = microtime(true) - $time;
            }
        } else {
            $quicktipResults = [];
98
99
        }

100
        $metager->waitForMainResults();
Dominik Hebeler's avatar
Dominik Hebeler committed
101
102
103
        if (!empty($timings)) {
            $timings["waitForMainResults"] = microtime(true) - $time;
        }
104
105

        $metager->retrieveResults();
Dominik Hebeler's avatar
Dominik Hebeler committed
106
107
108
        if (!empty($timings)) {
            $timings["retrieveResults"] = microtime(true) - $time;
        }
109

110
111
        # Alle Ergebnisse vor der Zusammenführung ranken:
        $metager->rankAll();
Dominik Hebeler's avatar
Dominik Hebeler committed
112
113
114
        if (!empty($timings)) {
            $timings["rankAll"] = microtime(true) - $time;
        }
115

116
        # Ergebnisse der Suchmaschinen kombinieren:
117
        $metager->prepareResults($timings);
118

Dominik Hebeler's avatar
Dominik Hebeler committed
119
120
121
122
123
124
125
        $finished = true;
        foreach ($metager->getEngines() as $engine) {
            if ($engine->loaded) {
                $engine->setNew(false);
                $engine->markNew();
            }
        }
Davide Aprea's avatar
Davide Aprea committed
126
127
128
129
130
131
132
133
134
135
136
137
138
        try {
            Cache::put("loader_" . $metager->getSearchUid(), [
                "metager" => [
                    "apiAuthorized" => $metager->isApiAuthorized(),
                ],
                "adgoal" => [
                    "loaded" => $metager->isAdgoalLoaded(),
                    "adgoalHash" => $metager->getAdgoalHash(),
                ],
                "engines" => $metager->getEngines(),
            ], 60 * 60);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
139
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
140
141
142
        if (!empty($timings)) {
            $timings["Filled resultloader Cache"] = microtime(true) - $time;
        }
143

144
        # Die Ausgabe erstellen:
145
        $resultpage = $metager->createView($quicktipResults);
Dominik Hebeler's avatar
Dominik Hebeler committed
146
        if ($spamEntry !== null) {
147
148
149
150
151
            try {
                Cache::put('spam.' . $metager->getFokus() . "." . md5($spamEntry), $resultpage->render(), 604800);
            } catch (\Exception $e) {
                Log::error($e->getMessage());
            }
152
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
153

Dominik Hebeler's avatar
Dominik Hebeler committed
154
155
156
157
158
159
160
161
        if (!empty($timings)) {
            $timings["createView"] = microtime(true) - $time;
        }

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

Dominik Hebeler's avatar
Dominik Hebeler committed
162
        $registry = \Prometheus\CollectorRegistry::getDefault();
163
164
        $counter = $registry->getOrRegisterCounter('metager', 'result_counter', 'counts total number of returned results', []);
        $counter->incBy(sizeof($metager->getResults()));
Dominik Hebeler's avatar
Dominik Hebeler committed
165
166
        $counter = $registry->getOrRegisterCounter('metager', 'query_counter', 'counts total number of search queries', []);
        $counter->inc();
167

168
169
170
171
        // 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) {
172
            echo($responsePart);
173
174
            flush();
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
175
176
        $requestTime = microtime(true) - $time;
        \App\PrometheusExporter::Duration($requestTime, "request_time");
Dominik Hebeler's avatar
Dominik Hebeler committed
177
178
    }

Dominik Hebeler's avatar
Dominik Hebeler committed
179
180
181
182
183
184
185
186
    public function searchTimings(Request $request, MetaGer $metager)
    {
        $request->merge([
            'eingabe' => "Hannover",
        ]);
        return $this->search($request, $metager, true);
    }

187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    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
202
        $request->request->add(["javascript" => true]);
203
204
205
        # Create a MetaGer Instance with the supplied hash
        $hash = $request->input('loadMore', '');

206
207
208
209
210
211
        # Parser Skripte einhängen
        $dir = app_path() . "/Models/parserSkripte/";
        foreach (scandir($dir) as $filename) {
            $path = $dir . $filename;
            if (is_file($path)) {
                require_once $path;
212
            }
213
        }
214

215
216
        $cached = Cache::get($hash);
        if ($cached === null) {
217
218
            return response()->json(['finished' => true]);
        }
219

220
221
222
223
        $engines = $cached["engines"];
        $adgoal = $cached["adgoal"];
        $mg = $cached["metager"];

Dominik Hebeler's avatar
Dominik Hebeler committed
224
        $metager = new MetaGer(substr($hash, strpos($hash, "loader_") + 7));
225
226
227
        $metager->setApiAuthorized($mg["apiAuthorized"]);
        $metager->setAdgoalLoaded($adgoal["loaded"]);
        $metager->setAdgoalHash($adgoal["adgoalHash"]);
228

229
        $metager->parseFormData($request, false);
230
231
232
233
        # Nach Spezialsuchen überprüfen:
        $metager->checkSpecialSearches($request);
        $metager->restoreEngines($engines);

Dominik Hebeler's avatar
Dominik Hebeler committed
234
235
236
        # Checks Cache for engine Results
        $metager->checkCache();

237
        $metager->retrieveResults();
238

239
240
241
242
243
244
        $metager->rankAll();
        $metager->prepareResults();

        $result = [
            'finished' => true,
            'newResults' => [],
245
            'changedResults' => [],
246
247
248
        ];
        $result["nextSearchLink"] = $metager->nextSearchLink();

249
        $newResults = 0;
250
        foreach ($metager->getResults() as $index => $resultTmp) {
Davide Aprea's avatar
Davide Aprea committed
251
            if ($resultTmp->new || $resultTmp->changed) {
252
253
254
                if ($metager->getFokus() !== "bilder") {
                    $view = View::make('layouts.result', ['index' => $index, 'result' => $resultTmp, 'metager' => $metager]);
                    $html = $view->render();
Davide Aprea's avatar
Davide Aprea committed
255
                    if (!$resultTmp->new && $resultTmp->changed) {
256
257
258
259
                        $result['changedResults'][$index] = $html;
                    } else {
                        $result['newResults'][$index] = $html;
                    }
260
261
262
263
                    $result["imagesearch"] = false;
                } else {
                    $view = View::make('layouts.image_result', ['index' => $index, 'result' => $resultTmp, 'metager' => $metager]);
                    $html = $view->render();
Davide Aprea's avatar
Davide Aprea committed
264
                    if (!$resultTmp->new && $resultTmp->changed) {
265
266
267
268
                        $result['changedResults'][$index] = $html;
                    } else {
                        $result['newResults'][$index] = $html;
                    }
269
                    $result["imagesearch"] = true;
270
                }
271
                $newResults++;
272
273
            }
        }
274

Dominik Hebeler's avatar
Dominik Hebeler committed
275
        $finished = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
276
        $enginesLoaded = [];
Dominik Hebeler's avatar
Dominik Hebeler committed
277
278
        foreach ($engines as $engine) {
            if (!$engine->loaded) {
Dominik Hebeler's avatar
Dominik Hebeler committed
279
                $enginesLoaded[$engine->name] = false;
Dominik Hebeler's avatar
Dominik Hebeler committed
280
281
                $finished = false;
            } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
282
                $enginesLoaded[$engine->name] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
283
284
285
286
                $engine->setNew(false);
                $engine->markNew();
            }
        }
287

288
        if (!$metager->isAdgoalLoaded()) {
289
            $finished = false;
290
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
291
292

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

295
        if ($newResults > 0) {
296
297
298
299
            $registry = \Prometheus\CollectorRegistry::getDefault();
            $counter = $registry->getOrRegisterCounter('metager', 'result_counter', 'counts total number of returned results', []);
            $counter->incBy($newResults);
        }
300
        // Update new Engines
301
302
303
304
305
306
307
308
309
310
        Cache::put("loader_" . $metager->getSearchUid(), [
            "metager" => [
                "apiAuthorized" => $metager->isApiAuthorized(),
            ],
            "adgoal" => [
                "loaded" => $metager->isAdgoalLoaded(),
                "adgoalHash" => $metager->getAdgoalHash(),
            ],
            "engines" => $metager->getEngines(),
        ], 1 * 60);
311
312
313
314

        # JSON encoding will fail if invalid UTF-8 Characters are in this string
        # mb_convert_encoding will remove thise invalid characters for us
        $result = mb_convert_encoding($result, "UTF-8", "UTF-8");
315
316
317
        return response()->json($result);
    }

318
319
320
321
322
323
324
325
    public function botProtection($redirect)
    {
        $hash = md5(date('YmdHi'));
        return view('botProtection')
            ->with('hash', $hash)
            ->with('r', $redirect);
    }

326
327
    public function get($url)
    {
328
        $ctx = stream_context_create(array('http' => array('timeout' => 2)));
329
        return file_get_contents($url, false, $ctx);
330
    }
331
332
333
334
335
336

    private function startsWith($haystack, $needle)
    {
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }
337
338
339

    public function tips(Request $request)
    {
340
341
342
343
344
345
        $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";
        }
346
347
348
        if (LaravelLocalization::getCurrentLocale() == "en") {
            $tipserver .= "?locale=en";
        }
349
        $tips_text = file_get_contents($tipserver);
350
        $tips = [];
351
        try {
Dominik Hebeler's avatar
Dominik Hebeler committed
352
            $tips_xml = \simplexml_load_string($tips_text);
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367

            $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);
    }
368

369
    public function quicktips(Request $request)
370
    {
371
        $search = $request->input('search', '');
372
        $quotes = $request->input('quotes', 'on');
373
        if (empty($search)) {
Dominik Hebeler's avatar
Dominik Hebeler committed
374
            abort(404);
375
376
        }

377
        $quicktips = new \App\Models\Quicktips\Quicktips($search, $quotes);
Dominik Hebeler's avatar
Dominik Hebeler committed
378
379
380
        return view('quicktips')
            ->with('quicktips', $quicktips->getResults())
            ->with('search', $search);
381
    }
382
}