Completed
Push — master ( e5efd9...393714 )
by Yannick
35:31
created

Image::addSpotterImage()   D

Complexity

Conditions 17
Paths 65

Size

Total Lines 25
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 21
nc 65
nop 3
dl 0
loc 25
rs 4.9807
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
require_once(dirname(__FILE__).'/class.Spotter.php');
3
require_once(dirname(__FILE__).'/class.Common.php');
4
require_once(dirname(__FILE__).'/settings.php');
5
6
class Image {
7
	public $db;
8
9
	public function __construct($dbc = null) {
10
		$Connection = new Connection($dbc);
11
		$this->db = $Connection->db();
12
		if ($this->db === null) die('Error: No DB connection. (Image)');
13
	}
14
15
	/**
16
	* Gets the images based on the aircraft registration
17
	*
18
	* @return Array the images list
19
	*
20
	*/
21
	public function getSpotterImage($registration,$aircraft_icao = '', $airline_icao = '')
22
	{
23
		$registration = filter_var($registration,FILTER_SANITIZE_STRING);
24
		$aircraft_icao = filter_var($aircraft_icao,FILTER_SANITIZE_STRING);
25
		$airline_icao = filter_var($airline_icao,FILTER_SANITIZE_STRING);
26
		$reg = $registration;
27
		if (($reg == '' || $reg == 'NA') && $aircraft_icao != '') $reg = $aircraft_icao.$airline_icao;
28
		$reg = trim($reg);
29
		$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 
30
			FROM spotter_image 
31
			WHERE spotter_image.registration = :registration LIMIT 1";
32
		$sth = $this->db->prepare($query);
33
		$sth->execute(array(':registration' => $reg));
34
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
35
		if (!empty($result)) return $result;
36
		elseif ($registration != '' && ($aircraft_icao != '' || $airline_icao != '')) return $this->getSpotterImage('',$aircraft_icao,$airline_icao);
37
		else return array();
38
	}
39
40
	/**
41
	* Gets the images based on the ship name
42
	*
43
	* @return Array the images list
44
	*
45
	*/
46
	public function getMarineImage($mmsi,$imo = '',$name = '')
47
	{
48
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
49
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
50
		$name = filter_var($name,FILTER_SANITIZE_STRING);
51
		$name = trim($name);
52
		$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 
53
			FROM marine_image 
54
			WHERE marine_image.mmsi = :mmsi";
55
		$query_data = array(':mmsi' => $mmsi);
56
		if ($imo != '') {
57
			$query .= " AND marine_image.imo = :imo";
58
			$query_data = array_merge($query_data,array(':imo' => $imo));
59
		}
60
		if ($name != '') {
61
			$query .= " AND marine_image.name = :name";
62
			$query_data = array_merge($query_data,array(':name' => $name));
63
		}
64
		$query .= " LIMIT 1";
65
		$sth = $this->db->prepare($query);
66
		$sth->execute($query_data);
67
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
68
		return $result;
69
	}
70
71
	/**
72
	* Gets the image copyright based on the Exif data
73
	*
74
	* @return String image copyright
75
	*
76
	*/
77
	public function getExifCopyright($url) {
78
		$exif = exif_read_data($url);
79
		$copyright = '';
80
		if (isset($exif['COMPUTED']['copyright'])) $copyright = $exif['COMPUTED']['copyright'];
81
		elseif (isset($exif['copyright'])) $copyright = $exif['copyright'];
82
		if ($copyright != '') {
83
			$copyright = str_replace('Copyright ','',$copyright);
84
			$copyright = str_replace('© ','',$copyright);
85
			$copyright = str_replace('(c) ','',$copyright);
86
		}
87
		return $copyright;
88
	}
89
90
	/**
91
	* Adds the images based on the aircraft registration
92
	*
93
	* @return String either success or error
94
	*
95
	*/
96
	public function addSpotterImage($registration,$aircraft_icao = '', $airline_icao = '')
97
	{
98
		global $globalDebug,$globalAircraftImageFetch, $globalOffline;
99
		if ((isset($globalAircraftImageFetch) && $globalAircraftImageFetch === FALSE) || (isset($globalOffline) && $globalOffline === TRUE)) return '';
100
		$registration = filter_var($registration,FILTER_SANITIZE_STRING);
101
		$registration = trim($registration);
102
		//getting the aircraft image
103
		if ($globalDebug && $registration != '') echo 'Try to find an aircraft image for '.$registration.'...';
104
		elseif ($globalDebug && $aircraft_icao != '') echo 'Try to find an aircraft image for '.$aircraft_icao.'...';
105
		elseif ($globalDebug && $airline_icao != '') echo 'Try to find an aircraft image for '.$airline_icao.'...';
106
		$image_url = $this->findAircraftImage($registration,$aircraft_icao,$airline_icao);
107
		if ($registration == '' && $aircraft_icao != '') $registration = $aircraft_icao.$airline_icao;
108
		if ($image_url['original'] != '') {
109
			if ($globalDebug) echo 'Found !'."\n";
110
			$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)";
111
			try {
112
				$sth = $this->db->prepare($query);
113
				$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']));
114
			} catch(PDOException $e) {
115
				echo $e->getMessage()."\n";
116
				return "error";
117
			}
118
		} elseif ($globalDebug) echo "Not found :'(\n";
119
		return "success";
120
	}
