Completed
Push — master ( 4c7cc5...b46f56 )
by Yannick
28:52
created

Image::getMarineImage()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 35
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 26
nc 12
nop 4
dl 0
loc 35
rs 5.2653
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This class is part of FlightAirmap. It's used to get Image
4
 *
5
 * Copyright (c) Ycarus (Yannick Chabanois) at Zugaina <[email protected]>
6
 * Licensed under AGPL license.
7
 * For more information see: https://www.flightairmap.com/
8
*/
9
require_once(dirname(__FILE__).'/class.Spotter.php');
10
require_once(dirname(__FILE__).'/class.Common.php');
11
require_once(dirname(__FILE__).'/settings.php');
12
13
class Image {
14
	public $db;
15
16
	/*
17
	 * Initialize connection to DB
18
	*/
19
	public function __construct($dbc = null) {
20
		$Connection = new Connection($dbc);
21
		$this->db = $Connection->db();
22
		if ($this->db === null) die('Error: No DB connection. (Image)');
23
	}
24
25
	/**
26
	* Gets the images based on the aircraft registration
27
	*
28
	* @return Array the images list
29
	*
30
	*/
31
	public function getSpotterImage($registration,$aircraft_icao = '', $airline_icao = '')
32
	{
33
		$registration = filter_var($registration,FILTER_SANITIZE_STRING);
34
		$aircraft_icao = filter_var($aircraft_icao,FILTER_SANITIZE_STRING);
35
		$airline_icao = filter_var($airline_icao,FILTER_SANITIZE_STRING);
36
		$reg = $registration;
37
		if (($reg == '' || $reg == 'NA') && $aircraft_icao != '') $reg = $aircraft_icao.$airline_icao;
38
		$reg = trim($reg);
39
		$query  = "SELECT spotter_image.image, spotter_image.image_thumbnail, spotter_image.image_source, spotter_image.image_source_website,spotter_image.image_copyright, spotter_image.registration 
40
			FROM spotter_image 
41
			WHERE spotter_image.registration = :registration LIMIT 1";
42
		$sth = $this->db->prepare($query);
43
		$sth->execute(array(':registration' => $reg));
44
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
45
		if (!empty($result)) return $result;
46
		elseif ($registration != '' && ($aircraft_icao != '' || $airline_icao != '')) return $this->getSpotterImage('',$aircraft_icao,$airline_icao);
47
		else return array();
48
	}
49
50
	/**
51
	* Gets the images based on the ship name
52
	*
53
	* @return Array the images list
54
	*
55
	*/
56
	public function getMarineImage($mmsi,$imo = '',$name = '',$type_name = '')
57
	{
58
		global $globalMarineImagePics;
59
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
60
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
61
		$name = filter_var($name,FILTER_SANITIZE_STRING);
62
		$type_name = str_replace('&#39;',"'",filter_var($type_name,FILTER_SANITIZE_STRING));
63
		if (isset($globalMarineImagePics) && !empty($globalMarineImagePics)) {
64
			if ($type_name != '' && isset($globalMarineImagePics['type'][$type_name])) {
65
				if (!isset($globalMarineImagePics['type'][$type_name]['image_thumbnail'])) {
66
					$globalMarineImagePics['type'][$type_name]['image_thumbnail'] = $globalMarineImagePics['type'][$type_name]['image'];
67
				}
68
				return array($globalMarineImagePics['type'][$type_name]+array('image_thumbnail' => '','image' => '', 'image_copyright' => '','image_source' => '','image_source_website' => ''));
69
			}
70
		}
71
		$name = trim($name);
72
		if ($mmsi == '' && $imo == '' && $name == '') return array();
73
		$query  = "SELECT marine_image.image, marine_image.image_thumbnail, marine_image.image_source, marine_image.image_source_website,marine_image.image_copyright, marine_image.mmsi, marine_image.imo, marine_image.name 
74
			FROM marine_image 
75
			WHERE marine_image.mmsi = :mmsi";
76
		$query_data = array(':mmsi' => $mmsi);
77
		if ($imo != '') {
78
			$query .= " AND marine_image.imo = :imo";
79
			$query_data = array_merge($query_data,array(':imo' => $imo));
80
		}
81
		if ($name != '') {
82
			$query .= " AND marine_image.name = :name";
83
			$query_data = array_merge($query_data,array(':name' => $name));
84
		}
85
		$query .= " LIMIT 1";
86
		$sth = $this->db->prepare($query);
87
		$sth->execute($query_data);
88
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
89
		return $result;
90
	}
91
92
	/**
93
	* Gets the image copyright based on the Exif data
94
	*
95
	* @return String image copyright
96
	*
97
	*/
98
	public function getExifCopyright($url) {
99
		$exif = exif_read_data($url);
100
		$copyright = '';
101
		if (isset($exif['COMPUTED']['copyright'])) $copyright = $exif['COMPUTED']['copyright'];
102
		elseif (isset($exif['copyright'])) $copyright = $exif['copyright'];
103
		if ($copyright != '') {
104
			$copyright = str_replace('Copyright ','',$copyright);
105
			$copyright = str_replace('© ','',$copyright);
106
			$copyright = str_replace('(c) ','',$copyright);
107
		}
108
		return $copyright;
109
	}
110
111
	/**
112
	* Adds the images based on the aircraft registration
113
	*
114
	* @return String either success or error
115
	*
116
	*/
117
	public function addSpotterImage($registration,$aircraft_icao = '', $airline_icao = '')
118
	{
119
		global $globalDebug,$globalAircraftImageFetch, $globalOffline;
120
		if ((isset($globalAircraftImageFetch) && $globalAircraftImageFetch === FALSE) || (isset($globalOffline) && $globalOffline === TRUE)) return '';
121
		$registration = filter_var($registration,FILTER_SANITIZE_STRING);
122
		$registration = trim($registration);
123
		//getting the aircraft image
124
		if ($globalDebug && $registration != '') echo 'Try to find an aircraft image for '.$registration.'...';
125
		elseif ($globalDebug && $aircraft_icao != '') echo 'Try to find an aircraft image for '.$aircraft_icao.'...';
126
		elseif ($globalDebug && $airline_icao != '') echo 'Try to find an aircraft image for '.$airline_icao.'...';
127
		$image_url = $this->findAircraftImage($registration,$aircraft_icao,$airline_icao);
128
		if ($registration == '' && $aircraft_icao != '') $registration = $aircraft_icao.$airline_icao;
129
		if ($image_url['original'] != '') {
130
			if ($globalDebug) echo 'Found !'."\n";
131
			$query  = "INSERT INTO spotter_image (registration, image, image_thumbnail, image_copyright, image_source,image_source_website) VALUES (:registration,:image,:image_thumbnail,:copyright,:source,:source_website)";
132
			try {
133
				$sth = $this->db->prepare($query);
134
				$sth->execute(array(':registration' => $registration,':image' => $image_url['original'],':image_thumbnail' => $image_url['thumbnail'], ':copyright' => $image_url['copyright'],':source' => $image_url['source'],':source_website' => $image_url['source_website']));
135
			} catch(PDOException $e) {
136
				echo $e->getMessage()."\n";
137
				return "error";
138
			}
139
		} elseif ($globalDebug) echo "Not found :'(\n";
140
		return "success";
141
	}
142
143
	/**
144
	* Adds the images based on the marine name
145
	*
146
	* @return String either success or error
147
	*
148
	*/
149
	public function addMarineImage($mmsi,$imo = '',$name = '')
150
	{
151
		global $globalDebug,$globalMarineImageFetch, $globalOffline;
152
		if ((isset($globalMarineImageFetch) && !$globalMarineImageFetch) || (isset($globalOffline) && $globalOffline === TRUE)) return '';
153
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
154
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
155
		$name = filter_var($name,FILTER_SANITIZE_STRING);
156
		$name = trim($name);
157
		$Marine = new Marine($this->db);
158
		if ($imo == '' || $name == '') {
159
			$identity = $Marine->getIdentity($mmsi);
160
			if (isset($identity[0]['mmsi'])) {
161
				$imo = $identity[0]['imo'];
162
				if ($identity[0]['ship_name'] != '') $name = $identity[0]['ship_name'];
163
			}
164
		}
165
		unset($Marine);
166
167
		//getting the aircraft image
168
		if ($globalDebug && $name != '') echo 'Try to find an vessel image for '.$name.'...';
169
		$image_url = $this->findMarineImage($mmsi,$imo,$name);
170
		if ($image_url['original'] != '') {
171
			if ($globalDebug) echo 'Found !'."\n";
172
			$query  = "INSERT INTO marine_image (mmsi,imo,name, image, image_thumbnail, image_copyright, image_source,image_source_website) VALUES (:mmsi,:imo,:name,:image,:image_thumbnail,:copyright,:source,:source_website)";
173
			try {
174
				$sth = $this->db->prepare($query);
175
				$sth->execute(array(':mmsi' => $mmsi,':imo' => $imo,':name' => $name,':image' => $image_url['original'],':image_thumbnail' => $image_url['thumbnail'], ':copyright' => $image_url['copyright'],':source' => $image_url['source'],':source_website' => $image_url['source_website']));
176
			} catch(PDOException $e) {
177
				echo $e->getMessage()."\n";
178
				return "error";
179
			}
180
		} elseif ($globalDebug) echo "Not found :'(\n";
181
		return "success";
182
	}
183
184
	/**
185
	* Gets the aircraft image
186
	*
187
	* @param String $aircraft_registration the registration of the aircraft
188
	* @return Array the aircraft thumbnail, orignal url and copyright
189
	*
190
	*/
191
	public function findAircraftImage($aircraft_registration, $aircraft_icao = '', $airline_icao = '')
192
	{
193
		global $globalAircraftImageSources, $globalIVAO, $globalAircraftImageCheckICAO, $globalVA;
194
		$Spotter = new Spotter($this->db);
195
		if (!isset($globalIVAO)) $globalIVAO = FALSE;
196
		$aircraft_registration = filter_var($aircraft_registration,FILTER_SANITIZE_STRING);
197
		if ($aircraft_registration != '' && $aircraft_registration != 'NA' && (!isset($globalVA) || $globalVA !== TRUE)) {
198
			if (strpos($aircraft_registration,'/') !== false) return array('thumbnail' => '','original' => '', 'copyright' => '','source' => '','source_website' => '');
199
			$aircraft_registration = urlencode(trim($aircraft_registration));
200
			$aircraft_info = $Spotter->getAircraftInfoByRegistration($aircraft_registration);
201
			if (isset($aircraft_info[0]['aircraft_name'])) $aircraft_name = $aircraft_info[0]['aircraft_name'];
202
			else $aircraft_name = '';
203
			if (isset($aircraft_info[0]['aircraft_icao'])) $aircraft_name = $aircraft_info[0]['aircraft_icao'];
204
			else $aircraft_icao = '';
205
			if (isset($aircraft_info[0]['airline_icao'])) $airline_icao = $aircraft_info[0]['airline_icao'];
206
			else $airline_icao = '';
207
		} elseif ($aircraft_icao != '') {
208
			$aircraft_info = $Spotter->getAllAircraftInfo($aircraft_icao);
209
			if (isset($aircraft_info[0]['type'])) $aircraft_name = $aircraft_info[0]['type'];
210
			else $aircraft_name = '';
211
			$aircraft_registration = $aircraft_icao;
212
		} else return array('thumbnail' => '','original' => '', 'copyright' => '', 'source' => '','source_website' => '');
213
		unset($Spotter);
214
		if (!isset($globalAircraftImageSources)) $globalAircraftImageSources = array('ivaomtl','wikimedia','airportdata','deviantart','flickr','bing','jetphotos','planepictures','planespotters');
215
		foreach ($globalAircraftImageSources as $source) {
216
			$source = strtolower($source);
217
			if ($source == 'ivaomtl' && $globalIVAO && $aircraft_icao != '' && $airline_icao != '') $images_array = $this->fromIvaoMtl('aircraft',$aircraft_icao,$airline_icao);
218
			if ($source == 'planespotters' && !$globalIVAO && extension_loaded('simplexml')) $images_array = $this->fromPlanespotters('aircraft',$aircraft_registration,$aircraft_name);
219
			if ($source == 'flickr' && extension_loaded('simplexml')) $images_array = $this->fromFlickr('aircraft',$aircraft_registration,$aircraft_name);
220
			if ($source == 'bing') $images_array = $this->fromBing('aircraft',$aircraft_registration,$aircraft_name);
221
			if ($source == 'deviantart' && extension_loaded('simplexml')) $images_array = $this->fromDeviantart('aircraft',$aircraft_registration,$aircraft_name);
222
			if ($source == 'wikimedia') $images_array = $this->fromWikimedia('aircraft',$aircraft_registration,$aircraft_name);
223
			if ($source == 'jetphotos' && !$globalIVAO && class_exists("DomDocument")) $images_array = $this->fromJetPhotos('aircraft',$aircraft_registration,$aircraft_name);
224
			if ($source == 'planepictures' && !$globalIVAO && class_exists("DomDocument")) $images_array = $this->fromPlanePictures('aircraft',$aircraft_registration,$aircraft_name);
225
			if ($source == 'airportdata' && !$globalIVAO) $images_array = $this->fromAirportData('aircraft',$aircraft_registration,$aircraft_name);
226
			if ($source == 'customsources') $images_array = $this->fromCustomSource('aircraft',$aircraft_registration,$aircraft_name);
227
			if (isset($images_array) && $images_array['original'] != '') return $images_array;
228
		}
229
		if ((!isset($globalAircraftImageCheckICAO) || $globalAircraftImageCheckICAO === TRUE) && isset($aircraft_icao)) return $this->findAircraftImage($aircraft_icao);
230
		return array('thumbnail' => '','original' => '', 'copyright' => '','source' => '','source_website' => '');
231
	}
232
233
	/**
234
	* Gets the vessel image
235
	*
236
	* @param String $mmsi the vessel mmsi
237
	* @param String $imo the vessel imo
238
	* @param String $name the vessel name
239
	* @return Array the aircraft thumbnail, orignal url and copyright
240
	*
241
	*/
242
	public function findMarineImage($mmsi,$imo = '',$name = '')
0 ignored issues
show
Unused Code introduced by
The parameter $imo is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
243
	{
244
		global $globalMarineImageSources;
245
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
246
		//$imo = filter_var($imo,FILTER_SANITIZE_STRING);
247
		$name = filter_var($name,FILTER_SANITIZE_STRING);
248
		$name = trim($name);
249
		if (strlen($name) < 4) return array('thumbnail' => '','original' => '', 'copyright' => '', 'source' => '','source_website' => '');
250
		/*
251
		$Marine = new Marine($this->db);
252
		if ($imo == '' || $name == '') {
253
			$identity = $Marine->getIdentity($mmsi);
254
			if (isset($identity[0]['mmsi'])) {
255
				$imo = $identity[0]['imo'];
256
				$name = $identity[0]['ship_name'];
257
			}
258
		}
259
		unset($Marine);
260
		*/
261
		if (!isset($globalMarineImageSources)) $globalMarineImageSources = array('wikimedia','deviantart','flickr','bing');
262
		foreach ($globalMarineImageSources as $source) {
263
			$source = strtolower($source);
264
			if ($source == 'flickr') $images_array = $this->fromFlickr('marine',$mmsi,$name);
265
			if ($source == 'bing') $images_array = $this->fromBing('marine',$mmsi,$name);
266
			if ($source == 'deviantart') $images_array = $this->fromDeviantart('marine',$mmsi,$name);
267
			if ($source == 'wikimedia') $images_array = $this->fromWikimedia('marine',$mmsi,$name);
268
			if ($source == 'customsources') $images_array = $this->fromCustomSource('marine',$mmsi,$name);
269
			if (isset($images_array) && $images_array['original'] != '') return $images_array;
270
		}
271
		return array('thumbnail' => '','original' => '', 'copyright' => '','source' => '','source_website' => '');
272
	}
273
274
	/**
275
	* Gets the aircraft image from Planespotters
276
	*
277
	* @param String $aircraft_registration the registration of the aircraft
278
	* @param String $aircraft_name type of the aircraft
279
	* @return Array the aircraft thumbnail, orignal url and copyright
280
	*
281
	*/
282
	public function fromPlanespotters($type,$aircraft_registration, $aircraft_name='') {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
283
		$Common = new Common();
284
		// If aircraft registration is only number, also check with aircraft model
285
		if (preg_match('/^[[:digit]]+$/',$aircraft_registration) && $aircraft_name != '') {
286
			$url= 'http://www.planespotters.net/Aviation_Photos/search.php?tag='.$aircraft_registration.'&actype=s_'.urlencode($aircraft_name).'&output=rss';
287
		} else {
288
			//$url= 'http://www.planespotters.net/Aviation_Photos/search.php?tag='.$airline_aircraft_type.'&output=rss';
289
			$url= 'http://www.planespotters.net/Aviation_Photos/search.php?reg='.$aircraft_registration.'&output=rss';
290
		}
291
		$data = $Common->getData($url);
292
		if (substr($data, 0, 5) != "<?xml") return false;
293
		if ($xml = simplexml_load_string($data)) {
294
			if (isset($xml->channel->item)) {
295
				$image_url = array();
296
				$thumbnail_url = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->thumbnail->attributes()->url);
297
				$image_url['thumbnail'] = $thumbnail_url;
298
				$image_url['original'] = str_replace('thumbnail','original',$thumbnail_url);
299
				$image_url['copyright'] = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->copyright);
300
				$image_url['source_website'] = trim((string)$xml->channel->item->link);
301
				$image_url['source'] = 'planespotters';
302
				return $image_url;
303
			}
304
		} 
