MetaGerSearch.php 11.8 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 Illuminate\Http\Request;
Phil Höfer's avatar
Phil Höfer committed
8
use LaravelLocalization;
Dominik Hebeler's avatar
Dominik Hebeler committed
9
10
11

class MetaGerSearch extends Controller
{
12
    public function search(Request $request, MetaGer $metager)
13
    {
14
        $focus = $request->input("focus", "web");
15
        if ($focus !== "angepasst" && $this->startsWith($focus, "focus_")) {
16
17
18
19
20
21
            $metager->parseFormData($request);
            if ($metager->doBotProtection($request->input('bot', ""))) {
                return redirect(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), url("/noaccess", ['redirect' => base64_encode(url()->full())])));
            }
            return $metager->createView();
        }
22
        #die($request->header('User-Agent'));
23
        $time = microtime();
24
25
        # Mit gelieferte Formulardaten parsen und abspeichern:
        $metager->parseFormData($request);
26
27
28
29
30
31

        # Ein Schutz gegen bestimmte Bot-Angriffe, die uns passiert sind.
        if ($metager->doBotProtection($request->input('bot', ""))) {
            return redirect(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), url("/noaccess", ['redirect' => base64_encode(url()->full())])));
        }

32
33
        # Nach Spezialsuchen überprüfen:
        $metager->checkSpecialSearches($request);
34

35
36
        # Alle Suchmaschinen erstellen
        $metager->createSearchEngines($request);
37

38
39
40
        # Alle Ergebnisse vor der Zusammenführung ranken:
        $metager->rankAll();

41
        # Ergebnisse der Suchmaschinen kombinieren:
Phil Höfer's avatar
Phil Höfer committed
42
        $metager->prepareResults();
43

44
45
        # Die Ausgabe erstellen:
        return $metager->createView();
Dominik Hebeler's avatar
Dominik Hebeler committed
46
47
    }

48
49
50
51
52
53
54
55
    public function botProtection($redirect)
    {
        $hash = md5(date('YmdHi'));
        return view('botProtection')
            ->with('hash', $hash)
            ->with('r', $redirect);
    }

56
    public function quicktips(Request $request, MetaGer $metager)