121
122
	/**
123
	* Adds the images based on the marine name
124
	*
125
	* @return String either success or error
126
	*
127
	*/
128
	public function addMarineImage($mmsi,$imo = '',$name = '')
129
	{
130
		global $globalDebug,$globalMarineImageFetch, $globalOffline;
131
		if ((isset($globalMarineImageFetch) && !$globalMarineImageFetch) || (isset($globalOffline) && $globalOffline === TRUE)) return '';
132
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
133
		$imo = filter_var($imo,FILTER_SANITIZE_STRING);
134
		$name = filter_var($name,FILTER_SANITIZE_STRING);
135
		$name = trim($name);
136
		$Marine = new Marine($this->db);
137
		if ($imo == '' || $name == '') {
138
			$identity = $Marine->getIdentity($mmsi);
139
			if (isset($identity[0]['mmsi'])) {
140
				$imo = $identity[0]['imo'];
141
				if ($identity[0]['ship_name'] != '') $name = $identity[0]['ship_name'];
142
			}
143
		}
144
		unset($Marine);
145
146
		//getting the aircraft image
147
		if ($globalDebug && $name != '') echo 'Try to find an vessel image for '.$name.'...';
148
		$image_url = $this->findMarineImage($mmsi,$imo,$name);
149
		if ($image_url['original'] != '') {
150
			if ($globalDebug) echo 'Found !'."\n";
151
			$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)";
152
			try {
153
				$sth = $this->db->prepare($query);
154
				$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']));
155
			} catch(PDOException $e) {
156
				echo $e->getMessage()."\n";
157
				return "error";
158
			}
159
		} elseif ($globalDebug) echo "Not found :'(\n";
160
		return "success";
161
	}
162
163
	/**
164
	* Gets the aircraft image
165
	*
166
	* @param String $aircraft_registration the registration of the aircraft
167
	* @return Array the aircraft thumbnail, orignal url and copyright
168
	*
169
	*/
170
	public function findAircraftImage($aircraft_registration, $aircraft_icao = '', $airline_icao = '')
