Accident::add()   F
last analyzed

Complexity

Conditions 27
Paths 1985

Size

Total Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 27
nc 1985
nop 2
dl 0
loc 65
rs 0
c 0
b 0
f 0

How to fix   Long Method    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 for Accidents/Incidents data.
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.Connection.php');
10
require_once(dirname(__FILE__).'/class.Spotter.php');
11
require_once(dirname(__FILE__).'/class.Image.php');
12
require_once(dirname(__FILE__).'/class.Translation.php');
13
14
class Accident {
15
	public $db;
16
17
	/*
18
	 * Initialize DB connection
19
	 */
20
	public function __construct($dbc = null) {
21
		$Connection = new Connection($dbc);
22
		$this->db = $Connection->db();
23
		if ($this->db === null) die('Error: No DB connection. (Accident)');
24
	}
25
26
	/*
27
	 * Get all aircrafts registration by accidents
28
	 * @return Array Return all registrations in accidents table
29
	*/
30
	public function get() {
31
		$query = 'SELECT DISTINCT registration FROM accidents ORDER BY date DESC';
32
		$sth = $this->db->prepare($query);
33
		$sth->execute();
34
		$result = $sth->fetchAll(PDO::FETCH_ASSOC);
35
		return $result;
36
	}
37
38
	/**
39
	* Get Accidents data from DB
40
	* @param String $limit Limit
41
	* @param String $type Set type accident or incident
42
	* @param String $date get data for a date
43
	* @return array Return Accidents data in array
44
	*/
45
	public function getAccidentData($limit = '',$type = '',$date = '') {
46
		global $globalDBdriver;
47
		$Image = new Image($this->db);
48
		$Spotter = new Spotter($this->db);
49
		$Translation = new Translation($this->db);
50
		$date = filter_var($date,FILTER_SANITIZE_STRING);
51
		date_default_timezone_set('UTC');
52
		$result = array();
53
		$limit_query = '';
54
		if ($limit != "")
55
		{
56
			$limit_array = explode(",", $limit);
57
			$limit_array[0] = filter_var($limit_array[0],FILTER_SANITIZE_NUMBER_INT);
58
			$limit_array[1] = filter_var($limit_array[1],FILTER_SANITIZE_NUMBER_INT);
59
			if ($limit_array[0] >= 0 && $limit_array[1] >= 0)
60
			{
61
				$limit_query = " LIMIT ".$limit_array[1]." OFFSET ".$limit_array[0];
62
			}
63
		}
64
65
		if ($type != '') {
66
			if ($date != '') {
67
				if (preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/",$date)) {
68
					$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type AND date = :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
69
					//$query = "SELECT accidents.registration, accidents.ident, accidents.date, accidents.url, accidents.country, accidents.place, accidents.title, accidents.fatalities, accidents.type, accidents.ident, accidents.aircraft_manufacturer, accidents.aircraft_name, accidents.airline_name, accidents.airline_icao, spotter_output.flightaware_id FROM accidents LEFT OUTER JOIN spotter_output ON accidents.registration = spotter_output.registration WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type AND date = :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
70
					$query_values = array(':type' => $type,':date' => $date);
71
				} elseif (preg_match("/^[0-9]{4}-[0-9]{2}$/",$date)) {
72
					$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type AND date BETWEEN :dated AND :datef GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
73
					$query_values = array(':type' => $type,':dated' => $date.'-01', ':datef' => $date.'-31');
74
				} elseif (preg_match("/^[0-9]{4}$/",$date)) {
75
					if ($globalDBdriver == 'mysql') {
76
						$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type AND YEAR(date) = :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
77
					} else {
78
						$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type AND EXTRACT(YEAR FROM date) = :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
79
					}
80
					$query_values = array(':type' => $type,':date' => $date);
81
				} else {
82
					$date = $date.'%';
83
					if ($globalDBdriver == 'mysql') {
84
						$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type AND DATE_FORMAT(date,'%Y-%m-%d') LIKE :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
85
						$query_values = array(':type' => $type,':date' => $date);
86
					} else {
87
						$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type AND to_char(date,'YYYY-MM-DD') LIKE :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
88
						//$query = "SELECT accidents.registration, accidents.ident, accidents.date, accidents.url, accidents.country, accidents.place, accidents.title, accidents.fatalities, accidents.type, accidents.ident, accidents.aircraft_manufacturer, accidents.aircraft_name, accidents.airline_name, accidents.airline_icao, spotter_output.flightaware_id FROM accidents LEFT OUTER JOIN spotter_output ON accidents.registration = spotter_output.registration WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type AND to_char(date,'YYYY-MM-DD') LIKE :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
89
						$query_values = array(':type' => $type,':date' => $date);
90
					}
91
				}
92
			} else {
93
				//$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
94
				$query = "SELECT * FROM accidents WHERE type = :type ORDER BY accidents.date DESC".$limit_query;
95
				//$query = "SELECT accidents.registration, accidents.ident, accidents.date, accidents.url, accidents.country, accidents.place, accidents.title, accidents.fatalities, accidents.type, accidents.ident, accidents.aircraft_manufacturer, accidents.aircraft_name, accidents.airline_name, accidents.airline_icao, spotter_output.flightaware_id FROM accidents LEFT OUTER JOIN spotter_output ON accidents.registration = spotter_output.registration WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE type = :type GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
96
				$query_values = array(':type' => $type);
97
			}
98
		} else {
99
			if ($date != '') {
100
				if (preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/",$date)) {
101
					$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE date = :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
102
					//$query = "SELECT accidents.registration, accidents.ident, accidents.date, accidents.url, accidents.country, accidents.place, accidents.title, accidents.fatalities, accidents.type, accidents.ident, accidents.aircraft_manufacturer, accidents.aircraft_name, accidents.airline_name, accidents.airline_icao, spotter_output.flightaware_id FROM accidents LEFT OUTER JOIN spotter_output ON accidents.registration = spotter_output.registration WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE date = :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
103
				} else {
104
					$date = $date.'%';
105
					$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE to_char(date,'YYYY-MM-DD') LIKE :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
106
					//$query = "SELECT accidents.registration, accidents.ident, accidents.date, accidents.url, accidents.country, accidents.place, accidents.title, accidents.fatalities, accidents.type, accidents.ident, accidents.aircraft_manufacturer, accidents.aircraft_name, accidents.airline_name, accidents.airline_icao, spotter_output.flightaware_id FROM accidents LEFT OUTER JOIN spotter_output ON accidents.registration = spotter_output.registration WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents WHERE to_char(date,'YYYY-MM-DD') LIKE :date GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
107
				}
108
				$query_values = array(':date' => $date);
109
			} else {
110
				//$query = "SELECT * FROM accidents WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
111
				$query = "SELECT * FROM accidents ORDER BY accidents.date DESC".$limit_query;
112
				//$query = "SELECT accidents.registration, accidents.ident, accidents.date, accidents.url, accidents.country, accidents.place, accidents.title, accidents.fatalities, accidents.type, accidents.ident, accidents.aircraft_manufacturer, accidents.aircraft_name, accidents.airline_name, accidents.airline_icao, spotter_output.flightaware_id FROM accidents LEFT OUTER JOIN spotter_output ON accidents.registration = spotter_output.registration WHERE accidents_id IN (SELECT max(accidents_id) FROM accidents GROUP BY registration) ORDER BY accidents.date DESC".$limit_query;
113
				$query_values = array();
114
			}
115
		}
116
		try {
117
			$sth = $this->db->prepare($query);
118
			$sth->execute($query_values);
119
		} catch(PDOException $e) {
120
			echo "error : ".$e->getMessage();
121
			return array();
122
		}
123
		$i = 0;
124
		while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
125
			if (preg_match('/^[\w\-]+$/',$row['registration'])) {
126
				$data = array();
127
				if ($row['registration'] != '') {
128
					$image_array = $Image->getSpotterImage($row['registration']);
129
					if (count($image_array) > 0) $data = array_merge($data,array('image' => $image_array[0]['image'],'image_thumbnail' => $image_array[0]['image_thumbnail'],'image_copyright' => $image_array[0]['image_copyright'],'image_source' => $image_array[0]['image_source'],'image_source_website' => $image_array[0]['image_source_website']));
130
					else $data = array_merge($data,array('image' => '','image_thumbnail' => '','image_copyright' => '','image_source' => '','image_source_website' => ''));
131
					$aircraft_type = $Spotter->getAllAircraftTypeByRegistration($row['registration']);
132
					$aircraft_info = $Spotter->getAllAircraftInfo($aircraft_type);
133
					if (!empty($aircraft_info)) {
134
						$data['aircraft_type'] = $aircraft_info[0]['icao'];
135
						$data['aircraft_name'] = $aircraft_info[0]['type'];
136
						$data['aircraft_manufacturer'] = $aircraft_info[0]['manufacturer'];
137
					} else {
138
						$data = array_merge($data,array('aircraft_type' => 'NA'));
139
					}
140
					$owner_data = $Spotter->getAircraftOwnerByRegistration($row['registration']);
141
					if (!empty($owner_data)) {
142
						$data['aircraft_owner'] = $owner_data['owner'];
143
						$data['aircraft_base'] = $owner_data['base'];
144
						$data['aircraft_date_first_reg'] = $owner_data['date_first_reg'];
145
					}
146
				} else $data = array_merge($data,array('image' => '','image_thumbnail' => '','image_copyright' => '','image_source' => '','image_source_website' => ''));
147
				if ($row['registration'] == '') $row['registration'] = 'NA';
148
				if ($row['ident'] == '') $row['ident'] = 'NA';
149
				$identicao = $Spotter->getAllAirlineInfo(substr($row['ident'],0,3));
150
				if (isset($identicao[0])) {
151
					if (substr($row['ident'],0,2) == 'AF') {
152
						if (filter_var(substr($row['ident'],2),FILTER_VALIDATE_INT,array("flags"=>FILTER_FLAG_ALLOW_OCTAL))) $icao = $row['ident'];
153
						else $icao = 'AFR'.ltrim(substr($row['ident'],2),'0');
154
					} else $icao = $identicao[0]['icao'].ltrim(substr($row['ident'],2),'0');
155
					$data = array_merge($data,array('airline_icao' => $identicao[0]['icao'],'airline_name' => $identicao[0]['name']));
156
				} else $icao = $row['ident'];
157
				$icao = $Translation->checkTranslation($icao,false);
158
				//$data = array_merge($data,array('registration' => $row['registration'], 'date' => $row['date'], 'ident' => $icao,'url' => $row['url']));
159
				if ($row['airline_name'] != '' && !isset($data['airline_name'])) {
160
					//echo 'Check airline info... for '.$row['airline_name'].' ';
161
					//echo $row['airline_name'];
162
					$airline_info = $Spotter->getAllAirlineInfoByName($row['airline_name']);
163
					if (!empty($airline_info)) {
164
						//echo 'data found !'."\n";
165
						//print_r($airline_info);
166
						$data = array_merge($data,$airline_info);
167
					} 
168
					//else echo 'No data...'."\n";
169
				}
170
				$data = array_merge($row,$data);
171
				if ($data['ident'] == null) $data['ident'] = $icao;
172
				if ($data['title'] == null) {
173
					$data['message'] = $row['type'].' of '.$row['registration'].' at '.$row['place'].','.$row['country'];
174
				} else $data['message'] = strtolower($data['title']);
175
				$ids = $Spotter->getAllIDByRegistration($data['registration'],true);
176
				$date = $data['date'];
177
				if (isset($ids[$date])) {
178
					$data['spotted'] = TRUE;
179
					$data['flightaware_id'] = $ids[$date]['flightaware_id'];
180
					$data['spotter_id'] = $ids[$date]['spotter_id'];
181
				} elseif (isset($ids[0])) {
182
					$data['spotted_registration'] = TRUE;
183
					$data['flightaware_id'] = $ids[0]['flightaware_id'];
184
					//$data['spotter_id'] = $ids[0]['spotter_id'];
185
				}
186
				$result[] = $data;
187
			}
188
			$i++;
189
		}
190
		if (isset($result)) {
191
			$result[0]['query_number_rows'] = $i;
192
			return $result;
193
		}
194
		else return array();
195
	}
