MetaGerSearch.php 12.3 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 16 17 18 19 20
        
        if ($focus === "maps") {
            $searchinput = $request->input('eingabe', '');
            return redirect()->to('https://maps.metager.de/map/' . $searchinput . '/1240908.5493525574,6638783.2192695495,6');
        }

21
        if ($focus !== "angepasst" && $this->startsWith($focus, "focus_")) {
22 23 24 25 26 27
            $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();
        }
28
        #die($request->header('User-Agent'));
29
        $time = microtime();
30 31
        # Mit gelieferte Formulardaten parsen und abspeichern:
        $metager->parseFormData($request);
32 33 34 35 36 37

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

38 39
        # Nach Spezialsuchen überprüfen:
        $metager->checkSpecialSearches($request);
40

41 42
        # Alle Suchmaschinen erstellen
        $metager->createSearchEngines($request);
43

44 45 46
        # Alle Ergebnisse vor der Zusammenführung ranken:
        $metager->rankAll();

47
        # Ergebnisse der Suchmaschinen kombinieren:
Phil Höfer's avatar
Phil Höfer committed
48
        $metager->prepareResults();
49

50 51
        # Die Ausgabe erstellen:
        return $metager->createView();
Dominik Hebeler's avatar
Dominik Hebeler committed
52 53
    }

54 55 56 57 58 59 60 61
    public function botProtection($redirect)
    {
        $hash = md5(date('YmdHi'));
        return view('botProtection')
            ->with('hash', $hash)
            ->with('r', $redirect);
    }

62
    public function quicktips(Request $request, MetaGer $metager)
63
    {
Phil Höfer's avatar
Phil Höfer committed
64
        $q          = $request->input('q', '');
Dominik Hebeler's avatar
Dominik Hebeler committed
65
        $mquicktips = [];
Phil Höfer's avatar
Phil Höfer committed
66 67 68
        $quicktips  = [];
        $spruch     = "";

69 70 71 72 73 74 75 76 77 78
        # 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
79
                    $realQuery .= $word . " ";
Phil Höfer's avatar
Phil Höfer committed
80
                }
81
            }
Aria Givi's avatar
Aria Givi committed
82 83
            $realQuery = rtrim($realQuery);
            
84 85 86 87 88 89 90 91 92 93 94 95 96
            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
97
                }
98

Phil Höfer's avatar
Phil Höfer committed
99
            }
100 101
        } catch (\ErrorException $e) {
        }
Phil Höfer's avatar
Phil Höfer committed
102

103
        if (APP::getLocale() === "de") {
104 105 106 107 108 109 110 111
            # 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
112

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

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
            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;
134
                    }
135
                }
136
                fclose($file);
137
            }
Phil Höfer's avatar
Phil Höfer committed
138

139 140 141
            # 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
142

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

145 146 147 148 149 150
                $searchWords = explode(' ', $q);
                $within      = false;
                foreach ($searchWords as $word) {
                    if (stripos($result["name"], $word) !== false) {
                        $within = true;
                    }
151
                }
152 153 154 155
                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
156

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
                    $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;
175
                }
176
            } catch (\ErrorException $e) {
Phil Höfer's avatar
Phil Höfer committed
177

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

227 228 229 230 231
                    if (App::isLocale('de')) {
                        array_unshift($mquicktips, $quicktip);
                    } else {
                        $mquicktips[] = $quicktip;
                    }
232
                }
Phil Höfer's avatar
Phil Höfer committed
233
            }
Phil Höfer's avatar
Phil Höfer committed
234

235 236 237 238 239
            # 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
240

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

244 245 246 247 248 249 250 251 252 253
            # 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']];
                }
254
            }
255
        }
Phil Höfer's avatar
Phil Höfer committed
256

257 258 259 260
        return view('quicktip')
            ->with('spruch', $spruch)
            ->with('mqs', $mquicktips);

261 262
    }

263 264
    public function tips()
    {
265
        $file = storage_path() . "/app/public/tips.txt";
266
        $tips = [];
267 268
        if (file_exists($file)) {
            $tips = file($file);
269 270 271 272 273 274
        }
        return view('tips')
            ->with('title', 'MetaGer - Tipps & Tricks')
            ->with('tips', $tips);
    }

275 276
    public function get($url)
    {
277 278
	   $ctx = stream_context_create(array('http'=>array('timeout' => 2,)));
        return file_get_contents($url, false, $ctx);
279
    }
280 281 282 283 284 285

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