171
	{
172
		global $globalAircraftImageSources, $globalIVAO, $globalAircraftImageCheckICAO, $globalVA;
173
		$Spotter = new Spotter($this->db);
174
		if (!isset($globalIVAO)) $globalIVAO = FALSE;
175
		$aircraft_registration = filter_var($aircraft_registration,FILTER_SANITIZE_STRING);
176
		if ($aircraft_registration != '' && $aircraft_registration != 'NA' && (!isset($globalVA) || $globalVA !== TRUE)) {
177
			if (strpos($aircraft_registration,'/') !== false) return array('thumbnail' => '','original' => '', 'copyright' => '','source' => '','source_website' => '');
178
			$aircraft_registration = urlencode(trim($aircraft_registration));
179
			$aircraft_info = $Spotter->getAircraftInfoByRegistration($aircraft_registration);
180
			if (isset($aircraft_info[0]['aircraft_name'])) $aircraft_name = $aircraft_info[0]['aircraft_name'];
181
			else $aircraft_name = '';
182
			if (isset($aircraft_info[0]['aircraft_icao'])) $aircraft_name = $aircraft_info[0]['aircraft_icao'];
183
			else $aircraft_icao = '';
184
			if (isset($aircraft_info[0]['airline_icao'])) $airline_icao = $aircraft_info[0]['airline_icao'];
185
			else $airline_icao = '';
186
		} elseif ($aircraft_icao != '') {
187
			$aircraft_info = $Spotter->getAllAircraftInfo($aircraft_icao);
188
			if (isset($aircraft_info[0]['type'])) $aircraft_name = $aircraft_info[0]['type'];
189
			else $aircraft_name = '';
190
			$aircraft_registration = $aircraft_icao;
191
		} else return array('thumbnail' => '','original' => '', 'copyright' => '', 'source' => '','source_website' => '');
192
		unset($Spotter);
193
		if (!isset($globalAircraftImageSources)) $globalAircraftImageSources = array('ivaomtl','wikimedia','airportdata','deviantart','flickr','bing','jetphotos','planepictures','planespotters');
194
		foreach ($globalAircraftImageSources as $source) {
195
			$source = strtolower($source);
196
			if ($source == 'ivaomtl' && $globalIVAO && $aircraft_icao != '' && $airline_icao != '') $images_array = $this->fromIvaoMtl('aircraft',$aircraft_icao,$airline_icao);
197
			if ($source == 'planespotters' && !$globalIVAO && extension_loaded('simplexml')) $images_array = $this->fromPlanespotters('aircraft',$aircraft_registration,$aircraft_name);
198
			if ($source == 'flickr' && extension_loaded('simplexml')) $images_array = $this->fromFlickr('aircraft',$aircraft_registration,$aircraft_name);
199
			if ($source == 'bing') $images_array = $this->fromBing('aircraft',$aircraft_registration,$aircraft_name);
200
			if ($source == 'deviantart' && extension_loaded('simplexml')) $images_array = $this->fromDeviantart('aircraft',$aircraft_registration,$aircraft_name);
201
			if ($source == 'wikimedia') $images_array = $this->fromWikimedia('aircraft',$aircraft_registration,$aircraft_name);
202
			if ($source == 'jetphotos' && !$globalIVAO && class_exists("DomDocument")) $images_array = $this->fromJetPhotos('aircraft',$aircraft_registration,$aircraft_name);
203
			if ($source == 'planepictures' && !$globalIVAO && class_exists("DomDocument")) $images_array = $this->fromPlanePictures('aircraft',$aircraft_registration,$aircraft_name);
204
			if ($source == 'airportdata' && !$globalIVAO) $images_array = $this->fromAirportData('aircraft',$aircraft_registration,$aircraft_name);
205
			if ($source == 'customsources') $images_array = $this->fromCustomSource('aircraft',$aircraft_registration,$aircraft_name);
206
			if (isset($images_array) && $images_array['original'] != '') return $images_array;
207
		}
208
		if ((!isset($globalAircraftImageCheckICAO) || $globalAircraftImageCheckICAO === TRUE) && isset($aircraft_icao)) return $this->findAircraftImage($aircraft_icao);
209
		return array('thumbnail' => '','original' => '', 'copyright' => '','source' => '','source_website' => '');
210
	}
211
212
	/**
213
	* Gets the vessel image
214
	*
215
	* @param String $mmsi the vessel mmsi
216
	* @param String $imo the vessel imo
217
	* @param String $name the vessel name
218
	* @return Array the aircraft thumbnail, orignal url and copyright
219
	*
220
	*/
221
	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...