196
197
	/*
198
	* Get fatalities by year
199
	* @return Array number of fatalities by year
200
	*/
201
	public function countFatalitiesByYear() {
202
		//$query = 'SELECT EXTRACT(year FROM date) AS year, SUM(fatalities) as count FROM accidents WHERE accidents_id IN (SELECT MAX(accidents_id) FROM accidents WHERE fatalities > 0 AND EXTRACT(year FROM date) > 2006 GROUP BY registration) GROUP BY EXTRACT(year FROM date) ORDER BY year';
203
		$query = "SELECT EXTRACT(year FROM date) AS year, SUM(fatalities) as count FROM accidents WHERE accidents_id IN (SELECT MAX(accidents_id) FROM accidents WHERE fatalities > 0 AND date > '2006-01-01 00:00:00' GROUP BY registration) GROUP BY EXTRACT(year FROM date) ORDER BY year";
204
		try {
205
			$sth = $this->db->prepare($query);
206
			$sth->execute();
207
		} catch(PDOException $e) {
208
			echo "Error : ".$e->getMessage();
209
			return array();
210
		}
211
		return $sth->fetchAll(PDO::FETCH_ASSOC);
212
	}
213
214
	/*
215
	* Get fatalities last 12 months
216
	* @return Array number of fatalities last 12 months
217
	*/
