MetaGerSearch.php 12.1 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
        # DuckDuckGo-!bangs
        try {
            $placeholder = "0X0plchldr0X0";
            $searchWords = explode(" ", $q);
            $dummyQuery  = "";
            $realQuery   = "";
            foreach ($searchWords as $index => $word) {
                if ($word[0] === "!") {
                    $dummyQuery .= $word . " ";
                } else {
Aria Givi's avatar
Aria Givi committed
73
                    $realQuery .= $word . " ";
Phil Höfer's avatar
Phil Höfer committed
74
                }
75
            }
Aria Givi's avatar
Aria Givi committed
76
77
            $realQuery = rtrim($realQuery);
            
78
79
80
81
82
83
84
85
86
87
88
89
90
            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
91
                }
92

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

97
        if (APP::getLocale() === "de") {
98
99
100
101
102
103
104
105
            # 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
106

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

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
            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;
128
                    }
129
                }
130
                fclose($file);
131
            }
Phil Höfer's avatar
Phil Höfer committed
132

133
134
135
            # 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
136

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

139
140
141
142
143
144
                $searchWords = explode(' ', $q);
                $within      = false;
                foreach ($searchWords as $word) {
                    if (stripos($result["name"], $word) !== false) {
                        $within = true;
                    }
145
                }
146
147
148
149
                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
150

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
                    $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;
169
                }
170
            } catch (\ErrorException $e) {
Phil Höfer's avatar
Phil Höfer committed
171

172
173
            }
        }
Phil Höfer's avatar
Phil Höfer committed
174
    
175
        # Wikipedia Quicktip
176
        $url             = "https://" . APP::getLocale() . ".wikipedia.org/w/api.php?action=opensearch&search=" . urlencode($q) . "&limit=10&namespace=0&format=json&redirects=resolve";
177
178
179
180
181
182
    	try{
    		$content = $this->get($url);
    	}catch(\ErrorException $e){
    		$content = "";
    	}
        $decodedResponse = json_decode($content, true);
183
        if (isset($decodedResponse[1][0]) && isset($decodedResponse[2][0]) && isset($decodedResponse[3][0])) {
184
185
            $quicktip     = [];
            $firstSummary = $decodedResponse[2][0];
186
            // Wenn es mehr als ein Ergebnis gibt
187
188
189
190
191
192
193
194
195
196
197
            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;
198
199
200
201
202
203
204
                $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');
            }
205
            $quicktips[] = $quicktip;
206
207
        }
        $mquicktips = array_merge($mquicktips, $quicktips);
Phil Höfer's avatar
Phil Höfer committed
208
    
Phil Höfer's avatar
Phil Höfer committed
209
        if (APP::getLocale() === "de") {
210
211
212
213
214
215
216
217
218
219
            # 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
220

221
222
223
224
225
                    if (App::isLocale('de')) {
                        array_unshift($mquicktips, $quicktip);
                    } else {
                        $mquicktips[] = $quicktip;
                    }
226
                }
Phil Höfer's avatar
Phil Höfer committed
227
            }
Phil Höfer's avatar
Phil Höfer committed
228

229
230
231
232
233
            # 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
234

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

238
239
240
241
242
243
244
245
246
247
            # 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']];
                }
248
            }
249
        }
Phil Höfer's avatar
Phil Höfer committed
250

251
252
253
254
        return view('quicktip')
            ->with('spruch', $spruch)
            ->with('mqs', $mquicktips);

255
256
    }

257
258
    public function tips()
    {
259
        $file = storage_path() . "/app/public/tips.txt";
260
        $tips = [];
261
262
        if (file_exists($file)) {
            $tips = file($file);
263
264
265
266
267
268
        }
        return view('tips')
            ->with('title', 'MetaGer - Tipps & Tricks')
            ->with('tips', $tips);
    }

269
270
    public function get($url)
    {
271
272
	   $ctx = stream_context_create(array('http'=>array('timeout' => 2,)));
        return file_get_contents($url, false, $ctx);
273
    }
274
275
276
277
278
279

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