222
	{
223
		global $globalMarineImageSources;
224
		$mmsi = filter_var($mmsi,FILTER_SANITIZE_STRING);
225
		//$imo = filter_var($imo,FILTER_SANITIZE_STRING);
226
		$name = filter_var($name,FILTER_SANITIZE_STRING);
227
		$name = trim($name);
228
		if (strlen($name) < 4) return array('thumbnail' => '','original' => '', 'copyright' => '', 'source' => '','source_website' => '');
229
		/*
230
		$Marine = new Marine($this->db);
231
		if ($imo == '' || $name == '') {
232
			$identity = $Marine->getIdentity($mmsi);
233
			if (isset($identity[0]['mmsi'])) {
234
				$imo = $identity[0]['imo'];
235
				$name = $identity[0]['ship_name'];
236
			}
237
		}
238
		unset($Marine);
239
		*/
240
		if (!isset($globalMarineImageSources)) $globalMarineImageSources = array('wikimedia','deviantart','flickr','bing');
241
		foreach ($globalMarineImageSources as $source) {
242
			$source = strtolower($source);
243
			if ($source == 'flickr') $images_array = $this->fromFlickr('marine',$mmsi,$name);
244
			if ($source == 'bing') $images_array = $this->fromBing('marine',$mmsi,$name);
245
			if ($source == 'deviantart') $images_array = $this->fromDeviantart('marine',$mmsi,$name);
246
			if ($source == 'wikimedia') $images_array = $this->fromWikimedia('marine',$mmsi,$name);
247
			if ($source == 'customsources') $images_array = $this->fromCustomSource('marine',$mmsi,$name);
248
			if (isset($images_array) && $images_array['original'] != '') return $images_array;
249
		}
250
		return array('thumbnail' => '','original' => '', 'copyright' => '','source' => '','source_website' => '');
251
	}
252
253
	/**
254
	* Gets the aircraft image from Planespotters
255
	*
256
	* @param String $aircraft_registration the registration of the aircraft
257
	* @param String $aircraft_name type of the aircraft
258
	* @return Array the aircraft thumbnail, orignal url and copyright
259
	*
260
	*/
261
	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...
262
		$Common = new Common();
263
		// If aircraft registration is only number, also check with aircraft model
264
		if (preg_match('/^[[:digit]]+$/',$aircraft_registration) && $aircraft_name != '') {
265
			$url= 'http://www.planespotters.net/Aviation_Photos/search.php?tag='.$aircraft_registration.'&actype=s_'.urlencode($aircraft_name).'&output=rss';
266
		} else {
267
			//$url= 'http://www.planespotters.net/Aviation_Photos/search.php?tag='.$airline_aircraft_type.'&output=rss';
268
			$url= 'http://www.planespotters.net/Aviation_Photos/search.php?reg='.$aircraft_registration.'&output=rss';
269
		}
270
		$data = $Common->getData($url);
271
		if (substr($data, 0, 5) != "<?xml") return false;
272
		if ($xml = simplexml_load_string($data)) {
273
			if (isset($xml->channel->item)) {
274
				$image_url = array();
275
				$thumbnail_url = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->thumbnail->attributes()->url);
276
				$image_url['thumbnail'] = $thumbnail_url;
277
				$image_url['original'] = str_replace('thumbnail','original',$thumbnail_url);
278
				$image_url['copyright'] = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->copyright);
279
				$image_url['source_website'] = trim((string)$xml->channel->item->link);
280
				$image_url['source'] = 'planespotters';
281
				return $image_url;
282
			}
283
		} 
284
		return false;
285
	}
286
287
	/**
288
	* Gets the aircraft image from Deviantart
289
	*
290
	* @param String $registration the registration of the aircraft
291
	* @param String $name type of the aircraft
292
	* @return Array the aircraft thumbnail, orignal url and copyright
293
	*
294
	*/
