MetaGerSearch.php 11.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 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
        #die($request->header('User-Agent'));
15
        $time = microtime();
16
17
        # Mit gelieferte Formulardaten parsen und abspeichern:
        $metager->parseFormData($request);
18
19
20
21
22
23

        # 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())])));
        }

24
25
        # Nach Spezialsuchen überprüfen:
        $metager->checkSpecialSearches($request);
26

27
28
        # Alle Suchmaschinen erstellen
        $metager->createSearchEngines($request);
29

30
31
32
        # Alle Ergebnisse vor der Zusammenführung ranken:
        $metager->rankAll();

33
        # Ergebnisse der Suchmaschinen kombinieren:
Phil Höfer's avatar
Phil Höfer committed
34
        $metager->prepareResults();
35

36
37
        # Die Ausgabe erstellen:
        return $metager->createView();
Dominik Hebeler's avatar
Dominik Hebeler committed
38
39
    }

40
41
42
43
44
45
46
47
    public function botProtection($redirect)
    {
        $hash = md5(date('YmdHi'));
        return view('botProtection')
            ->with('hash', $hash)
            ->with('r', $redirect);
    }

48
    public function quicktips(Request $request, MetaGer $metager)
49
    {
Phil Höfer's avatar
Phil Höfer committed
50
        $q          = $request->input('q', '');
Dominik Hebeler's avatar
Dominik Hebeler committed
51
        $mquicktips = [];
Phil Höfer's avatar
Phil Höfer committed
52
53
54
        $quicktips  = [];
        $spruch     = "";

55
56
57
58
59
60
61
62
63
64
65
        # 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
66
                }
67
68
69
70
71
72
73
74
75
76
77
78
79
80
            }
            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
81
                }
82

Phil Höfer's avatar
Phil Höfer committed
83
            }
84
85
        } catch (\ErrorException $e) {
        }
Phil Höfer's avatar
Phil Höfer committed
86

87
        if (APP::getLocale() === "de") {
88
89
90
91
92
93
94
95
            # 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
96

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

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
            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;
118
                    }
119
                }
120
                fclose($file);
121
            }
Phil Höfer's avatar
Phil Höfer committed
122

123
124
125
            # 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
126

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

129
130
131
132
133
134
                $searchWords = explode(' ', $q);
                $within      = false;
                foreach ($searchWords as $word) {
                    if (stripos($result["name"], $word) !== false) {
                        $within = true;
                    }
135
                }
136
137
138
139
                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
140

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
                    $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;
159
                }
160
            } catch (\ErrorException $e) {
Phil Höfer's avatar
Phil Höfer committed
161

162
163
164
165
            }
        }

        # Wikipedia Quicktip
166
        $url             = "https://" . APP::getLocale() . ".wikipedia.org/w/api.php?action=opensearch&search=" . urlencode($q) . "&limit=10&namespace=0&format=json&redirects=resolve";
167
        $decodedResponse = json_decode($this->get($url), true);
168
        if (isset($decodedResponse[1][0]) && isset($decodedResponse[2][0]) && isset($decodedResponse[3][0])) {
169
170
            $quicktip     = [];
            $firstSummary = $decodedResponse[2][0];
171
            // Wenn es mehr als ein Ergebnis gibt
172
173
174
175
176
177
178
179
180
181
182
            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;
183
184
185
186
187
188
189
                $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');
            }
190
            $quicktips[] = $quicktip;
191
192
193
        }
        $mquicktips = array_merge($mquicktips, $quicktips);

Phil Höfer's avatar
Phil Höfer committed
194
        if (APP::getLocale() === "de") {
195
196
197
198
199
200
201
202
203
204
            # 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
205

206
207
208
209
210
                    if (App::isLocale('de')) {
                        array_unshift($mquicktips, $quicktip);
                    } else {
                        $mquicktips[] = $quicktip;
                    }
211
                }
Phil Höfer's avatar
Phil Höfer committed
212
            }
Phil Höfer's avatar
Phil Höfer committed
213

214
215
216
217
218
            # 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
219

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

223
224
225
226
227
228
229
230
231
232
            # 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']];
                }
233
            }
234
        }
Phil Höfer's avatar
Phil Höfer committed
235

236
237
238
239
        return view('quicktip')
            ->with('spruch', $spruch)
            ->with('mqs', $mquicktips);

240
241
    }

242
243
    public function tips()
    {
244
        $file = storage_path() . "/app/public/tips.txt";
245
        $tips = [];
246
247
        if (file_exists($file)) {
            $tips = file($file);
248
249
250
251
252
253
        }
        return view('tips')
            ->with('title', 'MetaGer - Tipps & Tricks')
            ->with('tips', $tips);
    }

254
255
    public function get($url)
    {
256
        return file_get_contents($url);
257
258
    }
}