218
	public function countFatalitiesLast12Months() {
219
		global $globalDBdriver;
220
		if ($globalDBdriver == 'mysql') {
221
			$query = "SELECT EXTRACT(month FROM date) AS month, EXTRACT(year FROM date) AS year, SUM(fatalities) as count FROM accidents WHERE accidents_id IN (SELECT MAX(accidents_id) FROM accidents WHERE fatalities > 0 AND date > DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY registration) GROUP BY EXTRACT(month FROM date), EXTRACT(year FROM date) ORDER BY year,month";
222
		} else {
223
			$query = "SELECT EXTRACT(month FROM date) AS month, EXTRACT(year FROM date) AS year, SUM(fatalities) as count FROM accidents WHERE accidents_id IN (SELECT MAX(accidents_id) FROM accidents WHERE fatalities > 0 AND date > (current_date - INTERVAL '12 months') GROUP BY registration) GROUP BY EXTRACT(month FROM date), EXTRACT(year FROM date) ORDER BY year,month";
224
		}
225
		try {
226
			$sth = $this->db->prepare($query);
227
			$sth->execute();
228
		} catch(PDOException $e) {
229
			echo "Error : ".$e->getMessage();
230
			return array();
231
		}
232
		return $sth->fetchAll(PDO::FETCH_ASSOC);
233
	}