305
		return false;
306
	}
307
308
	/**
309
	* Gets the aircraft image from Deviantart
310
	*
311
	* @param String $registration the registration of the aircraft
312
	* @param String $name type of the aircraft
313
	* @return Array the aircraft thumbnail, orignal url and copyright
314
	*
315
	*/
316
	public function fromDeviantart($type,$registration, $name='') {
317
		$Common = new Common();
318
		if ($type == 'aircraft') {
319
			// If aircraft registration is only number, also check with aircraft model
320
			if (preg_match('/^[[:digit]]+$/',$registration) && $name != '') {
321
				$url= 'http://backend.deviantart.com/rss.xml?type=deviation&q='.$registration.'%20'.urlencode($name);
322
			} else {
323
				$url= 'http://backend.deviantart.com/rss.xml?type=deviation&q=aircraft%20'.$registration;
324
			}
325
		} elseif ($type == 'marine') {
326
			$url= 'http://backend.deviantart.com/rss.xml?type=deviation&q=ship%20"'.urlencode($name).'"';
327
		} else {
328
			$url= 'http://backend.deviantart.com/rss.xml?type=deviation&q="'.urlencode($name).'"';
329
		}
330
		$data = $Common->getData($url);
331
		if (substr($data, 0, 5) != "<?xml") return false;
332
		if ($xml = simplexml_load_string($data)) {
333
			if (isset($xml->channel->item->link)) {
334
				$image_url = array();
335
				$thumbnail_url = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->thumbnail->attributes()->url);
336
				$image_url['thumbnail'] = $thumbnail_url;
337
				$original_url = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->content->attributes()->url);
338
				$image_url['original'] = $original_url;
339
				$image_url['copyright'] = str_replace('Copyright ','',trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->copyright));