57
    {
Phil Höfer's avatar
Phil Höfer committed
58
        $q          = $request->input('q', '');
Dominik Hebeler's avatar
Dominik Hebeler committed
59
        $mquicktips = [];
Phil Höfer's avatar
Phil Höfer committed
60
61
62
        $quicktips  = [];
        $spruch     = "";

63
64
65
66
67
68
69
70
71
72
73
        # DuckDuckGo-!bangs
        try {
            $placeholder = "0X0plchldr0X0";
            $searchWords = explode(" ", $q);
            $dummyQuery  = "";
            $realQuery   = "";
            foreach ($searchWords as $index => $word) {
                if ($word[0] === "!") {
                    $dummyQuery .= $word . " ";
                } else {
                    $realQuery .= $word;
Phil Höfer's avatar
Phil Höfer committed
74
                }
75
76
77
78
79
80
81
82
83
84
85
86
87
88
            }
            if ($dummyQuery !== "") {
                $dummyQuery .= $placeholder;
                $url = "https://api.duckduckgo.com/?format=json&no_redirect=1&t=MetaGerDE&q=" . urlencode($dummyQuery);

                $result = json_decode($this->get($url), true);

                if (isset($result["Redirect"])) {
                    $bang            = [];
                    $bang["title"]   = trans('metaGerSearch.quicktips.bang.title');
                    $bang["URL"]     = str_replace($placeholder, urlencode(trim($realQuery)), $result["Redirect"]);
                    $bang["summary"] = '<a href="' . $bang["URL"] . '" target=_blank class="btn btn-primary" style="margin-top:5px;color: #fff">' . trans('metaGerSearch.quicktips.bang.buttonlabel') . " " . parse_url($bang["URL"], PHP_URL_HOST) . '&hellip;</a>';
                    $bang["gefVon"]  = trans('metaGerSearch.quicktips.bang.from') . " <a href = \"https://api.duckduckgo.com/\" target=\"_blank\" rel=\"noopener\">DuckDuckGo</a>";
                    $mquicktips[]    = $bang;
Phil Höfer's avatar
Phil Höfer committed
89
                }
90

Phil Höfer's avatar
Phil Höfer committed
91
            }
92
93
        } catch (\ErrorException $e) {
        }
Phil Höfer's avatar
Phil Höfer committed
94

95
        if (APP::getLocale() === "de") {
96
97
98
99
100
101
102
103
            # Spruch
            $spruecheFile = storage_path() . "/app/public/sprueche.txt";
            if (file_exists($spruecheFile) && $request->has('sprueche')) {
                $sprueche = file($spruecheFile);
                $spruch   = $sprueche[array_rand($sprueche)];
            } else {
                $spruch = "";
            }
Phil Höfer's avatar
Phil Höfer committed
104

105
106
            # manuelle Quicktips:
            $file = storage_path() . "/app/public/qtdata.csv";
Phil Höfer's avatar
Phil Höfer committed
107

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
            if (file_exists($file) && $q !== '') {
                $file = fopen($file, 'r');
                while (($line = fgetcsv($file)) !== false) {
                    $words = array_slice($line, 3);
                    $isIn  = false;
                    foreach ($words as $word) {
                        $word = strtolower($word);
                        if (strpos($q, $word) !== false) {
                            $isIn = true;
                            break;
                        }
                    }
                    if ($isIn === true) {
                        $quicktip            = array('QT_Type' => "MQT");
                        $quicktip["URL"]     = $line[0];
                        $quicktip["title"]   = $line[1];
                        $quicktip["summary"] = $line[2];
                        $mquicktips[]        = $quicktip;
126
                    }
127
                }
128
                fclose($file);
129
            }
Phil Höfer's avatar
Phil Höfer committed
130

131
132
133
            # Wetter
            try {
                $url = "http://api.openweathermap.org/data/2.5/weather?type=accurate&units=metric&lang=" . APP::getLocale() . "&q=" . urlencode($q) . "&APPID=" . getenv("openweathermap");
Phil Höfer's avatar
Phil Höfer committed
134

135
                $result = json_decode($this->get($url), true);
Phil Höfer's avatar
Phil Höfer committed
136

137
138
139
140
141
142
                $searchWords = explode(' ', $q);
                $within      = false;
                foreach ($searchWords as $word) {
                    if (stripos($result["name"], $word) !== false) {
                        $within = true;
                    }
143
                }
144
145
146
147
                if ($within) {
                    $weather          = [];
                    $weather["title"] = "Wetter in " . $result["name"];
                    $weather["URL"]   = "http://openweathermap.org/city/" . $result["id"];
Phil Höfer's avatar
Phil Höfer committed
148

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
                    $summary = '<b class="detail-short">' . $result["main"]["temp"] . " °C, " . $result["weather"][0]["description"] . "</b>";
                    $details = '<table  class="table table-condensed"><tr><td>Temperatur</td><td>' . $result["main"]["temp_min"] . " bis " . $result["main"]["temp_max"] . " °C</td></tr>";
                    $details .= "<tr><td>Druck</td><td>" . $result["main"]["pressure"] . " hPa</td></tr>";
                    $details .= "<tr><td>Luftfeuchtigkeit</td><td>" . $result["main"]["humidity"] . " %</td></tr>";
                    $details .= "<tr><td>Wind</td><td>" . $result["wind"]["speed"] . " m/s, " . $result["wind"]["deg"] . "°</td></tr>";
                    $details .= "<tr><td>Bewölkung</td><td>" . $result["clouds"]["all"] . " %</td></tr>";
                    if (isset($result->rain)) {
                        $details .= " | Regen letzte drei Stunden: " . $result["rain"]["3h"] . " h";
                    }
                    $details .= "</table>";
                    $weather["summary"]   = $summary;
                    $weather["details"]   = $details;
                    $weather["gefVon"]    = "von <a href = \"https://openweathermap.org\" target=\"_blank\" rel=\"noopener\">Openweathermap</a>";
                    $requestData          = [];
                    $requestData["url"]   = "http://openweathermap.org/img/w/";
                    $weather["image"]     = action('Pictureproxy@get', $requestData) . $result["weather"][0]["icon"] . ".png";
                    $weather["image-alt"] = $result["weather"][0]["main"];
                    $mquicktips[]         = $weather;
167
                }
168
            } catch (\ErrorException $e) {
Phil Höfer's avatar
Phil Höfer committed
169

170
171
172
173
            }
        }

        # Wikipedia Quicktip
174
        $url             = "https://" . APP::getLocale() . ".wikipedia.org/w/api.php?action=opensearch&search=" . urlencode($q) . "&limit=10&namespace=0&format=json&redirects=resolve";
175
        $decodedResponse = json_decode($this->get($url), true);
176
        if (isset($decodedResponse[1][0]) && isset($decodedResponse[2][0]) && isset($decodedResponse[3][0])) {
177
178
            $quicktip     = [];
            $firstSummary = $decodedResponse[2][0];
179
            // Wenn es mehr als ein Ergebnis gibt
180
181
182
183
184
185
186
187
188
189
190
            if (isset($decodedResponse[1][1])) {
                // Solange noch zusätzliche Seiten vorhanden sind, füge sie der Tabelle hinzu
                $details = '<table class=table table-condensed>';
                for ($i = 1;isset($decodedResponse[1][$i]) && isset($decodedResponse[2][$i]) && isset($decodedResponse[3][$i]); $i++) {
                    $details .= '<tr><td><a href="' . $decodedResponse[3][$i] . '" target="_blank" rel="noopener">' . $decodedResponse[1][$i] . '</a></td></tr>';
                }
                $details .= '</table>';
                $quicktip["title"]   = $decodedResponse[1][0];
                $quicktip["URL"]     = $decodedResponse[3][0];
                $quicktip["summary"] = $decodedResponse[2][0];
                $quicktip["details"] = $details;
191
192
193
194
195
196
197
                $quicktip['gefVon']  = trans('metaGerSearch.quicktips.wikipedia.adress');
            } else {
                $quicktip["title"]   = $decodedResponse[1][0];
                $quicktip["URL"]     = $decodedResponse[3][0];
                $quicktip["summary"] = $decodedResponse[2][0];
                $quicktip['gefVon']  = trans('metaGerSearch.quicktips.wikipedia.adress');
            }
198
            $quicktips[] = $quicktip;
199
200
201
        }
        $mquicktips = array_merge($mquicktips, $quicktips);

Phil Höfer's avatar
Phil Höfer committed
202
        if (APP::getLocale() === "de") {
203
204
205
206
207
208
209
210
211
212
            # Dict.cc Quicktip
            if (count(explode(' ', $q)) < 3) {
                $url             = "http://www.dict.cc/metager.php?s=" . urlencode($q);
                $decodedResponse = json_decode($this->get($url), true);
                if ($decodedResponse["headline"] != "" && $decodedResponse["link"] != "") {
                    $quicktip            = [];
                    $quicktip["title"]   = $decodedResponse["headline"];
                    $quicktip["URL"]     = $decodedResponse["link"];
                    $quicktip["summary"] = implode(", ", $decodedResponse["translations"]);
                    $quicktip['gefVon']  = trans('metaGerSearch.quicktips.dictcc.adress');
Phil Höfer's avatar
Phil Höfer committed
213

214
215
216
217
218
                    if (App::isLocale('de')) {
                        array_unshift($mquicktips, $quicktip);
                    } else {
                        $mquicktips[] = $quicktip;
                    }
219
                }
Phil Höfer's avatar
Phil Höfer committed
220
            }
Phil Höfer's avatar
Phil Höfer committed
221

222
223
224
225
226
            # wussten Sie schon
            $file = storage_path() . "/app/public/tips.txt";
            if (file_exists($file)) {
                $tips = file($file);
                $tip  = $tips[array_rand($tips)];
Phil Höfer's avatar
Phil Höfer committed
227

228
229
                $mquicktips[] = ['title' => trans('metaGerSearch.quicktips.tips.title'), 'summary' => $tip, 'URL' => '/tips'];
            }
Phil Höfer's avatar
Phil Höfer committed
230

231
232
233
234
235
236
237
238
239
240
            # Werbelinks
            $file = storage_path() . "/app/public/ads.txt";
            if (file_exists($file)) {
                $ads = json_decode(file_get_contents($file), true);
                $ad  = $ads[array_rand($ads)];
                if (isset($ads['details'])) {
                    $mquicktips[] = ['title' => $ad['title'], 'summary' => $ad['summary'], 'details' => $ad['details'], 'URL' => $ad['URL']];
                } else {
                    $mquicktips[] = ['title' => $ad['title'], 'summary' => $ad['summary'], 'URL' => $ad['URL']];
                }
241
            }
242
        }
Phil Höfer's avatar
Phil Höfer committed
243

244
245
246
247
        return view('quicktip')
            ->with('spruch', $spruch)
            ->with('mqs', $mquicktips);

248
249
    }

250
251
    public function tips()
    {
252
        $file = storage_path() . "/app/public/tips.txt";
253
        $tips = [];
254
255
        if (file_exists($file)) {
            $tips = file($file);
256
257
258
259
260
261
        }
        return view('tips')
            ->with('title', 'MetaGer - Tipps & Tricks')
            ->with('tips', $tips);
    }

262
263
    public function get($url)
    {
264
        return file_get_contents($url);
265
    }
266
267
268
269
270
271

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