234
235
	/*
236
	* Import csv accidents file into the DB
237
	* @param String $file filename of the file to import
238
	*/
239
	public function import($file) {
240
		global $globalDebug;
241
		if ($globalDebug) echo 'Import '.$file."\n";
242
		$result = array();
243
		if (file_exists($file)) {
244
			if (($handle = fopen($file,'r')) !== FALSE) {
245
				while (($data = fgetcsv($handle,2000,",")) !== FALSE) {
246
					if (isset($data[1]) && $data[1] != '0000-00-00 00:00:00') {
247
						$result[] = array('registration' => $data[0],'date' => strtotime($data[1]),'url' => $data[2],'country' => $data[3],'place' => $data[4],'title' => $data[5],'fatalities' => $data[6],'latitude' => $data[7],'longitude' => $data[8],'type' => $data[9],'ident' => $data[10],'aircraft_manufacturer' => $data[11],'aircraft_name' => $data[12],'operator' => $data[13],'source' => 'website_fam');
248
					}
249
				}
250
				fclose($handle);
251
			}
252
			if (!empty($result)) $this->add($result,true);
253
			elseif ($globalDebug) echo 'Nothing to import';
254
		}
255
	}
256
257
	/*
258
	* Check if file changed since last update, if true import modified files
259
	*/