340
				$image_url['source_website'] = trim((string)$xml->channel->item->link);
341
				$image_url['source'] = 'deviantart';
342
				return $image_url;
343
			}
344
		} 
345
		return false;
346
	}
347
348
	/**
349
	* Gets the aircraft image from JetPhotos
350
	*
351
	* @param String $aircraft_registration the registration of the aircraft
352
	* @param String $aircraft_name type of the aircraft
353
	* @return Array the aircraft thumbnail, orignal url and copyright
354
	*
355
	*/
356
	public function fromJetPhotos($type,$aircraft_registration, $aircraft_name='') {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $aircraft_name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
357
		$Common = new Common();
358
		$url= 'http://jetphotos.net/showphotos.php?displaymode=2&regsearch='.$aircraft_registration;
359
		$data = $Common->getData($url);
360
		$dom = new DOMDocument();
361
		@$dom->loadHTML($data);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
362
		$all_pics = array();
363
		foreach($dom->getElementsByTagName('img') as $image) {
364
			if ($image->getAttribute('itemprop') == "http://schema.org/image") {
365
				$all_pics[] = $image->getAttribute('src');
366
			}
367
		}
368
		$all_authors = array();
369
		foreach($dom->getElementsByTagName('meta') as $author) {
370
			if ($author->getAttribute('itemprop') == "http://schema.org/author") {
371
				$all_authors[] = $author->getAttribute('content');
372
			}
373
		}
374
		$all_ref = array();
375
		foreach($dom->getElementsByTagName('a') as $link) {
376
			$all_ref[] = $link->getAttribute('href');
377
		}
378
		if (isset($all_pics[0])) {
379
			$image_url = array();
380
			$image_url['thumbnail'] = $all_pics[0];
381
			$image_url['original'] = str_replace('_tb','',$all_pics[0]);
382
			$image_url['copyright'] = $all_authors[0];
383
			$image_url['source_website'] = 'http://jetphotos.net'.$all_ref[8];
384
			$image_url['source'] = 'JetPhotos';
385
			return $image_url;
386
		}
387
		return false;
388
	}