295
	public function fromDeviantart($type,$registration, $name='') {
296
		$Common = new Common();
297
		if ($type == 'aircraft') {
298
			// If aircraft registration is only number, also check with aircraft model
299
			if (preg_match('/^[[:digit]]+$/',$registration) && $name != '') {
300
				$url= 'http://backend.deviantart.com/rss.xml?type=deviation&q='.$registration.'%20'.urlencode($name);
301
			} else {
302
				$url= 'http://backend.deviantart.com/rss.xml?type=deviation&q=aircraft%20'.$registration;
303
			}
304
		} elseif ($type == 'marine') {
305
			$url= 'http://backend.deviantart.com/rss.xml?type=deviation&q=ship%20"'.urlencode($name).'"';
306
		} else {
307
			$url= 'http://backend.deviantart.com/rss.xml?type=deviation&q="'.urlencode($name).'"';
308
		}
309
		$data = $Common->getData($url);
310
		if (substr($data, 0, 5) != "<?xml") return false;
311
		if ($xml = simplexml_load_string($data)) {
312
			if (isset($xml->channel->item->link)) {
313
				$image_url = array();
314
				$thumbnail_url = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->thumbnail->attributes()->url);
315
				$image_url['thumbnail'] = $thumbnail_url;
316
				$original_url = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->content->attributes()->url);
317
				$image_url['original'] = $original_url;
318
				$image_url['copyright'] = str_replace('Copyright ','',trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->copyright));
319
				$image_url['source_website'] = trim((string)$xml->channel->item->link);
320
				$image_url['source'] = 'deviantart';
321
				return $image_url;
322
			}
323
		} 
324
		return false;
325
	}
326
327
	/**
328
	* Gets the aircraft image from JetPhotos
329
	*
330
	* @param String $aircraft_registration the registration of the aircraft
331
	* @param String $aircraft_name type of the aircraft
332
	* @return Array the aircraft thumbnail, orignal url and copyright
333
	*
334
	*/
335
	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...
336
		$Common = new Common();
337
		$url= 'http://jetphotos.net/showphotos.php?displaymode=2&regsearch='.$aircraft_registration;
338
		$data = $Common->getData($url);
339
		$dom = new DOMDocument();
340
		@$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...
341
		$all_pics = array();
342
		foreach($dom->getElementsByTagName('img') as $image) {
343
			if ($image->getAttribute('itemprop') == "http://schema.org/image") {
344
				$all_pics[] = $image->getAttribute('src');
345
			}
346
		}
347
		$all_authors = array();
348
		foreach($dom->getElementsByTagName('meta') as $author) {
349
			if ($author->getAttribute('itemprop') == "http://schema.org/author") {
350
				$all_authors[] = $author->getAttribute('content');
351
			}
352
		}
353
		$all_ref = array();
354
		foreach($dom->getElementsByTagName('a') as $link) {
355
			$all_ref[] = $link->getAttribute('href');
356
		}
357
		if (isset($all_pics[0])) {
358
			$image_url = array();
359
			$image_url['thumbnail'] = $all_pics[0];
360
			$image_url['original'] = str_replace('_tb','',$all_pics[0]);
361
			$image_url['copyright'] = $all_authors[0];
362
			$image_url['source_website'] = 'http://jetphotos.net'.$all_ref[8];
363
			$image_url['source'] = 'JetPhotos';
364
			return $image_url;
365
		}
366
		return false;
367
	}
368
369
	/**
370
	* Gets the aircraft image from PlanePictures
371
	*
372
	* @param String $aircraft_registration the registration of the aircraft
373
	* @param String $aircraft_name type of the aircraft
374
	* @return Array the aircraft thumbnail, orignal url and copyright
375
	*
376
	*/
377
	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...
378
		$Common = new Common();
379
		$url= 'http://www.planepictures.net/netsearch4.cgi?srch='.$aircraft_registration.'&stype=reg&srng=2';
380
		$data = $Common->getData($url);
381
		$dom = new DOMDocument();
382
		@$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...
383
		$all_pics = array();
384
		foreach($dom->getElementsByTagName('img') as $image) {
385
			$all_pics[] = $image->getAttribute('src');
386
		}
387
		$all_links = array();
388
		foreach($dom->getElementsByTagName('a') as $link) {
389
			$all_links[] = array('text' => $link->textContent,'href' => $link->getAttribute('href'));
390
		}