260
	public function download_update() {
261
		global $globalDebug;
262
		require_once('class.Common.php');
263
		$Common = new Common();
264
		$all_md5 = array();
265
		$all_md5_new = array();
266
		if (file_exists(dirname(__FILE__).'/../install/tmp/cr-all.md5')) {
267
			if ($this->check_accidents_nb() > 0) {
268
				if (($handle = fopen(dirname(__FILE__).'/../install/tmp/cr-all.md5','r')) !== FALSE) {
269
					while (($data = fgetcsv($handle,2000,"\t")) !== FALSE) {
270
						if (isset($data[1])) {
271
							$year = $data[0];
272
							$all_md5[$year] = $data[1];
273
						}
274
					}
275
					fclose($handle);
276
				}
277
			}
278
		}
279
		$Common->download('http://data.flightairmap.fr/data/cr/cr-all.md5',dirname(__FILE__).'/../install/tmp/cr-all.md5');
280
		if (file_exists(dirname(__FILE__).'/../install/tmp/cr-all.md5')) {
281
			if (($handle = fopen(dirname(__FILE__).'/../install/tmp/cr-all.md5','r')) !== FALSE) {
282
				while (($data = fgetcsv($handle,2000,"\t")) !== FALSE) {
283
					if (isset($data[1])) {
284
						$year = $data[0];
285
						$all_md5_new[$year] = $data[1];
286
					}
287
				}
288
				fclose($handle);
289
			} elseif ($globalDebug) echo "Can't open ".dirname(__FILE__).'/../install/tmp/cr-all.md5';
290
		} elseif ($globalDebug) echo 'Download cr-all.md5 failed. '.dirname(__FILE__).'/../install/tmp/cr-all.md5 not here.';
291
		$result = $Common->arr_diff($all_md5_new,$all_md5);
292
		if (empty($result) && $globalDebug) echo 'Nothing to update';
293
		foreach ($result as $file => $md5) {
294
			$Common->download('http://data.flightairmap.fr/data/cr/'.$file,dirname(__FILE__).'/../install/tmp/'.$file);
295
			if (file_exists(dirname(__FILE__).'/../install/tmp/'.$file)) $this->import(dirname(__FILE__).'/../install/tmp/'.$file);
296
			elseif ($globalDebug) echo 'Download '.$file.' failed';
297
		}
298
	}
299
300
	/*
301
	* Add data to DB
302
	* @param Array $crash An array with accidents/incidents data
303
	*/
304
	public function add($crash,$new = false) {
305
		global $globalTransaction, $globalDebug, $globalAircraftImageFetch;
306
		require_once('class.Connection.php');
307
		require_once('class.Image.php');
308
		require_once('class.Spotter.php');
309
		$Connection = new Connection($this->db);
310
		$Image = new Image($this->db);
311
		$Spotter = new Spotter($this->db);
312
313
		if (empty($crash)) return false;
314
		if ($new === false) {
315
			$query_delete = 'DELETE FROM accidents WHERE source = :source';
316
			$sthd = $Connection->db->prepare($query_delete);
317
			$sthd->execute(array(':source' => $crash[0]['source']));
318
		}
319
		if ($globalTransaction) $Connection->db->beginTransaction();
320
		$initial_array = array('ident' => null,'type' => 'accident','url' => null,'registration' => null, 'date' => null, 'place' => null,'country' => null, 'latitude' => null, 'longitude' => null, 'fatalities' => null, 'title' => '','source' => '','aircraft_manufacturer' => null,'aircraft_name' => null,'operator' => null);
321
		$query_check = 'SELECT COUNT(*) as nb FROM accidents WHERE registration = :registration AND date = :date AND type = :type AND source = :source';
322
		$sth_check = $Connection->db->prepare($query_check);
323
		$query = 'INSERT INTO accidents (aircraft_manufacturer,aircraft_name,ident,registration,date,url,country,place,title,fatalities,latitude,longitude,type,airline_name,source) VALUES (:aircraft_manufacturer,:aircraft_name,:ident,:registration,:date,:url,:country,:place,:title,:fatalities,:latitude,:longitude,:type,:airline_name,:source)';
324
		$sth = $Connection->db->prepare($query);
325
		$j = 0;
326
		try {
327
			foreach ($crash as $cr) {
328
				//print_r($cr);
329
				$cr = $cr + $initial_array;
330
				$cr = array_map(function($value) {
331
					return $value === "" ? NULL : $value;
332
				}, $cr);
333
				if ($cr['date'] != '' && $cr['registration'] != null && $cr['registration'] != '' && $cr['registration'] != '?' && $cr['registration'] != '-' && strtolower($cr['registration']) != 'unknown' && $cr['date'] < time() && !preg_match('/\s/',$cr['registration'])) {
334
					if (strpos($cr['registration'],'-') === FALSE) $cr['registration'] = $Spotter->convertAircraftRegistration($cr['registration']);
335
					$query_check_values = array(':registration' => $cr['registration'],':date' => date('Y-m-d',$cr['date']),':type' => $cr['type'],':source' => $cr['source']);
336
					$sth_check->execute($query_check_values);
337
					$result_check = $sth_check->fetchAll(PDO::FETCH_ASSOC);
338
					if ($result_check[0]['nb'] == 0) {
339
						$query_values = array(':registration' => trim($cr['registration']),':date' => date('Y-m-d',$cr['date']),':url' => $cr['url'],':country' => $cr['country'],':place' => $cr['place'],':title' => $cr['title'],':fatalities' => $cr['fatalities'],':latitude' => $cr['latitude'],':longitude' => $cr['longitude'],':type' => $cr['type'],':source' => $cr['source'],':ident' => $cr['ident'],':aircraft_manufacturer' => $cr['aircraft_manufacturer'],':aircraft_name' => $cr['aircraft_name'],':airline_name' => $cr['operator']);
340
						$sth->execute($query_values);
341
						if ($cr['date'] > time()-(30*86400)) {
342
							if ($globalAircraftImageFetch) {
343
								$imgchk = $Image->getSpotterImage($cr['registration']);
344
								if (empty($imgchk)) {
345
									if ($globalDebug) echo "\t".'Get image for '.$cr['registration'].'...';
346
									$Image->addSpotterImage($cr['registration']);
347
									if ($globalDebug) echo "\t".'Done'."\n";
348
								}
349
								// elseif ($globalDebug) echo 'Image already in DB'."\n";
350
							}
351
							if ($cr['title'] == '') $cr['title'] = $cr['registration'].' '.$cr['type'];
352
							$Spotter->setHighlightFlightByRegistration($cr['registration'],$cr['title'],date('Y-m-d',$cr['date']));
353
						}
354
					}
355
				}
356
				if ($globalTransaction && $j % 1000 == 0) {
357
					$Connection->db->commit();
358
					$Connection->db->beginTransaction();
359
				}
360
			}
361
			if ($globalTransaction) $Connection->db->commit();
362
		} catch(PDOException $e) {
363
			if ($globalTransaction) $Connection->db->rollBack();
364
			echo $e->getMessage();
365
		}
366
		$sth_check->closeCursor();
367
		return '';
368
	}