389
390
	/**
391
	* Gets the aircraft image from PlanePictures
392
	*
393
	* @param String $aircraft_registration the registration of the aircraft
394
	* @param String $aircraft_name type of the aircraft
395
	* @return Array the aircraft thumbnail, orignal url and copyright
396
	*
397
	*/
398
	public function fromPlanePictures($type,$aircraft_registration, $aircraft_name='') {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $aircraft_name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
399
		$Common = new Common();
400
		$url= 'http://www.planepictures.net/netsearch4.cgi?srch='.$aircraft_registration.'&stype=reg&srng=2';
401
		$data = $Common->getData($url);
402
		$dom = new DOMDocument();
403
		@$dom->loadHTML($data);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
404
		$all_pics = array();
405
		foreach($dom->getElementsByTagName('img') as $image) {
406
			$all_pics[] = $image->getAttribute('src');
407
		}
408
		$all_links = array();
409
		foreach($dom->getElementsByTagName('a') as $link) {
410
			$all_links[] = array('text' => $link->textContent,'href' => $link->getAttribute('href'));
411
		}
412
		if (isset($all_pics[1]) && !preg_match('/bit.ly/',$all_pics[1]) && !preg_match('/flagge/',$all_pics[1])) {
413
			$image_url = array();
414
			$image_url['thumbnail'] = 'http://www.planepictures.net/'.$all_pics[1];
415
			$image_url['original'] = 'http://www.planepictures.net/'.str_replace('_TN','',$all_pics[1]);
416
			$image_url['copyright'] = $all_links[6]['text'];
417
			$image_url['source_website'] = 'http://www.planepictures.net/'.$all_links[2]['href'];
418
			$image_url['source'] = 'PlanePictures';
419
			return $image_url;
420
		}
421
		return false;
422
	}