391
		if (isset($all_pics[1]) && !preg_match('/bit.ly/',$all_pics[1]) && !preg_match('/flagge/',$all_pics[1])) {
392
			$image_url = array();
393
			$image_url['thumbnail'] = 'http://www.planepictures.net/'.$all_pics[1];
394
			$image_url['original'] = 'http://www.planepictures.net/'.str_replace('_TN','',$all_pics[1]);
395
			$image_url['copyright'] = $all_links[6]['text'];
396
			$image_url['source_website'] = 'http://www.planepictures.net/'.$all_links[2]['href'];
397
			$image_url['source'] = 'PlanePictures';
398
			return $image_url;
399
		}
400
		return false;
401
	}
402
403
	/**
404
	* Gets the aircraft image from Flickr
405
	*
406
	* @param String $registration the registration of the aircraft
407
	* @param String $name type of the aircraft
408
	* @return Array the aircraft thumbnail, orignal url and copyright
409
	*
410
	*/
411
	public function fromFlickr($type,$registration,$name='') {
412
		$Common = new Common();
413
		if ($type == 'aircraft') {
414
			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);
415
			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';
416
		} elseif ($type == 'marine') {
417
			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);
418
			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';
419
		}
420
		$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...
421
		if (substr($data, 0, 5) != "<?xml") return false;
422
		if ($xml = simplexml_load_string($data)) {
423
			if (isset($xml->channel->item)) {
424
				$original_url = trim((string)$xml->channel->item->enclosure->attributes()->url);
425
				$image_url = array();
426
				$image_url['thumbnail'] = $original_url;
427
				$image_url['original'] = $original_url;
428
				$image_url['copyright'] = trim((string)$xml->channel->item->children('http://search.yahoo.com/mrss/')->credit);
429
				$image_url['source_website'] = trim((string)$xml->channel->item->link);
430
				$image_url['source'] = 'flickr';
431
				return $image_url;
432
			}
433
		} 
434
		return false;
435
	}
436
437
	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...
438
		$Common = new Common();
439
		//echo "\n".'SEARCH IMAGE : http://mtlcatalog.ivao.aero/images/aircraft/'.$aircraft_icao.$airline_icao.'.jpg';
440
		if ($Common->urlexist('http://mtlcatalog.ivao.aero/images/aircraft/'.$aircraft_icao.$airline_icao.'.jpg')) {
441
			$image_url = array();
442
			$image_url['thumbnail'] = 'http://mtlcatalog.ivao.aero/images/aircraft/'.$aircraft_icao.$airline_icao.'.jpg';
443
			$image_url['original'] = 'http://mtlcatalog.ivao.aero/images/aircraft/'.$aircraft_icao.$airline_icao.'.jpg';
444
			$image_url['copyright'] = 'IVAO';
445
			$image_url['source_website'] = 'http://mtlcatalog.ivao.aero/';
446
			$image_url['source'] = 'ivao.aero';
447
			return $image_url;
448
		} else {
449
			return false;
450
		}
451
	}
452
453
	/**
454
	* Gets the aircraft image from Bing
455
	*
456
	* @param String $aircraft_registration the registration of the aircraft
457
	* @param String $aircraft_name type of the aircraft
458
	* @return Array the aircraft thumbnail, orignal url and copyright
459
	*
460
	*/
461
	public function fromBing($type,$aircraft_registration,$aircraft_name='') {
462
		global $globalImageBingKey;
463
		$Common = new Common();
464
		if (!isset($globalImageBingKey) || $globalImageBingKey == '') return false;
465
		if ($type == 'aircraft') {
466
			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';
467
			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';
468
		} elseif ($type == 'marine') {
469
			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';
470
			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';
471
		}
472
		$headers = array("Authorization: Basic " . base64_encode("ignored:".$globalImageBingKey));
473
		$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...
474
		$result = json_decode($data);
475
		if (isset($result->d->results[0]->MediaUrl)) {
476
			$image_url = array();
477
			$image_url['original'] = $result->d->results[0]->MediaUrl;
478
			$image_url['source_website'] = $result->d->results[0]->SourceUrl;
479
			// Thumbnail can't be used this way...
480
			// $image_url['thumbnail'] = $result->d->results[0]->Thumbnail->MediaUrl;
481
			$image_url['thumbnail'] = $result->d->results[0]->MediaUrl;
482
			$url = parse_url($image_url['source_website']);
483
			$image_url['copyright'] = $url['host'];
484
			$image_url['source'] = 'bing';
485
			return $image_url;
486
		}
487
		return false;
488
	}