369
370
	/*
371
	* Get number of accidents
372
	* @return Integer Number of accidents/incidents in table
373
	*/
374
	public static function check_accidents_nb() {
375
			$query = "SELECT COUNT(*) as nb FROM accidents";
376
		try {
377
			$Connection = new Connection();
378
			$sth = $Connection->db->prepare($query);
379
			$sth->execute();
380
		} catch(PDOException $e) {
381
			return "error : ".$e->getMessage();
382
		}
383
		$row = $sth->fetch(PDO::FETCH_ASSOC);
384
		return $row['nb'];
385
	}
386
387
    /**
388
     * Check if lastest accident update date is older than 1 day
389
     * @return bool|string
390
     */
391
    public static function check_last_accidents_update() {
392
		global $globalDBdriver;
393
		if ($globalDBdriver == 'mysql') {
394
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_accident_db' AND value > DATE_SUB(NOW(), INTERVAL 1 DAY)";
395
		} else {
396
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_accident_db' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 DAYS'";
397
		}
398
		try {
399
			$Connection = new Connection();
400
			$sth = $Connection->db->prepare($query);
401
			$sth->execute();
402
		} catch(PDOException $e) {
403
			return "error : ".$e->getMessage();
404
		}
405
		$row = $sth->fetch(PDO::FETCH_ASSOC);
406
		if ($row['nb'] > 0) return false;
407
		else return true;
408
	}
409
410
    /**
411
     * Insert accident update date
412
     * @return string
413
     */
414
    public static function insert_last_accidents_update() {
415
		$query = "DELETE FROM config WHERE name = 'last_update_accident_db';
416
		    INSERT INTO config (name,value) VALUES ('last_update_accident_db',NOW());";
417
		try {
418
			$Connection = new Connection();
419
			$sth = $Connection->db->prepare($query);
420
			$sth->execute();
421
		} catch(PDOException $e) {
422
			return "error : ".$e->getMessage();
423
		}
424
		return '';
425
	}
426
427
}
428
?>