423
424
	/**
425
	* Gets the aircraft image from Flickr
426
	*
427
	* @param String $registration the registration of the aircraft
428
	* @param String $name type of the aircraft
429
	* @return Array the aircraft thumbnail, orignal url and copyright
430
	*
431
	*/
432
	public function fromFlickr($type,$registration,$name='') {
433
		$Common = new Common();
434
		if ($type == 'aircraft') {
435
			if ($name != '') $url = 'https://api.flickr.com/services/feeds/photos_public.gne?format=rss2&license=1,2,3,4,5,6,7&per_page=1&tags='.$registration.','.urlencode($name);
436
			else $url = 'https://api.flickr.com/services/feeds/photos_public.gne?format=rss2&license=1,2,3,4,5,6,7&per_page=1&tags='.$registration.',aircraft';
437
		} elseif ($type == 'marine') {
438
			if ($name != '') $url = 'https://api.flickr.com/services/feeds/photos_public.gne?format=rss2&license=1,2,3,4,5,6,7&per_page=1&tags=ship,'.urlencode($name);
439
			else $url = 'https://api.flickr.com/services/feeds/photos_public.gne?format=rss2&license=1,2,3,4,5,6,7&per_page=1&tags='.$registration.',ship';
440
		}
441
		$data = $Common->getData($url);
0 ignored issues
show
Bug introduced by
The variable $url does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
442
		if (substr($data, 0, 5) != "<?xml") return false;
443
		if ($xml = simplexml_load_string($data)) {
444
			if (isset($xml->channel->item)) {
445
				$original_url = trim((string)$xml->channel->item->enclosure->attributes()->url);
446
				$image_url = array();
447
				$image_url['thumbnail'] = $original_url;
448
				$image_url['original'] = $original_url;
449
				$image_url['copyright'] = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->credit);
450
				$image_url['source_website'] = trim((string)$xml->channel->item->link);
451
				$image_url['source'] = 'flickr';
452
				return $image_url;
453
			}
454
		} 