489
490
	/**
491
	* Gets the aircraft image from airport-data
492
	*
493
	* @param String $aircraft_registration the registration of the aircraft
494
	* @param String $aircraft_name type of the aircraft
495
	* @return Array the aircraft thumbnail, orignal url and copyright
496
	*
497
	*/
498
	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...
499
		$Common = new Common();
500
		$url = 'http://www.airport-data.com/api/ac_thumb.json?&n=1&r='.$aircraft_registration;
501
		$data = $Common->getData($url);
502
		$result = json_decode($data);
503
		if (isset($result->count) && $result->count > 0) {
504
			$image_url = array();
505
			$image_url['original'] = str_replace('thumbnails','large',$result->data[0]->image);
506
			$image_url['source_website'] = $result->data[0]->link;
507
			$image_url['thumbnail'] = $result->data[0]->image;
508
			$image_url['copyright'] = $result->data[0]->photographer;
509
			$image_url['source'] = 'AirportData';
510
			return $image_url;
511
		}
512
		return false;
513
	}
514
515
	/**
516
	* Gets image from WikiMedia
517
	*
518
	* @param String $registration the registration of the aircraft/mmsi
519
	* @param String $name name
520
	* @return Array the aircraft thumbnail, orignal url and copyright
521
	*
522
	*/
523
	public function fromWikimedia($type,$registration,$name='') {
524
		$Common = new Common();
525
		if ($type == 'aircraft') {
526
			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);
527
			else $url = 'https://commons.wikimedia.org/w/api.php?action=query&list=search&format=json&srlimit=1&srnamespace=6&continue&srsearch="'.$registration.'"%20aircraft';
528
		} elseif ($type == 'marine') {
529
			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"';
530
			else return false;
531
		}
532
		$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...
533
		$result = json_decode($data);
534
		if (isset($result->query->search[0]->title)) {
535
			$fileo = $result->query->search[0]->title;
536
			if (substr($fileo,-3) == 'pdf') return false;
537
			$file = urlencode($fileo);
538
			$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;
539
			$data2 = $Common->getData($url2);
540
			$result2 = json_decode($data2);
541
			if (isset($result2->query->pages)) {
542
				foreach ($result2->query->pages as $page) {
543
					if (isset($page->imageinfo[0]->user)) {
544
						$image_url = array();
545
						$image_url['copyright'] = 'Wikimedia, '.$page->imageinfo[0]->user;
546
						$image_url['original'] = $page->imageinfo[0]->url;
547
						$image_url['thumbnail'] = $page->imageinfo[0]->thumburl;
548
						$image_url['source'] = 'wikimedia';
549
						$image_url['source_website'] = 'http://commons.wikimedia.org/wiki/'.$fileo;
550
						//return $image_url;
551
					}
552
				}
553
			}
554
			if (isset($image_url['original'])) {
555
				$url2 = 'https://commons.wikimedia.org/w/api.php?action=query&prop=imageinfo&iiprop=extmetadata&format=json&continue&titles='.$file;
556
				$data2 = $Common->getData($url2);
557
				$result2 = json_decode($data2);
558
				if (isset($result2->query->pages)) {
559
					foreach ($result2->query->pages as $page) {
560
						if (isset($page->imageinfo[0]->extmetadata->Artist)) {
561
							$image_url['copyright'] = preg_replace('/ from(.*)/','',strip_tags($page->imageinfo[0]->extmetadata->Artist->value));
562
							if (isset($page->imageinfo[0]->extmetadata->License->value)) {
563
								$image_url['copyright'] = $image_url['copyright'].' (under '.$page->imageinfo[0]->extmetadata->License->value.')';
564
							}
565
							$image_url['copyright'] = trim(str_replace('\n','',$image_url['copyright']));
566
							return $image_url;
567
						}
568
					}
569
				}
570
				return $image_url;
571
			}
572
		}
573
		return false;
574
	}
