Searchengine.php 11 KB
Newer Older
1
2
<?php

3
namespace App\Models;
4
use App\MetaGer;
5
6
use Log;
use Redis;
7

8
abstract class Searchengine
9
10
{

11
	protected $ch; 	# Curl Handle zum erhalten der Ergebnisse
12
13
14
15
16
17
	protected $fp;
	protected $getString = "";
	protected $engine;
    protected $counter = 0;
    protected $enabled;
    protected $socketNumber = null;
18
	public $results = [];
19

20
	function __construct(\SimpleXMLElement $engine, MetaGer $metager)
21
	{
22

23
24
25
		foreach($engine->attributes() as $key => $value){
			$this->$key = $value->__toString();
		}
26

27
28
29
30
31
32
33
34
		# User-Agent definieren:
		if( isset($_SERVER['HTTP_USER_AGENT']))
		{
			$this->useragent = $_SERVER['HTTP_USER_AGENT'];
		}else
		{
			$this->useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1";
		}
35
		$this->ip = $metager->getIp();
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
		$this->gefVon = "<a href=\"" . $this->homepage . "\" target=\"_blank\">" . $this->displayName . "</a>";
		$this->startTime = microtime();
		$this->getString = $this->generateGetString($metager->getEingabe(), $metager->getUrl(), $metager->getLanguage(), $metager->getCategory());
		$counter = 0;

		# Wir benötigen einen verfügbaren Socket, über den wir kommunizieren können:
		$this->fp = $this->getFreeSocket();

		do
		{
			#try
			#{
				
				
			/*}catch(\Exception $e)
			{
				# Connection Timeout: Wir schalten die Suchmaschine aus:
				$this->disable($metager->getSumaFile(), "Die Suchmaschine " . $this->name . " wurde deaktiviert, weil keine Verbindung aufgebaut werden konnte");
				break;
			}*/
			if(!$this->fp)
			{
				// Mache etwas
				Log::error("Konnte keine Verbindung zur Suchmaschine: " . $this->name . " aufbauen.");
				break;
			}else
			{
				$out = "GET " . $this->getString . " HTTP/1.1\r\n";
				$out .= "Host: " . $this->host . "\r\n";
				$out .= "User-Agent: " . $this->useragent . "\r\n";
				$out .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
				$out .= "Accept-Language: de,en-US;q=0.7,en;q=0.3\r\n";
				$out .= "Accept-Encoding: gzip, deflate, br\r\n";
				$out .= "Connection: keep-alive\r\n\r\n";
				// Daten senden:
				#try 
				#{
					if(fwrite($this->fp, $out))
					{
						break;
					}else
					{
						abort(500, "Fehler beim schreiben.");
					}
					
				#}catch(\Exception $e)
				#{
				#	fclose($this->fp);
				#	if($counter >= 5)
				#	{
#
				#		Log::error("Konnte auch nach 6 Versuchen keine schreibbare Verbindung zum Server \"" . $this->host . "\" aufbauen.");
				#		break;
				#	}
				#}
			}
		}while(true);
	}

	public abstract function loadResults(String $result);

	private function getFreeSocket()
	{
		# Je nach Auslastung des Servers ( gleichzeitige Abfragen ), kann es sein, dass wir mehrere Sockets benötigen um die Abfragen ohne Wartezeit beantworten zu können.
		# pfsockopen öffnet dabei einen persistenten Socket, der also auch zwischen den verschiedenen php Prozessen geteilt werden kann. 
		# Wenn der Hostname mit einem bereits erstellten Socket übereinstimmt, wird die Verbindung also aufgegriffen und fortgeführt.
		# Allerdings dürfen wir diesen nur verwenden, wenn er nicht bereits von einem anderen Prozess zur Kommunikation verwendet wird.
		# Wenn dem so ist, probieren wir den nächsten Socket zu verwenden.
		# Dies festzustellen ist komplizierter, als man sich das vorstellt. Folgendes System sollte funktionieren:
		# 1. Stelle fest, ob dieser Socket neu erstellt wurde, oder ob ein existierender geöffnet wurde.

		$counter = 0;
		do
		{
			if(intval(Redis::getBit($this->name, $counter)) === 0)
			{

				#die($counter . "Socket.");
				Redis::setBit($this->name, $counter, 1);
				$this->socketNumber = $counter;

				try
				{
					$fp = pfsockopen($this->getHost() . ":" . $this->port . "/$counter", $this->port, $errstr, $errno, 1);
					return $fp;
				}catch(\ErrorException $e)
				{
					return null;
				}
				
				
			}
			$counter++;
		}while($counter < 20);

		# Wenn wir hier hin kommen, läuft etwas falsch! Wir kappen alle bestehenden Verbindungen:
		$connectionError = false;
		for($i = 0; $i < 20; $i++)
		{
			if(!$connectionError)
			{
				try
				{
					$fp = pfsockopen($this->getHost() . ":" . $this->port . "/$counter", $this->port, $errstr, $errno, 1);
					fclose($fp);
				}catch(\ErrorException $e)
				{
					$connectionError = true;
				}
			}
			
			Redis::setBit($this->name, $i, 0);
			
		}

		abort(500, "Konnte keinen freien Socket bekommen für: " . $this->name);
	}

	public function disable(string $sumaFile, string $message)
	{
		Log::info($message);
		$xml = simplexml_load_file($sumaFile);
		$xml->xpath("//sumas/suma[@name='" . $this->name . "']")['0']['disabled'] = "1";
		$xml->saveXML($sumaFile);
	}

	public function closeFp()
	{
		fclose($this->fp);
	}

	public function retrieveResults()
	{
		
		$headers = '';
		$body = '';
		$length = 0;
		if(!$this->fp)
		{
			return;
		}
		// We need a waiting Loop to wait till the server is ready
		// get headers FIRST
		stream_set_blocking($this->fp, 1);
		do
		{
    		// use fgets() not fread(), fgets stops reading at first newline
   			// or buffer which ever one is reached first
    		$data = fgets($this->fp, BUFFER_LENGTH);
    		if($data === false)
    		{
    			usleep(10000);
    			continue;
    		}
    		// a sincle CRLF indicates end of headers
    		if ($data === false || $data == CRLF || feof($this->fp)) {
        		// break BEFORE OUTPUT
        		break;
    		}
    		if( sizeof(($tmp = explode(": ", $data))) === 2 )
    			$headers[trim($tmp[0])] = trim($tmp[1]);
		}
		while (true);
		// end of headers

		if( isset($headers["Transfer-Encoding"]) && $headers["Transfer-Encoding"] === "chunked" )
		{
			$body = $this->readChunked();
		}elseif( isset($headers['Content-Length']) )
		{
			$length = trim($headers['Content-Length']);
			if(is_numeric($length) && $length >= 1)
				$body = fread($this->fp, $headers['Content-Length']);
		}
		Redis::setBit($this->name, $this->socketNumber, 0 );

		if( isset($headers["Content-Encoding"]) && $headers['Content-Encoding'] === "gzip")
		{
			$body = $this->gunzip($body);
		}
		#die(print_r($headers));
		// $body and $headers should contain your stream data
		$this->loadResults($body);
		#print(print_r($headers, TRUE) . $body);
		#exit;
221
222
	}

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
	private function readChunked()
	{
		$body = '';
		// read from chunked stream
		// loop though the stream
		do
		{
	    	// NOTE: for chunked encoding to work properly make sure
	    	// there is NOTHING (besides newlines) before the first hexlength

	    	// get the line which has the length of this chunk (use fgets here)
	    	$line = fgets($this->fp, BUFFER_LENGTH);

	    	// if it's only a newline this normally means it's read
	    	// the total amount of data requested minus the newline
	    	// continue to next loop to make sure we're done
	    	if ($line == CRLF) {
	        	continue;
	    	}

	    	// the length of the block is sent in hex decode it then loop through
	    	// that much data get the length
	    	// NOTE: hexdec() ignores all non hexadecimal chars it finds
	    	$length = hexdec($line);

	    	if (!is_int($length)) {
	        	trigger_error('Most likely not chunked encoding', E_USER_ERROR);
	    	}

		    // zero is sent when at the end of the chunks
		    // or the end of the stream or error
		    if ($line === false || $length < 1 || feof($this->fp)) {
		    	if($length <= 0)
		            	fgets($this->fp, BUFFER_LENGTH);
		        // break out of the streams loop
		        break;
		    }

		    // loop though the chunk
		    do
		    {
		        // read $length amount of data
		        // (use fread here)
		        $data = fread($this->fp, $length);

		        // remove the amount received from the total length on the next loop
		        // it'll attempt to read that much less data
		        $length -= strlen($data);

		        // PRINT out directly
		        #print $data;
		        #flush();
		        // you could also save it directly to a file here

		        // store in string for later use
		        $body .= $data;

		        // zero or less or end of connection break
		        if ($length <= 0 || feof($this->fp))
		        {
		            // break out of the chunk loop
		            if($length <= 0)
		            	fgets($this->fp, BUFFER_LENGTH);
		            break;
		        }
		    }
		    while (true);
		    // end of chunk loop
		}
		while (true);
		// end of stream loop
		return $body;
	}

	private function gunzip($zipped) {
      $offset = 0;
      if (substr($zipped,0,2) == "\x1f\x8b")
         $offset = 2;
      if (substr($zipped,$offset,1) == "\x08")  
      {
      	try
      	{
         return gzinflate(substr($zipped, $offset + 8));
      	} catch (\Exception $e)
      	{
      		abort(500, "Fehler beim unzip des Ergebnisses von folgendem Anbieter: " . $this->name);
      	}
      }
      return "Unknown Format";
   }  

	protected function getHost()
	{
		$return = "";
		if( $this->port === "443" )
		{
			$return .= "tls://";
		}else
		{
			$return .= "tcp://";
		}
		$return .= $this->host;
		return $return;
	}
327

328
329
330
331
332
	public function getCurlInfo()
	{
		return curl_getinfo($this->ch);
	}

333
334
335
336
337
	public function getCurlErrors()
	{
		return curl_errno($this->ch);
	}

338
339
340
	public function addCurlHandle ($mh)
	{
		curl_multi_add_handle($mh, $this->ch);
341
342
	}

343
344
345
346
347
	public function removeCurlHandle ($mh)
	{
		curl_multi_remove_handle($mh, $this->ch);
	}

348
	private function generateGetString($query, $url, $language, $category)
349
350
	{
		$getString = "";
351

352
		# Skript:
353
354
355
356
		if(strlen($this->skript) > 0)
			$getString .= $this->skript;
		else
			$getString .= "/";
357
		# FormData:
358
359
		if(strlen($this->formData) > 0)
			$getString .= "?" . $this->formData;
360
361
362
363
364
365
366
367

		# Wir müssen noch einige Platzhalter in dem GET-String ersetzen:
		if( strpos($getString, "<<USERAGENT>>") ){
			$getString = str_replace("<<USERAGENT>>", $this->urlEncode($this->useragent), $getString);
		}

		if( strpos($getString, "<<QUERY>>") )
		{
368
			$getString = str_replace("<<QUERY>>", $this->urlEncode($query), $getString);
369
370
371
372
		}

		if( strpos($getString, "<<IP>>") )
		{
373
			$getString = str_replace("<<IP>>", $this->urlEncode($this->ip), $getString);
374
375
376
377
		}

		if( strpos($getString, "<<LANGUAGE>>") )
		{
378
			$getString = str_replace("<<LANGUAGE>>", $this->urlEncode($language), $getString);
379
380
381
382
		}

		if( strpos($getString, "<<CATEGORY>>") )
		{
383
			$getString = str_replace("<<CATEGORY>>", $this->urlEncode($category), $getString);
384
		}
385
386
387

		if( strpos($getString, "<<AFFILDATA>>") )
		{
388
			$getString = str_replace("<<AFFILDATA>>", $this->getOvertureAffilData($url), $getString);
389
		}
390
391
392
		return $getString;
	}

393
	protected function urlEncode($string)
394
395
396
397
398
399
400
401
402
403
	{
		if(isset($this->inputEncoding))
		{
			return urlencode(mb_convert_encoding($string, $this->inputEncoding));
		}else
		{
			return urlencode($string);
		}
	}

404
	private function getOvertureAffilData($url)
405
	{
406
	    $affil_data = 'ip=' . $this->ip;
407
408
409
	    $affil_data .= '&ua=' . $this->useragent;  
	    if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
	       $affil_data .= '&xfip=' . $_SERVER['HTTP_X_FORWARDED_FOR'];
410
	    }
411
	    $affilDataValue = $this->urlEncode($affil_data);
412
		# Wir benötigen die ServeUrl:
413
		$serveUrl = $this->urlEncode($url);
414

415
416
		return "&affilData=" . $affilDataValue . "&serveUrl=" . $serveUrl;
	}
417
418
419
420
421

	public function isEnabled ()
	{
		return $this->enabled;
	}
422
}