455
		return false;
456
	}
457
458
	public function fromIvaoMtl($type,$aircraft_icao,$airline_icao) {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
459
		$Common = new Common();
460
		//echo "\n".'SEARCH IMAGE : http://mtlcatalog.ivao.aero/images/aircraft/'.$aircraft_icao.$airline_icao.'.jpg';
461
		if ($Common->urlexist('http://mtlcatalog.ivao.aero/images/aircraft/'.$aircraft_icao.$airline_icao.'.jpg')) {
462
			$image_url = array();
463
			$image_url['thumbnail'] = 'http://mtlcatalog.ivao.aero/images/aircraft/'.$aircraft_icao.$airline_icao.'.jpg';
464
			$image_url['original'] = 'http://mtlcatalog.ivao.aero/images/aircraft/'.$aircraft_icao.$airline_icao.'.jpg';
465
			$image_url['copyright'] = 'IVAO';
466
			$image_url['source_website'] = 'http://mtlcatalog.ivao.aero/';
467
			$image_url['source'] = 'ivao.aero';
468
			return $image_url;
469
		} else {
470
			return false;
471
		}
472
	}
473
474
	/**
475
	* Gets the aircraft image from Bing
476
	*
477
	* @param String $aircraft_registration the registration of the aircraft
478
	* @param String $aircraft_name type of the aircraft
479
	* @return Array the aircraft thumbnail, orignal url and copyright
480
	*
481
	*/
482
	public function fromBing($type,$aircraft_registration,$aircraft_name='') {
483
		global $globalImageBingKey;
484
		$Common = new Common();
485
		if (!isset($globalImageBingKey) || $globalImageBingKey == '') return false;
486
		if ($type == 'aircraft') {
487
			if ($aircraft_name != '') $url = 'https://api.datamarket.azure.com/Bing/Search/v1/Image?$format=json&$top=1&Query=%27'.$aircraft_registration.'%20'.urlencode($aircraft_name).'%20-site:planespotters.com%20-site:flickr.com%27';
488
			else $url = 'https://api.datamarket.azure.com/Bing/Search/v1/Image?$format=json&$top=1&Query=%27%2B'.$aircraft_registration.'%20%2Baircraft%20-site:planespotters.com%20-site:flickr.com%27';
489
		} elseif ($type == 'marine') {
490
			if ($aircraft_name != '') $url = 'https://api.datamarket.azure.com/Bing/Search/v1/Image?$format=json&$top=1&Query=%27'.urlencode($aircraft_name).'%20%2Bship%20-site:flickr.com%27';
491
			else $url = 'https://api.datamarket.azure.com/Bing/Search/v1/Image?$format=json&$top=1&Query=%27%2B'.$aircraft_registration.'%20%2Bship%20-site:flickr.com%27';
492
		}
493
		$headers = array("Authorization: Basic " . base64_encode("ignored:".$globalImageBingKey));
494
		$data = $Common->getData($url,'get','',$headers);
0 ignored issues
show
Bug introduced by
The variable $url does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
495
		$result = json_decode($data);
496
		if (isset($result->d->results[0]->MediaUrl)) {
497
			$image_url = array();
498
			$image_url['original'] = $result->d->results[0]->MediaUrl;
499
			$image_url['source_website'] = $result->d->results[0]->SourceUrl;
500
			// Thumbnail can't be used this way...
501
			// $image_url['thumbnail'] = $result->d->results[0]->Thumbnail->MediaUrl;
502
			$image_url['thumbnail'] = $result->d->results[0]->MediaUrl;
503
			$url = parse_url($image_url['source_website']);
504
			$image_url['copyright'] = $url['host'];
505
			$image_url['source'] = 'bing';
506
			return $image_url;
507
		}
508
		return false;
509
	}
