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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
        $quicktips  = [];
        $spruch     = "";

        if (APP::getLocale() === "de") {

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

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

                    if (isset($result["Redirect"])) {
                        $bang            = [];
                        $bang["title"]   = "!bang-Weiterleitung";
                        $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">Weitersuchen auf ' . parse_url($bang["URL"], PHP_URL_HOST) . '&hellip;</a>';
                        $bang["gefVon"]  = "von <a href = \"https://api.duckduckgo.com/\" target=\"_blank\" rel=\"noopener\">DuckDuckGo</a>";
                        $mquicktips[]    = $bang;
                    }

                }
            } catch (\ErrorException $e) {
            }

89
90
91
92
93
94
95
96
            # 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
97

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

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

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

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

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

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

163
164
165
166
            }
        }

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

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

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

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

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

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

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

241
242
    }

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

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