575
576
	/**
577
	* Gets the aircraft image from custom url
578
	*
579
	* @param String $registration the registration of the aircraft
580
	* @param String $name type of the aircraft
581
	* @return Array the aircraft thumbnail, orignal url and copyright
582
	*
583
	*/
584
	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...
585
		global $globalAircraftImageCustomSources, $globalMarineImageCustomSources, $globalDebug;
586
		//$globalAircraftImageCustomSource[] = array('thumbnail' => '','original' => '', 'copyright' => '', 'source_website' => '', 'source' => '','exif' => true);
587
		if (!empty($globalAircraftImageCustomSources) && $type == 'aircraft') {
588
			$customsources = array();
589
			if (!isset($globalAircraftImageCustomSources[0])) {
590
				$customsources[] = $globalAircraftImageCustomSources;
591
			} else {
592
				$customsources = $globalAircraftImageCustomSources;
593
			}
594
			foreach ($customsources as $source) {
595
				$Common = new Common();
596
				if (!isset($source['original']) && $globalDebug) {
597
					echo 'original entry not found for $globalAircraftImageCustomSources.';
598
					print_r($source);
599
					print_r($customsources);
600
				}
601
				$url = str_replace('{registration}',$registration,$source['original']);
602
				$url_thumbnail = str_replace('{registration}',$registration,$source['thumbnail']);
603
				if ($Common->urlexist($url)) {
604
					$image_url = array();
605
					$image_url['thumbnail'] = $url_thumbnail;
606
					$image_url['original'] = $url;
607
					if ($source['exif'] && exif_imagetype($url) == IMAGETYPE_JPEG) $exifCopyright = $this->getExifCopyright($url);
608
					else $exifCopyright = '';
609
					if ($exifCopyright  != '') $image_url['copyright'] = $exifCopyright;
610
					elseif (isset($source['copyright'])) $image_url['copyright'] = $source['copyright'];
611
					else $image_url['copyright'] = $source['source_website'];
612
					$image_url['source_website'] = $source['source_website'];
613
					$image_url['source'] = $source['source'];
614
					return $image_url;
615
				}
616
			}
617
			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...
618
		} 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...
619
		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...
620
			$customsources = array();
621
			if (!isset($globalMarineImageCustomSources[0])) {
622
				$customsources[] = $globalMarineImageCustomSources;
623
			} else {
624
				$customsources = $globalMarineImageCustomSources;
625
			}
626
			foreach ($customsources as $source) {
627
				$Common = new Common();
628
				if (!isset($source['original']) && $globalDebug) {
629
					echo 'original entry not found for $globalMarineImageCustomSources.';
630
					print_r($source);
631
					print_r($customsources);
632
				}
633
				$url = str_replace('{registration}',$registration,$source['original']);
634
				$url = str_replace('{mmsi}',$registration,$url);
635
				$url = str_replace('{name}',$name,$url);
636
				$url_thumbnail = str_replace('{registration}',$registration,$source['thumbnail']);
637
				$url_thumbnail = str_replace('{mmsi}',$registration,$url_thumbnail);
638
				$url_thumbnail = str_replace('{name}',$name,$url_thumbnail);
639
				if ($Common->urlexist($url)) {
640
					$image_url = array();
641
					$image_url['thumbnail'] = $url_thumbnail;
642
					$image_url['original'] = $url;
643
					if ($source['exif'] && exif_imagetype($url) == IMAGETYPE_JPEG) $exifCopyright = $this->getExifCopyright($url);
644
					else $exifCopyright = '';
645
					if ($exifCopyright  != '') $image_url['copyright'] = $exifCopyright;
646
					elseif (isset($source['copyright'])) $image_url['copyright'] = $source['copyright'];
647
					else $image_url['copyright'] = $source['source_website'];
648
					$image_url['source_website'] = $source['source_website'];
649
					$image_url['source'] = $source['source'];
650
					return $image_url;
651
				}
652
			}
653
			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...
654
		} else return false;
655
	}
656
}
657
658
//$Image = new Image();
659
//print_r($Image->fromAirportData('F-GZHM'));
660
661
?>