510
511
	/**
512
	* Gets the aircraft image from airport-data
513
	*
514
	* @param String $aircraft_registration the registration of the aircraft
515
	* @param String $aircraft_name type of the aircraft
516
	* @return Array the aircraft thumbnail, orignal url and copyright
517
	*
518
	*/
519
	public function fromAirportData($type,$aircraft_registration,$aircraft_name='') {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $aircraft_name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
520
		$Common = new Common();
521
		$url = 'http://www.airport-data.com/api/ac_thumb.json?&n=1&r='.$aircraft_registration;
522
		$data = $Common->getData($url);
523
		$result = json_decode($data);
524
		if (isset($result->count) && $result->count > 0) {
525
			$image_url = array();
526
			$image_url['original'] = str_replace('thumbnails','large',$result->data[0]->image);
527
			$image_url['source_website'] = $result->data[0]->link;
528
			$image_url['thumbnail'] = $result->data[0]->image;
529
			$image_url['copyright'] = $result->data[0]->photographer;
530
			$image_url['source'] = 'AirportData';
531
			return $image_url;
532
		}
533
		return false;
534
	}
535
536
	/**
537
	* Gets image from WikiMedia
538
	*
539
	* @param String $registration the registration of the aircraft/mmsi
540
	* @param String $name name
541
	* @return Array the aircraft thumbnail, orignal url and copyright
542
	*
543
	*/
544
	public function fromWikimedia($type,$registration,$name='') {
545
		$Common = new Common();
546
		if ($type == 'aircraft') {
547
			if ($name != '') $url = 'https://commons.wikimedia.org/w/api.php?action=query&list=search&format=json&srlimit=1&srnamespace=6&continue&srsearch="'.$registration.'"%20'.urlencode($name);
548
			else $url = 'https://commons.wikimedia.org/w/api.php?action=query&list=search&format=json&srlimit=1&srnamespace=6&continue&srsearch="'.$registration.'"%20aircraft';
549
		} elseif ($type == 'marine') {
550
			if ($name != '') $url = 'https://commons.wikimedia.org/w/api.php?action=query&list=search&format=json&srlimit=1&srnamespace=6&continue&srsearch="'.urlencode($name).'%20ship"';
551
			else return false;
552
		}
553
		$data = $Common->getData($url);
0 ignored issues
show
Bug introduced by
The variable $url does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
554
		$result = json_decode($data);
555
		if (isset($result->query->search[0]->title)) {
556
			$fileo = $result->query->search[0]->title;
557
			if (substr($fileo,-3) == 'pdf') return false;
558
			$file = urlencode($fileo);
559
			$url2 = 'https://commons.wikimedia.org/w/api.php?action=query&format=json&continue&iilimit=500&prop=imageinfo&iiprop=user|url|size|mime|sha1|timestamp&iiurlwidth=200%27&titles='.$file;
560
			$data2 = $Common->getData($url2);
561
			$result2 = json_decode($data2);
562
			if (isset($result2->query->pages)) {
563
				foreach ($result2->query->pages as $page) {
564
					if (isset($page->imageinfo[0]->user)) {
565
						$image_url = array();
566
						$image_url['copyright'] = 'Wikimedia, '.$page->imageinfo[0]->user;
567
						$image_url['original'] = $page->imageinfo[0]->url;
568
						$image_url['thumbnail'] = $page->imageinfo[0]->thumburl;
569
						$image_url['source'] = 'wikimedia';
570
						$image_url['source_website'] = 'http://commons.wikimedia.org/wiki/'.$fileo;
571
						//return $image_url;
572
					}
573
				}
574
			}
575
			if (isset($image_url['original'])) {
576
				$url2 = 'https://commons.wikimedia.org/w/api.php?action=query&prop=imageinfo&iiprop=extmetadata&format=json&continue&titles='.$file;
577
				$data2 = $Common->getData($url2);
578
				$result2 = json_decode($data2);
579
				if (isset($result2->query->pages)) {
580
					foreach ($result2->query->pages as $page) {
581
						if (isset($page->imageinfo[0]->extmetadata->Artist)) {
582
							$image_url['copyright'] = preg_replace('/ from(.*)/','',strip_tags($page->imageinfo[0]->extmetadata->Artist->value));
583
							if (isset($page->imageinfo[0]->extmetadata->License->value)) {
584
								$image_url['copyright'] = $image_url['copyright'].' (under '.$page->imageinfo[0]->extmetadata->License->value.')';
585
							}
586
							$image_url['copyright'] = trim(str_replace('\n','',$image_url['copyright']));
587
							return $image_url;
588
						}
589
					}
590
				}
591
				return $image_url;
592
			}
593
		}
594
		return false;
595
	}
596
597
	/**
598
	* Gets the aircraft image from custom url
599
	*
600
	* @param String $registration the registration of the aircraft
601
	* @param String $name type of the aircraft
602
	* @return Array the aircraft thumbnail, orignal url and copyright
603
	*
604
	*/
605
	public function fromCustomSource($type,$registration,$name='') {
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
606
		global $globalAircraftImageCustomSources, $globalMarineImageCustomSources, $globalDebug;
607
		//$globalAircraftImageCustomSource[] = array('thumbnail' => '','original' => '', 'copyright' => '', 'source_website' => '', 'source' => '','exif' => true);
608
		if (!empty($globalAircraftImageCustomSources) && $type == 'aircraft') {
609
			$customsources = array();
610
			if (!isset($globalAircraftImageCustomSources[0])) {
611
				$customsources[] = $globalAircraftImageCustomSources;
612
			} else {
613
				$customsources = $globalAircraftImageCustomSources;
614
			}
615
			foreach ($customsources as $source) {
616
				$Common = new Common();
617
				if (!isset($source['original']) && $globalDebug) {
618
					echo 'original entry not found for $globalAircraftImageCustomSources.';
619
					print_r($source);
620
					print_r($customsources);
621
				}
622
				$url = str_replace('{registration}',$registration,$source['original']);
623
				$url_thumbnail = str_replace('{registration}',$registration,$source['thumbnail']);
624
				if ($Common->urlexist($url)) {
625
					$image_url = array();
626
					$image_url['thumbnail'] = $url_thumbnail;
627
					$image_url['original'] = $url;
628
					if ($source['exif'] && exif_imagetype($url) == IMAGETYPE_JPEG) $exifCopyright = $this->getExifCopyright($url);
629
					else $exifCopyright = '';
630
					if ($exifCopyright  != '') $image_url['copyright'] = $exifCopyright;
631
					elseif (isset($source['copyright'])) $image_url['copyright'] = $source['copyright'];
632
					else $image_url['copyright'] = $source['source_website'];
633
					$image_url['source_website'] = $source['source_website'];
634
					$image_url['source'] = $source['source'];
635
					return $image_url;
636
				}
637
			}
638
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Image::fromCustomSource of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
639
		} else return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Image::fromCustomSource of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
640
		if (!empty($globalMarineImageCustomSources) && $type == 'marine') {
0 ignored issues
show
Unused Code introduced by
if (!empty($globalMarine...e { return false; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
641
			$customsources = array();
642
			if (!isset($globalMarineImageCustomSources[0])) {
643
				$customsources[] = $globalMarineImageCustomSources;
644
			} else {
645
				$customsources = $globalMarineImageCustomSources;
646
			}
647
			foreach ($customsources as $source) {
648
				$Common = new Common();
649
				if (!isset($source['original']) && $globalDebug) {
650
					echo 'original entry not found for $globalMarineImageCustomSources.';
651
					print_r($source);
652
					print_r($customsources);
653
				}
654
				$url = str_replace('{registration}',$registration,$source['original']);
655
				$url = str_replace('{mmsi}',$registration,$url);
656
				$url = str_replace('{name}',$name,$url);
657
				$url_thumbnail = str_replace('{registration}',$registration,$source['thumbnail']);
658
				$url_thumbnail = str_replace('{mmsi}',$registration,$url_thumbnail);
659
				$url_thumbnail = str_replace('{name}',$name,$url_thumbnail);
660
				if ($Common->urlexist($url)) {
661
					$image_url = array();
662
					$image_url['thumbnail'] = $url_thumbnail;
663
					$image_url['original'] = $url;
664
					if ($source['exif'] && exif_imagetype($url) == IMAGETYPE_JPEG) $exifCopyright = $this->getExifCopyright($url);
665
					else $exifCopyright = '';
666
					if ($exifCopyright  != '') $image_url['copyright'] = $exifCopyright;
667
					elseif (isset($source['copyright'])) $image_url['copyright'] = $source['copyright'];
668
					else $image_url['copyright'] = $source['source_website'];
669
					$image_url['source_website'] = $source['source_website'];
670
					$image_url['source'] = $source['source'];
671
					return $image_url;
672
				}
673
			}
674
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Image::fromCustomSource of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
675
		} else return false;
676
	}
677
}
678
679
//$Image = new Image();
680
//print_r($Image->fromAirportData('F-GZHM'));
681
682
?>