Passed
Push — master ( e8097c...9fd6b6 )
by Jonathan
05:26
created
src/Webtrees/Module/GeoDispersion/AdminConfigController.php 3 patches
Indentation   +221 added lines, -221 removed lines patch added patch discarded remove patch
@@ -36,58 +36,58 @@  discard block
 block discarded – undo
36 36
  */
37 37
 class AdminConfigController extends MvcController
38 38
 {    
39
-    /**
40
-     * GeoAnalysis Provider
41
-     * @var GeoAnalysisProvider $provider
42
-     */
43
-    protected $provider;    
39
+	/**
40
+	 * GeoAnalysis Provider
41
+	 * @var GeoAnalysisProvider $provider
42
+	 */
43
+	protected $provider;    
44 44
     
45
-    /**
46
-     * Constructor for Admin Config controller
47
-     * @param AbstractModule $module
48
-     */
49
-    public function __construct(AbstractModule $module) {
50
-        parent::__construct($module);
45
+	/**
46
+	 * Constructor for Admin Config controller
47
+	 * @param AbstractModule $module
48
+	 */
49
+	public function __construct(AbstractModule $module) {
50
+		parent::__construct($module);
51 51
         
52
-        $this->provider = $this->module->getProvider();
53
-    }    
52
+		$this->provider = $this->module->getProvider();
53
+	}    
54 54
     
55
-    /**
56
-     * Pages
57
-     */
55
+	/**
56
+	 * Pages
57
+	 */
58 58
         
59
-    /**
60
-     * AdminConfig@index
61
-     */
62
-    public function index() {
63
-        $wt_tree = Globals::getTree();
64
-        Theme::theme(new AdministrationTheme)->init($wt_tree);
65
-        $controller = new PageController();
66
-        $controller
67
-            ->restrictAccess(Auth::isManager($wt_tree))
68
-            ->setPageTitle($this->module->getTitle());
59
+	/**
60
+	 * AdminConfig@index
61
+	 */
62
+	public function index() {
63
+		$wt_tree = Globals::getTree();
64
+		Theme::theme(new AdministrationTheme)->init($wt_tree);
65
+		$controller = new PageController();
66
+		$controller
67
+			->restrictAccess(Auth::isManager($wt_tree))
68
+			->setPageTitle($this->module->getTitle());
69 69
         
70
-        $data = new ViewBag();
71
-        $data->set('title', $controller->getPageTitle());
72
-        $data->set('tree', $wt_tree);
70
+		$data = new ViewBag();
71
+		$data->set('title', $controller->getPageTitle());
72
+		$data->set('tree', $wt_tree);
73 73
         
74
-        $data->set('root_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig');
74
+		$data->set('root_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig');
75 75
                 
76
-        $table_id = 'table-geoanalysis-' . Uuid::uuid4();
77
-        $data->set('table_id', $table_id);
76
+		$table_id = 'table-geoanalysis-' . Uuid::uuid4();
77
+		$data->set('table_id', $table_id);
78 78
         
79
-        $other_trees = array();
80
-        foreach (Tree::getAll() as $tree) {
81
-            if($tree->getTreeId() != $wt_tree->getTreeId()) $other_trees[] = $tree;
82
-        }      
83
-        $data->set('other_trees', $other_trees);
79
+		$other_trees = array();
80
+		foreach (Tree::getAll() as $tree) {
81
+			if($tree->getTreeId() != $wt_tree->getTreeId()) $other_trees[] = $tree;
82
+		}      
83
+		$data->set('other_trees', $other_trees);
84 84
         
85
-        $data->set('places_hierarchy', $this->provider->getPlacesHierarchy());
85
+		$data->set('places_hierarchy', $this->provider->getPlacesHierarchy());
86 86
         
87
-        $controller
88
-            ->addExternalJavascript(WT_JQUERY_DATATABLES_JS_URL)
89
-            ->addExternalJavascript(WT_DATATABLES_BOOTSTRAP_JS_URL)
90
-            ->addInlineJavascript('
87
+		$controller
88
+			->addExternalJavascript(WT_JQUERY_DATATABLES_JS_URL)
89
+			->addExternalJavascript(WT_DATATABLES_BOOTSTRAP_JS_URL)
90
+			->addInlineJavascript('
91 91
 				jQuery.fn.dataTableExt.oSort["text-asc"] = textCompareAsc;
92 92
 				jQuery.fn.dataTableExt.oSort["text-desc"] = textCompareDesc;
93 93
                 
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 				});
120 120
                 
121 121
                 ')
122
-                ->addInlineJavascript('				
122
+				->addInlineJavascript('				
123 123
                     function set_geoanalysis_status(ga_id, status, gedcom) {
124 124
                 		jQuery.ajax({
125 125
                             url: "module.php", 
@@ -163,54 +163,54 @@  discard block
 block discarded – undo
163 163
                 ');
164 164
         
165 165
         
166
-        ViewFactory::make('AdminConfig', $this, $controller, $data)->render();
167
-    }
166
+		ViewFactory::make('AdminConfig', $this, $controller, $data)->render();
167
+	}
168 168
 
169
-    /**
170
-     * AdminConfig@jsonGeoAnalysisList
171
-     */
172
-    public function jsonGeoAnalysisList() {
173
-        $wt_tree = Globals::getTree();
174
-        $controller = new JsonController();
175
-        $controller
176
-            ->restrictAccess(Auth::isManager($wt_tree));
169
+	/**
170
+	 * AdminConfig@jsonGeoAnalysisList
171
+	 */
172
+	public function jsonGeoAnalysisList() {
173
+		$wt_tree = Globals::getTree();
174
+		$controller = new JsonController();
175
+		$controller
176
+			->restrictAccess(Auth::isManager($wt_tree));
177 177
         
178
-        // Generate an AJAX/JSON response for datatables to load a block of rows
179
-        $search = Filter::postArray('search');
180
-        if($search) $search = $search['value'];
181
-        $start  = Filter::postInteger('start');
182
-        $length = Filter::postInteger('length');
183
-        $order  = Filter::postArray('order');
178
+		// Generate an AJAX/JSON response for datatables to load a block of rows
179
+		$search = Filter::postArray('search');
180
+		if($search) $search = $search['value'];
181
+		$start  = Filter::postInteger('start');
182
+		$length = Filter::postInteger('length');
183
+		$order  = Filter::postArray('order');
184 184
         
185
-        foreach($order as $key => &$value) {
186
-            switch($value['column']) {
187
-                case 3:
188
-                    $value['column'] = 'majgd_descr';
189
-                    break;
190
-                case 5;
191
-                    $value['column'] = 'majgd_sublevel';
192
-                    break;
193
-                default:
194
-                    unset($order[$key]);
195
-            }
196
-        }
185
+		foreach($order as $key => &$value) {
186
+			switch($value['column']) {
187
+				case 3:
188
+					$value['column'] = 'majgd_descr';
189
+					break;
190
+				case 5;
191
+					$value['column'] = 'majgd_sublevel';
192
+					break;
193
+				default:
194
+					unset($order[$key]);
195
+			}
196
+		}
197 197
         
198
-        /** @var GeoAnalysisProvider $provider */
199
-        $provider = $this->module->getProvider();
198
+		/** @var GeoAnalysisProvider $provider */
199
+		$provider = $this->module->getProvider();
200 200
         
201
-        $list = $provider->getFilteredGeoAnalysisList($search, $order, $start, $length);
202
-        $recordsFiltered = count($list);
203
-        $recordsTotal = $this->provider->getGeoAnalysisCount();
201
+		$list = $provider->getFilteredGeoAnalysisList($search, $order, $start, $length);
202
+		$recordsFiltered = count($list);
203
+		$recordsTotal = $this->provider->getGeoAnalysisCount();
204 204
         
205
-        $data = array();
206
-        $place_hierarchy = $this->provider->getPlacesHierarchy();
207
-        foreach($list as $ga) {
208
-            /** @var GeoAnalysis $ga */
205
+		$data = array();
206
+		$place_hierarchy = $this->provider->getPlacesHierarchy();
207
+		foreach($list as $ga) {
208
+			/** @var GeoAnalysis $ga */
209 209
             
210
-            $datum = array();
211
-            $options= $ga->getOptions();
210
+			$datum = array();
211
+			$options= $ga->getOptions();
212 212
             
213
-            $datum[0] = '
213
+			$datum[0] = '
214 214
                 <div class="btn-group">
215 215
                     <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
216 216
                         <i class="fa fa-pencil"></i><span class="caret"></span>
@@ -234,112 +234,112 @@  discard block
 block discarded – undo
234 234
                        </li>
235 235
                     </ul>
236 236
                 </div>';
237
-		    $datum[1] = $ga->getId();
238
-		    $datum[2] = $ga->isEnabled() ? 
237
+			$datum[1] = $ga->getId();
238
+			$datum[2] = $ga->isEnabled() ? 
239 239
 				'<i class="fa fa-check"></i><span class="sr-only">'.I18N::translate('Enabled').'</span>' : 
240 240
 				'<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('Disabled').'</span>';
241
-		    $datum[3] = $ga->getTitle();
242
-		    $analysis_level = $ga->getAnalysisLevel();
243
-		    if($place_hierarchy['type'] == 'header') {
244
-		        $datum[4] = $place_hierarchy['hierarchy'][$analysis_level - 1];
245
-		    } else {
246
-		        $datum[4] = $analysis_level . '(' . $place_hierarchy['hierarchy'][$analysis_level - 1] . ')';
247
-		    }
248
-		    $datum[5] = $ga->getAnalysisLevel();
249
-		    $datum[6] = '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('None').'</span>';
250
-		    $datum[7] = '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('None').'</span>';
251
-		    if($ga->hasMap()) {
252
-		        if($options->getMap()->isLoaded()) {
253
-    		        $datum[6] = $options->getMap()->getDescription();
254
-    		        $datum[7] = '<span data-toggle="tooltip" title="' . $options->getMap()->getTopLevelName() . '" />';
255
-    		        $top_level = $options->getMapLevel();
256
-    		        if($place_hierarchy['type'] == 'header') {
257
-    		            $datum[7] .= $place_hierarchy['hierarchy'][$top_level - 1];
258
-    		        } else {
259
-    		            $datum[7] .= $top_level . '(' . $place_hierarchy['hierarchy'][$top_level - 1] . ')';
260
-    		        }
261
-    		        $datum[7] .= '</span>';
262
-		        }
263
-		        else {
264
-		            $datum[6] = I18N::translate('Error when loading map.');
265
-		        }
266
-		    }
267
-		    $datum[8] = $options->isUsingFlags() ? 
241
+			$datum[3] = $ga->getTitle();
242
+			$analysis_level = $ga->getAnalysisLevel();
243
+			if($place_hierarchy['type'] == 'header') {
244
+				$datum[4] = $place_hierarchy['hierarchy'][$analysis_level - 1];
245
+			} else {
246
+				$datum[4] = $analysis_level . '(' . $place_hierarchy['hierarchy'][$analysis_level - 1] . ')';
247
+			}
248
+			$datum[5] = $ga->getAnalysisLevel();
249
+			$datum[6] = '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('None').'</span>';
250
+			$datum[7] = '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('None').'</span>';
251
+			if($ga->hasMap()) {
252
+				if($options->getMap()->isLoaded()) {
253
+					$datum[6] = $options->getMap()->getDescription();
254
+					$datum[7] = '<span data-toggle="tooltip" title="' . $options->getMap()->getTopLevelName() . '" />';
255
+					$top_level = $options->getMapLevel();
256
+					if($place_hierarchy['type'] == 'header') {
257
+						$datum[7] .= $place_hierarchy['hierarchy'][$top_level - 1];
258
+					} else {
259
+						$datum[7] .= $top_level . '(' . $place_hierarchy['hierarchy'][$top_level - 1] . ')';
260
+					}
261
+					$datum[7] .= '</span>';
262
+				}
263
+				else {
264
+					$datum[6] = I18N::translate('Error when loading map.');
265
+				}
266
+			}
267
+			$datum[8] = $options->isUsingFlags() ? 
268 268
 				'<i class="fa fa-check"></i><span class="sr-only">'.I18N::translate('Yes').'</span>' : 
269 269
 				'<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('No').'</span>';
270
-		    $datum[9] = $options->getMaxDetailsInGen() > 0 ? $options->getMaxDetailsInGen() : I18N::translate('All');
270
+			$datum[9] = $options->getMaxDetailsInGen() > 0 ? $options->getMaxDetailsInGen() : I18N::translate('All');
271 271
 		    
272
-		    $data[] = $datum;
273
-        }
272
+			$data[] = $datum;
273
+		}
274 274
         
275
-        $controller->pageHeader();
275
+		$controller->pageHeader();
276 276
         
277
-        $controller->encode(array(
278
-            'draw'            => Filter::getInteger('draw'),
279
-            'recordsTotal'    => $recordsTotal,
280
-            'recordsFiltered' => $recordsFiltered,
281
-            'data'            => $data
282
-        ));
277
+		$controller->encode(array(
278
+			'draw'            => Filter::getInteger('draw'),
279
+			'recordsTotal'    => $recordsTotal,
280
+			'recordsFiltered' => $recordsFiltered,
281
+			'data'            => $data
282
+		));
283 283
         
284
-    }
284
+	}
285 285
 
286
-    /**
287
-     * AdminConfig@edit
288
-     */
289
-    public function edit() {
290
-        $ga_id = Filter::getInteger('ga_id');
291
-        $ga = $this->provider->getGeoAnalysis($ga_id, false);
286
+	/**
287
+	 * AdminConfig@edit
288
+	 */
289
+	public function edit() {
290
+		$ga_id = Filter::getInteger('ga_id');
291
+		$ga = $this->provider->getGeoAnalysis($ga_id, false);
292 292
         
293
-        $this->renderEdit($ga);
294
-    }
293
+		$this->renderEdit($ga);
294
+	}
295 295
     
296
-    /**
297
-     * AdminConfig@add
298
-     */
299
-    public function add() {
300
-        $this->renderEdit(null);
301
-    }
296
+	/**
297
+	 * AdminConfig@add
298
+	 */
299
+	public function add() {
300
+		$this->renderEdit(null);
301
+	}
302 302
     
303
-    /**
304
-     * AdminConfig@save
305
-     */
306
-    public function save() {
307
-        $wt_tree = Globals::getTree();
308
-        $tmp_contrl = new PageController();
309
-        $tmp_contrl->restrictAccess(
310
-            Auth::isManager($wt_tree) 
311
-            && Filter::checkCsrf()
312
-         );
303
+	/**
304
+	 * AdminConfig@save
305
+	 */
306
+	public function save() {
307
+		$wt_tree = Globals::getTree();
308
+		$tmp_contrl = new PageController();
309
+		$tmp_contrl->restrictAccess(
310
+			Auth::isManager($wt_tree) 
311
+			&& Filter::checkCsrf()
312
+		 );
313 313
         
314
-        $ga_id          = Filter::postInteger('ga_id');
315
-        $description    = Filter::post('description');
316
-        $analysislevel  = Filter::postInteger('analysislevel');
317
-        $use_map        = Filter::postBool('use_map');
318
-        if($use_map) {
319
-            $map_file   = base64_decode(Filter::post('map_file'));
320
-            $map_top_level   = Filter::postInteger('map_top_level');
321
-        }
322
-        $use_flags      = Filter::postBool('use_flags');
323
-        $gen_details    = Filter::postInteger('gen_details');
314
+		$ga_id          = Filter::postInteger('ga_id');
315
+		$description    = Filter::post('description');
316
+		$analysislevel  = Filter::postInteger('analysislevel');
317
+		$use_map        = Filter::postBool('use_map');
318
+		if($use_map) {
319
+			$map_file   = base64_decode(Filter::post('map_file'));
320
+			$map_top_level   = Filter::postInteger('map_top_level');
321
+		}
322
+		$use_flags      = Filter::postBool('use_flags');
323
+		$gen_details    = Filter::postInteger('gen_details');
324 324
         
325
-        $success = false; 
326
-        if($ga_id) {
327
-            $ga = $this->provider->getGeoAnalysis($ga_id, false);
328
-            if($ga) {
329
-                $ga->setTitle($description);
330
-                $ga->setAnalysisLevel($analysislevel + 1);
331
-                $options = $ga->getOptions();
332
-                if($options) {
333
-                    $options->setUsingFlags($use_flags);
334
-                    $options->setMaxDetailsInGen($gen_details);
335
-                    if($use_map) {
336
-                        $options->setMap(new OutlineMap($map_file));
337
-                        $options->setMapLevel($map_top_level + 1);
338
-                    }
339
-                    else {
340
-                        $options->setMap(null);
341
-                    }
342
-                }
325
+		$success = false; 
326
+		if($ga_id) {
327
+			$ga = $this->provider->getGeoAnalysis($ga_id, false);
328
+			if($ga) {
329
+				$ga->setTitle($description);
330
+				$ga->setAnalysisLevel($analysislevel + 1);
331
+				$options = $ga->getOptions();
332
+				if($options) {
333
+					$options->setUsingFlags($use_flags);
334
+					$options->setMaxDetailsInGen($gen_details);
335
+					if($use_map) {
336
+						$options->setMap(new OutlineMap($map_file));
337
+						$options->setMapLevel($map_top_level + 1);
338
+					}
339
+					else {
340
+						$options->setMap(null);
341
+					}
342
+				}
343 343
 				
344 344
 				$res = $this->provider->updateGeoAnalysis($ga);
345 345
 				if($res) {
@@ -352,8 +352,8 @@  discard block
 block discarded – undo
352 352
 					FlashMessages::addMessage(I18N::translate('An error occured while updating the geographical dispersion analysis “%s”', $ga->getTitle()), 'danger');
353 353
 					Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'. $ga->getId() .'” could not be updated. See error log.');
354 354
 				}
355
-            }
356
-        } else {
355
+			}
356
+		} else {
357 357
 			$ga = $this->provider->createGeoAnalysis(
358 358
 				$description,
359 359
 				$analysislevel + 1,
@@ -371,33 +371,33 @@  discard block
 block discarded – undo
371 371
 				FlashMessages::addMessage(I18N::translate('An error occured while adding the geographical dispersion analysis “%s”', $description), 'danger');
372 372
 				Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis “'.$description.'” could not be added. See error log.');
373 373
 			}
374
-        }
374
+		}
375 375
         
376
-        $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $wt_tree->getNameUrl();
377
-        if(!$success) {			
378
-            if($ga) {
379
-                $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@edit&ga_id='. $ga->getId() .'&ged=' . $wt_tree->getNameUrl();
380
-            }
381
-            else {
382
-                $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@add&ged=' . $wt_tree->getNameUrl();
383
-            }
384
-        }        
385
-        header('Location: ' . WT_BASE_URL . $redirection_url);
376
+		$redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $wt_tree->getNameUrl();
377
+		if(!$success) {			
378
+			if($ga) {
379
+				$redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@edit&ga_id='. $ga->getId() .'&ged=' . $wt_tree->getNameUrl();
380
+			}
381
+			else {
382
+				$redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@add&ged=' . $wt_tree->getNameUrl();
383
+			}
384
+		}        
385
+		header('Location: ' . WT_BASE_URL . $redirection_url);
386 386
         
387
-    }
387
+	}
388 388
      
389 389
 	/**
390 390
 	 * Renders the edit form, whether it is an edition of an existing GeoAnalysis, or the addition of a new one.
391 391
 	 * 
392 392
 	 * @param (GeoAnalysis!null) $ga GeoAnalysis to edit
393 393
 	 */
394
-    protected function renderEdit(GeoAnalysis $ga = null) {
395
-        $wt_tree = Globals::getTree();
396
-        Theme::theme(new AdministrationTheme)->init($wt_tree);
397
-        $controller = new PageController();        
398
-        $controller
399
-            ->restrictAccess(Auth::isManager($wt_tree))
400
-            ->addInlineJavascript('
394
+	protected function renderEdit(GeoAnalysis $ga = null) {
395
+		$wt_tree = Globals::getTree();
396
+		Theme::theme(new AdministrationTheme)->init($wt_tree);
397
+		$controller = new PageController();        
398
+		$controller
399
+			->restrictAccess(Auth::isManager($wt_tree))
400
+			->addInlineJavascript('
401 401
                 function toggleMapOptions() {
402 402
                     if($("input:radio[name=\'use_map\']:checked").val() == 1) {
403 403
                         $("#map_options").show();
@@ -411,34 +411,34 @@  discard block
 block discarded – undo
411 411
                 toggleMapOptions();
412 412
             ');
413 413
         
414
-        $data = new ViewBag();
415
-        if($ga) {
416
-            $controller->setPageTitle(I18N::translate('Edit the geographical dispersion analysis'));
417
-            $data->set('geo_analysis', $ga);
418
-        } else {
419
-            $controller->setPageTitle(I18N::translate('Add a geographical dispersion analysis'));
420
-        }
414
+		$data = new ViewBag();
415
+		if($ga) {
416
+			$controller->setPageTitle(I18N::translate('Edit the geographical dispersion analysis'));
417
+			$data->set('geo_analysis', $ga);
418
+		} else {
419
+			$controller->setPageTitle(I18N::translate('Add a geographical dispersion analysis'));
420
+		}
421 421
         
422
-        $data->set('title', $controller->getPageTitle());
423
-        $data->set('admin_config_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $wt_tree->getNameUrl());
424
-        $data->set('module_title', $this->module->getTitle());
425
-        $data->set('save_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@save&ged=' . $wt_tree->getNameUrl());
426
-        $data->set('places_hierarchy', $this->provider->getPlacesHierarchy());
422
+		$data->set('title', $controller->getPageTitle());
423
+		$data->set('admin_config_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $wt_tree->getNameUrl());
424
+		$data->set('module_title', $this->module->getTitle());
425
+		$data->set('save_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@save&ged=' . $wt_tree->getNameUrl());
426
+		$data->set('places_hierarchy', $this->provider->getPlacesHierarchy());
427 427
     
428
-        $map_list = array_map(
429
-            function(OutlineMap $map) {
430
-                return $map->getDescription();
431
-            },
432
-            $this->provider->getOutlineMapsList()
433
-            );
434
-        asort($map_list);
435
-        $data->set('map_list', $map_list);
428
+		$map_list = array_map(
429
+			function(OutlineMap $map) {
430
+				return $map->getDescription();
431
+			},
432
+			$this->provider->getOutlineMapsList()
433
+			);
434
+		asort($map_list);
435
+		$data->set('map_list', $map_list);
436 436
     
437
-        $gen_details = array(0 => I18N::translate('All'));
438
-        for($i = 1; $i <= 10 ; $i++) $gen_details[$i] = $i;
439
-        $data->set('generation_details', $gen_details);
437
+		$gen_details = array(0 => I18N::translate('All'));
438
+		for($i = 1; $i <= 10 ; $i++) $gen_details[$i] = $i;
439
+		$data->set('generation_details', $gen_details);
440 440
     
441
-        ViewFactory::make('GeoAnalysisEdit', $this, $controller, $data)->render();
442
-    }
441
+		ViewFactory::make('GeoAnalysisEdit', $this, $controller, $data)->render();
442
+	}
443 443
     
444 444
 }
445 445
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +44 added lines, -46 removed lines patch added patch discarded remove patch
@@ -71,14 +71,14 @@  discard block
 block discarded – undo
71 71
         $data->set('title', $controller->getPageTitle());
72 72
         $data->set('tree', $wt_tree);
73 73
         
74
-        $data->set('root_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig');
74
+        $data->set('root_url', 'module.php?mod='.$this->module->getName().'&mod_action=AdminConfig');
75 75
                 
76
-        $table_id = 'table-geoanalysis-' . Uuid::uuid4();
76
+        $table_id = 'table-geoanalysis-'.Uuid::uuid4();
77 77
         $data->set('table_id', $table_id);
78 78
         
79 79
         $other_trees = array();
80 80
         foreach (Tree::getAll() as $tree) {
81
-            if($tree->getTreeId() != $wt_tree->getTreeId()) $other_trees[] = $tree;
81
+            if ($tree->getTreeId() != $wt_tree->getTreeId()) $other_trees[] = $tree;
82 82
         }      
83 83
         $data->set('other_trees', $other_trees);
84 84
         
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
                     processing: true,
102 102
                     serverSide : true,
103 103
 					ajax : {
104
-						url : "module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@jsonGeoAnalysisList&ged='. $wt_tree->getNameUrl().'",
104
+						url : "module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@jsonGeoAnalysisList&ged='.$wt_tree->getNameUrl().'",
105 105
                         type : "POST"
106 106
 					},
107 107
                     columns: [
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
                             url: "module.php", 
126 126
                             type: "GET",
127 127
                             data: {
128
-                			    mod: "' . $this->module->getName() .'",
128
+                			    mod: "' . $this->module->getName().'",
129 129
                                 mod_action:  "GeoAnalysis@setStatus",
130 130
                 			    ga_id: ga_id,
131 131
                 			    ged: typeof gedcom === "undefined" ? WT_GEDCOM : gedcom,
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
                             },
134 134
                             error: function(result, stat, error) {
135 135
                                 var err = typeof result.responseJSON === "undefined" ? error : result.responseJSON.error;
136
-                                alert("' . I18N::translate('An error occured while editing this analysis:') . '" + err);
136
+                                alert("' . I18N::translate('An error occured while editing this analysis:').'" + err);
137 137
                             },
138 138
                             complete: function(result, stat) {
139 139
                                 geoAnalysisTable.ajax.reload(null, false);
@@ -146,14 +146,14 @@  discard block
 block discarded – undo
146 146
                             url: "module.php", 
147 147
                             type: "GET",
148 148
                             data: {
149
-                			    mod: "' . $this->module->getName() .'",
149
+                			    mod: "' . $this->module->getName().'",
150 150
                                 mod_action:  "GeoAnalysis@delete",
151 151
                 			    ga_id: ga_id,
152 152
                 			    ged: typeof gedcom === "undefined" ? WT_GEDCOM : gedcom
153 153
                             },
154 154
                             error: function(result, stat, error) {
155 155
                                 var err = typeof result.responseJSON === "undefined" ? error : result.responseJSON.error;
156
-                                alert("' . I18N::translate('An error occured while deleting this analysis:') . '" + err);
156
+                                alert("' . I18N::translate('An error occured while deleting this analysis:').'" + err);
157 157
                             },
158 158
                             complete: function(result, stat) {
159 159
                                 geoAnalysisTable.ajax.reload(null, false);
@@ -177,13 +177,13 @@  discard block
 block discarded – undo
177 177
         
178 178
         // Generate an AJAX/JSON response for datatables to load a block of rows
179 179
         $search = Filter::postArray('search');
180
-        if($search) $search = $search['value'];
180
+        if ($search) $search = $search['value'];
181 181
         $start  = Filter::postInteger('start');
182 182
         $length = Filter::postInteger('length');
183 183
         $order  = Filter::postArray('order');
184 184
         
185
-        foreach($order as $key => &$value) {
186
-            switch($value['column']) {
185
+        foreach ($order as $key => &$value) {
186
+            switch ($value['column']) {
187 187
                 case 3:
188 188
                     $value['column'] = 'majgd_descr';
189 189
                     break;
@@ -204,11 +204,11 @@  discard block
 block discarded – undo
204 204
         
205 205
         $data = array();
206 206
         $place_hierarchy = $this->provider->getPlacesHierarchy();
207
-        foreach($list as $ga) {
207
+        foreach ($list as $ga) {
208 208
             /** @var GeoAnalysis $ga */
209 209
             
210 210
             $datum = array();
211
-            $options= $ga->getOptions();
211
+            $options = $ga->getOptions();
212 212
             
213 213
             $datum[0] = '
214 214
                 <div class="btn-group">
@@ -218,45 +218,44 @@  discard block
 block discarded – undo
218 218
                     <ul class="dropdown-menu" role="menu">
219 219
                        <li>
220 220
                             <a href="#" onclick="return set_geoanalysis_status('. $ga->getId().', '.($ga->isEnabled() ? 'false' : 'true').', \''.Filter::escapeJs($wt_tree->getName()).'\');">
221
-                                <i class="fa fa-fw '.($ga->isEnabled() ? 'fa-times' : 'fa-check').'"></i> ' . ($ga->isEnabled() ? I18N::translate('Disable') : I18N::translate('Enable')) . '
221
+                                <i class="fa fa-fw '.($ga->isEnabled() ? 'fa-times' : 'fa-check').'"></i> '.($ga->isEnabled() ? I18N::translate('Disable') : I18N::translate('Enable')).'
222 222
                             </a>
223 223
                        </li>
224 224
                         <li>
225 225
                             <a href="module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@edit&ga_id='.$ga->getId().'&ged='.$wt_tree->getName().'">
226
-                                <i class="fa fa-fw fa-pencil"></i> ' . I18N::translate('Edit') . '
226
+                                <i class="fa fa-fw fa-pencil"></i> ' . I18N::translate('Edit').'
227 227
                             </a>
228 228
                        </li>
229 229
                        <li class="divider" />
230 230
                        <li>
231 231
                             <a href="#" onclick="return delete_geoanalysis('. $ga->getId().', \''.Filter::escapeJs($wt_tree->getName()).'\');">
232
-                                <i class="fa fa-fw fa-trash-o"></i> ' . I18N::translate('Delete') . '
232
+                                <i class="fa fa-fw fa-trash-o"></i> ' . I18N::translate('Delete').'
233 233
                             </a>
234 234
                        </li>
235 235
                     </ul>
236 236
                 </div>';
237 237
 		    $datum[1] = $ga->getId();
238 238
 		    $datum[2] = $ga->isEnabled() ? 
239
-				'<i class="fa fa-check"></i><span class="sr-only">'.I18N::translate('Enabled').'</span>' : 
240
-				'<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('Disabled').'</span>';
239
+				'<i class="fa fa-check"></i><span class="sr-only">'.I18N::translate('Enabled').'</span>' : '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('Disabled').'</span>';
241 240
 		    $datum[3] = $ga->getTitle();
242 241
 		    $analysis_level = $ga->getAnalysisLevel();
243
-		    if($place_hierarchy['type'] == 'header') {
242
+		    if ($place_hierarchy['type'] == 'header') {
244 243
 		        $datum[4] = $place_hierarchy['hierarchy'][$analysis_level - 1];
245 244
 		    } else {
246
-		        $datum[4] = $analysis_level . '(' . $place_hierarchy['hierarchy'][$analysis_level - 1] . ')';
245
+		        $datum[4] = $analysis_level.'('.$place_hierarchy['hierarchy'][$analysis_level - 1].')';
247 246
 		    }
248 247
 		    $datum[5] = $ga->getAnalysisLevel();
249 248
 		    $datum[6] = '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('None').'</span>';
250 249
 		    $datum[7] = '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('None').'</span>';
251
-		    if($ga->hasMap()) {
252
-		        if($options->getMap()->isLoaded()) {
250
+		    if ($ga->hasMap()) {
251
+		        if ($options->getMap()->isLoaded()) {
253 252
     		        $datum[6] = $options->getMap()->getDescription();
254
-    		        $datum[7] = '<span data-toggle="tooltip" title="' . $options->getMap()->getTopLevelName() . '" />';
253
+    		        $datum[7] = '<span data-toggle="tooltip" title="'.$options->getMap()->getTopLevelName().'" />';
255 254
     		        $top_level = $options->getMapLevel();
256
-    		        if($place_hierarchy['type'] == 'header') {
255
+    		        if ($place_hierarchy['type'] == 'header') {
257 256
     		            $datum[7] .= $place_hierarchy['hierarchy'][$top_level - 1];
258 257
     		        } else {
259
-    		            $datum[7] .= $top_level . '(' . $place_hierarchy['hierarchy'][$top_level - 1] . ')';
258
+    		            $datum[7] .= $top_level.'('.$place_hierarchy['hierarchy'][$top_level - 1].')';
260 259
     		        }
261 260
     		        $datum[7] .= '</span>';
262 261
 		        }
@@ -265,8 +264,7 @@  discard block
 block discarded – undo
265 264
 		        }
266 265
 		    }
267 266
 		    $datum[8] = $options->isUsingFlags() ? 
268
-				'<i class="fa fa-check"></i><span class="sr-only">'.I18N::translate('Yes').'</span>' : 
269
-				'<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('No').'</span>';
267
+				'<i class="fa fa-check"></i><span class="sr-only">'.I18N::translate('Yes').'</span>' : '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('No').'</span>';
270 268
 		    $datum[9] = $options->getMaxDetailsInGen() > 0 ? $options->getMaxDetailsInGen() : I18N::translate('All');
271 269
 		    
272 270
 		    $data[] = $datum;
@@ -315,24 +313,24 @@  discard block
 block discarded – undo
315 313
         $description    = Filter::post('description');
316 314
         $analysislevel  = Filter::postInteger('analysislevel');
317 315
         $use_map        = Filter::postBool('use_map');
318
-        if($use_map) {
316
+        if ($use_map) {
319 317
             $map_file   = base64_decode(Filter::post('map_file'));
320
-            $map_top_level   = Filter::postInteger('map_top_level');
318
+            $map_top_level = Filter::postInteger('map_top_level');
321 319
         }
322 320
         $use_flags      = Filter::postBool('use_flags');
323 321
         $gen_details    = Filter::postInteger('gen_details');
324 322
         
325 323
         $success = false; 
326
-        if($ga_id) {
324
+        if ($ga_id) {
327 325
             $ga = $this->provider->getGeoAnalysis($ga_id, false);
328
-            if($ga) {
326
+            if ($ga) {
329 327
                 $ga->setTitle($description);
330 328
                 $ga->setAnalysisLevel($analysislevel + 1);
331 329
                 $options = $ga->getOptions();
332
-                if($options) {
330
+                if ($options) {
333 331
                     $options->setUsingFlags($use_flags);
334 332
                     $options->setMaxDetailsInGen($gen_details);
335
-                    if($use_map) {
333
+                    if ($use_map) {
336 334
                         $options->setMap(new OutlineMap($map_file));
337 335
                         $options->setMapLevel($map_top_level + 1);
338 336
                     }
@@ -342,7 +340,7 @@  discard block
 block discarded – undo
342 340
                 }
343 341
 				
344 342
 				$res = $this->provider->updateGeoAnalysis($ga);
345
-				if($res) {
343
+				if ($res) {
346 344
 					FlashMessages::addMessage(I18N::translate('The geographical dispersion analysis “%s” has been successfully updated', $res->getTitle()), 'success');
347 345
 					Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'.$res->getId().'” has been updated.');
348 346
 					$ga = $res;
@@ -350,7 +348,7 @@  discard block
 block discarded – undo
350 348
 				}
351 349
 				else {
352 350
 					FlashMessages::addMessage(I18N::translate('An error occured while updating the geographical dispersion analysis “%s”', $ga->getTitle()), 'danger');
353
-					Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'. $ga->getId() .'” could not be updated. See error log.');
351
+					Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'.$ga->getId().'” could not be updated. See error log.');
354 352
 				}
355 353
             }
356 354
         } else {
@@ -362,7 +360,7 @@  discard block
 block discarded – undo
362 360
 				$use_flags,
363 361
 				$gen_details
364 362
 			);
365
-			if($ga) {
363
+			if ($ga) {
366 364
 				FlashMessages::addMessage(I18N::translate('The geographical dispersion analysis “%s” has been successfully added.', $ga->getTitle()), 'success');
367 365
 				Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'.$ga->getId().'” has been added.');
368 366
 				$success = true;
@@ -373,16 +371,16 @@  discard block
 block discarded – undo
373 371
 			}
374 372
         }
375 373
         
376
-        $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $wt_tree->getNameUrl();
377
-        if(!$success) {			
378
-            if($ga) {
379
-                $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@edit&ga_id='. $ga->getId() .'&ged=' . $wt_tree->getNameUrl();
374
+        $redirection_url = 'module.php?mod='.$this->module->getName().'&mod_action=AdminConfig&ged='.$wt_tree->getNameUrl();
375
+        if (!$success) {			
376
+            if ($ga) {
377
+                $redirection_url = 'module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@edit&ga_id='.$ga->getId().'&ged='.$wt_tree->getNameUrl();
380 378
             }
381 379
             else {
382
-                $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@add&ged=' . $wt_tree->getNameUrl();
380
+                $redirection_url = 'module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@add&ged='.$wt_tree->getNameUrl();
383 381
             }
384 382
         }        
385
-        header('Location: ' . WT_BASE_URL . $redirection_url);
383
+        header('Location: '.WT_BASE_URL.$redirection_url);
386 384
         
387 385
     }
388 386
      
@@ -412,7 +410,7 @@  discard block
 block discarded – undo
412 410
             ');
413 411
         
414 412
         $data = new ViewBag();
415
-        if($ga) {
413
+        if ($ga) {
416 414
             $controller->setPageTitle(I18N::translate('Edit the geographical dispersion analysis'));
417 415
             $data->set('geo_analysis', $ga);
418 416
         } else {
@@ -420,9 +418,9 @@  discard block
 block discarded – undo
420 418
         }
421 419
         
422 420
         $data->set('title', $controller->getPageTitle());
423
-        $data->set('admin_config_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $wt_tree->getNameUrl());
421
+        $data->set('admin_config_url', 'module.php?mod='.$this->module->getName().'&mod_action=AdminConfig&ged='.$wt_tree->getNameUrl());
424 422
         $data->set('module_title', $this->module->getTitle());
425
-        $data->set('save_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@save&ged=' . $wt_tree->getNameUrl());
423
+        $data->set('save_url', 'module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@save&ged='.$wt_tree->getNameUrl());
426 424
         $data->set('places_hierarchy', $this->provider->getPlacesHierarchy());
427 425
     
428 426
         $map_list = array_map(
@@ -435,7 +433,7 @@  discard block
 block discarded – undo
435 433
         $data->set('map_list', $map_list);
436 434
     
437 435
         $gen_details = array(0 => I18N::translate('All'));
438
-        for($i = 1; $i <= 10 ; $i++) $gen_details[$i] = $i;
436
+        for ($i = 1; $i <= 10; $i++) $gen_details[$i] = $i;
439 437
         $data->set('generation_details', $gen_details);
440 438
     
441 439
         ViewFactory::make('GeoAnalysisEdit', $this, $controller, $data)->render();
Please login to merge, or discard this patch.
Braces   +14 added lines, -13 removed lines patch added patch discarded remove patch
@@ -78,7 +78,9 @@  discard block
 block discarded – undo
78 78
         
79 79
         $other_trees = array();
80 80
         foreach (Tree::getAll() as $tree) {
81
-            if($tree->getTreeId() != $wt_tree->getTreeId()) $other_trees[] = $tree;
81
+            if($tree->getTreeId() != $wt_tree->getTreeId()) {
82
+            	$other_trees[] = $tree;
83
+            }
82 84
         }      
83 85
         $data->set('other_trees', $other_trees);
84 86
         
@@ -177,7 +179,9 @@  discard block
 block discarded – undo
177 179
         
178 180
         // Generate an AJAX/JSON response for datatables to load a block of rows
179 181
         $search = Filter::postArray('search');
180
-        if($search) $search = $search['value'];
182
+        if($search) {
183
+        	$search = $search['value'];
184
+        }
181 185
         $start  = Filter::postInteger('start');
182 186
         $length = Filter::postInteger('length');
183 187
         $order  = Filter::postArray('order');
@@ -259,8 +263,7 @@  discard block
 block discarded – undo
259 263
     		            $datum[7] .= $top_level . '(' . $place_hierarchy['hierarchy'][$top_level - 1] . ')';
260 264
     		        }
261 265
     		        $datum[7] .= '</span>';
262
-		        }
263
-		        else {
266
+		        } else {
264 267
 		            $datum[6] = I18N::translate('Error when loading map.');
265 268
 		        }
266 269
 		    }
@@ -335,8 +338,7 @@  discard block
 block discarded – undo
335 338
                     if($use_map) {
336 339
                         $options->setMap(new OutlineMap($map_file));
337 340
                         $options->setMapLevel($map_top_level + 1);
338
-                    }
339
-                    else {
341
+                    } else {
340 342
                         $options->setMap(null);
341 343
                     }
342 344
                 }
@@ -347,8 +349,7 @@  discard block
 block discarded – undo
347 349
 					Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'.$res->getId().'” has been updated.');
348 350
 					$ga = $res;
349 351
 					$success = true;
350
-				}
351
-				else {
352
+				} else {
352 353
 					FlashMessages::addMessage(I18N::translate('An error occured while updating the geographical dispersion analysis “%s”', $ga->getTitle()), 'danger');
353 354
 					Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'. $ga->getId() .'” could not be updated. See error log.');
354 355
 				}
@@ -366,8 +367,7 @@  discard block
 block discarded – undo
366 367
 				FlashMessages::addMessage(I18N::translate('The geographical dispersion analysis “%s” has been successfully added.', $ga->getTitle()), 'success');
367 368
 				Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'.$ga->getId().'” has been added.');
368 369
 				$success = true;
369
-			}
370
-			else {
370
+			} else {
371 371
 				FlashMessages::addMessage(I18N::translate('An error occured while adding the geographical dispersion analysis “%s”', $description), 'danger');
372 372
 				Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis “'.$description.'” could not be added. See error log.');
373 373
 			}
@@ -377,8 +377,7 @@  discard block
 block discarded – undo
377 377
         if(!$success) {			
378 378
             if($ga) {
379 379
                 $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@edit&ga_id='. $ga->getId() .'&ged=' . $wt_tree->getNameUrl();
380
-            }
381
-            else {
380
+            } else {
382 381
                 $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig@add&ged=' . $wt_tree->getNameUrl();
383 382
             }
384 383
         }        
@@ -435,7 +434,9 @@  discard block
 block discarded – undo
435 434
         $data->set('map_list', $map_list);
436 435
     
437 436
         $gen_details = array(0 => I18N::translate('All'));
438
-        for($i = 1; $i <= 10 ; $i++) $gen_details[$i] = $i;
437
+        for($i = 1; $i <= 10 ; $i++) {
438
+        	$gen_details[$i] = $i;
439
+        }
439 440
         $data->set('generation_details', $gen_details);
440 441
     
441 442
         ViewFactory::make('GeoAnalysisEdit', $this, $controller, $data)->render();
Please login to merge, or discard this patch.
src/Webtrees/Module/GeoDispersion/Model/OutlineMap.php 3 patches
Indentation   +146 added lines, -146 removed lines patch added patch discarded remove patch
@@ -22,187 +22,187 @@
 block discarded – undo
22 22
 	 * Name of the file containing the description of the map.
23 23
 	 * @var string $filename
24 24
 	 */
25
-    protected $filename;
25
+	protected $filename;
26 26
     
27 27
 	/**
28 28
 	 * Indicates whether the description has been loaded from the file.
29 29
 	 * @var bool $is_loaded
30 30
 	 */
31
-    protected $is_loaded;
31
+	protected $is_loaded;
32 32
     
33 33
 	/**
34 34
 	 * Description/title of the map.
35 35
 	 * @var string $description
36 36
 	 */
37
-    protected $description;
37
+	protected $description;
38 38
     
39 39
 	/**
40 40
 	 * Name(s) of the parent level(s) of the map.
41 41
 	 * @var string $is_loaded
42 42
 	 */
43
-    protected $top_level_name;
44
-    
45
-    /**
46
-     * Map canvas
47
-     * @var OutlineMapCanvas $canvas
48
-     */
49
-    protected $canvas;
50
-    
51
-    /**
52
-     * Map subdivisions
53
-     * @var array $subdivisions
54
-     */
55
-    protected $subdivisions;
56
-    
57
-    /**
58
-     * Places mappings
59
-     * @var array $subdivisions
60
-     */
61
-    protected $mappings;
62
-    
63
-    /**
64
-     * Constructor for GeoAnalysisMap.
65
-     *
66
-     * @param string $filename Outline map file name
67
-     * @param bool $load Should the map be loaded immediately
68
-     */
69
-    public function __construct($filename, $load = false) {
70
-        $this->filename = $filename;
71
-        $this->is_loaded = false;
72
-        $this->subdivisions = array();
73
-        $this->mappings = array();
74
-        if($load) $this->load();
75
-    }
76
-    
77
-    /**
78
-     * Load the map settings contained within its XML representation
79
-     *
80
-     * XML structure :
81
-     * 	- displayName : Display name of the map
82
-     * 	- topLevel : Values of the top level subdivisions (separated by commas, if multiple)
83
-     * 	- canvas : all settings related to the map canvas.
84
-     * 		- width : canvas width, in px
85
-     * 		- height : canvas height, in px
86
-     * 		- maxcolor : color to identify places with ancestors, RGB hexadecimal
87
-     * 		- hovercolor : same as previous, color when mouse is hovering the place, RGB hexadecimal
88
-     * 		- bgcolor : map background color, RGB hexadecimal
89
-     * 		- bgstroke : map stroke color, RGB hexadecimal
90
-     * 		- defaultcolor : default color of places, RGB hexadecimal
91
-     * 		- defaultstroke : default stroke color, RGB hexadecimal
92
-     * 	- subdvisions : for each subdivision :
43
+	protected $top_level_name;
44
+    
45
+	/**
46
+	 * Map canvas
47
+	 * @var OutlineMapCanvas $canvas
48
+	 */
49
+	protected $canvas;
50
+    
51
+	/**
52
+	 * Map subdivisions
53
+	 * @var array $subdivisions
54
+	 */
55
+	protected $subdivisions;
56
+    
57
+	/**
58
+	 * Places mappings
59
+	 * @var array $subdivisions
60
+	 */
61
+	protected $mappings;
62
+    
63
+	/**
64
+	 * Constructor for GeoAnalysisMap.
65
+	 *
66
+	 * @param string $filename Outline map file name
67
+	 * @param bool $load Should the map be loaded immediately
68
+	 */
69
+	public function __construct($filename, $load = false) {
70
+		$this->filename = $filename;
71
+		$this->is_loaded = false;
72
+		$this->subdivisions = array();
73
+		$this->mappings = array();
74
+		if($load) $this->load();
75
+	}
76
+    
77
+	/**
78
+	 * Load the map settings contained within its XML representation
79
+	 *
80
+	 * XML structure :
81
+	 * 	- displayName : Display name of the map
82
+	 * 	- topLevel : Values of the top level subdivisions (separated by commas, if multiple)
83
+	 * 	- canvas : all settings related to the map canvas.
84
+	 * 		- width : canvas width, in px
85
+	 * 		- height : canvas height, in px
86
+	 * 		- maxcolor : color to identify places with ancestors, RGB hexadecimal
87
+	 * 		- hovercolor : same as previous, color when mouse is hovering the place, RGB hexadecimal
88
+	 * 		- bgcolor : map background color, RGB hexadecimal
89
+	 * 		- bgstroke : map stroke color, RGB hexadecimal
90
+	 * 		- defaultcolor : default color of places, RGB hexadecimal
91
+	 * 		- defaultstroke : default stroke color, RGB hexadecimal
92
+	 * 	- subdvisions : for each subdivision :
93 93
 	 *		- id : Subdivision id, must be compatible with PHP variable constraints, and unique
94
-     * 		- name: Display name for the place
94
+	 * 		- name: Display name for the place
95 95
 	 *		- parent: if any, describe to which parent level the place if belonging to
96
-     * 		- <em>Element value<em> : SVG description of the subdvision shape
96
+	 * 		- <em>Element value<em> : SVG description of the subdvision shape
97 97
 	 *	- mapping : for each subdivision :
98 98
 	 *		- name : Name of the place to map
99
-     * 		- mapto: Name of the place to map to
99
+	 * 		- mapto: Name of the place to map to
100 100
 	 * 
101
-     */
102
-    protected function load() {
103
-        if(file_exists(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename)){
104
-            $xml = simplexml_load_file(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename);
105
-            if($xml){
106
-                $this->description = trim($xml->displayName);
107
-                $this->top_level_name = trim($xml->topLevel);
108
-                $this->canvas = new OutlineMapCanvas(
109
-                    trim($xml->canvas->width),
110
-                    trim($xml->canvas->height), 
111
-                    trim($xml->canvas->maxcolor), 
112
-                    trim($xml->canvas->hovercolor), 
113
-                    trim($xml->canvas->bgcolor),
114
-                    trim($xml->canvas->bgstroke),
115
-                    trim($xml->canvas->defaultcolor), 
116
-                    trim($xml->canvas->defaultstroke)
117
-                );
118
-                foreach($xml->subdivisions->children() as $subdivision){
119
-                    $attributes = $subdivision->attributes();
120
-                    $key = I18N::strtolower(trim($attributes['name']));
121
-                    if(isset($attributes['parent'])) $key .= '@'. I18N::strtolower(trim($attributes['parent']));
122
-                    $this->subdivisions[$key] = array(
123
-                        'id' => trim($attributes['id']),
124
-                        'displayname' => trim($attributes['name']),
125
-                        'coord' => trim($subdivision[0])
126
-                    );
127
-                }
128
-                if(isset($xml->mappings)) {
129
-                    foreach($xml->mappings->children() as $mappings){
130
-                        $attributes = $mappings->attributes();
131
-                        $this->mappings[I18N::strtolower(trim($attributes['name']))] = I18N::strtolower(trim($attributes['mapto']));
132
-                    }
133
-                }
134
-                $this->is_loaded = true;
135
-                return;
136
-            }
137
-        }
138
-        throw new \Exception('The Outline Map could not be loaded from XML.');
139
-    }
140
-    
141
-    /**
142
-     * Get the status of the map loading from the XML file.
143
-     * 
144
-     * @return bool
145
-     */
146
-    public function isLoaded() {
147
-        try{
148
-            if(!$this->is_loaded) $this->load();
149
-        }
150
-        catch (\Exception $ex) { }
151
-        return $this->is_loaded;
152
-    }
101
+	 */
102
+	protected function load() {
103
+		if(file_exists(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename)){
104
+			$xml = simplexml_load_file(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename);
105
+			if($xml){
106
+				$this->description = trim($xml->displayName);
107
+				$this->top_level_name = trim($xml->topLevel);
108
+				$this->canvas = new OutlineMapCanvas(
109
+					trim($xml->canvas->width),
110
+					trim($xml->canvas->height), 
111
+					trim($xml->canvas->maxcolor), 
112
+					trim($xml->canvas->hovercolor), 
113
+					trim($xml->canvas->bgcolor),
114
+					trim($xml->canvas->bgstroke),
115
+					trim($xml->canvas->defaultcolor), 
116
+					trim($xml->canvas->defaultstroke)
117
+				);
118
+				foreach($xml->subdivisions->children() as $subdivision){
119
+					$attributes = $subdivision->attributes();
120
+					$key = I18N::strtolower(trim($attributes['name']));
121
+					if(isset($attributes['parent'])) $key .= '@'. I18N::strtolower(trim($attributes['parent']));
122
+					$this->subdivisions[$key] = array(
123
+						'id' => trim($attributes['id']),
124
+						'displayname' => trim($attributes['name']),
125
+						'coord' => trim($subdivision[0])
126
+					);
127
+				}
128
+				if(isset($xml->mappings)) {
129
+					foreach($xml->mappings->children() as $mappings){
130
+						$attributes = $mappings->attributes();
131
+						$this->mappings[I18N::strtolower(trim($attributes['name']))] = I18N::strtolower(trim($attributes['mapto']));
132
+					}
133
+				}
134
+				$this->is_loaded = true;
135
+				return;
136
+			}
137
+		}
138
+		throw new \Exception('The Outline Map could not be loaded from XML.');
139
+	}
140
+    
141
+	/**
142
+	 * Get the status of the map loading from the XML file.
143
+	 * 
144
+	 * @return bool
145
+	 */
146
+	public function isLoaded() {
147
+		try{
148
+			if(!$this->is_loaded) $this->load();
149
+		}
150
+		catch (\Exception $ex) { }
151
+		return $this->is_loaded;
152
+	}
153 153
     
154 154
 	/**
155 155
 	 * Get the map file name.
156 156
 	 * @return string
157 157
 	 */
158
-    public function getFileName() {
159
-        return $this->filename;
160
-    }
158
+	public function getFileName() {
159
+		return $this->filename;
160
+	}
161 161
     
162 162
 	/**
163 163
 	 * Get the map file name.
164 164
 	 * @return string
165 165
 	 */
166
-    public function getDescription() {
167
-        if(!$this->is_loaded) $this->load();
168
-        return $this->description;
169
-    }
166
+	public function getDescription() {
167
+		if(!$this->is_loaded) $this->load();
168
+		return $this->description;
169
+	}
170 170
     
171 171
 	/**
172 172
 	 * Get the name of the map parent level. 
173 173
 	 * @return string
174 174
 	 */
175
-    public function getTopLevelName() {
176
-        if(!$this->is_loaded) $this->load();
177
-        return $this->top_level_name;
178
-    }    
179
-    
180
-    /**
181
-     * Get the Outline Map canvas.
182
-     * @return \MyArtJaub\Webtrees\Module\GeoDispersion\Model\OutlineMapCanvas
183
-     */
184
-    public function getCanvas() {
185
-        if(!$this->is_loaded) $this->load();
186
-        return $this->canvas;
187
-    }
188
-    
189
-	/**
190
-     * Get the subdivisions of the map.
191
-     * @return array
192
-     */
193
-    public function getSubdivisions() {
194
-        if(!$this->is_loaded) $this->load();
195
-        return $this->subdivisions;
196
-    }
197
-    
198
-	/**
199
-     * Get the places mappings of the map.
200
-     * @return array
201
-     */
202
-    public function getPlacesMappings() {
203
-        if(!$this->is_loaded) $this->load();
204
-        return $this->mappings;
205
-    }
175
+	public function getTopLevelName() {
176
+		if(!$this->is_loaded) $this->load();
177
+		return $this->top_level_name;
178
+	}    
179
+    
180
+	/**
181
+	 * Get the Outline Map canvas.
182
+	 * @return \MyArtJaub\Webtrees\Module\GeoDispersion\Model\OutlineMapCanvas
183
+	 */
184
+	public function getCanvas() {
185
+		if(!$this->is_loaded) $this->load();
186
+		return $this->canvas;
187
+	}
188
+    
189
+	/**
190
+	 * Get the subdivisions of the map.
191
+	 * @return array
192
+	 */
193
+	public function getSubdivisions() {
194
+		if(!$this->is_loaded) $this->load();
195
+		return $this->subdivisions;
196
+	}
197
+    
198
+	/**
199
+	 * Get the places mappings of the map.
200
+	 * @return array
201
+	 */
202
+	public function getPlacesMappings() {
203
+		if(!$this->is_loaded) $this->load();
204
+		return $this->mappings;
205
+	}
206 206
     
207 207
 }
208 208
  
209 209
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
         $this->is_loaded = false;
72 72
         $this->subdivisions = array();
73 73
         $this->mappings = array();
74
-        if($load) $this->load();
74
+        if ($load) $this->load();
75 75
     }
76 76
     
77 77
     /**
@@ -100,9 +100,9 @@  discard block
 block discarded – undo
100 100
 	 * 
101 101
      */
102 102
     protected function load() {
103
-        if(file_exists(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename)){
103
+        if (file_exists(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename)) {
104 104
             $xml = simplexml_load_file(WT_ROOT.WT_MODULES_DIR.Constants::MODULE_MAJ_GEODISP_NAME.'/maps/'.$this->filename);
105
-            if($xml){
105
+            if ($xml) {
106 106
                 $this->description = trim($xml->displayName);
107 107
                 $this->top_level_name = trim($xml->topLevel);
108 108
                 $this->canvas = new OutlineMapCanvas(
@@ -115,18 +115,18 @@  discard block
 block discarded – undo
115 115
                     trim($xml->canvas->defaultcolor), 
116 116
                     trim($xml->canvas->defaultstroke)
117 117
                 );
118
-                foreach($xml->subdivisions->children() as $subdivision){
118
+                foreach ($xml->subdivisions->children() as $subdivision) {
119 119
                     $attributes = $subdivision->attributes();
120 120
                     $key = I18N::strtolower(trim($attributes['name']));
121
-                    if(isset($attributes['parent'])) $key .= '@'. I18N::strtolower(trim($attributes['parent']));
121
+                    if (isset($attributes['parent'])) $key .= '@'.I18N::strtolower(trim($attributes['parent']));
122 122
                     $this->subdivisions[$key] = array(
123 123
                         'id' => trim($attributes['id']),
124 124
                         'displayname' => trim($attributes['name']),
125 125
                         'coord' => trim($subdivision[0])
126 126
                     );
127 127
                 }
128
-                if(isset($xml->mappings)) {
129
-                    foreach($xml->mappings->children() as $mappings){
128
+                if (isset($xml->mappings)) {
129
+                    foreach ($xml->mappings->children() as $mappings) {
130 130
                         $attributes = $mappings->attributes();
131 131
                         $this->mappings[I18N::strtolower(trim($attributes['name']))] = I18N::strtolower(trim($attributes['mapto']));
132 132
                     }
@@ -144,8 +144,8 @@  discard block
 block discarded – undo
144 144
      * @return bool
145 145
      */
146 146
     public function isLoaded() {
147
-        try{
148
-            if(!$this->is_loaded) $this->load();
147
+        try {
148
+            if (!$this->is_loaded) $this->load();
149 149
         }
150 150
         catch (\Exception $ex) { }
151 151
         return $this->is_loaded;
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
 	 * @return string
165 165
 	 */
166 166
     public function getDescription() {
167
-        if(!$this->is_loaded) $this->load();
167
+        if (!$this->is_loaded) $this->load();
168 168
         return $this->description;
169 169
     }
170 170
     
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	 * @return string
174 174
 	 */
175 175
     public function getTopLevelName() {
176
-        if(!$this->is_loaded) $this->load();
176
+        if (!$this->is_loaded) $this->load();
177 177
         return $this->top_level_name;
178 178
     }    
179 179
     
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
      * @return \MyArtJaub\Webtrees\Module\GeoDispersion\Model\OutlineMapCanvas
183 183
      */
184 184
     public function getCanvas() {
185
-        if(!$this->is_loaded) $this->load();
185
+        if (!$this->is_loaded) $this->load();
186 186
         return $this->canvas;
187 187
     }
188 188
     
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
      * @return array
192 192
      */
193 193
     public function getSubdivisions() {
194
-        if(!$this->is_loaded) $this->load();
194
+        if (!$this->is_loaded) $this->load();
195 195
         return $this->subdivisions;
196 196
     }
197 197
     
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
      * @return array
201 201
      */
202 202
     public function getPlacesMappings() {
203
-        if(!$this->is_loaded) $this->load();
203
+        if (!$this->is_loaded) $this->load();
204 204
         return $this->mappings;
205 205
     }
206 206
     
Please login to merge, or discard this patch.
Braces   +25 added lines, -10 removed lines patch added patch discarded remove patch
@@ -71,7 +71,9 @@  discard block
 block discarded – undo
71 71
         $this->is_loaded = false;
72 72
         $this->subdivisions = array();
73 73
         $this->mappings = array();
74
-        if($load) $this->load();
74
+        if($load) {
75
+        	$this->load();
76
+        }
75 77
     }
76 78
     
77 79
     /**
@@ -118,7 +120,9 @@  discard block
 block discarded – undo
118 120
                 foreach($xml->subdivisions->children() as $subdivision){
119 121
                     $attributes = $subdivision->attributes();
120 122
                     $key = I18N::strtolower(trim($attributes['name']));
121
-                    if(isset($attributes['parent'])) $key .= '@'. I18N::strtolower(trim($attributes['parent']));
123
+                    if(isset($attributes['parent'])) {
124
+                    	$key .= '@'. I18N::strtolower(trim($attributes['parent']));
125
+                    }
122 126
                     $this->subdivisions[$key] = array(
123 127
                         'id' => trim($attributes['id']),
124 128
                         'displayname' => trim($attributes['name']),
@@ -145,9 +149,10 @@  discard block
 block discarded – undo
145 149
      */
146 150
     public function isLoaded() {
147 151
         try{
148
-            if(!$this->is_loaded) $this->load();
149
-        }
150
-        catch (\Exception $ex) { }
152
+            if(!$this->is_loaded) {
153
+            	$this->load();
154
+            }
155
+        } catch (\Exception $ex) { }
151 156
         return $this->is_loaded;
152 157
     }
153 158
     
@@ -164,7 +169,9 @@  discard block
 block discarded – undo
164 169
 	 * @return string
165 170
 	 */
166 171
     public function getDescription() {
167
-        if(!$this->is_loaded) $this->load();
172
+        if(!$this->is_loaded) {
173
+        	$this->load();
174
+        }
168 175
         return $this->description;
169 176
     }
170 177
     
@@ -173,7 +180,9 @@  discard block
 block discarded – undo
173 180
 	 * @return string
174 181
 	 */
175 182
     public function getTopLevelName() {
176
-        if(!$this->is_loaded) $this->load();
183
+        if(!$this->is_loaded) {
184
+        	$this->load();
185
+        }
177 186
         return $this->top_level_name;
178 187
     }    
179 188
     
@@ -182,7 +191,9 @@  discard block
 block discarded – undo
182 191
      * @return \MyArtJaub\Webtrees\Module\GeoDispersion\Model\OutlineMapCanvas
183 192
      */
184 193
     public function getCanvas() {
185
-        if(!$this->is_loaded) $this->load();
194
+        if(!$this->is_loaded) {
195
+        	$this->load();
196
+        }
186 197
         return $this->canvas;
187 198
     }
188 199
     
@@ -191,7 +202,9 @@  discard block
 block discarded – undo
191 202
      * @return array
192 203
      */
193 204
     public function getSubdivisions() {
194
-        if(!$this->is_loaded) $this->load();
205
+        if(!$this->is_loaded) {
206
+        	$this->load();
207
+        }
195 208
         return $this->subdivisions;
196 209
     }
197 210
     
@@ -200,7 +213,9 @@  discard block
 block discarded – undo
200 213
      * @return array
201 214
      */
202 215
     public function getPlacesMappings() {
203
-        if(!$this->is_loaded) $this->load();
216
+        if(!$this->is_loaded) {
217
+        	$this->load();
218
+        }
204 219
         return $this->mappings;
205 220
     }
206 221
     
Please login to merge, or discard this patch.
src/Webtrees/Module/GeoDispersion/GeoAnalysisController.php 3 patches
Indentation   +230 added lines, -230 removed lines patch added patch discarded remove patch
@@ -36,47 +36,47 @@  discard block
 block discarded – undo
36 36
  */
37 37
 class GeoAnalysisController extends MvcController
38 38
 {
39
-    /**
40
-     * GeoAnalysis Provider
41
-     * @var GeoAnalysisProvider $provider
42
-     */
43
-    protected $provider;
39
+	/**
40
+	 * GeoAnalysis Provider
41
+	 * @var GeoAnalysisProvider $provider
42
+	 */
43
+	protected $provider;
44 44
     
45
-    /**
46
-     * Constructor for GeoAnalysis controller
47
-     * @param AbstractModule $module
48
-     */
49
-    public function __construct(AbstractModule $module) {
50
-        parent::__construct($module);
45
+	/**
46
+	 * Constructor for GeoAnalysis controller
47
+	 * @param AbstractModule $module
48
+	 */
49
+	public function __construct(AbstractModule $module) {
50
+		parent::__construct($module);
51 51
         
52
-        $this->provider = $this->module->getProvider();
53
-    }    
52
+		$this->provider = $this->module->getProvider();
53
+	}    
54 54
     
55
-    /**
56
-     * Pages
57
-     */
55
+	/**
56
+	 * Pages
57
+	 */
58 58
         
59
-    /**
60
-     * GeoAnalysis@index
61
-     */
62
-    public function index() {
59
+	/**
60
+	 * GeoAnalysis@index
61
+	 */
62
+	public function index() {
63 63
         
64
-        $controller = new PageController();
65
-        $controller->setPageTitle(I18N::translate('Sosa Geographical dispersion'));
64
+		$controller = new PageController();
65
+		$controller->setPageTitle(I18N::translate('Sosa Geographical dispersion'));
66 66
         
67
-        $data = new ViewBag();
68
-        $data->set('title', $controller->getPageTitle());
69
-        $data->set('has_analysis', false);
67
+		$data = new ViewBag();
68
+		$data->set('title', $controller->getPageTitle());
69
+		$data->set('has_analysis', false);
70 70
         
71
-        $ga_id = Filter::getInteger('ga_id');        
71
+		$ga_id = Filter::getInteger('ga_id');        
72 72
         
73
-        if($ga_id && $ga = $this->provider->getGeoAnalysis($ga_id)) {
74
-            $data->set('has_analysis', true);
75
-            $data->set('geoanalysis', $ga);
73
+		if($ga_id && $ga = $this->provider->getGeoAnalysis($ga_id)) {
74
+			$data->set('has_analysis', true);
75
+			$data->set('geoanalysis', $ga);
76 76
             
77
-            $controller
78
-                ->addExternalJavascript(Constants::WT_RAPHAEL_JS_URL())
79
-                ->addInlineJavascript('
77
+			$controller
78
+				->addExternalJavascript(Constants::WT_RAPHAEL_JS_URL())
79
+				->addInlineJavascript('
80 80
                 jQuery("#geodispersion-tabs").tabs();
81 81
                 jQuery("#geodispersion-tabs").css("visibility", "visible");
82 82
                 
@@ -97,128 +97,128 @@  discard block
 block discarded – undo
97 97
 					"json"
98 98
 				);
99 99
             ');
100
-        }
100
+		}
101 101
         
102
-        ViewFactory::make('GeoAnalysis', $this, $controller, $data)->render();
103
-    }
102
+		ViewFactory::make('GeoAnalysis', $this, $controller, $data)->render();
103
+	}
104 104
     
105
-    /**
106
-     * GeoAnalysis@listAll
107
-     */
108
-    public function listAll() {
105
+	/**
106
+	 * GeoAnalysis@listAll
107
+	 */
108
+	public function listAll() {
109 109
         
110
-        $controller = new PageController();
111
-        $controller->setPageTitle(I18N::translate('Sosa Geographical dispersion'));
110
+		$controller = new PageController();
111
+		$controller->setPageTitle(I18N::translate('Sosa Geographical dispersion'));
112 112
         
113
-        $data = new ViewBag();
114
-        $data->set('title', $controller->getPageTitle());
115
-        $data->set('has_list', false);
113
+		$data = new ViewBag();
114
+		$data->set('title', $controller->getPageTitle());
115
+		$data->set('has_list', false);
116 116
         
117
-        $ga_list = $this->provider->getGeoAnalysisList();
118
-        if(count($ga_list) > 0 ) {
119
-             $data->set('has_list', true);
120
-             $data->set('geoanalysislist', $ga_list);
121
-        }
117
+		$ga_list = $this->provider->getGeoAnalysisList();
118
+		if(count($ga_list) > 0 ) {
119
+			 $data->set('has_list', true);
120
+			 $data->set('geoanalysislist', $ga_list);
121
+		}
122 122
         
123
-        ViewFactory::make('GeoAnalysisList', $this, $controller, $data)->render();        
124
-    }
123
+		ViewFactory::make('GeoAnalysisList', $this, $controller, $data)->render();        
124
+	}
125 125
     	
126 126
 	/**
127 127
 	 * GeoAnalysis@setStatus
128 128
 	 */
129
-    public function setStatus() {
130
-        $controller = new JsonController();
129
+	public function setStatus() {
130
+		$controller = new JsonController();
131 131
         
132
-        $ga_id = Filter::getInteger('ga_id');
133
-        $ga = $this->provider->getGeoAnalysis($ga_id, false);
132
+		$ga_id = Filter::getInteger('ga_id');
133
+		$ga = $this->provider->getGeoAnalysis($ga_id, false);
134 134
         
135
-        $controller->restrictAccess(
136
-            true // Filter::checkCsrf()   -- Cannot use CSRF on a GET request (modules can only work with GET requests)
137
-            &&  Auth::isManager(Globals::getTree()) 
138
-            && $ga !== null
139
-        );
135
+		$controller->restrictAccess(
136
+			true // Filter::checkCsrf()   -- Cannot use CSRF on a GET request (modules can only work with GET requests)
137
+			&&  Auth::isManager(Globals::getTree()) 
138
+			&& $ga !== null
139
+		);
140 140
         
141
-        $status = Filter::getBool('status');
142
-        $res = array('geoanalysis' => $ga->getId() , 'error' => null);
143
-        try{
144
-            $this->provider->setGeoAnalysisStatus($ga, $status);
145
-            $res['status'] = $status;
141
+		$status = Filter::getBool('status');
142
+		$res = array('geoanalysis' => $ga->getId() , 'error' => null);
143
+		try{
144
+			$this->provider->setGeoAnalysisStatus($ga, $status);
145
+			$res['status'] = $status;
146 146
 			Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" has been '. ($status ? 'enabled' : 'disabled') .'.');
147
-        }
148
-        catch (\Exception $ex) {
149
-            $res['error'] = $ex->getMessage();
147
+		}
148
+		catch (\Exception $ex) {
149
+			$res['error'] = $ex->getMessage();
150 150
 			Log::addErrorLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" could not be ' . ($status ? 'enabled' : 'disabled') .'. Error: '. $ex->getMessage());
151
-        }
151
+		}
152 152
         
153
-        $controller->pageHeader();
154
-        if($res['error']) http_response_code(500);
153
+		$controller->pageHeader();
154
+		if($res['error']) http_response_code(500);
155 155
         
156
-        $controller->encode($res);
157
-    }
156
+		$controller->encode($res);
157
+	}
158 158
     
159 159
 	/**
160
-     * GeoAnalysis@delete
161
-     */
162
-    public function delete() {
163
-        $controller = new JsonController();
160
+	 * GeoAnalysis@delete
161
+	 */
162
+	public function delete() {
163
+		$controller = new JsonController();
164 164
     
165
-        $ga_id = Filter::getInteger('ga_id');
166
-        $ga = $this->provider->getGeoAnalysis($ga_id, false);
165
+		$ga_id = Filter::getInteger('ga_id');
166
+		$ga = $this->provider->getGeoAnalysis($ga_id, false);
167 167
     
168
-        $controller->restrictAccess(
169
-            true // Filter::checkCsrf()   -- Cannot use CSRF on a GET request (modules can only work with GET requests)
170
-            &&  Auth::isManager(Globals::getTree())
171
-            && $ga
172
-            );
168
+		$controller->restrictAccess(
169
+			true // Filter::checkCsrf()   -- Cannot use CSRF on a GET request (modules can only work with GET requests)
170
+			&&  Auth::isManager(Globals::getTree())
171
+			&& $ga
172
+			);
173 173
             
174
-        $res = array('geoanalysis' => $ga->getId() , 'error' => null);
175
-        try{
176
-            $this->provider->deleteGeoAnalysis($ga);
174
+		$res = array('geoanalysis' => $ga->getId() , 'error' => null);
175
+		try{
176
+			$this->provider->deleteGeoAnalysis($ga);
177 177
 			Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" has been deleted.');
178
-        }
179
-        catch (\Exception $ex) {
180
-            $res['error'] = $ex->getMessage();
178
+		}
179
+		catch (\Exception $ex) {
180
+			$res['error'] = $ex->getMessage();
181 181
 			Log::addErrorLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" could not be deleted. Error: '. $ex->getMessage());
182
-        }
182
+		}
183 183
     
184
-        $controller->pageHeader();
185
-        if($res['error']) http_response_code(500);
184
+		$controller->pageHeader();
185
+		if($res['error']) http_response_code(500);
186 186
 
187
-        $controller->encode($res);
188
-    }
187
+		$controller->encode($res);
188
+	}
189 189
         	
190
-    /**
191
-     * GeoAnalysis@dataTabs
192
-     */
193
-    public function dataTabs() {
194
-        $wt_tree = Globals::getTree();
195
-        $controller = new JsonController();
190
+	/**
191
+	 * GeoAnalysis@dataTabs
192
+	 */
193
+	public function dataTabs() {
194
+		$wt_tree = Globals::getTree();
195
+		$controller = new JsonController();
196 196
         
197
-        $ga_id = Filter::getInteger('ga_id');
198
-        $ga = $this->provider->getGeoAnalysis($ga_id);
199
-        $sosa_provider = new SosaProvider($wt_tree, Auth::user());
197
+		$ga_id = Filter::getInteger('ga_id');
198
+		$ga = $this->provider->getGeoAnalysis($ga_id);
199
+		$sosa_provider = new SosaProvider($wt_tree, Auth::user());
200 200
         
201
-        $controller
202
-            ->restrictAccess($ga && $sosa_provider->isSetup())
203
-            ->pageHeader();
201
+		$controller
202
+			->restrictAccess($ga && $sosa_provider->isSetup())
203
+			->pageHeader();
204 204
         
205
-        $jsonArray = array();
205
+		$jsonArray = array();
206 206
         
207
-        list($placesDispGeneral, $placesDispGenerations) = $ga->getAnalysisResults($sosa_provider->getAllSosaWithGenerations());
207
+		list($placesDispGeneral, $placesDispGenerations) = $ga->getAnalysisResults($sosa_provider->getAllSosaWithGenerations());
208 208
         
209
-        $flags = array();
210
-        if($placesDispGeneral && $ga->getOptions() && $ga->getOptions()->isUsingFlags()) {
211
-            $mapProvider = new GoogleMapsProvider();            
212
-            foreach($placesDispGeneral['places'] as $place => $count) {
213
-                $flags[$place] = $mapProvider->getPlaceIcon(new Place($place, $wt_tree));
214
-            }
215
-        }
209
+		$flags = array();
210
+		if($placesDispGeneral && $ga->getOptions() && $ga->getOptions()->isUsingFlags()) {
211
+			$mapProvider = new GoogleMapsProvider();            
212
+			foreach($placesDispGeneral['places'] as $place => $count) {
213
+				$flags[$place] = $mapProvider->getPlaceIcon(new Place($place, $wt_tree));
214
+			}
215
+		}
216 216
         
217
-        $jsonArray['generaltab'] = $this->htmlPlacesAnalysisGeneralTab($ga, $placesDispGeneral, $flags);
218
-        $jsonArray['generationstab'] = $this->htmlPlacesAnalysisGenerationsTab($ga, $placesDispGenerations, $flags);
217
+		$jsonArray['generaltab'] = $this->htmlPlacesAnalysisGeneralTab($ga, $placesDispGeneral, $flags);
218
+		$jsonArray['generationstab'] = $this->htmlPlacesAnalysisGenerationsTab($ga, $placesDispGenerations, $flags);
219 219
 
220
-        $controller->encode($jsonArray);
221
-    }
220
+		$controller->encode($jsonArray);
221
+	}
222 222
     
223 223
 	/**
224 224
 	 * Returns HTML code for the GeoAnalysis general tab (can be either a map or a table).
@@ -228,71 +228,71 @@  discard block
 block discarded – undo
228 228
 	 * @param (null|array) $flags Array of flags
229 229
 	 * @return string HTML code for the general tab
230 230
 	 */
231
-    protected function htmlPlacesAnalysisGeneralTab(GeoAnalysis $ga, $placesGeneralResults, $flags= null) {        
232
-        if(!empty($placesGeneralResults)){
233
-            $data = new ViewBag();
231
+	protected function htmlPlacesAnalysisGeneralTab(GeoAnalysis $ga, $placesGeneralResults, $flags= null) {        
232
+		if(!empty($placesGeneralResults)){
233
+			$data = new ViewBag();
234 234
             
235
-            $nb_found = $placesGeneralResults['knownsum'];
236
-            $nb_other = 0;
237
-            if(isset($placesGeneralResults['other'])) $nb_other =$placesGeneralResults['other'];
238
-            $nb_unknown = $placesGeneralResults['unknown'];
235
+			$nb_found = $placesGeneralResults['knownsum'];
236
+			$nb_other = 0;
237
+			if(isset($placesGeneralResults['other'])) $nb_other =$placesGeneralResults['other'];
238
+			$nb_unknown = $placesGeneralResults['unknown'];
239 239
             
240
-            $data->set('stats_gen_nb_found', $nb_found);
241
-            $data->set('stats_gen_nb_other', $nb_other);
242
-            $data->set('stats_gen_nb_unknown', $nb_unknown);
240
+			$data->set('stats_gen_nb_found', $nb_found);
241
+			$data->set('stats_gen_nb_other', $nb_other);
242
+			$data->set('stats_gen_nb_unknown', $nb_unknown);
243 243
             
244
-            $data->set('use_flags', $ga->getOptions() && $ga->getOptions()->isUsingFlags());
244
+			$data->set('use_flags', $ga->getOptions() && $ga->getOptions()->isUsingFlags());
245 245
             
246
-            if($ga->hasMap()) {
247
-                $max = $placesGeneralResults['max'];
248
-                $map = $ga->getOptions()->getMap();
249
-                if($map->isLoaded()) {
250
-                    $results_by_subdivs = $map->getSubdivisions();
251
-                    $places_mappings = $map->getPlacesMappings();
252
-                    foreach ($placesGeneralResults['places'] as $location => $count) {
253
-                        $levelvalues = array_reverse(array_map('trim',explode(',', $location)));
254
-                        $level_map = $ga->getAnalysisLevel() - $ga->getOptions()->getMapLevel();
255
-                        if($level_map >= 0 && $level_map < count($levelvalues)) {
256
-                            $levelref = I18N::strtolower($levelvalues[0] . '@' . $levelvalues[$level_map]);
257
-                            if(!isset($results_by_subdivs[$levelref])) { $levelref = $levelvalues[0]; }
258
-                        }
259
-                        else {
260
-                            $levelref = $levelvalues[0];
261
-                        }
262
-                        $levelref = I18N::strtolower($levelref);
263
-                        if(isset($places_mappings[$levelref])) $levelref = $places_mappings[$levelref];
264
-                        if(isset($results_by_subdivs[$levelref])) {
265
-                            $count_subd = isset($results_by_subdivs[$levelref]['count']) ? $results_by_subdivs[$levelref]['count'] : 0;
266
-                            $count_subd  += $count;
267
-                            $results_by_subdivs[$levelref]['count'] = $count_subd;   
268
-                            $results_by_subdivs[$levelref]['transparency'] = Functions::safeDivision($count_subd, $max);
269
-                            if($ga->getOptions()->isUsingFlags() && $flags) {
270
-                                $results_by_subdivs[$levelref]['place'] = new Place($location, Globals::getTree());
271
-                                $results_by_subdivs[$levelref]['flag'] = $flags[$location];
272
-                            }
273
-                        }
274
-                    }             
246
+			if($ga->hasMap()) {
247
+				$max = $placesGeneralResults['max'];
248
+				$map = $ga->getOptions()->getMap();
249
+				if($map->isLoaded()) {
250
+					$results_by_subdivs = $map->getSubdivisions();
251
+					$places_mappings = $map->getPlacesMappings();
252
+					foreach ($placesGeneralResults['places'] as $location => $count) {
253
+						$levelvalues = array_reverse(array_map('trim',explode(',', $location)));
254
+						$level_map = $ga->getAnalysisLevel() - $ga->getOptions()->getMapLevel();
255
+						if($level_map >= 0 && $level_map < count($levelvalues)) {
256
+							$levelref = I18N::strtolower($levelvalues[0] . '@' . $levelvalues[$level_map]);
257
+							if(!isset($results_by_subdivs[$levelref])) { $levelref = $levelvalues[0]; }
258
+						}
259
+						else {
260
+							$levelref = $levelvalues[0];
261
+						}
262
+						$levelref = I18N::strtolower($levelref);
263
+						if(isset($places_mappings[$levelref])) $levelref = $places_mappings[$levelref];
264
+						if(isset($results_by_subdivs[$levelref])) {
265
+							$count_subd = isset($results_by_subdivs[$levelref]['count']) ? $results_by_subdivs[$levelref]['count'] : 0;
266
+							$count_subd  += $count;
267
+							$results_by_subdivs[$levelref]['count'] = $count_subd;   
268
+							$results_by_subdivs[$levelref]['transparency'] = Functions::safeDivision($count_subd, $max);
269
+							if($ga->getOptions()->isUsingFlags() && $flags) {
270
+								$results_by_subdivs[$levelref]['place'] = new Place($location, Globals::getTree());
271
+								$results_by_subdivs[$levelref]['flag'] = $flags[$location];
272
+							}
273
+						}
274
+					}             
275 275
                 
276
-                    $data->set('map', $map);
277
-                    $data->set('results_by_subdivisions', $results_by_subdivs);
278
-                }
276
+					$data->set('map', $map);
277
+					$data->set('results_by_subdivisions', $results_by_subdivs);
278
+				}
279 279
                 
280
-                $html = ViewFactory::make('GeoAnalysisTabGeneralMap', $this, new BaseController(), $data)->getHtmlPartial();
281
-            }
282
-            else {
283
-                $results = $placesGeneralResults['places'];
284
-                arsort($results);
285
-                $data->set('results', $results);
286
-                $data->set('analysis_level', $ga->getAnalysisLevel());
280
+				$html = ViewFactory::make('GeoAnalysisTabGeneralMap', $this, new BaseController(), $data)->getHtmlPartial();
281
+			}
282
+			else {
283
+				$results = $placesGeneralResults['places'];
284
+				arsort($results);
285
+				$data->set('results', $results);
286
+				$data->set('analysis_level', $ga->getAnalysisLevel());
287 287
                 
288
-                $html = ViewFactory::make('GeoAnalysisTabGeneralTable', $this, new BaseController(), $data)->getHtmlPartial();
289
-            }
290
-        }
291
-        else {
292
-            $html = '<p class="warning">' . I18N::translate('No data is available for the general analysis.') . '</p>';
293
-        }
294
-        return $html;
295
-    }
288
+				$html = ViewFactory::make('GeoAnalysisTabGeneralTable', $this, new BaseController(), $data)->getHtmlPartial();
289
+			}
290
+		}
291
+		else {
292
+			$html = '<p class="warning">' . I18N::translate('No data is available for the general analysis.') . '</p>';
293
+		}
294
+		return $html;
295
+	}
296 296
     
297 297
 	/**
298 298
 	 * Returns HTML code for the GeoAnalysis generations tab.
@@ -302,66 +302,66 @@  discard block
 block discarded – undo
302 302
 	 * @param (null|array) $flags Array of flags
303 303
 	 * @return string HTML code for the generations tab
304 304
 	 */
305
-    protected function htmlPlacesAnalysisGenerationsTab(GeoAnalysis $ga, $placesGenerationsResults, $flags = null) {        
306
-        if(!empty($placesGenerationsResults) && $ga->getOptions()){
307
-            $data = new ViewBag();
305
+	protected function htmlPlacesAnalysisGenerationsTab(GeoAnalysis $ga, $placesGenerationsResults, $flags = null) {        
306
+		if(!empty($placesGenerationsResults) && $ga->getOptions()){
307
+			$data = new ViewBag();
308 308
             
309
-            ksort($placesGenerationsResults);
309
+			ksort($placesGenerationsResults);
310 310
             
311
-            $detailslevel = $ga->getOptions()->getMaxDetailsInGen();
312
-            $data->set('max_details_gen', $detailslevel);    
313
-            $data->set('use_flags', $ga->getOptions()->isUsingFlags());
314
-            $data->set('analysis_level', $ga->getAnalysisLevel());
315
-            $display_all_places = !is_null($detailslevel) && $detailslevel == 0;
316
-            $data->set('display_all_places', $display_all_places);
311
+			$detailslevel = $ga->getOptions()->getMaxDetailsInGen();
312
+			$data->set('max_details_gen', $detailslevel);    
313
+			$data->set('use_flags', $ga->getOptions()->isUsingFlags());
314
+			$data->set('analysis_level', $ga->getAnalysisLevel());
315
+			$display_all_places = !is_null($detailslevel) && $detailslevel == 0;
316
+			$data->set('display_all_places', $display_all_places);
317 317
             
318
-            $results_by_gen = array();
319
-            foreach($placesGenerationsResults as $gen => $genData){
320
-                $sum = 0;
321
-                $other = 0;
322
-                $unknown = 0;
323
-                if(isset($genData['sum'])) $sum = $genData['sum'];
324
-                if(isset($genData['other'])) $other = $genData['other'];
325
-                if(isset($genData['unknown'])) $unknown = $genData['unknown'];
318
+			$results_by_gen = array();
319
+			foreach($placesGenerationsResults as $gen => $genData){
320
+				$sum = 0;
321
+				$other = 0;
322
+				$unknown = 0;
323
+				if(isset($genData['sum'])) $sum = $genData['sum'];
324
+				if(isset($genData['other'])) $other = $genData['other'];
325
+				if(isset($genData['unknown'])) $unknown = $genData['unknown'];
326 326
                 
327
-                if($sum > 0) {                
328
-                    $results_by_gen[$gen]['sum'] = $sum;
329
-                    $results_by_gen[$gen]['other'] = $other;
330
-                    $results_by_gen[$gen]['unknown'] = $unknown;
331
-                    $results_by_gen[$gen]['places'] = array();                    
332
-                    arsort($genData['places']);
327
+				if($sum > 0) {                
328
+					$results_by_gen[$gen]['sum'] = $sum;
329
+					$results_by_gen[$gen]['other'] = $other;
330
+					$results_by_gen[$gen]['unknown'] = $unknown;
331
+					$results_by_gen[$gen]['places'] = array();                    
332
+					arsort($genData['places']);
333 333
                     
334
-                    if($display_all_places){
335
-                        foreach($genData['places'] as $placename=> $count){
336
-                            $results_by_gen[$gen]['places'][$placename]['count'] = $count;
334
+					if($display_all_places){
335
+						foreach($genData['places'] as $placename=> $count){
336
+							$results_by_gen[$gen]['places'][$placename]['count'] = $count;
337 337
                             
338
-                            if($ga->getOptions() && $ga->getOptions()->isUsingFlags() && ($flag = $flags[$placename]) != ''){
339
-                                $results_by_gen[$gen]['places'][$placename]['place'] = new Place($placename, Globals::getTree());
340
-                                $results_by_gen[$gen]['places'][$placename]['flag'] = $flag;
341
-                            }
342
-                        }
343
-                    }
344
-                    else {
345
-                        $tmp = $genData['places'];
346
-                        if($other > 0) {
347
-                            $tmp = array_slice($tmp, 0, 5, true);
348
-                            $tmp['other'] = $other;
349
-                            arsort($tmp);  
350
-                        }                      
351
-                        $results_by_gen[$gen]['places'] = array_slice($tmp, 0, 5, true);                        
352
-                    }
353
-                }
354
-            }
338
+							if($ga->getOptions() && $ga->getOptions()->isUsingFlags() && ($flag = $flags[$placename]) != ''){
339
+								$results_by_gen[$gen]['places'][$placename]['place'] = new Place($placename, Globals::getTree());
340
+								$results_by_gen[$gen]['places'][$placename]['flag'] = $flag;
341
+							}
342
+						}
343
+					}
344
+					else {
345
+						$tmp = $genData['places'];
346
+						if($other > 0) {
347
+							$tmp = array_slice($tmp, 0, 5, true);
348
+							$tmp['other'] = $other;
349
+							arsort($tmp);  
350
+						}                      
351
+						$results_by_gen[$gen]['places'] = array_slice($tmp, 0, 5, true);                        
352
+					}
353
+				}
354
+			}
355 355
             
356
-            $data->set('results_by_generations', $results_by_gen);
356
+			$data->set('results_by_generations', $results_by_gen);
357 357
             
358
-            $html = ViewFactory::make('GeoAnalysisTabGenerations', $this, new BaseController(), $data)->getHtmlPartial();
358
+			$html = ViewFactory::make('GeoAnalysisTabGenerations', $this, new BaseController(), $data)->getHtmlPartial();
359 359
             
360
-        }
361
-        else {
362
-            $html = '<p class="warning">' . I18N::translate('No data is available for the generations analysis.') . '</p>';
363
-        }
364
-        return $html;
365
-    }
360
+		}
361
+		else {
362
+			$html = '<p class="warning">' . I18N::translate('No data is available for the generations analysis.') . '</p>';
363
+		}
364
+		return $html;
365
+	}
366 366
         
367 367
 }
368 368
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
         
71 71
         $ga_id = Filter::getInteger('ga_id');        
72 72
         
73
-        if($ga_id && $ga = $this->provider->getGeoAnalysis($ga_id)) {
73
+        if ($ga_id && $ga = $this->provider->getGeoAnalysis($ga_id)) {
74 74
             $data->set('has_analysis', true);
75 75
             $data->set('geoanalysis', $ga);
76 76
             
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
                 jQuery.get(
84 84
 					"module.php",
85 85
 					{
86
-                        "mod" : "'. $this->module->getName() .'",  
86
+                        "mod" : "'. $this->module->getName().'",  
87 87
                         "mod_action": "GeoAnalysis@dataTabs",
88 88
                         "ga_id" : "'.$ga_id.'"
89 89
                     },
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
         $data->set('has_list', false);
116 116
         
117 117
         $ga_list = $this->provider->getGeoAnalysisList();
118
-        if(count($ga_list) > 0 ) {
118
+        if (count($ga_list) > 0) {
119 119
              $data->set('has_list', true);
120 120
              $data->set('geoanalysislist', $ga_list);
121 121
         }
@@ -139,19 +139,19 @@  discard block
 block discarded – undo
139 139
         );
140 140
         
141 141
         $status = Filter::getBool('status');
142
-        $res = array('geoanalysis' => $ga->getId() , 'error' => null);
143
-        try{
142
+        $res = array('geoanalysis' => $ga->getId(), 'error' => null);
143
+        try {
144 144
             $this->provider->setGeoAnalysisStatus($ga, $status);
145 145
             $res['status'] = $status;
146
-			Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" has been '. ($status ? 'enabled' : 'disabled') .'.');
146
+			Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" has been '.($status ? 'enabled' : 'disabled').'.');
147 147
         }
148 148
         catch (\Exception $ex) {
149 149
             $res['error'] = $ex->getMessage();
150
-			Log::addErrorLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" could not be ' . ($status ? 'enabled' : 'disabled') .'. Error: '. $ex->getMessage());
150
+			Log::addErrorLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" could not be '.($status ? 'enabled' : 'disabled').'. Error: '.$ex->getMessage());
151 151
         }
152 152
         
153 153
         $controller->pageHeader();
154
-        if($res['error']) http_response_code(500);
154
+        if ($res['error']) http_response_code(500);
155 155
         
156 156
         $controller->encode($res);
157 157
     }
@@ -171,18 +171,18 @@  discard block
 block discarded – undo
171 171
             && $ga
172 172
             );
173 173
             
174
-        $res = array('geoanalysis' => $ga->getId() , 'error' => null);
175
-        try{
174
+        $res = array('geoanalysis' => $ga->getId(), 'error' => null);
175
+        try {
176 176
             $this->provider->deleteGeoAnalysis($ga);
177 177
 			Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" has been deleted.');
178 178
         }
179 179
         catch (\Exception $ex) {
180 180
             $res['error'] = $ex->getMessage();
181
-			Log::addErrorLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" could not be deleted. Error: '. $ex->getMessage());
181
+			Log::addErrorLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" could not be deleted. Error: '.$ex->getMessage());
182 182
         }
183 183
     
184 184
         $controller->pageHeader();
185
-        if($res['error']) http_response_code(500);
185
+        if ($res['error']) http_response_code(500);
186 186
 
187 187
         $controller->encode($res);
188 188
     }
@@ -207,9 +207,9 @@  discard block
 block discarded – undo
207 207
         list($placesDispGeneral, $placesDispGenerations) = $ga->getAnalysisResults($sosa_provider->getAllSosaWithGenerations());
208 208
         
209 209
         $flags = array();
210
-        if($placesDispGeneral && $ga->getOptions() && $ga->getOptions()->isUsingFlags()) {
210
+        if ($placesDispGeneral && $ga->getOptions() && $ga->getOptions()->isUsingFlags()) {
211 211
             $mapProvider = new GoogleMapsProvider();            
212
-            foreach($placesDispGeneral['places'] as $place => $count) {
212
+            foreach ($placesDispGeneral['places'] as $place => $count) {
213 213
                 $flags[$place] = $mapProvider->getPlaceIcon(new Place($place, $wt_tree));
214 214
             }
215 215
         }
@@ -228,13 +228,13 @@  discard block
 block discarded – undo
228 228
 	 * @param (null|array) $flags Array of flags
229 229
 	 * @return string HTML code for the general tab
230 230
 	 */
231
-    protected function htmlPlacesAnalysisGeneralTab(GeoAnalysis $ga, $placesGeneralResults, $flags= null) {        
232
-        if(!empty($placesGeneralResults)){
231
+    protected function htmlPlacesAnalysisGeneralTab(GeoAnalysis $ga, $placesGeneralResults, $flags = null) {        
232
+        if (!empty($placesGeneralResults)) {
233 233
             $data = new ViewBag();
234 234
             
235 235
             $nb_found = $placesGeneralResults['knownsum'];
236 236
             $nb_other = 0;
237
-            if(isset($placesGeneralResults['other'])) $nb_other =$placesGeneralResults['other'];
237
+            if (isset($placesGeneralResults['other'])) $nb_other = $placesGeneralResults['other'];
238 238
             $nb_unknown = $placesGeneralResults['unknown'];
239 239
             
240 240
             $data->set('stats_gen_nb_found', $nb_found);
@@ -243,30 +243,30 @@  discard block
 block discarded – undo
243 243
             
244 244
             $data->set('use_flags', $ga->getOptions() && $ga->getOptions()->isUsingFlags());
245 245
             
246
-            if($ga->hasMap()) {
246
+            if ($ga->hasMap()) {
247 247
                 $max = $placesGeneralResults['max'];
248 248
                 $map = $ga->getOptions()->getMap();
249
-                if($map->isLoaded()) {
249
+                if ($map->isLoaded()) {
250 250
                     $results_by_subdivs = $map->getSubdivisions();
251 251
                     $places_mappings = $map->getPlacesMappings();
252 252
                     foreach ($placesGeneralResults['places'] as $location => $count) {
253
-                        $levelvalues = array_reverse(array_map('trim',explode(',', $location)));
253
+                        $levelvalues = array_reverse(array_map('trim', explode(',', $location)));
254 254
                         $level_map = $ga->getAnalysisLevel() - $ga->getOptions()->getMapLevel();
255
-                        if($level_map >= 0 && $level_map < count($levelvalues)) {
256
-                            $levelref = I18N::strtolower($levelvalues[0] . '@' . $levelvalues[$level_map]);
257
-                            if(!isset($results_by_subdivs[$levelref])) { $levelref = $levelvalues[0]; }
255
+                        if ($level_map >= 0 && $level_map < count($levelvalues)) {
256
+                            $levelref = I18N::strtolower($levelvalues[0].'@'.$levelvalues[$level_map]);
257
+                            if (!isset($results_by_subdivs[$levelref])) { $levelref = $levelvalues[0]; }
258 258
                         }
259 259
                         else {
260 260
                             $levelref = $levelvalues[0];
261 261
                         }
262 262
                         $levelref = I18N::strtolower($levelref);
263
-                        if(isset($places_mappings[$levelref])) $levelref = $places_mappings[$levelref];
264
-                        if(isset($results_by_subdivs[$levelref])) {
263
+                        if (isset($places_mappings[$levelref])) $levelref = $places_mappings[$levelref];
264
+                        if (isset($results_by_subdivs[$levelref])) {
265 265
                             $count_subd = isset($results_by_subdivs[$levelref]['count']) ? $results_by_subdivs[$levelref]['count'] : 0;
266
-                            $count_subd  += $count;
266
+                            $count_subd += $count;
267 267
                             $results_by_subdivs[$levelref]['count'] = $count_subd;   
268 268
                             $results_by_subdivs[$levelref]['transparency'] = Functions::safeDivision($count_subd, $max);
269
-                            if($ga->getOptions()->isUsingFlags() && $flags) {
269
+                            if ($ga->getOptions()->isUsingFlags() && $flags) {
270 270
                                 $results_by_subdivs[$levelref]['place'] = new Place($location, Globals::getTree());
271 271
                                 $results_by_subdivs[$levelref]['flag'] = $flags[$location];
272 272
                             }
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
             }
290 290
         }
291 291
         else {
292
-            $html = '<p class="warning">' . I18N::translate('No data is available for the general analysis.') . '</p>';
292
+            $html = '<p class="warning">'.I18N::translate('No data is available for the general analysis.').'</p>';
293 293
         }
294 294
         return $html;
295 295
     }
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 	 * @return string HTML code for the generations tab
304 304
 	 */
305 305
     protected function htmlPlacesAnalysisGenerationsTab(GeoAnalysis $ga, $placesGenerationsResults, $flags = null) {        
306
-        if(!empty($placesGenerationsResults) && $ga->getOptions()){
306
+        if (!empty($placesGenerationsResults) && $ga->getOptions()) {
307 307
             $data = new ViewBag();
308 308
             
309 309
             ksort($placesGenerationsResults);
@@ -316,26 +316,26 @@  discard block
 block discarded – undo
316 316
             $data->set('display_all_places', $display_all_places);
317 317
             
318 318
             $results_by_gen = array();
319
-            foreach($placesGenerationsResults as $gen => $genData){
319
+            foreach ($placesGenerationsResults as $gen => $genData) {
320 320
                 $sum = 0;
321 321
                 $other = 0;
322 322
                 $unknown = 0;
323
-                if(isset($genData['sum'])) $sum = $genData['sum'];
324
-                if(isset($genData['other'])) $other = $genData['other'];
325
-                if(isset($genData['unknown'])) $unknown = $genData['unknown'];
323
+                if (isset($genData['sum'])) $sum = $genData['sum'];
324
+                if (isset($genData['other'])) $other = $genData['other'];
325
+                if (isset($genData['unknown'])) $unknown = $genData['unknown'];
326 326
                 
327
-                if($sum > 0) {                
327
+                if ($sum > 0) {                
328 328
                     $results_by_gen[$gen]['sum'] = $sum;
329 329
                     $results_by_gen[$gen]['other'] = $other;
330 330
                     $results_by_gen[$gen]['unknown'] = $unknown;
331 331
                     $results_by_gen[$gen]['places'] = array();                    
332 332
                     arsort($genData['places']);
333 333
                     
334
-                    if($display_all_places){
335
-                        foreach($genData['places'] as $placename=> $count){
334
+                    if ($display_all_places) {
335
+                        foreach ($genData['places'] as $placename=> $count) {
336 336
                             $results_by_gen[$gen]['places'][$placename]['count'] = $count;
337 337
                             
338
-                            if($ga->getOptions() && $ga->getOptions()->isUsingFlags() && ($flag = $flags[$placename]) != ''){
338
+                            if ($ga->getOptions() && $ga->getOptions()->isUsingFlags() && ($flag = $flags[$placename]) != '') {
339 339
                                 $results_by_gen[$gen]['places'][$placename]['place'] = new Place($placename, Globals::getTree());
340 340
                                 $results_by_gen[$gen]['places'][$placename]['flag'] = $flag;
341 341
                             }
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
                     }
344 344
                     else {
345 345
                         $tmp = $genData['places'];
346
-                        if($other > 0) {
346
+                        if ($other > 0) {
347 347
                             $tmp = array_slice($tmp, 0, 5, true);
348 348
                             $tmp['other'] = $other;
349 349
                             arsort($tmp);  
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
             
360 360
         }
361 361
         else {
362
-            $html = '<p class="warning">' . I18N::translate('No data is available for the generations analysis.') . '</p>';
362
+            $html = '<p class="warning">'.I18N::translate('No data is available for the generations analysis.').'</p>';
363 363
         }
364 364
         return $html;
365 365
     }
Please login to merge, or discard this patch.
Braces   +28 added lines, -21 removed lines patch added patch discarded remove patch
@@ -144,14 +144,15 @@  discard block
 block discarded – undo
144 144
             $this->provider->setGeoAnalysisStatus($ga, $status);
145 145
             $res['status'] = $status;
146 146
 			Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" has been '. ($status ? 'enabled' : 'disabled') .'.');
147
-        }
148
-        catch (\Exception $ex) {
147
+        } catch (\Exception $ex) {
149 148
             $res['error'] = $ex->getMessage();
150 149
 			Log::addErrorLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" could not be ' . ($status ? 'enabled' : 'disabled') .'. Error: '. $ex->getMessage());
151 150
         }
152 151
         
153 152
         $controller->pageHeader();
154
-        if($res['error']) http_response_code(500);
153
+        if($res['error']) {
154
+        	http_response_code(500);
155
+        }
155 156
         
156 157
         $controller->encode($res);
157 158
     }
@@ -175,14 +176,15 @@  discard block
 block discarded – undo
175 176
         try{
176 177
             $this->provider->deleteGeoAnalysis($ga);
177 178
 			Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" has been deleted.');
178
-        }
179
-        catch (\Exception $ex) {
179
+        } catch (\Exception $ex) {
180 180
             $res['error'] = $ex->getMessage();
181 181
 			Log::addErrorLog('Module '.$this->module->getName().' : Geo Analysis ID "'.$ga->getId().'" could not be deleted. Error: '. $ex->getMessage());
182 182
         }
183 183
     
184 184
         $controller->pageHeader();
185
-        if($res['error']) http_response_code(500);
185
+        if($res['error']) {
186
+        	http_response_code(500);
187
+        }
186 188
 
187 189
         $controller->encode($res);
188 190
     }
@@ -234,7 +236,9 @@  discard block
 block discarded – undo
234 236
             
235 237
             $nb_found = $placesGeneralResults['knownsum'];
236 238
             $nb_other = 0;
237
-            if(isset($placesGeneralResults['other'])) $nb_other =$placesGeneralResults['other'];
239
+            if(isset($placesGeneralResults['other'])) {
240
+            	$nb_other =$placesGeneralResults['other'];
241
+            }
238 242
             $nb_unknown = $placesGeneralResults['unknown'];
239 243
             
240 244
             $data->set('stats_gen_nb_found', $nb_found);
@@ -255,12 +259,13 @@  discard block
 block discarded – undo
255 259
                         if($level_map >= 0 && $level_map < count($levelvalues)) {
256 260
                             $levelref = I18N::strtolower($levelvalues[0] . '@' . $levelvalues[$level_map]);
257 261
                             if(!isset($results_by_subdivs[$levelref])) { $levelref = $levelvalues[0]; }
258
-                        }
259
-                        else {
262
+                        } else {
260 263
                             $levelref = $levelvalues[0];
261 264
                         }
262 265
                         $levelref = I18N::strtolower($levelref);
263
-                        if(isset($places_mappings[$levelref])) $levelref = $places_mappings[$levelref];
266
+                        if(isset($places_mappings[$levelref])) {
267
+                        	$levelref = $places_mappings[$levelref];
268
+                        }
264 269
                         if(isset($results_by_subdivs[$levelref])) {
265 270
                             $count_subd = isset($results_by_subdivs[$levelref]['count']) ? $results_by_subdivs[$levelref]['count'] : 0;
266 271
                             $count_subd  += $count;
@@ -278,8 +283,7 @@  discard block
 block discarded – undo
278 283
                 }
279 284
                 
280 285
                 $html = ViewFactory::make('GeoAnalysisTabGeneralMap', $this, new BaseController(), $data)->getHtmlPartial();
281
-            }
282
-            else {
286
+            } else {
283 287
                 $results = $placesGeneralResults['places'];
284 288
                 arsort($results);
285 289
                 $data->set('results', $results);
@@ -287,8 +291,7 @@  discard block
 block discarded – undo
287 291
                 
288 292
                 $html = ViewFactory::make('GeoAnalysisTabGeneralTable', $this, new BaseController(), $data)->getHtmlPartial();
289 293
             }
290
-        }
291
-        else {
294
+        } else {
292 295
             $html = '<p class="warning">' . I18N::translate('No data is available for the general analysis.') . '</p>';
293 296
         }
294 297
         return $html;
@@ -320,9 +323,15 @@  discard block
 block discarded – undo
320 323
                 $sum = 0;
321 324
                 $other = 0;
322 325
                 $unknown = 0;
323
-                if(isset($genData['sum'])) $sum = $genData['sum'];
324
-                if(isset($genData['other'])) $other = $genData['other'];
325
-                if(isset($genData['unknown'])) $unknown = $genData['unknown'];
326
+                if(isset($genData['sum'])) {
327
+                	$sum = $genData['sum'];
328
+                }
329
+                if(isset($genData['other'])) {
330
+                	$other = $genData['other'];
331
+                }
332
+                if(isset($genData['unknown'])) {
333
+                	$unknown = $genData['unknown'];
334
+                }
326 335
                 
327 336
                 if($sum > 0) {                
328 337
                     $results_by_gen[$gen]['sum'] = $sum;
@@ -340,8 +349,7 @@  discard block
 block discarded – undo
340 349
                                 $results_by_gen[$gen]['places'][$placename]['flag'] = $flag;
341 350
                             }
342 351
                         }
343
-                    }
344
-                    else {
352
+                    } else {
345 353
                         $tmp = $genData['places'];
346 354
                         if($other > 0) {
347 355
                             $tmp = array_slice($tmp, 0, 5, true);
@@ -357,8 +365,7 @@  discard block
 block discarded – undo
357 365
             
358 366
             $html = ViewFactory::make('GeoAnalysisTabGenerations', $this, new BaseController(), $data)->getHtmlPartial();
359 367
             
360
-        }
361
-        else {
368
+        } else {
362 369
             $html = '<p class="warning">' . I18N::translate('No data is available for the generations analysis.') . '</p>';
363 370
         }
364 371
         return $html;
Please login to merge, or discard this patch.
src/Webtrees/ImageBuilder.php 3 patches
Indentation   +299 added lines, -299 removed lines patch added patch discarded remove patch
@@ -22,61 +22,61 @@  discard block
 block discarded – undo
22 22
  */
23 23
 class ImageBuilder {
24 24
     
25
-    /**
26
-     * Reference media
27
-     * @var Media $media
28
-     */
29
-    protected $media;
25
+	/**
26
+	 * Reference media
27
+	 * @var Media $media
28
+	 */
29
+	protected $media;
30 30
     
31
-    /**
32
-     * Use TTF font
33
-     * @var bool $use_ttf
34
-     */
35
-    protected $use_ttf;
31
+	/**
32
+	 * Use TTF font
33
+	 * @var bool $use_ttf
34
+	 */
35
+	protected $use_ttf;
36 36
     
37
-    /**
38
-     * Expiration offset. Default is one day.
39
-     * @var int $expire_offset
40
-     */
41
-    protected $expire_offset;
37
+	/**
38
+	 * Expiration offset. Default is one day.
39
+	 * @var int $expire_offset
40
+	 */
41
+	protected $expire_offset;
42 42
    
43
-    /**
44
-     * Should the certificate display a watermark
45
-     * @var bool $show_watermark
46
-     */
47
-    protected $show_watermark;
43
+	/**
44
+	 * Should the certificate display a watermark
45
+	 * @var bool $show_watermark
46
+	 */
47
+	protected $show_watermark;
48 48
         
49
-    /**
50
-     * Maximum watermark font size. Default is 18.
51
-     * @var int $font_max_size
52
-     */
53
-    protected $font_max_size;
49
+	/**
50
+	 * Maximum watermark font size. Default is 18.
51
+	 * @var int $font_max_size
52
+	 */
53
+	protected $font_max_size;
54 54
     
55
-    /**
56
-     * Watermark font color, in hexadecimal. Default is #4D6DF3.
57
-     * @var string $font_color
58
-     */
59
-    protected $font_color;
55
+	/**
56
+	 * Watermark font color, in hexadecimal. Default is #4D6DF3.
57
+	 * @var string $font_color
58
+	 */
59
+	protected $font_color;
60 60
     
61
-    /**
62
-     * Should the image be rendered as attachment (vs inline)     * 
63
-     * @var bool $as_attachment
64
-     */
65
-    protected $as_attachment;
61
+	/**
62
+	 * Should the image be rendered as attachment (vs inline)     * 
63
+	 * @var bool $as_attachment
64
+	 */
65
+	protected $as_attachment;
66 66
     
67 67
 	/**
68
-	* Contructor for ImageBuilder
69
-	*
70
-	* @param Media|null $media Reference media object
71
-	*/
68
+	 * Contructor for ImageBuilder
69
+	 *
70
+	 * @param Media|null $media Reference media object
71
+	 */
72 72
 	public function __construct(Media $media = null){
73
-	    $this->media = $media;
74
-	    $this->use_ttf = function_exists('imagettftext');
75
-	    $this->expire_offset = 3600 * 24;
76
-	    $this->show_watermark = true;
77
-	    $this->font_max_size = 18;
78
-	    $this->font_color = '#4D6DF3';
79
-	    $this->as_attachment = false;
73
+		$this->media = $media;
74
+		$this->use_ttf = function_exists('imagettftext');
75
+		$this->expire_offset = 3600 * 24;
76
+		$this->show_watermark = true;
77
+		$this->font_max_size = 18;
78
+		$this->font_color = '#4D6DF3';
79
+		$this->as_attachment = false;
80 80
 	}
81 81
 	
82 82
 	/**
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 	 * @return int
86 86
 	 */
87 87
 	public function getExpireOffset() {
88
-	    return $this->expire_offset;
88
+		return $this->expire_offset;
89 89
 	}
90 90
 	
91 91
 	/**
@@ -95,8 +95,8 @@  discard block
 block discarded – undo
95 95
 	 * @return ImageBuilder
96 96
 	 */
97 97
 	public function setExpireOffset($expireOffset) {
98
-	    if($expireOffset) $this->expire_offset = $expireOffset;
99
-	    return $this;
98
+		if($expireOffset) $this->expire_offset = $expireOffset;
99
+		return $this;
100 100
 	}
101 101
 	
102 102
 	/**
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 	 * @return bool
106 106
 	 */
107 107
 	public function isShowWatermark() {
108
-	    return $this->show_watermark;
108
+		return $this->show_watermark;
109 109
 	}
110 110
 	
111 111
 	/**
@@ -115,8 +115,8 @@  discard block
 block discarded – undo
115 115
 	 * @return ImageBuilder
116 116
 	 */
117 117
 	public function setShowWatermark($show_watermark) {
118
-	    if(!is_null($show_watermark)) $this->show_watermark = $show_watermark;
119
-	    return $this;
118
+		if(!is_null($show_watermark)) $this->show_watermark = $show_watermark;
119
+		return $this;
120 120
 	}
121 121
 	
122 122
 	/**
@@ -126,8 +126,8 @@  discard block
 block discarded – undo
126 126
 	 * @return ImageBuilder
127 127
 	 */
128 128
 	public function setFontMaxSize($font_max_size) {
129
-	    if($font_max_size) $this->font_max_size = $font_max_size;
130
-	    return $this;
129
+		if($font_max_size) $this->font_max_size = $font_max_size;
130
+		return $this;
131 131
 	}
132 132
 	
133 133
 	/**
@@ -137,8 +137,8 @@  discard block
 block discarded – undo
137 137
 	 * @return ImageBuilder
138 138
 	 */
139 139
 	public function setFontColor($font_color) {
140
-	    if($font_color) $this->font_color = $font_color;
141
-	    return $this;
140
+		if($font_color) $this->font_color = $font_color;
141
+		return $this;
142 142
 	}
143 143
 	
144 144
 	/**
@@ -148,8 +148,8 @@  discard block
 block discarded – undo
148 148
 	 * @return ImageBuilder
149 149
 	 */
150 150
 	public function setAsAttachment($is_attachement) {
151
-	    if(is_bool($is_attachement)) $this->as_attachment = $is_attachement;
152
-	    return $this;
151
+		if(is_bool($is_attachement)) $this->as_attachment = $is_attachement;
152
+		return $this;
153 153
 	}
154 154
 	
155 155
 	/**
@@ -157,135 +157,135 @@  discard block
 block discarded – undo
157 157
 	 */
158 158
 	public function render(){
159 159
 	    
160
-	    if (!$this->media || !$this->media->canShow()) {
161
-	        Log::addMediaLog('Image Builder error: >' . I18N::translate('Missing or private media object.'));
162
-	        $this->renderError();
163
-	    }
160
+		if (!$this->media || !$this->media->canShow()) {
161
+			Log::addMediaLog('Image Builder error: >' . I18N::translate('Missing or private media object.'));
162
+			$this->renderError();
163
+		}
164 164
 	    
165
-	    $serverFilename = $this->media->getServerFilename();
165
+		$serverFilename = $this->media->getServerFilename();
166 166
 	    
167
-	    if (!file_exists($serverFilename)) {
168
-	        Log::addMediaLog('Image Builder error: >'. I18N::translate('The media object does not exist.').'< for path >'.$serverFilename.'<');
169
-	        $this->renderError();
170
-	    }
167
+		if (!file_exists($serverFilename)) {
168
+			Log::addMediaLog('Image Builder error: >'. I18N::translate('The media object does not exist.').'< for path >'.$serverFilename.'<');
169
+			$this->renderError();
170
+		}
171 171
 	    
172
-	    $mimetype = $this->media->mimeType();
173
-	    $imgsize = $this->media->getImageAttributes();
174
-	    $filetime = $this->media->getFiletime();
175
-	    $filetimeHeader = gmdate('D, d M Y H:i:s', $filetime) . ' GMT';	    
176
-	    $expireHeader = gmdate('D, d M Y H:i:s', WT_TIMESTAMP + $this->getExpireOffset()) . ' GMT';
172
+		$mimetype = $this->media->mimeType();
173
+		$imgsize = $this->media->getImageAttributes();
174
+		$filetime = $this->media->getFiletime();
175
+		$filetimeHeader = gmdate('D, d M Y H:i:s', $filetime) . ' GMT';	    
176
+		$expireHeader = gmdate('D, d M Y H:i:s', WT_TIMESTAMP + $this->getExpireOffset()) . ' GMT';
177 177
 	    
178
-	    $type = Functions::isImageTypeSupported($imgsize['ext']);
179
-	    $usewatermark = false;
180
-	    // if this image supports watermarks and the watermark module is intalled...
181
-	    if ($type) {
182
-	        $usewatermark = $this->isShowWatermark();
183
-	    }
178
+		$type = Functions::isImageTypeSupported($imgsize['ext']);
179
+		$usewatermark = false;
180
+		// if this image supports watermarks and the watermark module is intalled...
181
+		if ($type) {
182
+			$usewatermark = $this->isShowWatermark();
183
+		}
184 184
 	    
185
-	    // determine whether we have enough memory to watermark this image
186
-	    if ($usewatermark) {
187
-	        if (!FunctionsMedia::hasMemoryForImage($serverFilename)) {
188
-	            // not enough memory to watermark this file
189
-	            $usewatermark = false;
190
-	        }
191
-	    }
185
+		// determine whether we have enough memory to watermark this image
186
+		if ($usewatermark) {
187
+			if (!FunctionsMedia::hasMemoryForImage($serverFilename)) {
188
+				// not enough memory to watermark this file
189
+				$usewatermark = false;
190
+			}
191
+		}
192 192
 	    
193
-	    $etag = $this->media->getEtag();
193
+		$etag = $this->media->getEtag();
194 194
 	    
195
-	    // parse IF_MODIFIED_SINCE header from client
196
-	    $if_modified_since = 'x';
197
-	    if (!empty(Filter::server('HTTP_IF_MODIFIED_SINCE'))) {
198
-	        $if_modified_since = preg_replace('/;.*$/', '', Filter::server('HTTP_IF_MODIFIED_SINCE'));
199
-	    }
195
+		// parse IF_MODIFIED_SINCE header from client
196
+		$if_modified_since = 'x';
197
+		if (!empty(Filter::server('HTTP_IF_MODIFIED_SINCE'))) {
198
+			$if_modified_since = preg_replace('/;.*$/', '', Filter::server('HTTP_IF_MODIFIED_SINCE'));
199
+		}
200 200
 	    
201
-	    // parse IF_NONE_MATCH header from client
202
-	    $if_none_match = 'x';
203
-	    if (!empty(Filter::server('HTTP_IF_NONE_MATCH'))) {
204
-	        $if_none_match = str_replace('"', '', Filter::server('HTTP_IF_NONE_MATCH'));
205
-	    }
201
+		// parse IF_NONE_MATCH header from client
202
+		$if_none_match = 'x';
203
+		if (!empty(Filter::server('HTTP_IF_NONE_MATCH'))) {
204
+			$if_none_match = str_replace('"', '', Filter::server('HTTP_IF_NONE_MATCH'));
205
+		}
206 206
 	    
207
-	    // add caching headers.  allow browser to cache file, but not proxy
208
-	    header('Last-Modified: ' . $filetimeHeader);
209
-	    header('ETag: "' . $etag . '"');
210
-	    header('Expires: ' . $expireHeader);
211
-	    header('Cache-Control: max-age=' . $this->getExpireOffset() . ', s-maxage=0, proxy-revalidate');
207
+		// add caching headers.  allow browser to cache file, but not proxy
208
+		header('Last-Modified: ' . $filetimeHeader);
209
+		header('ETag: "' . $etag . '"');
210
+		header('Expires: ' . $expireHeader);
211
+		header('Cache-Control: max-age=' . $this->getExpireOffset() . ', s-maxage=0, proxy-revalidate');
212 212
 	    
213
-	    // if this file is already in the user’s cache, don’t resend it
214
-	    // first check if the if_modified_since param matches
215
-	    if ($if_modified_since === $filetimeHeader) {
216
-	        // then check if the etag matches
217
-	        if ($if_none_match === $etag) {
218
-	            http_response_code(304);
213
+		// if this file is already in the user’s cache, don’t resend it
214
+		// first check if the if_modified_since param matches
215
+		if ($if_modified_since === $filetimeHeader) {
216
+			// then check if the etag matches
217
+			if ($if_none_match === $etag) {
218
+				http_response_code(304);
219 219
 	    
220
-	            return;
221
-	        }
222
-	    }	    
220
+				return;
221
+			}
222
+		}	    
223 223
 
224
-	    // send headers for the image
225
-	    $disposition = $this->as_attachment ? 'attachment' : 'inline';
226
-	    header('Content-Type: ' . $mimetype);
227
-	    header('Content-Disposition: ' . $disposition . '; filename="' . addslashes(basename($this->media->getFilename())) . '"');
224
+		// send headers for the image
225
+		$disposition = $this->as_attachment ? 'attachment' : 'inline';
226
+		header('Content-Type: ' . $mimetype);
227
+		header('Content-Disposition: ' . $disposition . '; filename="' . addslashes(basename($this->media->getFilename())) . '"');
228 228
 	     
229
-	    if ($usewatermark) {
230
-	        // generate the watermarked image
231
-	        $imCreateFunc = 'imagecreatefrom' . $type;
232
-	        $imSendFunc   = 'image' . $type;
229
+		if ($usewatermark) {
230
+			// generate the watermarked image
231
+			$imCreateFunc = 'imagecreatefrom' . $type;
232
+			$imSendFunc   = 'image' . $type;
233 233
 	    
234
-	        if (function_exists($imCreateFunc) && function_exists($imSendFunc)) {
235
-	            $im = $imCreateFunc($serverFilename);
236
-	            $im = $this->applyWatermark($im);
234
+			if (function_exists($imCreateFunc) && function_exists($imSendFunc)) {
235
+				$im = $imCreateFunc($serverFilename);
236
+				$im = $this->applyWatermark($im);
237 237
 	    	    
238
-	            // send the image
239
-	            $imSendFunc($im);
240
-	            imagedestroy($im);
238
+				// send the image
239
+				$imSendFunc($im);
240
+				imagedestroy($im);
241 241
 	    
242
-	            return;
243
-	        } else {
244
-	            // this image is defective.  log it
245
-	            Log::addMediaLog('Image Builder error: >' . I18N::translate('This media file is broken and cannot be watermarked.') . '< in file >' . $serverFilename . '< memory used: ' . memory_get_usage());
246
-	        }
247
-	    }
242
+				return;
243
+			} else {
244
+				// this image is defective.  log it
245
+				Log::addMediaLog('Image Builder error: >' . I18N::translate('This media file is broken and cannot be watermarked.') . '< in file >' . $serverFilename . '< memory used: ' . memory_get_usage());
246
+			}
247
+		}
248 248
 	    
249
-	    // determine filesize of image (could be original or watermarked version)
250
-	    $filesize = filesize($serverFilename);
249
+		// determine filesize of image (could be original or watermarked version)
250
+		$filesize = filesize($serverFilename);
251 251
 	    
252
-	    // set content-length header, send file
253
-	    header('Content-Length: ' . $filesize);
252
+		// set content-length header, send file
253
+		header('Content-Length: ' . $filesize);
254 254
 	    
255
-	    // Some servers disable fpassthru() and readfile()
256
-	    if (function_exists('readfile')) {
257
-	        readfile($serverFilename);
258
-	    } else {
259
-	        $fp = fopen($serverFilename, 'rb');
260
-	        if (function_exists('fpassthru')) {
261
-	            fpassthru($fp);
262
-	        } else {
263
-	            while (!feof($fp)) {
264
-	                echo fread($fp, 65536);
265
-	            }
266
-	        }
267
-	        fclose($fp);
268
-	    }	    
255
+		// Some servers disable fpassthru() and readfile()
256
+		if (function_exists('readfile')) {
257
+			readfile($serverFilename);
258
+		} else {
259
+			$fp = fopen($serverFilename, 'rb');
260
+			if (function_exists('fpassthru')) {
261
+				fpassthru($fp);
262
+			} else {
263
+				while (!feof($fp)) {
264
+					echo fread($fp, 65536);
265
+				}
266
+			}
267
+			fclose($fp);
268
+		}	    
269 269
 	}
270 270
 	
271 271
 	/**
272 272
 	 * Render an error as an image.
273 273
 	 */
274 274
 	protected function renderError() {	
275
-	    $error = I18N::translate('The media file was not found in this family tree.');
275
+		$error = I18N::translate('The media file was not found in this family tree.');
276 276
 
277
-    	$width  = (mb_strlen($error) * 6.5 + 50) * 1.15;
278
-    	$height = 60;
279
-    	$im     = imagecreatetruecolor($width, $height); /* Create a black image */
280
-    	$bgc    = imagecolorallocate($im, 255, 255, 255); /* set background color */
281
-    	imagefilledrectangle($im, 2, 2, $width - 4, $height - 4, $bgc); /* create a rectangle, leaving 2 px border */
277
+		$width  = (mb_strlen($error) * 6.5 + 50) * 1.15;
278
+		$height = 60;
279
+		$im     = imagecreatetruecolor($width, $height); /* Create a black image */
280
+		$bgc    = imagecolorallocate($im, 255, 255, 255); /* set background color */
281
+		imagefilledrectangle($im, 2, 2, $width - 4, $height - 4, $bgc); /* create a rectangle, leaving 2 px border */
282 282
     
283
-    	$this->embedText($im, $error, 100, '255, 0, 0', WT_ROOT . Config::FONT_DEJAVU_SANS_TTF, 'top', 'left');
283
+		$this->embedText($im, $error, 100, '255, 0, 0', WT_ROOT . Config::FONT_DEJAVU_SANS_TTF, 'top', 'left');
284 284
     
285
-    	http_response_code(404);
286
-    	header('Content-Type: image/png');
287
-    	imagepng($im);
288
-    	imagedestroy($im);
285
+		http_response_code(404);
286
+		header('Content-Type: image/png');
287
+		imagepng($im);
288
+		imagedestroy($im);
289 289
 	}
290 290
 	
291 291
 	/**
@@ -297,25 +297,25 @@  discard block
 block discarded – undo
297 297
 	 */
298 298
 	protected function applyWatermark($im) {
299 299
 	    
300
-	    // text to watermark with	    
301
-	    if(method_exists($this->media, 'getWatermarkText')) {
302
-	       $word1_text = $this->media->getWatermarkText();
303
-	    }
304
-	    else {
305
-	        $word1_text = $this->media->getTitle();
306
-	    }
300
+		// text to watermark with	    
301
+		if(method_exists($this->media, 'getWatermarkText')) {
302
+		   $word1_text = $this->media->getWatermarkText();
303
+		}
304
+		else {
305
+			$word1_text = $this->media->getTitle();
306
+		}
307 307
 	
308
-	    $this->embedText(
309
-	        $im, 
310
-	        $word1_text, 
311
-	        $this->font_max_size,
312
-	        $this->font_color,
313
-	        WT_ROOT . Config::FONT_DEJAVU_SANS_TTF,
314
-	        'top', 
315
-	        'left'
316
-	     );
308
+		$this->embedText(
309
+			$im, 
310
+			$word1_text, 
311
+			$this->font_max_size,
312
+			$this->font_color,
313
+			WT_ROOT . Config::FONT_DEJAVU_SANS_TTF,
314
+			'top', 
315
+			'left'
316
+		 );
317 317
 	
318
-	    return ($im);
318
+		return ($im);
319 319
 	}
320 320
 	
321 321
 	/**
@@ -332,94 +332,94 @@  discard block
 block discarded – undo
332 332
 	 */
333 333
 	protected function embedText($im, $text, $maxsize, $color, $font, $vpos, $hpos) {
334 334
 	    
335
-	    // there are two ways to embed text with PHP
336
-	    // (preferred) using GD and FreeType you can embed text using any True Type font
337
-	    // (fall back) if that is not available, you can insert basic monospaced text
335
+		// there are two ways to embed text with PHP
336
+		// (preferred) using GD and FreeType you can embed text using any True Type font
337
+		// (fall back) if that is not available, you can insert basic monospaced text
338 338
 	    
339
-	    $col = $this->hexrgb($color);
340
-	    $textcolor = imagecolorallocate($im, $col['red'], $col['green'], $col['blue']);
339
+		$col = $this->hexrgb($color);
340
+		$textcolor = imagecolorallocate($im, $col['red'], $col['green'], $col['blue']);
341 341
 	    
342
-	    // make adjustments to settings that imagestring and imagestringup can’t handle
343
-	    if (!$this->use_ttf) {
344
-	        // imagestringup only writes up, can’t use top2bottom
345
-	        if ($hpos === 'top2bottom') {
346
-	            $hpos = 'bottom2top';
347
-	        }
348
-	    }
342
+		// make adjustments to settings that imagestring and imagestringup can’t handle
343
+		if (!$this->use_ttf) {
344
+			// imagestringup only writes up, can’t use top2bottom
345
+			if ($hpos === 'top2bottom') {
346
+				$hpos = 'bottom2top';
347
+			}
348
+		}
349 349
 	    
350
-	    $text       = I18N::reverseText($text);
351
-	    $height     = imagesy($im);
352
-	    $width      = imagesx($im);
353
-	    $calc_angle = rad2deg(atan($height / $width));
354
-	    $hypoth     = $height / sin(deg2rad($calc_angle));
350
+		$text       = I18N::reverseText($text);
351
+		$height     = imagesy($im);
352
+		$width      = imagesx($im);
353
+		$calc_angle = rad2deg(atan($height / $width));
354
+		$hypoth     = $height / sin(deg2rad($calc_angle));
355 355
 	    
356
-	    // vertical and horizontal position of the text
357
-	    switch ($vpos) {
358
-	        default:
359
-	        case 'top':
360
-	            $taille   = $this->textLength($maxsize, $width, $text);
361
-	            $pos_y    = $height * 0.15 + $taille;
362
-	            $pos_x    = $width * 0.15;
363
-	            $rotation = 0;
364
-	            break;
365
-	        case 'middle':
366
-	            $taille   = $this->textLength($maxsize, $width, $text);
367
-	            $pos_y    = ($height + $taille) / 2;
368
-	            $pos_x    = $width * 0.15;
369
-	            $rotation = 0;
370
-	            break;
371
-	        case 'bottom':
372
-	            $taille   = $this->textLength($maxsize, $width, $text);
373
-	            $pos_y    = ($height * .85 - $taille);
374
-	            $pos_x    = $width * 0.15;
375
-	            $rotation = 0;
376
-	            break;
377
-	        case 'across':
378
-	            switch ($hpos) {
379
-	                default:
380
-	                case 'left':
381
-	                    $taille   = $this->textLength($maxsize, $hypoth, $text);
382
-	                    $pos_y    = ($height * .85 - $taille);
383
-	                    $pos_x    = $width * 0.15;
384
-	                    $rotation = $calc_angle;
385
-	                    break;
386
-	                case 'right':
387
-	                    $taille   = $this->textLength($maxsize, $hypoth, $text);
388
-	                    $pos_y    = ($height * .15 - $taille);
389
-	                    $pos_x    = $width * 0.85;
390
-	                    $rotation = $calc_angle + 180;
391
-	                    break;
392
-	                case 'top2bottom':
393
-	                    $taille   = $this->textLength($maxsize, $height, $text);
394
-	                    $pos_y    = ($height * .15 - $taille);
395
-	                    $pos_x    = ($width * .90 - $taille);
396
-	                    $rotation = -90;
397
-	                    break;
398
-	                case 'bottom2top':
399
-	                    $taille   = $this->textLength($maxsize, $height, $text);
400
-	                    $pos_y    = $height * 0.85;
401
-	                    $pos_x    = $width * 0.15;
402
-	                    $rotation = 90;
403
-	                    break;
404
-	            }
405
-	            break;
406
-	    }
356
+		// vertical and horizontal position of the text
357
+		switch ($vpos) {
358
+			default:
359
+			case 'top':
360
+				$taille   = $this->textLength($maxsize, $width, $text);
361
+				$pos_y    = $height * 0.15 + $taille;
362
+				$pos_x    = $width * 0.15;
363
+				$rotation = 0;
364
+				break;
365
+			case 'middle':
366
+				$taille   = $this->textLength($maxsize, $width, $text);
367
+				$pos_y    = ($height + $taille) / 2;
368
+				$pos_x    = $width * 0.15;
369
+				$rotation = 0;
370
+				break;
371
+			case 'bottom':
372
+				$taille   = $this->textLength($maxsize, $width, $text);
373
+				$pos_y    = ($height * .85 - $taille);
374
+				$pos_x    = $width * 0.15;
375
+				$rotation = 0;
376
+				break;
377
+			case 'across':
378
+				switch ($hpos) {
379
+					default:
380
+					case 'left':
381
+						$taille   = $this->textLength($maxsize, $hypoth, $text);
382
+						$pos_y    = ($height * .85 - $taille);
383
+						$pos_x    = $width * 0.15;
384
+						$rotation = $calc_angle;
385
+						break;
386
+					case 'right':
387
+						$taille   = $this->textLength($maxsize, $hypoth, $text);
388
+						$pos_y    = ($height * .15 - $taille);
389
+						$pos_x    = $width * 0.85;
390
+						$rotation = $calc_angle + 180;
391
+						break;
392
+					case 'top2bottom':
393
+						$taille   = $this->textLength($maxsize, $height, $text);
394
+						$pos_y    = ($height * .15 - $taille);
395
+						$pos_x    = ($width * .90 - $taille);
396
+						$rotation = -90;
397
+						break;
398
+					case 'bottom2top':
399
+						$taille   = $this->textLength($maxsize, $height, $text);
400
+						$pos_y    = $height * 0.85;
401
+						$pos_x    = $width * 0.15;
402
+						$rotation = 90;
403
+						break;
404
+				}
405
+				break;
406
+		}
407 407
 	    
408
-	    // apply the text
409
-	    if ($this->use_ttf) {
410
-	        // if imagettftext throws errors, catch them with a custom error handler
411
-	        set_error_handler(array($this, 'imageTtfTextErrorHandler'));
412
-	        imagettftext($im, $taille, $rotation, $pos_x, $pos_y, $textcolor, $font, $text);
413
-	        restore_error_handler();
414
-	    }
415
-	    // Don’t use an ‘else’ here since imagettftextErrorHandler may have changed the value of $useTTF from true to false
416
-	    if (!$this->use_ttf) {
417
-	        if ($rotation !== 90) {
418
-	            imagestring($im, 5, $pos_x, $pos_y, $text, $textcolor);
419
-	        } else {
420
-	            imagestringup($im, 5, $pos_x, $pos_y, $text, $textcolor);
421
-	        }
422
-	    }
408
+		// apply the text
409
+		if ($this->use_ttf) {
410
+			// if imagettftext throws errors, catch them with a custom error handler
411
+			set_error_handler(array($this, 'imageTtfTextErrorHandler'));
412
+			imagettftext($im, $taille, $rotation, $pos_x, $pos_y, $textcolor, $font, $text);
413
+			restore_error_handler();
414
+		}
415
+		// Don’t use an ‘else’ here since imagettftextErrorHandler may have changed the value of $useTTF from true to false
416
+		if (!$this->use_ttf) {
417
+			if ($rotation !== 90) {
418
+				imagestring($im, 5, $pos_x, $pos_y, $text, $textcolor);
419
+			} else {
420
+				imagestringup($im, 5, $pos_x, $pos_y, $text, $textcolor);
421
+			}
422
+		}
423 423
 	
424 424
 	}
425 425
 	
@@ -431,53 +431,53 @@  discard block
 block discarded – undo
431 431
 	 */
432 432
 	protected function hexrgb ($hexstr)
433 433
 	{
434
-	    $int = hexdec($hexstr);
434
+		$int = hexdec($hexstr);
435 435
 	
436
-	    return array('red' => 0xFF & ($int >> 0x10),
437
-	        'green' => 0xFF & ($int >> 0x8),
438
-	        'blue' => 0xFF & $int);
436
+		return array('red' => 0xFF & ($int >> 0x10),
437
+			'green' => 0xFF & ($int >> 0x8),
438
+			'blue' => 0xFF & $int);
439 439
 	}
440 440
 	
441
-    /**
442
-     * Generate an approximate length of text, in pixels.
443
-     *
444
-     * @param int    $t
445
-     * @param int    $mxl
446
-     * @param string $text
447
-     *
448
-     * @return int
449
-     */
450
-    function textLength($t, $mxl, $text) {
451
-    	$taille_c = $t;
452
-    	$len      = mb_strlen($text);
453
-    	while (($taille_c - 2) * $len > $mxl) {
454
-    		$taille_c--;
455
-    		if ($taille_c == 2) {
456
-    			break;
457
-    		}
458
-    	}
441
+	/**
442
+	 * Generate an approximate length of text, in pixels.
443
+	 *
444
+	 * @param int    $t
445
+	 * @param int    $mxl
446
+	 * @param string $text
447
+	 *
448
+	 * @return int
449
+	 */
450
+	function textLength($t, $mxl, $text) {
451
+		$taille_c = $t;
452
+		$len      = mb_strlen($text);
453
+		while (($taille_c - 2) * $len > $mxl) {
454
+			$taille_c--;
455
+			if ($taille_c == 2) {
456
+				break;
457
+			}
458
+		}
459 459
     
460
-    	return $taille_c;
461
-    }
460
+		return $taille_c;
461
+	}
462 462
     
463
-    /**
464
-     * imagettftext is the function that is most likely to throw an error
465
-     * use this custom error handler to catch and log it
466
-     *
467
-     * @param int    $errno
468
-     * @param string $errstr
469
-     *
470
-     * @return bool
471
-     */
472
-    function imageTtfTextErrorHandler($errno, $errstr) {
473
-        // log the error
474
-        Log::addErrorLog('Image Builder error: >' . $errno . '/' . $errstr . '< while processing file >' . $this->media->getServerFilename() . '<');
463
+	/**
464
+	 * imagettftext is the function that is most likely to throw an error
465
+	 * use this custom error handler to catch and log it
466
+	 *
467
+	 * @param int    $errno
468
+	 * @param string $errstr
469
+	 *
470
+	 * @return bool
471
+	 */
472
+	function imageTtfTextErrorHandler($errno, $errstr) {
473
+		// log the error
474
+		Log::addErrorLog('Image Builder error: >' . $errno . '/' . $errstr . '< while processing file >' . $this->media->getServerFilename() . '<');
475 475
     
476
-        // change value of useTTF to false so the fallback watermarking can be used.
477
-        $this->use_ttf = false;
476
+		// change value of useTTF to false so the fallback watermarking can be used.
477
+		$this->use_ttf = false;
478 478
     
479
-        return true;
480
-    }
479
+		return true;
480
+	}
481 481
 		
482 482
 }
483 483
 
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 	*
70 70
 	* @param Media|null $media Reference media object
71 71
 	*/
72
-	public function __construct(Media $media = null){
72
+	public function __construct(Media $media = null) {
73 73
 	    $this->media = $media;
74 74
 	    $this->use_ttf = function_exists('imagettftext');
75 75
 	    $this->expire_offset = 3600 * 24;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	 * @return ImageBuilder
96 96
 	 */
97 97
 	public function setExpireOffset($expireOffset) {
98
-	    if($expireOffset) $this->expire_offset = $expireOffset;
98
+	    if ($expireOffset) $this->expire_offset = $expireOffset;
99 99
 	    return $this;
100 100
 	}
101 101
 	
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 	 * @return ImageBuilder
116 116
 	 */
117 117
 	public function setShowWatermark($show_watermark) {
118
-	    if(!is_null($show_watermark)) $this->show_watermark = $show_watermark;
118
+	    if (!is_null($show_watermark)) $this->show_watermark = $show_watermark;
119 119
 	    return $this;
120 120
 	}
121 121
 	
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 	 * @return ImageBuilder
127 127
 	 */
128 128
 	public function setFontMaxSize($font_max_size) {
129
-	    if($font_max_size) $this->font_max_size = $font_max_size;
129
+	    if ($font_max_size) $this->font_max_size = $font_max_size;
130 130
 	    return $this;
131 131
 	}
132 132
 	
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return ImageBuilder
138 138
 	 */
139 139
 	public function setFontColor($font_color) {
140
-	    if($font_color) $this->font_color = $font_color;
140
+	    if ($font_color) $this->font_color = $font_color;
141 141
 	    return $this;
142 142
 	}
143 143
 	
@@ -148,32 +148,32 @@  discard block
 block discarded – undo
148 148
 	 * @return ImageBuilder
149 149
 	 */
150 150
 	public function setAsAttachment($is_attachement) {
151
-	    if(is_bool($is_attachement)) $this->as_attachment = $is_attachement;
151
+	    if (is_bool($is_attachement)) $this->as_attachment = $is_attachement;
152 152
 	    return $this;
153 153
 	}
154 154
 	
155 155
 	/**
156 156
 	 * Render the image to the output.
157 157
 	 */
158
-	public function render(){
158
+	public function render() {
159 159
 	    
160 160
 	    if (!$this->media || !$this->media->canShow()) {
161
-	        Log::addMediaLog('Image Builder error: >' . I18N::translate('Missing or private media object.'));
161
+	        Log::addMediaLog('Image Builder error: >'.I18N::translate('Missing or private media object.'));
162 162
 	        $this->renderError();
163 163
 	    }
164 164
 	    
165 165
 	    $serverFilename = $this->media->getServerFilename();
166 166
 	    
167 167
 	    if (!file_exists($serverFilename)) {
168
-	        Log::addMediaLog('Image Builder error: >'. I18N::translate('The media object does not exist.').'< for path >'.$serverFilename.'<');
168
+	        Log::addMediaLog('Image Builder error: >'.I18N::translate('The media object does not exist.').'< for path >'.$serverFilename.'<');
169 169
 	        $this->renderError();
170 170
 	    }
171 171
 	    
172 172
 	    $mimetype = $this->media->mimeType();
173 173
 	    $imgsize = $this->media->getImageAttributes();
174 174
 	    $filetime = $this->media->getFiletime();
175
-	    $filetimeHeader = gmdate('D, d M Y H:i:s', $filetime) . ' GMT';	    
176
-	    $expireHeader = gmdate('D, d M Y H:i:s', WT_TIMESTAMP + $this->getExpireOffset()) . ' GMT';
175
+	    $filetimeHeader = gmdate('D, d M Y H:i:s', $filetime).' GMT';	    
176
+	    $expireHeader = gmdate('D, d M Y H:i:s', WT_TIMESTAMP + $this->getExpireOffset()).' GMT';
177 177
 	    
178 178
 	    $type = Functions::isImageTypeSupported($imgsize['ext']);
179 179
 	    $usewatermark = false;
@@ -205,10 +205,10 @@  discard block
 block discarded – undo
205 205
 	    }
206 206
 	    
207 207
 	    // add caching headers.  allow browser to cache file, but not proxy
208
-	    header('Last-Modified: ' . $filetimeHeader);
209
-	    header('ETag: "' . $etag . '"');
210
-	    header('Expires: ' . $expireHeader);
211
-	    header('Cache-Control: max-age=' . $this->getExpireOffset() . ', s-maxage=0, proxy-revalidate');
208
+	    header('Last-Modified: '.$filetimeHeader);
209
+	    header('ETag: "'.$etag.'"');
210
+	    header('Expires: '.$expireHeader);
211
+	    header('Cache-Control: max-age='.$this->getExpireOffset().', s-maxage=0, proxy-revalidate');
212 212
 	    
213 213
 	    // if this file is already in the user’s cache, don’t resend it
214 214
 	    // first check if the if_modified_since param matches
@@ -223,13 +223,13 @@  discard block
 block discarded – undo
223 223
 
224 224
 	    // send headers for the image
225 225
 	    $disposition = $this->as_attachment ? 'attachment' : 'inline';
226
-	    header('Content-Type: ' . $mimetype);
227
-	    header('Content-Disposition: ' . $disposition . '; filename="' . addslashes(basename($this->media->getFilename())) . '"');
226
+	    header('Content-Type: '.$mimetype);
227
+	    header('Content-Disposition: '.$disposition.'; filename="'.addslashes(basename($this->media->getFilename())).'"');
228 228
 	     
229 229
 	    if ($usewatermark) {
230 230
 	        // generate the watermarked image
231
-	        $imCreateFunc = 'imagecreatefrom' . $type;
232
-	        $imSendFunc   = 'image' . $type;
231
+	        $imCreateFunc = 'imagecreatefrom'.$type;
232
+	        $imSendFunc   = 'image'.$type;
233 233
 	    
234 234
 	        if (function_exists($imCreateFunc) && function_exists($imSendFunc)) {
235 235
 	            $im = $imCreateFunc($serverFilename);
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
 	            return;
243 243
 	        } else {
244 244
 	            // this image is defective.  log it
245
-	            Log::addMediaLog('Image Builder error: >' . I18N::translate('This media file is broken and cannot be watermarked.') . '< in file >' . $serverFilename . '< memory used: ' . memory_get_usage());
245
+	            Log::addMediaLog('Image Builder error: >'.I18N::translate('This media file is broken and cannot be watermarked.').'< in file >'.$serverFilename.'< memory used: '.memory_get_usage());
246 246
 	        }
247 247
 	    }
248 248
 	    
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 	    $filesize = filesize($serverFilename);
251 251
 	    
252 252
 	    // set content-length header, send file
253
-	    header('Content-Length: ' . $filesize);
253
+	    header('Content-Length: '.$filesize);
254 254
 	    
255 255
 	    // Some servers disable fpassthru() and readfile()
256 256
 	    if (function_exists('readfile')) {
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
     	$bgc    = imagecolorallocate($im, 255, 255, 255); /* set background color */
281 281
     	imagefilledrectangle($im, 2, 2, $width - 4, $height - 4, $bgc); /* create a rectangle, leaving 2 px border */
282 282
     
283
-    	$this->embedText($im, $error, 100, '255, 0, 0', WT_ROOT . Config::FONT_DEJAVU_SANS_TTF, 'top', 'left');
283
+    	$this->embedText($im, $error, 100, '255, 0, 0', WT_ROOT.Config::FONT_DEJAVU_SANS_TTF, 'top', 'left');
284 284
     
285 285
     	http_response_code(404);
286 286
     	header('Content-Type: image/png');
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 	protected function applyWatermark($im) {
299 299
 	    
300 300
 	    // text to watermark with	    
301
-	    if(method_exists($this->media, 'getWatermarkText')) {
301
+	    if (method_exists($this->media, 'getWatermarkText')) {
302 302
 	       $word1_text = $this->media->getWatermarkText();
303 303
 	    }
304 304
 	    else {
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 	        $word1_text, 
311 311
 	        $this->font_max_size,
312 312
 	        $this->font_color,
313
-	        WT_ROOT . Config::FONT_DEJAVU_SANS_TTF,
313
+	        WT_ROOT.Config::FONT_DEJAVU_SANS_TTF,
314 314
 	        'top', 
315 315
 	        'left'
316 316
 	     );
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
 	 * @param string $hexstr
430 430
 	 * @return int[]
431 431
 	 */
432
-	protected function hexrgb ($hexstr)
432
+	protected function hexrgb($hexstr)
433 433
 	{
434 434
 	    $int = hexdec($hexstr);
435 435
 	
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
      */
472 472
     function imageTtfTextErrorHandler($errno, $errstr) {
473 473
         // log the error
474
-        Log::addErrorLog('Image Builder error: >' . $errno . '/' . $errstr . '< while processing file >' . $this->media->getServerFilename() . '<');
474
+        Log::addErrorLog('Image Builder error: >'.$errno.'/'.$errstr.'< while processing file >'.$this->media->getServerFilename().'<');
475 475
     
476 476
         // change value of useTTF to false so the fallback watermarking can be used.
477 477
         $this->use_ttf = false;
Please login to merge, or discard this patch.
Braces   +16 added lines, -7 removed lines patch added patch discarded remove patch
@@ -95,7 +95,9 @@  discard block
 block discarded – undo
95 95
 	 * @return ImageBuilder
96 96
 	 */
97 97
 	public function setExpireOffset($expireOffset) {
98
-	    if($expireOffset) $this->expire_offset = $expireOffset;
98
+	    if($expireOffset) {
99
+	    	$this->expire_offset = $expireOffset;
100
+	    }
99 101
 	    return $this;
100 102
 	}
101 103
 	
@@ -115,7 +117,9 @@  discard block
 block discarded – undo
115 117
 	 * @return ImageBuilder
116 118
 	 */
117 119
 	public function setShowWatermark($show_watermark) {
118
-	    if(!is_null($show_watermark)) $this->show_watermark = $show_watermark;
120
+	    if(!is_null($show_watermark)) {
121
+	    	$this->show_watermark = $show_watermark;
122
+	    }
119 123
 	    return $this;
120 124
 	}
121 125
 	
@@ -126,7 +130,9 @@  discard block
 block discarded – undo
126 130
 	 * @return ImageBuilder
127 131
 	 */
128 132
 	public function setFontMaxSize($font_max_size) {
129
-	    if($font_max_size) $this->font_max_size = $font_max_size;
133
+	    if($font_max_size) {
134
+	    	$this->font_max_size = $font_max_size;
135
+	    }
130 136
 	    return $this;
131 137
 	}
132 138
 	
@@ -137,7 +143,9 @@  discard block
 block discarded – undo
137 143
 	 * @return ImageBuilder
138 144
 	 */
139 145
 	public function setFontColor($font_color) {
140
-	    if($font_color) $this->font_color = $font_color;
146
+	    if($font_color) {
147
+	    	$this->font_color = $font_color;
148
+	    }
141 149
 	    return $this;
142 150
 	}
143 151
 	
@@ -148,7 +156,9 @@  discard block
 block discarded – undo
148 156
 	 * @return ImageBuilder
149 157
 	 */
150 158
 	public function setAsAttachment($is_attachement) {
151
-	    if(is_bool($is_attachement)) $this->as_attachment = $is_attachement;
159
+	    if(is_bool($is_attachement)) {
160
+	    	$this->as_attachment = $is_attachement;
161
+	    }
152 162
 	    return $this;
153 163
 	}
154 164
 	
@@ -300,8 +310,7 @@  discard block
 block discarded – undo
300 310
 	    // text to watermark with	    
301 311
 	    if(method_exists($this->media, 'getWatermarkText')) {
302 312
 	       $word1_text = $this->media->getWatermarkText();
303
-	    }
304
-	    else {
313
+	    } else {
305 314
 	        $word1_text = $this->media->getTitle();
306 315
 	    }
307 316
 	
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/SosaStatsController.php 3 patches
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -27,229 +27,229 @@
 block discarded – undo
27 27
  */
28 28
 class SosaStatsController extends MvcController
29 29
 {
30
-    /**
31
-     * Sosa Provider for the controller
32
-     * @var SosaProvider $sosa_provider
33
-     */
34
-    protected $sosa_provider;
30
+	/**
31
+	 * Sosa Provider for the controller
32
+	 * @var SosaProvider $sosa_provider
33
+	 */
34
+	protected $sosa_provider;
35 35
     
36
-    /**
37
-     * Constructor for SosaStatsController
38
-     * @param AbstractModule $module
39
-     */
40
-    public function __construct(AbstractModule $module) {
41
-        parent::__construct($module);
36
+	/**
37
+	 * Constructor for SosaStatsController
38
+	 * @param AbstractModule $module
39
+	 */
40
+	public function __construct(AbstractModule $module) {
41
+		parent::__construct($module);
42 42
         
43
-        $this->sosa_provider = new SosaProvider(Globals::getTree(), Auth::user());
44
-    }
43
+		$this->sosa_provider = new SosaProvider(Globals::getTree(), Auth::user());
44
+	}
45 45
     
46
-    /**
47
-     * Pages
48
-     */
46
+	/**
47
+	 * Pages
48
+	 */
49 49
     
50
-    /**
51
-     * SosaStats@index
52
-     */
53
-    public function index() {
54
-        $wt_tree = Globals::getTree();
55
-        $controller = new PageController();
56
-        $controller
57
-            ->setPageTitle(I18N::translate('Sosa Statistics'))
58
-            ->addInlineJavascript('$(".help_tooltip").tooltip();')
59
-        ;
50
+	/**
51
+	 * SosaStats@index
52
+	 */
53
+	public function index() {
54
+		$wt_tree = Globals::getTree();
55
+		$controller = new PageController();
56
+		$controller
57
+			->setPageTitle(I18N::translate('Sosa Statistics'))
58
+			->addInlineJavascript('$(".help_tooltip").tooltip();')
59
+		;
60 60
 
61
-        $view_bag = new ViewBag();
62
-        $view_bag->set('title', $controller->getPageTitle());
63
-        $view_bag->set('is_setup', false);
61
+		$view_bag = new ViewBag();
62
+		$view_bag->set('title', $controller->getPageTitle());
63
+		$view_bag->set('is_setup', false);
64 64
         
65
-        if($this->sosa_provider->isSetup()) {
66
-            $view_bag->set('is_setup', true);
65
+		if($this->sosa_provider->isSetup()) {
66
+			$view_bag->set('is_setup', true);
67 67
             
68
-            $view_bag->set('root_indi', $this->sosa_provider->getRootIndi());
68
+			$view_bag->set('root_indi', $this->sosa_provider->getRootIndi());
69 69
             
70
-            $sosaCount = $this->sosa_provider->getSosaCount();
71
-            $diffSosaCount = $this->sosa_provider->getDifferentSosaCount();
70
+			$sosaCount = $this->sosa_provider->getSosaCount();
71
+			$diffSosaCount = $this->sosa_provider->getDifferentSosaCount();
72 72
             
73
-            $general_stats = array(
74
-                'sosa_count' => $sosaCount,
75
-                'distinct_count' => $diffSosaCount,
76
-                'sosa_rate' => Functions::safeDivision($diffSosaCount, $this->sosa_provider->getTotalIndividuals()),
77
-                'pedi_collapse' => 1 - Functions::safeDivision($diffSosaCount, $sosaCount),
78
-                'mean_gen_time' => $this->sosa_provider->getMeanGenerationTime()
79
-            );
80
-            $view_bag->set('general_stats', $general_stats);
73
+			$general_stats = array(
74
+				'sosa_count' => $sosaCount,
75
+				'distinct_count' => $diffSosaCount,
76
+				'sosa_rate' => Functions::safeDivision($diffSosaCount, $this->sosa_provider->getTotalIndividuals()),
77
+				'pedi_collapse' => 1 - Functions::safeDivision($diffSosaCount, $sosaCount),
78
+				'mean_gen_time' => $this->sosa_provider->getMeanGenerationTime()
79
+			);
80
+			$view_bag->set('general_stats', $general_stats);
81 81
             
82
-            $stats_gen = $this->sosa_provider->getStatisticsByGeneration();
83
-            $view_bag->set('missinganc_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaList@missing&ged='.$wt_tree->getNameUrl().'&gen=');
84
-            $view_bag->set('sosaanc_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaList&ged='.$wt_tree->getNameUrl().'&gen=');
82
+			$stats_gen = $this->sosa_provider->getStatisticsByGeneration();
83
+			$view_bag->set('missinganc_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaList@missing&ged='.$wt_tree->getNameUrl().'&gen=');
84
+			$view_bag->set('sosaanc_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaList&ged='.$wt_tree->getNameUrl().'&gen=');
85 85
             
86
-            $gen_theoretical=1;
87
-            $total_theoretical=0;
88
-            $prev_diff=0;
89
-            $prev_known=0.5;
90
-            $gen_equiv=0;            
91
-            $generation_stats = array();
86
+			$gen_theoretical=1;
87
+			$total_theoretical=0;
88
+			$prev_diff=0;
89
+			$prev_known=0.5;
90
+			$gen_equiv=0;            
91
+			$generation_stats = array();
92 92
             
93
-            foreach($stats_gen as $gen => $tab){
94
-                $genY1= I18N::translate('-');
95
-                $genY2= I18N::translate('-');
96
-                if($tab['firstBirth']>0) $genY1=$tab['firstEstimatedBirth'];
97
-                if($tab['lastBirth']>0) $genY2=$tab['lastEstimatedBirth'];
98
-                $total_theoretical += $gen_theoretical;
99
-                $perc_sosa_count_theor = Functions::safeDivision($tab['sosaCount'], $gen_theoretical);
100
-                $gen_equiv += $perc_sosa_count_theor;
101
-                $missing=2*$prev_known - $tab['sosaCount'];
102
-                $gen_diff=$tab['diffSosaTotalCount']-$prev_diff;
93
+			foreach($stats_gen as $gen => $tab){
94
+				$genY1= I18N::translate('-');
95
+				$genY2= I18N::translate('-');
96
+				if($tab['firstBirth']>0) $genY1=$tab['firstEstimatedBirth'];
97
+				if($tab['lastBirth']>0) $genY2=$tab['lastEstimatedBirth'];
98
+				$total_theoretical += $gen_theoretical;
99
+				$perc_sosa_count_theor = Functions::safeDivision($tab['sosaCount'], $gen_theoretical);
100
+				$gen_equiv += $perc_sosa_count_theor;
101
+				$missing=2*$prev_known - $tab['sosaCount'];
102
+				$gen_diff=$tab['diffSosaTotalCount']-$prev_diff;
103 103
                 
104
-                $generation_stats[$gen] = array(
105
-                    'gen_min_birth' => $genY1,
106
-                    'gen_max_birth' => $genY2,
107
-                    'theoretical' => $gen_theoretical,
108
-                    'known' => $tab['sosaCount'],
109
-                    'perc_known' => $perc_sosa_count_theor,
110
-                    'missing' => $missing,
111
-                    'perc_missing' => 1-Functions::safeDivision($tab['sosaCount'], 2*$prev_known),
112
-                    'total_known' => $tab['sosaTotalCount'],
113
-                    'perc_total_known' => Functions::safeDivision($tab['sosaTotalCount'], $total_theoretical),
114
-                    'different' => $gen_diff,
115
-                    'perc_different' => Functions::safeDivision($gen_diff, $tab['sosaCount']),
116
-                    'total_different' => $tab['diffSosaTotalCount'],
117
-                    'pedi_collapse' => 1 - Functions::safeDivision($tab['diffSosaTotalCount'], $tab['sosaTotalCount'])
118
-                );
104
+				$generation_stats[$gen] = array(
105
+					'gen_min_birth' => $genY1,
106
+					'gen_max_birth' => $genY2,
107
+					'theoretical' => $gen_theoretical,
108
+					'known' => $tab['sosaCount'],
109
+					'perc_known' => $perc_sosa_count_theor,
110
+					'missing' => $missing,
111
+					'perc_missing' => 1-Functions::safeDivision($tab['sosaCount'], 2*$prev_known),
112
+					'total_known' => $tab['sosaTotalCount'],
113
+					'perc_total_known' => Functions::safeDivision($tab['sosaTotalCount'], $total_theoretical),
114
+					'different' => $gen_diff,
115
+					'perc_different' => Functions::safeDivision($gen_diff, $tab['sosaCount']),
116
+					'total_different' => $tab['diffSosaTotalCount'],
117
+					'pedi_collapse' => 1 - Functions::safeDivision($tab['diffSosaTotalCount'], $tab['sosaTotalCount'])
118
+				);
119 119
                 
120
-                $gen_theoretical = $gen_theoretical * 2;
121
-                $prev_known=$tab['sosaCount'];
122
-                $prev_diff=$tab['diffSosaTotalCount'];
123
-            }
120
+				$gen_theoretical = $gen_theoretical * 2;
121
+				$prev_known=$tab['sosaCount'];
122
+				$prev_diff=$tab['diffSosaTotalCount'];
123
+			}
124 124
             
125
-            $view_bag->set('generation_stats', $generation_stats);
126
-            $view_bag->set('equivalent_gen', $gen_equiv);
125
+			$view_bag->set('generation_stats', $generation_stats);
126
+			$view_bag->set('equivalent_gen', $gen_equiv);
127 127
             
128
-            $top10multiancestors = $this->sosa_provider->getTopMultiSosaAncestorsNoTies(10);
129
-            $top10ancestors = array();
130
-            if($top10multiancestors !== null && count($top10multiancestors)) {
131
-                foreach($top10multiancestors as $pid => $count) {
132
-                    $indi = Individual::getInstance($pid, $wt_tree);
133
-                    if($indi !== null && $indi->canShowName()) {
134
-                        array_key_exists($count, $top10ancestors) ?
135
-                            $top10ancestors[$count][] = $indi:
136
-                            $top10ancestors[$count] = array($count => $indi);
137
-                    }
138
-                }
139
-            }
140
-            $view_bag->set('top10multiancestors', $top10ancestors);
128
+			$top10multiancestors = $this->sosa_provider->getTopMultiSosaAncestorsNoTies(10);
129
+			$top10ancestors = array();
130
+			if($top10multiancestors !== null && count($top10multiancestors)) {
131
+				foreach($top10multiancestors as $pid => $count) {
132
+					$indi = Individual::getInstance($pid, $wt_tree);
133
+					if($indi !== null && $indi->canShowName()) {
134
+						array_key_exists($count, $top10ancestors) ?
135
+							$top10ancestors[$count][] = $indi:
136
+							$top10ancestors[$count] = array($count => $indi);
137
+					}
138
+				}
139
+			}
140
+			$view_bag->set('top10multiancestors', $top10ancestors);
141 141
             
142
-            $view_bag->set('chart_img_g2', $this->htmlAncestorDispersionG2());
143
-            $view_bag->set('chart_img_g3', $this->htmlAncestorDispersionG3());
142
+			$view_bag->set('chart_img_g2', $this->htmlAncestorDispersionG2());
143
+			$view_bag->set('chart_img_g3', $this->htmlAncestorDispersionG3());
144 144
             
145
-        }
145
+		}
146 146
         
147
-        ViewFactory::make('SosaStats', $this, $controller, $view_bag)->render();   
148
-    }
147
+		ViewFactory::make('SosaStats', $this, $controller, $view_bag)->render();   
148
+	}
149 149
     
150
-    /**
151
-     * Returns HTML code for a graph showing the dispersion of ancestors across father & mother
152
-     * @return string HTML code
153
-     */
154
-     private function htmlAncestorDispersionG2()
155
-    {
156
-        $ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(2);
157
-        if(count($ancestorsDispGen2) == 0) return;
150
+	/**
151
+	 * Returns HTML code for a graph showing the dispersion of ancestors across father & mother
152
+	 * @return string HTML code
153
+	 */
154
+	 private function htmlAncestorDispersionG2()
155
+	{
156
+		$ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(2);
157
+		if(count($ancestorsDispGen2) == 0) return;
158 158
         
159
-        $size = '600x300';
159
+		$size = '600x300';
160 160
         
161
-        $total = array_sum($ancestorsDispGen2);
162
-        $father_count = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
163
-        $father = array (
164
-            'color' => '84beff', 
165
-            'count' => $father_count, 
166
-            'perc' => Functions::safeDivision($father_count, $total), 
167
-            'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fat')            
168
-        );
169
-        $mother_count = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
170
-        $mother = array (
171
-            'color' => 'ffd1dc', 
172
-            'count' => $mother_count, 
173
-            'perc' => Functions::safeDivision($mother_count, $total),
174
-            'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('mot')
175
-        );
176
-        $shared_count = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
177
-        $shared = array (
178
-            'color' => '777777', 
179
-            'count' => $shared_count, 
180
-            'perc' => Functions::safeDivision($shared_count, $total),
181
-            'name' => I18N::translate('Shared')
182
-        );
161
+		$total = array_sum($ancestorsDispGen2);
162
+		$father_count = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
163
+		$father = array (
164
+			'color' => '84beff', 
165
+			'count' => $father_count, 
166
+			'perc' => Functions::safeDivision($father_count, $total), 
167
+			'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fat')            
168
+		);
169
+		$mother_count = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
170
+		$mother = array (
171
+			'color' => 'ffd1dc', 
172
+			'count' => $mother_count, 
173
+			'perc' => Functions::safeDivision($mother_count, $total),
174
+			'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('mot')
175
+		);
176
+		$shared_count = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
177
+		$shared = array (
178
+			'color' => '777777', 
179
+			'count' => $shared_count, 
180
+			'perc' => Functions::safeDivision($shared_count, $total),
181
+			'name' => I18N::translate('Shared')
182
+		);
183 183
         
184
-        $chd = $this->arrayToExtendedEncoding(array(4095 * $father['perc'], 4095 * $shared['perc'], 4095 * $mother['perc']));
185
-        $chart_title = I18N::translate('Known Sosa ancestors\' dispersion');
186
-        $chl = 
187
-             $father['name'] . ' - ' . I18N::percentage($father['perc'], 1) . '|' .
188
-             $shared['name'] . ' - ' . I18N::percentage($shared['perc'], 1) . '|' .
189
-             $mother['name'] . ' - ' . I18N::percentage($mother['perc'], 1);
190
-        return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$father['color']},{$shared['color']},{$mother['color']}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
191
-    }
184
+		$chd = $this->arrayToExtendedEncoding(array(4095 * $father['perc'], 4095 * $shared['perc'], 4095 * $mother['perc']));
185
+		$chart_title = I18N::translate('Known Sosa ancestors\' dispersion');
186
+		$chl = 
187
+			 $father['name'] . ' - ' . I18N::percentage($father['perc'], 1) . '|' .
188
+			 $shared['name'] . ' - ' . I18N::percentage($shared['perc'], 1) . '|' .
189
+			 $mother['name'] . ' - ' . I18N::percentage($mother['perc'], 1);
190
+		return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$father['color']},{$shared['color']},{$mother['color']}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
191
+	}
192 192
     
193
-    /**
194
-     * Returns HTML code for a graph showing the dispersion of ancestors across grand-parents
195
-     * @return string HTML code
196
-     */
197
-    private function htmlAncestorDispersionG3()
198
-    {
199
-        $ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(3);
193
+	/**
194
+	 * Returns HTML code for a graph showing the dispersion of ancestors across grand-parents
195
+	 * @return string HTML code
196
+	 */
197
+	private function htmlAncestorDispersionG3()
198
+	{
199
+		$ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(3);
200 200
         
201
-        $size = '700x300';
201
+		$size = '700x300';
202 202
         
203
-        $color_motmot = 'ffd1dc';
204
-        $color_motfat = 'b998a0';
205
-        $color_fatfat = '577292';
206
-        $color_fatmot = '84beff';
207
-        $color_shared = '777777';
203
+		$color_motmot = 'ffd1dc';
204
+		$color_motfat = 'b998a0';
205
+		$color_fatfat = '577292';
206
+		$color_fatmot = '84beff';
207
+		$color_shared = '777777';
208 208
     
209
-        $total_fatfat = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
210
-        $total_fatmot = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
211
-        $total_motfat = array_key_exists(4, $ancestorsDispGen2) ? $ancestorsDispGen2[4] : 0;
212
-        $total_motmot = array_key_exists(8, $ancestorsDispGen2) ? $ancestorsDispGen2[8] : 0;
213
-        $total_sha = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
214
-        $total = $total_fatfat + $total_fatmot + $total_motfat+ $total_motmot + $total_sha;
209
+		$total_fatfat = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
210
+		$total_fatmot = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
211
+		$total_motfat = array_key_exists(4, $ancestorsDispGen2) ? $ancestorsDispGen2[4] : 0;
212
+		$total_motmot = array_key_exists(8, $ancestorsDispGen2) ? $ancestorsDispGen2[8] : 0;
213
+		$total_sha = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
214
+		$total = $total_fatfat + $total_fatmot + $total_motfat+ $total_motmot + $total_sha;
215 215
     
216
-        $chd = $this->arrayToExtendedEncoding(array(
217
-	    4095 * Functions::safeDivision($total_fatfat, $total), 
218
-            4095 * Functions::safeDivision($total_fatmot, $total),
219
-            4095 * Functions::safeDivision($total_sha, $total), 
220
-            4095 * Functions::safeDivision($total_motfat, $total),
221
-            4095 * Functions::safeDivision($total_motmot, $total)          
222
-        ));
223
-        $chart_title = I18N::translate('Known Sosa ancestors\' dispersion - G3');
224
-        $chl =
225
-            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatfat, $total), 1) . '|' .
226
-            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatmot, $total), 1) . '|' .
227
-            I18N::translate('Shared') . ' - ' . I18N::percentage(Functions::safeDivision($total_sha, $total), 1) . '|' .
228
-            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_motfat, $total), 1) . '|' .
229
-            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_motmot, $total), 1);
230
-         return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$color_fatfat},{$color_fatmot},{$color_shared},{$color_motfat},{$color_motmot}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
231
-    }
216
+		$chd = $this->arrayToExtendedEncoding(array(
217
+		4095 * Functions::safeDivision($total_fatfat, $total), 
218
+			4095 * Functions::safeDivision($total_fatmot, $total),
219
+			4095 * Functions::safeDivision($total_sha, $total), 
220
+			4095 * Functions::safeDivision($total_motfat, $total),
221
+			4095 * Functions::safeDivision($total_motmot, $total)          
222
+		));
223
+		$chart_title = I18N::translate('Known Sosa ancestors\' dispersion - G3');
224
+		$chl =
225
+			\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatfat, $total), 1) . '|' .
226
+			\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatmot, $total), 1) . '|' .
227
+			I18N::translate('Shared') . ' - ' . I18N::percentage(Functions::safeDivision($total_sha, $total), 1) . '|' .
228
+			\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_motfat, $total), 1) . '|' .
229
+			\Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_motmot, $total), 1);
230
+		 return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$color_fatfat},{$color_fatmot},{$color_shared},{$color_motfat},{$color_motmot}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
231
+	}
232 232
 
233
-    /**
234
-     * Convert an array to Google Chart encoding
235
-     * @param arrat $a Array to encode
236
-     * @return string
237
-     */
238
-    private function arrayToExtendedEncoding($a) {
239
-        $xencoding = WT_GOOGLE_CHART_ENCODING;
233
+	/**
234
+	 * Convert an array to Google Chart encoding
235
+	 * @param arrat $a Array to encode
236
+	 * @return string
237
+	 */
238
+	private function arrayToExtendedEncoding($a) {
239
+		$xencoding = WT_GOOGLE_CHART_ENCODING;
240 240
     
241
-        $encoding = '';
242
-        foreach ($a as $value) {
243
-            if ($value < 0) {
244
-                $value = 0;
245
-            }
246
-            $first  = (int) ($value / 64);
247
-            $second = $value % 64;
248
-            $encoding .= $xencoding[(int) $first] . $xencoding[(int) $second];
249
-        }
241
+		$encoding = '';
242
+		foreach ($a as $value) {
243
+			if ($value < 0) {
244
+				$value = 0;
245
+			}
246
+			$first  = (int) ($value / 64);
247
+			$second = $value % 64;
248
+			$encoding .= $xencoding[(int) $first] . $xencoding[(int) $second];
249
+		}
250 250
     
251
-        return $encoding;
252
-    }
251
+		return $encoding;
252
+	}
253 253
     
254 254
     
255 255
 }
256 256
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +37 added lines, -38 removed lines patch added patch discarded remove patch
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
         $view_bag->set('title', $controller->getPageTitle());
63 63
         $view_bag->set('is_setup', false);
64 64
         
65
-        if($this->sosa_provider->isSetup()) {
65
+        if ($this->sosa_provider->isSetup()) {
66 66
             $view_bag->set('is_setup', true);
67 67
             
68 68
             $view_bag->set('root_indi', $this->sosa_provider->getRootIndi());
@@ -83,23 +83,23 @@  discard block
 block discarded – undo
83 83
             $view_bag->set('missinganc_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaList@missing&ged='.$wt_tree->getNameUrl().'&gen=');
84 84
             $view_bag->set('sosaanc_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaList&ged='.$wt_tree->getNameUrl().'&gen=');
85 85
             
86
-            $gen_theoretical=1;
87
-            $total_theoretical=0;
88
-            $prev_diff=0;
89
-            $prev_known=0.5;
90
-            $gen_equiv=0;            
86
+            $gen_theoretical = 1;
87
+            $total_theoretical = 0;
88
+            $prev_diff = 0;
89
+            $prev_known = 0.5;
90
+            $gen_equiv = 0;            
91 91
             $generation_stats = array();
92 92
             
93
-            foreach($stats_gen as $gen => $tab){
94
-                $genY1= I18N::translate('-');
95
-                $genY2= I18N::translate('-');
96
-                if($tab['firstBirth']>0) $genY1=$tab['firstEstimatedBirth'];
97
-                if($tab['lastBirth']>0) $genY2=$tab['lastEstimatedBirth'];
93
+            foreach ($stats_gen as $gen => $tab) {
94
+                $genY1 = I18N::translate('-');
95
+                $genY2 = I18N::translate('-');
96
+                if ($tab['firstBirth'] > 0) $genY1 = $tab['firstEstimatedBirth'];
97
+                if ($tab['lastBirth'] > 0) $genY2 = $tab['lastEstimatedBirth'];
98 98
                 $total_theoretical += $gen_theoretical;
99 99
                 $perc_sosa_count_theor = Functions::safeDivision($tab['sosaCount'], $gen_theoretical);
100 100
                 $gen_equiv += $perc_sosa_count_theor;
101
-                $missing=2*$prev_known - $tab['sosaCount'];
102
-                $gen_diff=$tab['diffSosaTotalCount']-$prev_diff;
101
+                $missing = 2 * $prev_known - $tab['sosaCount'];
102
+                $gen_diff = $tab['diffSosaTotalCount'] - $prev_diff;
103 103
                 
104 104
                 $generation_stats[$gen] = array(
105 105
                     'gen_min_birth' => $genY1,
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
                     'known' => $tab['sosaCount'],
109 109
                     'perc_known' => $perc_sosa_count_theor,
110 110
                     'missing' => $missing,
111
-                    'perc_missing' => 1-Functions::safeDivision($tab['sosaCount'], 2*$prev_known),
111
+                    'perc_missing' => 1 - Functions::safeDivision($tab['sosaCount'], 2 * $prev_known),
112 112
                     'total_known' => $tab['sosaTotalCount'],
113 113
                     'perc_total_known' => Functions::safeDivision($tab['sosaTotalCount'], $total_theoretical),
114 114
                     'different' => $gen_diff,
@@ -118,8 +118,8 @@  discard block
 block discarded – undo
118 118
                 );
119 119
                 
120 120
                 $gen_theoretical = $gen_theoretical * 2;
121
-                $prev_known=$tab['sosaCount'];
122
-                $prev_diff=$tab['diffSosaTotalCount'];
121
+                $prev_known = $tab['sosaCount'];
122
+                $prev_diff = $tab['diffSosaTotalCount'];
123 123
             }
124 124
             
125 125
             $view_bag->set('generation_stats', $generation_stats);
@@ -127,13 +127,12 @@  discard block
 block discarded – undo
127 127
             
128 128
             $top10multiancestors = $this->sosa_provider->getTopMultiSosaAncestorsNoTies(10);
129 129
             $top10ancestors = array();
130
-            if($top10multiancestors !== null && count($top10multiancestors)) {
131
-                foreach($top10multiancestors as $pid => $count) {
130
+            if ($top10multiancestors !== null && count($top10multiancestors)) {
131
+                foreach ($top10multiancestors as $pid => $count) {
132 132
                     $indi = Individual::getInstance($pid, $wt_tree);
133
-                    if($indi !== null && $indi->canShowName()) {
133
+                    if ($indi !== null && $indi->canShowName()) {
134 134
                         array_key_exists($count, $top10ancestors) ?
135
-                            $top10ancestors[$count][] = $indi:
136
-                            $top10ancestors[$count] = array($count => $indi);
135
+                            $top10ancestors[$count][] = $indi : $top10ancestors[$count] = array($count => $indi);
137 136
                     }
138 137
                 }
139 138
             }
@@ -154,27 +153,27 @@  discard block
 block discarded – undo
154 153
      private function htmlAncestorDispersionG2()
155 154
     {
156 155
         $ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(2);
157
-        if(count($ancestorsDispGen2) == 0) return;
156
+        if (count($ancestorsDispGen2) == 0) return;
158 157
         
159 158
         $size = '600x300';
160 159
         
161 160
         $total = array_sum($ancestorsDispGen2);
162 161
         $father_count = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
163
-        $father = array (
162
+        $father = array(
164 163
             'color' => '84beff', 
165 164
             'count' => $father_count, 
166 165
             'perc' => Functions::safeDivision($father_count, $total), 
167 166
             'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fat')            
168 167
         );
169 168
         $mother_count = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
170
-        $mother = array (
169
+        $mother = array(
171 170
             'color' => 'ffd1dc', 
172 171
             'count' => $mother_count, 
173 172
             'perc' => Functions::safeDivision($mother_count, $total),
174 173
             'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('mot')
175 174
         );
176 175
         $shared_count = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
177
-        $shared = array (
176
+        $shared = array(
178 177
             'color' => '777777', 
179 178
             'count' => $shared_count, 
180 179
             'perc' => Functions::safeDivision($shared_count, $total),
@@ -184,10 +183,10 @@  discard block
 block discarded – undo
184 183
         $chd = $this->arrayToExtendedEncoding(array(4095 * $father['perc'], 4095 * $shared['perc'], 4095 * $mother['perc']));
185 184
         $chart_title = I18N::translate('Known Sosa ancestors\' dispersion');
186 185
         $chl = 
187
-             $father['name'] . ' - ' . I18N::percentage($father['perc'], 1) . '|' .
188
-             $shared['name'] . ' - ' . I18N::percentage($shared['perc'], 1) . '|' .
189
-             $mother['name'] . ' - ' . I18N::percentage($mother['perc'], 1);
190
-        return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$father['color']},{$shared['color']},{$mother['color']}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
186
+             $father['name'].' - '.I18N::percentage($father['perc'], 1).'|'.
187
+             $shared['name'].' - '.I18N::percentage($shared['perc'], 1).'|'.
188
+             $mother['name'].' - '.I18N::percentage($mother['perc'], 1);
189
+        return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$father['color']},{$shared['color']},{$mother['color']}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"".$chart_title."\" title=\"".$chart_title."\" />";
191 190
     }
192 191
     
193 192
     /**
@@ -211,7 +210,7 @@  discard block
 block discarded – undo
211 210
         $total_motfat = array_key_exists(4, $ancestorsDispGen2) ? $ancestorsDispGen2[4] : 0;
212 211
         $total_motmot = array_key_exists(8, $ancestorsDispGen2) ? $ancestorsDispGen2[8] : 0;
213 212
         $total_sha = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
214
-        $total = $total_fatfat + $total_fatmot + $total_motfat+ $total_motmot + $total_sha;
213
+        $total = $total_fatfat + $total_fatmot + $total_motfat + $total_motmot + $total_sha;
215 214
     
216 215
         $chd = $this->arrayToExtendedEncoding(array(
217 216
 	    4095 * Functions::safeDivision($total_fatfat, $total), 
@@ -222,12 +221,12 @@  discard block
 block discarded – undo
222 221
         ));
223 222
         $chart_title = I18N::translate('Known Sosa ancestors\' dispersion - G3');
224 223
         $chl =
225
-            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatfat, $total), 1) . '|' .
226
-            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatmot, $total), 1) . '|' .
227
-            I18N::translate('Shared') . ' - ' . I18N::percentage(Functions::safeDivision($total_sha, $total), 1) . '|' .
228
-            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_motfat, $total), 1) . '|' .
229
-            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_motmot, $total), 1);
230
-         return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$color_fatfat},{$color_fatmot},{$color_shared},{$color_motfat},{$color_motmot}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
224
+            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatfat').' - '.I18N::percentage(Functions::safeDivision($total_fatfat, $total), 1).'|'.
225
+            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatmot').' - '.I18N::percentage(Functions::safeDivision($total_fatmot, $total), 1).'|'.
226
+            I18N::translate('Shared').' - '.I18N::percentage(Functions::safeDivision($total_sha, $total), 1).'|'.
227
+            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motfat').' - '.I18N::percentage(Functions::safeDivision($total_motfat, $total), 1).'|'.
228
+            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motmot').' - '.I18N::percentage(Functions::safeDivision($total_motmot, $total), 1);
229
+         return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$color_fatfat},{$color_fatmot},{$color_shared},{$color_motfat},{$color_motmot}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"".$chart_title."\" title=\"".$chart_title."\" />";
231 230
     }
232 231
 
233 232
     /**
@@ -243,9 +242,9 @@  discard block
 block discarded – undo
243 242
             if ($value < 0) {
244 243
                 $value = 0;
245 244
             }
246
-            $first  = (int) ($value / 64);
245
+            $first  = (int)($value / 64);
247 246
             $second = $value % 64;
248
-            $encoding .= $xencoding[(int) $first] . $xencoding[(int) $second];
247
+            $encoding .= $xencoding[(int)$first].$xencoding[(int)$second];
249 248
         }
250 249
     
251 250
         return $encoding;
Please login to merge, or discard this patch.
Braces   +9 added lines, -3 removed lines patch added patch discarded remove patch
@@ -93,8 +93,12 @@  discard block
 block discarded – undo
93 93
             foreach($stats_gen as $gen => $tab){
94 94
                 $genY1= I18N::translate('-');
95 95
                 $genY2= I18N::translate('-');
96
-                if($tab['firstBirth']>0) $genY1=$tab['firstEstimatedBirth'];
97
-                if($tab['lastBirth']>0) $genY2=$tab['lastEstimatedBirth'];
96
+                if($tab['firstBirth']>0) {
97
+                	$genY1=$tab['firstEstimatedBirth'];
98
+                }
99
+                if($tab['lastBirth']>0) {
100
+                	$genY2=$tab['lastEstimatedBirth'];
101
+                }
98 102
                 $total_theoretical += $gen_theoretical;
99 103
                 $perc_sosa_count_theor = Functions::safeDivision($tab['sosaCount'], $gen_theoretical);
100 104
                 $gen_equiv += $perc_sosa_count_theor;
@@ -154,7 +158,9 @@  discard block
 block discarded – undo
154 158
      private function htmlAncestorDispersionG2()
155 159
     {
156 160
         $ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(2);
157
-        if(count($ancestorsDispGen2) == 0) return;
161
+        if(count($ancestorsDispGen2) == 0) {
162
+        	return;
163
+        }
158 164
         
159 165
         $size = '600x300';
160 166
         
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Schema/Migration1.php 2 patches
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -22,9 +22,9 @@
 block discarded – undo
22 22
 	public function upgrade() {
23 23
 
24 24
 		Database::exec(
25
-		    'ALTER TABLE `##maj_sosa`' . 
26
-		    ' ADD COLUMN majs_birth_year_est SMALLINT NULL AFTER majs_birth_year,' .
27
-		    ' ADD COLUMN majs_death_year_est SMALLINT NULL AFTER majs_death_year'
25
+			'ALTER TABLE `##maj_sosa`' . 
26
+			' ADD COLUMN majs_birth_year_est SMALLINT NULL AFTER majs_birth_year,' .
27
+			' ADD COLUMN majs_death_year_est SMALLINT NULL AFTER majs_death_year'
28 28
 		);
29 29
 	}
30 30
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -22,8 +22,8 @@
 block discarded – undo
22 22
 	public function upgrade() {
23 23
 
24 24
 		Database::exec(
25
-		    'ALTER TABLE `##maj_sosa`' . 
26
-		    ' ADD COLUMN majs_birth_year_est SMALLINT NULL AFTER majs_birth_year,' .
25
+		    'ALTER TABLE `##maj_sosa`'. 
26
+		    ' ADD COLUMN majs_birth_year_est SMALLINT NULL AFTER majs_birth_year,'.
27 27
 		    ' ADD COLUMN majs_death_year_est SMALLINT NULL AFTER majs_death_year'
28 28
 		);
29 29
 	}
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Model/SosaProvider.php 3 patches
Indentation   +623 added lines, -623 removed lines patch added patch discarded remove patch
@@ -22,395 +22,395 @@  discard block
 block discarded – undo
22 22
  */
23 23
 class SosaProvider {
24 24
     
25
-    /**
26
-     * Maximum number of generation the database is able to hold.
27
-     * @var int MAX_DB_GENERATIONS
28
-     */
29
-    const MAX_DB_GENERATIONS = 64;
30
-    
31
-    /**
32
-     * System's default user (ID -1 in the database
33
-     * @var User $default_user
34
-     */
35
-    protected static $default_user;
36
-    
37
-    /**
38
-     * Reference user
39
-     * @var User $user
40
-     */
41
-    protected $user;
42
-    
43
-    /**
44
-     * Reference tree
45
-     * @var Tree $tree
46
-     */
47
-    protected $tree;
48
-    
49
-    /**
50
-     * Cached list of Sosa Individuals by generation
51
-     * Format: key = generation, value = array ( sosa => Individual ID)
52
-     * @var array $sosa_list_by_gen
53
-     */
54
-    protected $sosa_list_by_gen;
55
-    
56
-    /**
57
-     * Cached list of Sosa Families by generation
58
-     * Format: key = generation, value = array ( sosa => Family ID)
59
-     * @var unknown $sosa_fam_list_by_gen
60
-     */
61
-    protected $sosa_fam_list_by_gen;
62
-    
63
-    /**
64
-     * Cached array of statistics by generation
65
-     * Format:  key = generation, 
66
-     *          value = array(
67
-     *              sosaCount, sosaTotalCount, diffSosaTotalCount, firstBirth, lastBirth, avgBirth
68
-     *           )
69
-     * @var array $statistics_tab
70
-     */
71
-    protected $statistics_tab;
72
-    
73
-    /**
74
-     * Has the provider's initialisation completed
75
-     * @var bool $is_setup
76
-     */
77
-    protected $is_setup;
78
-    
79
-    /**
80
-     * Constructor for Sosa Provider.
81
-     * A provider is defined in relation to a specific tree and reference user.
82
-     * 
83
-     * @param Tree $tree
84
-     * @param User $user
85
-     */
86
-    public function __construct(Tree $tree, User $user = null) {
87
-        if(self::$default_user === null) 
88
-            self::$default_user = User::find(-1);
25
+	/**
26
+	 * Maximum number of generation the database is able to hold.
27
+	 * @var int MAX_DB_GENERATIONS
28
+	 */
29
+	const MAX_DB_GENERATIONS = 64;
30
+    
31
+	/**
32
+	 * System's default user (ID -1 in the database
33
+	 * @var User $default_user
34
+	 */
35
+	protected static $default_user;
36
+    
37
+	/**
38
+	 * Reference user
39
+	 * @var User $user
40
+	 */
41
+	protected $user;
42
+    
43
+	/**
44
+	 * Reference tree
45
+	 * @var Tree $tree
46
+	 */
47
+	protected $tree;
48
+    
49
+	/**
50
+	 * Cached list of Sosa Individuals by generation
51
+	 * Format: key = generation, value = array ( sosa => Individual ID)
52
+	 * @var array $sosa_list_by_gen
53
+	 */
54
+	protected $sosa_list_by_gen;
55
+    
56
+	/**
57
+	 * Cached list of Sosa Families by generation
58
+	 * Format: key = generation, value = array ( sosa => Family ID)
59
+	 * @var unknown $sosa_fam_list_by_gen
60
+	 */
61
+	protected $sosa_fam_list_by_gen;
62
+    
63
+	/**
64
+	 * Cached array of statistics by generation
65
+	 * Format:  key = generation, 
66
+	 *          value = array(
67
+	 *              sosaCount, sosaTotalCount, diffSosaTotalCount, firstBirth, lastBirth, avgBirth
68
+	 *           )
69
+	 * @var array $statistics_tab
70
+	 */
71
+	protected $statistics_tab;
72
+    
73
+	/**
74
+	 * Has the provider's initialisation completed
75
+	 * @var bool $is_setup
76
+	 */
77
+	protected $is_setup;
78
+    
79
+	/**
80
+	 * Constructor for Sosa Provider.
81
+	 * A provider is defined in relation to a specific tree and reference user.
82
+	 * 
83
+	 * @param Tree $tree
84
+	 * @param User $user
85
+	 */
86
+	public function __construct(Tree $tree, User $user = null) {
87
+		if(self::$default_user === null) 
88
+			self::$default_user = User::find(-1);
89 89
         
90
-        $this->tree = $tree;
91
-        $this->user = $user;
92
-        $this->is_setup = true;
93
-        if($this->user === null) $this->user = Auth::user();
94
-        if(strlen($this->user->getUserId()) == 0) $this->user = self::$default_user;
90
+		$this->tree = $tree;
91
+		$this->user = $user;
92
+		$this->is_setup = true;
93
+		if($this->user === null) $this->user = Auth::user();
94
+		if(strlen($this->user->getUserId()) == 0) $this->user = self::$default_user;
95 95
         
96
-        // Check if the user, or the default user, has a root already setup;
97
-        if(empty($this->getRootIndiId())) {
98
-            if($this->user == self::$default_user) {  // If the default user is not setup
99
-                $this->is_setup = false;
100
-            }
101
-            else {
102
-                $this->user = self::$default_user;
103
-                $this->is_setup = $this->getRootIndiId() === null;
104
-            }            
105
-        }
106
-    }
107
-    
108
-    /**
109
-     * Returns is the Provider has been successfully set up
110
-     * @return bool
111
-     */
112
-    public function isSetup() {
113
-        return $this->is_setup;
114
-    }
115
-    
116
-    /**
117
-     * Return the root individual ID for the reference tree and user.
118
-     * @return string Individual ID
119
-     */
120
-    public function getRootIndiId() {
121
-        return $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
122
-    }
123
-    
124
-    /**
125
-     * Return the root individual for the reference tree and user.
126
-     * @return Individual Individual
127
-     */
128
-    public function getRootIndi() {
129
-        $root_indi_id = $this->getRootIndiId();
130
-        if(!empty($root_indi_id)) {
131
-            return Individual::getInstance($root_indi_id, $this->tree);
132
-        }
133
-        return null;
134
-    }
96
+		// Check if the user, or the default user, has a root already setup;
97
+		if(empty($this->getRootIndiId())) {
98
+			if($this->user == self::$default_user) {  // If the default user is not setup
99
+				$this->is_setup = false;
100
+			}
101
+			else {
102
+				$this->user = self::$default_user;
103
+				$this->is_setup = $this->getRootIndiId() === null;
104
+			}            
105
+		}
106
+	}
107
+    
108
+	/**
109
+	 * Returns is the Provider has been successfully set up
110
+	 * @return bool
111
+	 */
112
+	public function isSetup() {
113
+		return $this->is_setup;
114
+	}
115
+    
116
+	/**
117
+	 * Return the root individual ID for the reference tree and user.
118
+	 * @return string Individual ID
119
+	 */
120
+	public function getRootIndiId() {
121
+		return $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
122
+	}
123
+    
124
+	/**
125
+	 * Return the root individual for the reference tree and user.
126
+	 * @return Individual Individual
127
+	 */
128
+	public function getRootIndi() {
129
+		$root_indi_id = $this->getRootIndiId();
130
+		if(!empty($root_indi_id)) {
131
+			return Individual::getInstance($root_indi_id, $this->tree);
132
+		}
133
+		return null;
134
+	}
135 135
        
136
-    /*****************
136
+	/*****************
137 137
      * DATA CRUD LAYER
138 138
      *****************/
139 139
     
140
-    /**
141
-     * Remove all Sosa entries related to the gedcom file and user
142
-     */
143
-    public function deleteAll() {
144
-        if(!$this->is_setup) return;
145
-        Database::prepare(
146
-            'DELETE FROM `##maj_sosa`'.
147
-            ' WHERE majs_gedcom_id= :tree_id and majs_user_id = :user_id ')
148
-            ->execute(array(
149
-                'tree_id' => $this->tree->getTreeId(), 
150
-                'user_id' => $this->user->getUserId()                
151
-            ));
152
-    }
153
-    
154
-    /**
155
-     * Remove all ancestors of a sosa number
156
-     * 
157
-     * @param int $sosa
158
-     */
159
-    public function deleteAncestors($sosa) {
160
-        if(!$this->is_setup) return;
161
-        $gen = Functions::getGeneration($sosa);
162
-        Database::prepare(
163
-            'DELETE FROM `##maj_sosa`'.
164
-            ' WHERE majs_gedcom_id=:tree_id and majs_user_id = :user_id' .
165
-            ' AND majs_gen >= :gen' .
166
-            ' AND FLOOR(majs_sosa / (POW(2, (majs_gen - :gen)))) = :sosa'
167
-        )->execute(array(
168
-            'tree_id' => $this->tree->getTreeId(), 
169
-            'user_id' => $this->user->getUserId(),
170
-            'gen' => $gen,
171
-            'sosa' => $sosa
172
-        ));
173
-    }    
174
-    
175
-    /**
176
-     * Insert (or update if already existing) a list of Sosa individuals
177
-     * @param array $sosa_records
178
-     */
179
-    public function insertOrUpdate($sosa_records) {
180
-        if(!$this->is_setup) return;
140
+	/**
141
+	 * Remove all Sosa entries related to the gedcom file and user
142
+	 */
143
+	public function deleteAll() {
144
+		if(!$this->is_setup) return;
145
+		Database::prepare(
146
+			'DELETE FROM `##maj_sosa`'.
147
+			' WHERE majs_gedcom_id= :tree_id and majs_user_id = :user_id ')
148
+			->execute(array(
149
+				'tree_id' => $this->tree->getTreeId(), 
150
+				'user_id' => $this->user->getUserId()                
151
+			));
152
+	}
153
+    
154
+	/**
155
+	 * Remove all ancestors of a sosa number
156
+	 * 
157
+	 * @param int $sosa
158
+	 */
159
+	public function deleteAncestors($sosa) {
160
+		if(!$this->is_setup) return;
161
+		$gen = Functions::getGeneration($sosa);
162
+		Database::prepare(
163
+			'DELETE FROM `##maj_sosa`'.
164
+			' WHERE majs_gedcom_id=:tree_id and majs_user_id = :user_id' .
165
+			' AND majs_gen >= :gen' .
166
+			' AND FLOOR(majs_sosa / (POW(2, (majs_gen - :gen)))) = :sosa'
167
+		)->execute(array(
168
+			'tree_id' => $this->tree->getTreeId(), 
169
+			'user_id' => $this->user->getUserId(),
170
+			'gen' => $gen,
171
+			'sosa' => $sosa
172
+		));
173
+	}    
174
+    
175
+	/**
176
+	 * Insert (or update if already existing) a list of Sosa individuals
177
+	 * @param array $sosa_records
178
+	 */
179
+	public function insertOrUpdate($sosa_records) {
180
+		if(!$this->is_setup) return;
181 181
         
182
-        $treeid = $this->tree->getTreeId();
183
-        $userid = $this->user->getUserId();
184
-        $questionmarks_table = array();
185
-        $values_table = array();
182
+		$treeid = $this->tree->getTreeId();
183
+		$userid = $this->user->getUserId();
184
+		$questionmarks_table = array();
185
+		$values_table = array();
186 186
         
187
-        $i = 0;
188
-        foreach  ($sosa_records as $row) {
189
-            $gen = Functions::getGeneration($row['sosa']);
190
-            if($gen <= self::MAX_DB_GENERATIONS) {
191
-                $questionmarks_table[] = 
192
-                    '(:tree_id'.$i.', :user_id'.$i.', :sosa'.$i.', :indi_id'.$i.', :gen'.$i.', :byear'.$i.', :byearest'.$i.', :dyear'.$i.', :dyearest'.$i.')';
193
-                $values_table = array_merge(
194
-                    $values_table, 
195
-                    array(
196
-                        'tree_id'.$i => $treeid, 
197
-                        'user_id'.$i => $userid, 
198
-                        'sosa'.$i => $row['sosa'], 
199
-                        'indi_id'.$i => $row['indi'], 
200
-                        'gen'.$i => Functions::getGeneration($row['sosa']),
201
-                        'byear'.$i => $row['birth_year'],
202
-                        'byearest'.$i => $row['birth_year_est'],
203
-                        'dyear'.$i => $row['death_year'],
204
-                        'dyearest'.$i => $row['death_year_est']
205
-                    )
206
-                );
207
-            }
208
-            $i++;
209
-        }
187
+		$i = 0;
188
+		foreach  ($sosa_records as $row) {
189
+			$gen = Functions::getGeneration($row['sosa']);
190
+			if($gen <= self::MAX_DB_GENERATIONS) {
191
+				$questionmarks_table[] = 
192
+					'(:tree_id'.$i.', :user_id'.$i.', :sosa'.$i.', :indi_id'.$i.', :gen'.$i.', :byear'.$i.', :byearest'.$i.', :dyear'.$i.', :dyearest'.$i.')';
193
+				$values_table = array_merge(
194
+					$values_table, 
195
+					array(
196
+						'tree_id'.$i => $treeid, 
197
+						'user_id'.$i => $userid, 
198
+						'sosa'.$i => $row['sosa'], 
199
+						'indi_id'.$i => $row['indi'], 
200
+						'gen'.$i => Functions::getGeneration($row['sosa']),
201
+						'byear'.$i => $row['birth_year'],
202
+						'byearest'.$i => $row['birth_year_est'],
203
+						'dyear'.$i => $row['death_year'],
204
+						'dyearest'.$i => $row['death_year_est']
205
+					)
206
+				);
207
+			}
208
+			$i++;
209
+		}
210 210
         
211
-        $sql = 'REPLACE INTO `##maj_sosa`' .
212
-            ' (majs_gedcom_id, majs_user_id, majs_sosa, majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)' .
213
-            ' VALUES '. implode(',', $questionmarks_table);
214
-        Database::prepare($sql)->execute($values_table);
215
-    }
211
+		$sql = 'REPLACE INTO `##maj_sosa`' .
212
+			' (majs_gedcom_id, majs_user_id, majs_sosa, majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)' .
213
+			' VALUES '. implode(',', $questionmarks_table);
214
+		Database::prepare($sql)->execute($values_table);
215
+	}
216 216
     
217
-    /****************
217
+	/****************
218 218
      * SIMPLE QUERIES
219 219
      ****************/
220 220
     
221
-    /**
222
-     * Returns the list of Sosa numbers to which an individual is related.
223
-     * Format: key = sosa number, value = generation for the Sosa number
224
-     * 
225
-     * @param Individual $indi
226
-     * @return array Array of sosa numbers
227
-     */
228
-    public function getSosaNumbers(Individual $indi) {
229
-        if(!$this->is_setup) return array();
230
-        return Database::prepare(
231
-                'SELECT majs_sosa, majs_gen FROM `##maj_sosa`'.
232
-                ' WHERE majs_i_id=:indi_id AND majs_gedcom_id=:tree_id AND majs_user_id=:user_id'
233
-            )->execute(array(
234
-                'indi_id' => $indi->getXref(), 
235
-                'tree_id' => $this->tree->getTreeId(), 
236
-                'user_id' => $this->user->getUserId()
237
-            ))->fetchAssoc();
238
-    }
239
-    
240
-    /**
241
-     * Get the last generation of Sosa ancestors
242
-     *
243
-     * @return number Last generation if found, 1 otherwise
244
-     */
245
-    public function getLastGeneration() {
246
-        if(!$this->is_setup) return;
247
-        return Database::prepare(
248
-                'SELECT MAX(majs_gen) FROM `##maj_sosa`'.
249
-                ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'
250
-            )->execute(array(
251
-                'tree_id' => $this->tree->getTreeId(), 
252
-                'user_id' => $this->user->getUserId()                
253
-            ))->fetchOne() ?: 1;
254
-    }
255
-    
256
-    /*************
221
+	/**
222
+	 * Returns the list of Sosa numbers to which an individual is related.
223
+	 * Format: key = sosa number, value = generation for the Sosa number
224
+	 * 
225
+	 * @param Individual $indi
226
+	 * @return array Array of sosa numbers
227
+	 */
228
+	public function getSosaNumbers(Individual $indi) {
229
+		if(!$this->is_setup) return array();
230
+		return Database::prepare(
231
+				'SELECT majs_sosa, majs_gen FROM `##maj_sosa`'.
232
+				' WHERE majs_i_id=:indi_id AND majs_gedcom_id=:tree_id AND majs_user_id=:user_id'
233
+			)->execute(array(
234
+				'indi_id' => $indi->getXref(), 
235
+				'tree_id' => $this->tree->getTreeId(), 
236
+				'user_id' => $this->user->getUserId()
237
+			))->fetchAssoc();
238
+	}
239
+    
240
+	/**
241
+	 * Get the last generation of Sosa ancestors
242
+	 *
243
+	 * @return number Last generation if found, 1 otherwise
244
+	 */
245
+	public function getLastGeneration() {
246
+		if(!$this->is_setup) return;
247
+		return Database::prepare(
248
+				'SELECT MAX(majs_gen) FROM `##maj_sosa`'.
249
+				' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'
250
+			)->execute(array(
251
+				'tree_id' => $this->tree->getTreeId(), 
252
+				'user_id' => $this->user->getUserId()                
253
+			))->fetchOne() ?: 1;
254
+	}
255
+    
256
+	/*************
257 257
      * SOSA LISTS
258 258
      *************/
259 259
     
260
-    /**
261
-     * Return the list of all sosas, with the generations it belongs to
262
-     *
263
-     * @return array Associative array of Sosa ancestors, with their generation, comma separated
264
-     */
265
-    public function getAllSosaWithGenerations(){
266
-        if(!$this->is_setup) return array();
267
-        return Database::prepare(
268
-            'SELECT majs_i_id AS indi,' .
269
-            ' GROUP_CONCAT(DISTINCT majs_gen ORDER BY majs_gen ASC SEPARATOR ",") AS generations' .
270
-            ' FROM `##maj_sosa`' .
271
-            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id' .
272
-            ' GROUP BY majs_i_id'
273
-        )->execute(array(
274
-            'tree_id' => $this->tree->getTreeId(),
275
-            'user_id' => $this->user->getUserId()
276
-        ))->fetchAssoc();
277
-    }
278
-    
279
-    /**
280
-     * Get an associative array of Sosa individuals in generation G. Keys are Sosa numbers, values individuals.
281
-     *
282
-     * @param number $gen Generation
283
-     * @return array Array of Sosa individuals
284
-     */
285
-    public function getSosaListAtGeneration($gen){
286
-        if(!$this->is_setup) return array();
287
-        if(!$this->sosa_list_by_gen)
288
-            $this->sosa_list_by_gen = array();
260
+	/**
261
+	 * Return the list of all sosas, with the generations it belongs to
262
+	 *
263
+	 * @return array Associative array of Sosa ancestors, with their generation, comma separated
264
+	 */
265
+	public function getAllSosaWithGenerations(){
266
+		if(!$this->is_setup) return array();
267
+		return Database::prepare(
268
+			'SELECT majs_i_id AS indi,' .
269
+			' GROUP_CONCAT(DISTINCT majs_gen ORDER BY majs_gen ASC SEPARATOR ",") AS generations' .
270
+			' FROM `##maj_sosa`' .
271
+			' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id' .
272
+			' GROUP BY majs_i_id'
273
+		)->execute(array(
274
+			'tree_id' => $this->tree->getTreeId(),
275
+			'user_id' => $this->user->getUserId()
276
+		))->fetchAssoc();
277
+	}
278
+    
279
+	/**
280
+	 * Get an associative array of Sosa individuals in generation G. Keys are Sosa numbers, values individuals.
281
+	 *
282
+	 * @param number $gen Generation
283
+	 * @return array Array of Sosa individuals
284
+	 */
285
+	public function getSosaListAtGeneration($gen){
286
+		if(!$this->is_setup) return array();
287
+		if(!$this->sosa_list_by_gen)
288
+			$this->sosa_list_by_gen = array();
289 289
         
290
-        if($gen){
291
-            if(!isset($this->sosa_list_by_gen[$gen])){
292
-                $this->sosa_list_by_gen[$gen] = Database::prepare(
293
-                    'SELECT majs_sosa AS sosa, majs_i_id AS indi'.
294
-                    ' FROM `##maj_sosa`'.
295
-                    ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
296
-                    ' AND majs_gen = :gen'.
297
-                    ' ORDER BY majs_sosa ASC')
298
-                ->execute(array(
299
-                    'tree_id' => $this->tree->getTreeId(),
300
-                    'user_id' => $this->user->getUserId(),
301
-                    'gen' => $gen
302
-                ))
303
-                ->fetchAssoc();
304
-            }
305
-            return $this->sosa_list_by_gen[$gen];
306
-        }
307
-        return array();
308
-    }
309
-    
310
-    /**
311
-     * Get an associative array of Sosa families in generation G. Keys are Sosa numbers for the husband, values families.
312
-     *
313
-     * @param number $gen Generation
314
-     * @return array Array of Sosa families
315
-     */
316
-    public function getFamilySosaListAtGeneration($gen){
317
-        if(!$this->is_setup) return array();
318
-        if(!$this->sosa_fam_list_by_gen)
319
-            $this->sosa_fam_list_by_gen = array();
290
+		if($gen){
291
+			if(!isset($this->sosa_list_by_gen[$gen])){
292
+				$this->sosa_list_by_gen[$gen] = Database::prepare(
293
+					'SELECT majs_sosa AS sosa, majs_i_id AS indi'.
294
+					' FROM `##maj_sosa`'.
295
+					' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
296
+					' AND majs_gen = :gen'.
297
+					' ORDER BY majs_sosa ASC')
298
+				->execute(array(
299
+					'tree_id' => $this->tree->getTreeId(),
300
+					'user_id' => $this->user->getUserId(),
301
+					'gen' => $gen
302
+				))
303
+				->fetchAssoc();
304
+			}
305
+			return $this->sosa_list_by_gen[$gen];
306
+		}
307
+		return array();
308
+	}
309
+    
310
+	/**
311
+	 * Get an associative array of Sosa families in generation G. Keys are Sosa numbers for the husband, values families.
312
+	 *
313
+	 * @param number $gen Generation
314
+	 * @return array Array of Sosa families
315
+	 */
316
+	public function getFamilySosaListAtGeneration($gen){
317
+		if(!$this->is_setup) return array();
318
+		if(!$this->sosa_fam_list_by_gen)
319
+			$this->sosa_fam_list_by_gen = array();
320 320
         
321
-        if($gen){
322
-            if(!isset($this->sosa_fam_list_by_gen[$gen])){
323
-                $this->sosa_fam_list_by_gen[$gen] = Database::prepare(
324
-                    'SELECT s1.majs_sosa AS sosa, f_id AS fam'.
325
-                    ' FROM `##families`'.
326
-                    ' INNER JOIN `##maj_sosa` AS s1 ON (`##families`.f_husb = s1.majs_i_id AND `##families`.f_file = s1.majs_gedcom_id)'.
327
-                    ' INNER JOIN `##maj_sosa` AS s2 ON (`##families`.f_wife = s2.majs_i_id AND `##families`.f_file = s2.majs_gedcom_id)'.
328
-                    ' WHERE s1.majs_sosa + 1 = s2.majs_sosa'.
329
-                    ' AND s1.majs_gedcom_id= :tree_id AND s1.majs_user_id=:user_id'.
330
-                    ' AND s2.majs_gedcom_id= :tree_id AND s2.majs_user_id=:user_id'.
331
-                    ' AND s1.majs_gen = :gen'.
332
-                    ' ORDER BY s1.majs_sosa ASC'
333
-                    )
334
-                    ->execute(array(
335
-                        'tree_id' => $this->tree->getTreeId(),
336
-                        'user_id' => $this->user->getUserId(),
337
-                        'gen' => $gen
338
-                    ))
339
-                    ->fetchAssoc();
340
-            }
341
-            return $this->sosa_fam_list_by_gen[$gen];
342
-        }
343
-        return array();
344
-    }
345
-    
346
-    /**
347
-     * Get an associative array of Sosa individuals in generation G who are missing parents. Keys are Sosa numbers, values individuals.
348
-     *
349
-     * @param number $gen Generation
350
-     * @return array Array of Sosa individuals
351
-     */
352
-    public function getMissingSosaListAtGeneration($gen){
353
-        if(!$this->is_setup) return array();    
354
-        if($gen){
355
-            return $this->sosa_list_by_gen[$gen] = Database::prepare(
356
-                'SELECT schild.majs_sosa sosa, schild.majs_i_id indi, sfat.majs_sosa IS NOT NULL has_father, smot.majs_sosa IS NOT NULL has_mother'.
357
-                ' FROM `##maj_sosa` schild'.
358
-                ' LEFT JOIN `##maj_sosa` sfat ON ((schild.majs_sosa * 2) = sfat.majs_sosa AND schild.majs_gedcom_id = sfat.majs_gedcom_id AND schild.majs_user_id = sfat.majs_user_id)'.
359
-                ' LEFT JOIN `##maj_sosa` smot ON ((schild.majs_sosa * 2 + 1) = smot.majs_sosa AND schild.majs_gedcom_id = smot.majs_gedcom_id AND schild.majs_user_id = smot.majs_user_id)'.
360
-                ' WHERE schild.majs_gedcom_id = :tree_id AND schild.majs_user_id = :user_id'.
361
-                ' AND schild.majs_gen = :gen'.
362
-                ' AND (sfat.majs_sosa IS NULL OR smot.majs_sosa IS NULL)'.
363
-                ' ORDER BY schild.majs_sosa ASC')
364
-                ->execute(array(
365
-                    'tree_id' => $this->tree->getTreeId(),
366
-                    'user_id' => $this->user->getUserId(),
367
-                    'gen' => $gen - 1
368
-                ))->fetchAll(\PDO::FETCH_ASSOC);
369
-        }
370
-        return array();
371
-    }
372
-    
373
-    
374
-    
375
-    /*************
321
+		if($gen){
322
+			if(!isset($this->sosa_fam_list_by_gen[$gen])){
323
+				$this->sosa_fam_list_by_gen[$gen] = Database::prepare(
324
+					'SELECT s1.majs_sosa AS sosa, f_id AS fam'.
325
+					' FROM `##families`'.
326
+					' INNER JOIN `##maj_sosa` AS s1 ON (`##families`.f_husb = s1.majs_i_id AND `##families`.f_file = s1.majs_gedcom_id)'.
327
+					' INNER JOIN `##maj_sosa` AS s2 ON (`##families`.f_wife = s2.majs_i_id AND `##families`.f_file = s2.majs_gedcom_id)'.
328
+					' WHERE s1.majs_sosa + 1 = s2.majs_sosa'.
329
+					' AND s1.majs_gedcom_id= :tree_id AND s1.majs_user_id=:user_id'.
330
+					' AND s2.majs_gedcom_id= :tree_id AND s2.majs_user_id=:user_id'.
331
+					' AND s1.majs_gen = :gen'.
332
+					' ORDER BY s1.majs_sosa ASC'
333
+					)
334
+					->execute(array(
335
+						'tree_id' => $this->tree->getTreeId(),
336
+						'user_id' => $this->user->getUserId(),
337
+						'gen' => $gen
338
+					))
339
+					->fetchAssoc();
340
+			}
341
+			return $this->sosa_fam_list_by_gen[$gen];
342
+		}
343
+		return array();
344
+	}
345
+    
346
+	/**
347
+	 * Get an associative array of Sosa individuals in generation G who are missing parents. Keys are Sosa numbers, values individuals.
348
+	 *
349
+	 * @param number $gen Generation
350
+	 * @return array Array of Sosa individuals
351
+	 */
352
+	public function getMissingSosaListAtGeneration($gen){
353
+		if(!$this->is_setup) return array();    
354
+		if($gen){
355
+			return $this->sosa_list_by_gen[$gen] = Database::prepare(
356
+				'SELECT schild.majs_sosa sosa, schild.majs_i_id indi, sfat.majs_sosa IS NOT NULL has_father, smot.majs_sosa IS NOT NULL has_mother'.
357
+				' FROM `##maj_sosa` schild'.
358
+				' LEFT JOIN `##maj_sosa` sfat ON ((schild.majs_sosa * 2) = sfat.majs_sosa AND schild.majs_gedcom_id = sfat.majs_gedcom_id AND schild.majs_user_id = sfat.majs_user_id)'.
359
+				' LEFT JOIN `##maj_sosa` smot ON ((schild.majs_sosa * 2 + 1) = smot.majs_sosa AND schild.majs_gedcom_id = smot.majs_gedcom_id AND schild.majs_user_id = smot.majs_user_id)'.
360
+				' WHERE schild.majs_gedcom_id = :tree_id AND schild.majs_user_id = :user_id'.
361
+				' AND schild.majs_gen = :gen'.
362
+				' AND (sfat.majs_sosa IS NULL OR smot.majs_sosa IS NULL)'.
363
+				' ORDER BY schild.majs_sosa ASC')
364
+				->execute(array(
365
+					'tree_id' => $this->tree->getTreeId(),
366
+					'user_id' => $this->user->getUserId(),
367
+					'gen' => $gen - 1
368
+				))->fetchAll(\PDO::FETCH_ASSOC);
369
+		}
370
+		return array();
371
+	}
372
+    
373
+    
374
+    
375
+	/*************
376 376
      * STATISTICS
377 377
      *************/
378
-    /**
379
-     * Get the statistic array detailed by generation.
380
-     * Statistics for each generation are:
381
-     * 	- The number of Sosa in generation
382
-     * 	- The number of Sosa up to generation
383
-     *  - The number of distinct Sosa up to generation
384
-     *  - The year of the first birth in generation
385
-     *  - The year of the first estimated birth in generation
386
-     *  - The year of the last birth in generation
387
-     *  - The year of the last estimated birth in generation
388
-     *  - The average year of birth in generation
389
-     *
390
-     * @return array Statistics array
391
-     */
392
-    public function getStatisticsByGeneration() {
393
-        if(!$this->is_setup) return array();
394
-        if(!$this->statistics_tab) {
395
-            $this->statistics_tab = array();
396
-            if($maxGeneration = $this->getLastGeneration()) {
397
-                for ($gen = 1; $gen <= $maxGeneration; $gen++) {
398
-                    $birthStats = $this->getStatsBirthYearInGeneration($gen);
399
-                    $this->statistics_tab[$gen] = array(
400
-                        'sosaCount'				=>	$this->getSosaCountAtGeneration($gen),
401
-                        'sosaTotalCount'		=>	$this->getSosaCountUpToGeneration($gen),
402
-                        'diffSosaTotalCount'	=>	$this->getDifferentSosaCountUpToGeneration($gen),
403
-                        'firstBirth'			=>	$birthStats['first'],
404
-                        'firstEstimatedBirth'	=>	$birthStats['first_est'],
405
-                        'lastBirth'				=>	$birthStats['last'],
406
-                        'lastEstimatedBirth'	=>	$birthStats['last_est'],
407
-                        'avgBirth'				=>	$birthStats['avg']
408
-                    );
409
-                }
410
-            }
411
-        }
412
-        return $this->statistics_tab;        
413
-    }
378
+	/**
379
+	 * Get the statistic array detailed by generation.
380
+	 * Statistics for each generation are:
381
+	 * 	- The number of Sosa in generation
382
+	 * 	- The number of Sosa up to generation
383
+	 *  - The number of distinct Sosa up to generation
384
+	 *  - The year of the first birth in generation
385
+	 *  - The year of the first estimated birth in generation
386
+	 *  - The year of the last birth in generation
387
+	 *  - The year of the last estimated birth in generation
388
+	 *  - The average year of birth in generation
389
+	 *
390
+	 * @return array Statistics array
391
+	 */
392
+	public function getStatisticsByGeneration() {
393
+		if(!$this->is_setup) return array();
394
+		if(!$this->statistics_tab) {
395
+			$this->statistics_tab = array();
396
+			if($maxGeneration = $this->getLastGeneration()) {
397
+				for ($gen = 1; $gen <= $maxGeneration; $gen++) {
398
+					$birthStats = $this->getStatsBirthYearInGeneration($gen);
399
+					$this->statistics_tab[$gen] = array(
400
+						'sosaCount'				=>	$this->getSosaCountAtGeneration($gen),
401
+						'sosaTotalCount'		=>	$this->getSosaCountUpToGeneration($gen),
402
+						'diffSosaTotalCount'	=>	$this->getDifferentSosaCountUpToGeneration($gen),
403
+						'firstBirth'			=>	$birthStats['first'],
404
+						'firstEstimatedBirth'	=>	$birthStats['first_est'],
405
+						'lastBirth'				=>	$birthStats['last'],
406
+						'lastEstimatedBirth'	=>	$birthStats['last_est'],
407
+						'avgBirth'				=>	$birthStats['avg']
408
+					);
409
+				}
410
+			}
411
+		}
412
+		return $this->statistics_tab;        
413
+	}
414 414
     
415 415
 	/**
416 416
 	 * How many individuals exist in the tree.
@@ -418,262 +418,262 @@  discard block
 block discarded – undo
418 418
 	 * @return int
419 419
 	 */
420 420
 	public function getTotalIndividuals() {
421
-	    if(!$this->is_setup) return 0;
422
-	    return Database::prepare(
423
-	        'SELECT COUNT(*) FROM `##individuals`' .
424
-	        ' WHERE i_file = :tree_id')
425
-	        ->execute(array('tree_id' => $this->tree->getTreeId()))
426
-	        ->fetchOne() ?: 0;
421
+		if(!$this->is_setup) return 0;
422
+		return Database::prepare(
423
+			'SELECT COUNT(*) FROM `##individuals`' .
424
+			' WHERE i_file = :tree_id')
425
+			->execute(array('tree_id' => $this->tree->getTreeId()))
426
+			->fetchOne() ?: 0;
427
+	}
428
+    
429
+	/**
430
+	 * Get the total Sosa count for all generations
431
+	 *
432
+	 * @return number Number of Sosas
433
+	 */
434
+	public function getSosaCount(){
435
+		if(!$this->is_setup) return 0;
436
+		return Database::prepare(
437
+			'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
438
+			' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
439
+			->execute(array(
440
+				'tree_id' => $this->tree->getTreeId(), 
441
+				'user_id' => $this->user->getUserId() 
442
+			))->fetchOne() ?: 0;
443
+	}
444
+    
445
+	/**
446
+	 * Get the number of Sosa in a specific generation.
447
+	 *
448
+	 * @param number $gen Generation
449
+	 * @return number Number of Sosas in generation
450
+	 */
451
+	public function getSosaCountAtGeneration($gen){
452
+		if(!$this->is_setup) return 0;
453
+		return Database::prepare(
454
+			'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
455
+			' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
456
+			' AND majs_gen= :gen')
457
+		->execute(array(
458
+				'tree_id' => $this->tree->getTreeId(), 
459
+				'user_id' => $this->user->getUserId(),
460
+				'gen' => $gen            
461
+		))->fetchOne() ?: 0;
427 462
 	}
428 463
     
429
-    /**
430
-     * Get the total Sosa count for all generations
431
-     *
432
-     * @return number Number of Sosas
433
-     */
434
-    public function getSosaCount(){
435
-        if(!$this->is_setup) return 0;
436
-        return Database::prepare(
437
-            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
438
-            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
439
-            ->execute(array(
440
-                'tree_id' => $this->tree->getTreeId(), 
441
-                'user_id' => $this->user->getUserId() 
442
-            ))->fetchOne() ?: 0;
443
-    }
444
-    
445
-    /**
446
-     * Get the number of Sosa in a specific generation.
447
-     *
448
-     * @param number $gen Generation
449
-     * @return number Number of Sosas in generation
450
-     */
451
-    public function getSosaCountAtGeneration($gen){
452
-        if(!$this->is_setup) return 0;
453
-        return Database::prepare(
454
-            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
455
-            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
456
-            ' AND majs_gen= :gen')
457
-        ->execute(array(
458
-                'tree_id' => $this->tree->getTreeId(), 
459
-                'user_id' => $this->user->getUserId(),
460
-                'gen' => $gen            
461
-        ))->fetchOne() ?: 0;
462
-    }
463
-    
464
-    /**
465
-     * Get the total number of Sosa up to a specific generation.
466
-     *
467
-     * @param number $gen Generation
468
-     * @return number Total number of Sosas up to generation
469
-     */
470
-    public function getSosaCountUpToGeneration($gen){
471
-        if(!$this->is_setup) return 0;
472
-        return Database::prepare(
473
-            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
474
-            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
475
-            ' AND majs_gen <= :gen')
476
-        ->execute(array(
477
-                'tree_id' => $this->tree->getTreeId(), 
478
-                'user_id' => $this->user->getUserId(),
479
-                'gen' => $gen 
480
-        ))->fetchOne() ?: 0;
481
-    }
482
-    
483
-    /**
484
-     * Get the total number of distinct Sosa individual for all generations.
485
-     *
486
-     * @return number Total number of distinct individual
487
-     */
488
-    public function getDifferentSosaCount(){
489
-        if(!$this->is_setup) return 0;
490
-        return Database::prepare(
491
-            'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
492
-            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
493
-        ->execute(array(
494
-                'tree_id' => $this->tree->getTreeId(), 
495
-                'user_id' => $this->user->getUserId()
496
-        ))->fetchOne() ?: 0;
497
-    }
498
-    
499
-    /**
500
-     * Get the number of distinct Sosa individual up to a specific generation.
501
-     *
502
-     * @param number $gen Generation
503
-     * @return number Number of distinct Sosa individuals up to generation
504
-     */
505
-    public function getDifferentSosaCountUpToGeneration($gen){
506
-        if(!$this->is_setup) return 0;
507
-        return Database::prepare(
508
-            'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
509
-            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
510
-            ' AND majs_gen <= :gen')
511
-        ->execute(array(
512
-                'tree_id' => $this->tree->getTreeId(), 
513
-                'user_id' => $this->user->getUserId(),
514
-                'gen' => $gen 
515
-        ))->fetchOne() ?: 0;
516
-    }
517
-    
518
-    /**
519
-     * Get an array of birth statistics for a specific generation
520
-     * Statistics are :
521
-     * 	- first : First birth year in generation
522
-     *  - first_est: First estimated birth year in generation
523
-     *  - last : Last birth year in generation
524
-     *  - last_est : Last estimated birth year in generation
525
-     *  - avg : Average birth year (based on non-estimated birth date)
526
-     *
527
-     * @param number $gen Generation
528
-     * @return array Birth statistics array
529
-     */
530
-    public function getStatsBirthYearInGeneration($gen){
531
-        if(!$this->is_setup) return array('first' => 0, 'first_est' => 0, 'avg' => 0, 'last' => 0, 'last_est' => 0);
532
-        return Database::prepare(
533
-            'SELECT'.
534
-            ' MIN(majs_birth_year) AS first, MIN(majs_birth_year_est) AS first_est,'.
535
-            ' AVG(majs_birth_year) AS avg,'.
536
-            ' MAX(majs_birth_year) AS last, MAX(majs_birth_year_est) AS last_est'.
537
-            ' FROM `##maj_sosa`'.
538
-            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
539
-            ' AND majs_gen=:gen')
540
-            ->execute(array(
541
-                'tree_id' => $this->tree->getTreeId(), 
542
-                'user_id' => $this->user->getUserId(),
543
-                'gen' => $gen))
544
-            ->fetchOneRow(\PDO::FETCH_ASSOC) ?: array('first' => 0, 'first_est' => 0, 'avg' => 0, 'last' => 0, 'last_est' => 0);
545
-    }
546
-    
547
-    /**
548
-     * Get the mean generation time, based on a linear regression of birth years and generations
549
-     *
550
-     * @return number|NULL Mean generation time
551
-     */
552
-    public function getMeanGenerationTime(){
553
-        if(!$this->is_setup) return;
554
-        if(!$this->statistics_tab){
555
-            $this->getStatisticsByGeneration();
556
-        }
557
-        //Linear regression on x=generation and y=birthdate
558
-        $sum_xy = 0;
559
-        $sum_x=0;
560
-        $sum_y=0;
561
-        $sum_x2=0;
562
-        $n=count($this->statistics_tab);
563
-        foreach($this->statistics_tab as $gen=>$stats){
564
-            $sum_xy+=$gen*$stats['avgBirth'];
565
-            $sum_x+=$gen;
566
-            $sum_y+=$stats['avgBirth'];
567
-            $sum_x2+=$gen*$gen;
568
-        }
569
-        $denom=($n*$sum_x2)-($sum_x*$sum_x);
570
-        if($denom!=0){
571
-            return -(($n*$sum_xy)-($sum_x*$sum_y))/($denom);
572
-        }
573
-        return null;
574
-    }
575
-    
576
-    /**
577
-     * Return a computed array of statistics about the dispersion of ancestors across the ancestors
578
-     * at a specified generation.
579
-     * This statistics cannot be used for generations above 11, as it would cause a out of range in MySQL
580
-     * 
581
-     * Format: 
582
-     *  - key : a base-2 representation of the ancestor at generation G for which exclusive ancestors have been found,
583
-     *          -1 is used for shared ancestors
584
-     *          For instance base2(0100) = base10(4) represent the maternal grand father
585
-     *  - values: number of ancestors exclusively in the ancestors of the ancestor in key
586
-     *  
587
-     *  For instance a result at generation 3 could be :
588
-     *      array (   -1        =>  12      -> 12 ancestors are shared by the grand-parents
589
-     *                base10(1) =>  32      -> 32 ancestors are exclusive to the paternal grand-father
590
-     *                base10(2) =>  25      -> 25 ancestors are exclusive to the paternal grand-mother
591
-     *                base10(4) =>  12      -> 12 ancestors are exclusive to the maternal grand-father
592
-     *                base10(8) =>  30      -> 30 ancestors are exclusive to the maternal grand-mother
593
-     *            )
594
-     *  
595
-     * @param int $gen Reference generation
596
-     * @return array
597
-     */
598
-    public function getAncestorDispersionForGen($gen) {
599
-        if(!$this->is_setup || $gen > 11) return array();  // Going further than 11 gen will be out of range in the query
600
-        return Database::prepare(
601
-            'SELECT branches, count(i_id)'.
602
-            ' FROM ('.
603
-            '   SELECT i_id,'.
604
-            '       CASE'.
605
-            '           WHEN CEIL(LOG2(SUM(branch))) = LOG2(SUM(branch)) THEN SUM(branch)'.
606
-            '           ELSE -1'.   // We put all ancestors shared between some branches in the same bucket
607
-            '       END branches'.
608
-            '   FROM ('.
609
-            '       SELECT DISTINCT majs_i_id i_id,'.
610
-            '           POW(2, FLOOR(majs_sosa / POW(2, (majs_gen - :gen))) - POW(2, :gen -1)) branch'.
611
-            '       FROM `##maj_sosa`'.
612
-            '       WHERE majs_gedcom_id = :tree_id AND majs_user_id = :user_id'.
613
-            '           AND majs_gen >= :gen'.
614
-            '   ) indistat'.
615
-            '   GROUP BY i_id'.
616
-            ') grouped'.
617
-            ' GROUP BY branches')
618
-            ->execute(array(
619
-                'tree_id' => $this->tree->getTreeId(), 
620
-                'user_id' => $this->user->getUserId(),
621
-                'gen' => $gen
622
-            ))->fetchAssoc() ?: array();
623
-    }
624
-    
625
-    /**
626
-     * Return an array of the most duplicated root Sosa ancestors.
627
-     * The number of ancestors to return is limited by the parameter $limit.
628
-     * If several individuals are tied when reaching the limit, none of them are returned,
629
-     * which means that there can be less individuals returned than requested.
630
-     * 
631
-     * Format: 
632
-     *  - key : root Sosa individual
633
-     *  - value: number of duplications of the ancestor (e.g. 3 if it appears 3 times)
634
-     * 
635
-     * @param number $limit Maximum number of individuals to return
636
-     * @return array 
637
-     */
638
-    public function getTopMultiSosaAncestorsNoTies($limit) {
639
-        if(!$this->is_setup) return array();
640
-        return Database::prepare(
641
-            'SELECT sosa_i_id, sosa_count FROM ('.
642
-            '   SELECT'.
643
-            '       top_sosa.sosa_i_id, top_sosa.sosa_count, top_sosa.sosa_min,'.
644
-            '       @keep := IF(@prev_count = 0 OR sosa_count = @prev_count, @keep, 1) AS keep,'.
645
-            '       @prev_count := top_sosa.sosa_count AS prev_count'.
646
-            '   FROM ('.
647
-            '       SELECT'.
648
-            '           sosa.majs_i_id sosa_i_id,'.
649
-            '           COUNT(sosa.majs_sosa) sosa_count,'.
650
-            '           MIN(sosa.majs_sosa) sosa_min'.
651
-            '       FROM ##maj_sosa AS sosa'.
652
-            '       LEFT JOIN ##maj_sosa AS sosa_fat ON sosa_fat.majs_sosa = 2 * sosa.majs_sosa'.   // Link to sosa's father
653
-            '           AND sosa.majs_gedcom_id = sosa_fat.majs_gedcom_id'.
654
-            '           AND sosa.majs_user_id = sosa_fat.majs_user_id'.
655
-            '       LEFT JOIN ##maj_sosa AS sosa_mot on sosa_mot.majs_sosa = (2 * sosa.majs_sosa + 1)'.  // Link to sosa's mother
656
-            '           AND sosa.majs_gedcom_id = sosa_fat.majs_gedcom_id'.
657
-            '           AND sosa.majs_user_id = sosa_fat.majs_user_id'.
658
-            '       WHERE sosa.majs_gedcom_id = :tree_id'.
659
-            '       AND sosa.majs_user_id = :user_id'.
660
-            '       AND sosa_fat.majs_sosa IS NULL'.    // We keep only root individuals, i.e. those with no father or mother
661
-            '       AND sosa_mot.majs_sosa IS NULL'. 
662
-            '       GROUP BY sosa.majs_i_id'.
663
-            '       HAVING COUNT(sosa.majs_sosa) > 1'.   // Limit to the duplicate sosas.
664
-            '       ORDER BY COUNT(sosa.majs_sosa) DESC'.
665
-            '       LIMIT ' . ($limit + 1) . // We want to select one more than required
666
-            '   ) AS top_sosa,'.
667
-            '   (SELECT @prev_count := 0, @keep := 0) x'.
668
-            '   ORDER BY top_sosa.sosa_count ASC'.
669
-            ' ) top_sosa_list'.
670
-            ' WHERE keep = 1'.
671
-            ' ORDER BY sosa_count DESC, sosa_min ASC'
672
-            )->execute(array(
673
-                'tree_id' => $this->tree->getTreeId(),
674
-                'user_id' => $this->user->getUserId()
675
-            ))->fetchAssoc() ?: array();
676
-    }
464
+	/**
465
+	 * Get the total number of Sosa up to a specific generation.
466
+	 *
467
+	 * @param number $gen Generation
468
+	 * @return number Total number of Sosas up to generation
469
+	 */
470
+	public function getSosaCountUpToGeneration($gen){
471
+		if(!$this->is_setup) return 0;
472
+		return Database::prepare(
473
+			'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
474
+			' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
475
+			' AND majs_gen <= :gen')
476
+		->execute(array(
477
+				'tree_id' => $this->tree->getTreeId(), 
478
+				'user_id' => $this->user->getUserId(),
479
+				'gen' => $gen 
480
+		))->fetchOne() ?: 0;
481
+	}
482
+    
483
+	/**
484
+	 * Get the total number of distinct Sosa individual for all generations.
485
+	 *
486
+	 * @return number Total number of distinct individual
487
+	 */
488
+	public function getDifferentSosaCount(){
489
+		if(!$this->is_setup) return 0;
490
+		return Database::prepare(
491
+			'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
492
+			' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
493
+		->execute(array(
494
+				'tree_id' => $this->tree->getTreeId(), 
495
+				'user_id' => $this->user->getUserId()
496
+		))->fetchOne() ?: 0;
497
+	}
498
+    
499
+	/**
500
+	 * Get the number of distinct Sosa individual up to a specific generation.
501
+	 *
502
+	 * @param number $gen Generation
503
+	 * @return number Number of distinct Sosa individuals up to generation
504
+	 */
505
+	public function getDifferentSosaCountUpToGeneration($gen){
506
+		if(!$this->is_setup) return 0;
507
+		return Database::prepare(
508
+			'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
509
+			' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
510
+			' AND majs_gen <= :gen')
511
+		->execute(array(
512
+				'tree_id' => $this->tree->getTreeId(), 
513
+				'user_id' => $this->user->getUserId(),
514
+				'gen' => $gen 
515
+		))->fetchOne() ?: 0;
516
+	}
517
+    
518
+	/**
519
+	 * Get an array of birth statistics for a specific generation
520
+	 * Statistics are :
521
+	 * 	- first : First birth year in generation
522
+	 *  - first_est: First estimated birth year in generation
523
+	 *  - last : Last birth year in generation
524
+	 *  - last_est : Last estimated birth year in generation
525
+	 *  - avg : Average birth year (based on non-estimated birth date)
526
+	 *
527
+	 * @param number $gen Generation
528
+	 * @return array Birth statistics array
529
+	 */
530
+	public function getStatsBirthYearInGeneration($gen){
531
+		if(!$this->is_setup) return array('first' => 0, 'first_est' => 0, 'avg' => 0, 'last' => 0, 'last_est' => 0);
532
+		return Database::prepare(
533
+			'SELECT'.
534
+			' MIN(majs_birth_year) AS first, MIN(majs_birth_year_est) AS first_est,'.
535
+			' AVG(majs_birth_year) AS avg,'.
536
+			' MAX(majs_birth_year) AS last, MAX(majs_birth_year_est) AS last_est'.
537
+			' FROM `##maj_sosa`'.
538
+			' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
539
+			' AND majs_gen=:gen')
540
+			->execute(array(
541
+				'tree_id' => $this->tree->getTreeId(), 
542
+				'user_id' => $this->user->getUserId(),
543
+				'gen' => $gen))
544
+			->fetchOneRow(\PDO::FETCH_ASSOC) ?: array('first' => 0, 'first_est' => 0, 'avg' => 0, 'last' => 0, 'last_est' => 0);
545
+	}
546
+    
547
+	/**
548
+	 * Get the mean generation time, based on a linear regression of birth years and generations
549
+	 *
550
+	 * @return number|NULL Mean generation time
551
+	 */
552
+	public function getMeanGenerationTime(){
553
+		if(!$this->is_setup) return;
554
+		if(!$this->statistics_tab){
555
+			$this->getStatisticsByGeneration();
556
+		}
557
+		//Linear regression on x=generation and y=birthdate
558
+		$sum_xy = 0;
559
+		$sum_x=0;
560
+		$sum_y=0;
561
+		$sum_x2=0;
562
+		$n=count($this->statistics_tab);
563
+		foreach($this->statistics_tab as $gen=>$stats){
564
+			$sum_xy+=$gen*$stats['avgBirth'];
565
+			$sum_x+=$gen;
566
+			$sum_y+=$stats['avgBirth'];
567
+			$sum_x2+=$gen*$gen;
568
+		}
569
+		$denom=($n*$sum_x2)-($sum_x*$sum_x);
570
+		if($denom!=0){
571
+			return -(($n*$sum_xy)-($sum_x*$sum_y))/($denom);
572
+		}
573
+		return null;
574
+	}
575
+    
576
+	/**
577
+	 * Return a computed array of statistics about the dispersion of ancestors across the ancestors
578
+	 * at a specified generation.
579
+	 * This statistics cannot be used for generations above 11, as it would cause a out of range in MySQL
580
+	 * 
581
+	 * Format: 
582
+	 *  - key : a base-2 representation of the ancestor at generation G for which exclusive ancestors have been found,
583
+	 *          -1 is used for shared ancestors
584
+	 *          For instance base2(0100) = base10(4) represent the maternal grand father
585
+	 *  - values: number of ancestors exclusively in the ancestors of the ancestor in key
586
+	 *  
587
+	 *  For instance a result at generation 3 could be :
588
+	 *      array (   -1        =>  12      -> 12 ancestors are shared by the grand-parents
589
+	 *                base10(1) =>  32      -> 32 ancestors are exclusive to the paternal grand-father
590
+	 *                base10(2) =>  25      -> 25 ancestors are exclusive to the paternal grand-mother
591
+	 *                base10(4) =>  12      -> 12 ancestors are exclusive to the maternal grand-father
592
+	 *                base10(8) =>  30      -> 30 ancestors are exclusive to the maternal grand-mother
593
+	 *            )
594
+	 *  
595
+	 * @param int $gen Reference generation
596
+	 * @return array
597
+	 */
598
+	public function getAncestorDispersionForGen($gen) {
599
+		if(!$this->is_setup || $gen > 11) return array();  // Going further than 11 gen will be out of range in the query
600
+		return Database::prepare(
601
+			'SELECT branches, count(i_id)'.
602
+			' FROM ('.
603
+			'   SELECT i_id,'.
604
+			'       CASE'.
605
+			'           WHEN CEIL(LOG2(SUM(branch))) = LOG2(SUM(branch)) THEN SUM(branch)'.
606
+			'           ELSE -1'.   // We put all ancestors shared between some branches in the same bucket
607
+			'       END branches'.
608
+			'   FROM ('.
609
+			'       SELECT DISTINCT majs_i_id i_id,'.
610
+			'           POW(2, FLOOR(majs_sosa / POW(2, (majs_gen - :gen))) - POW(2, :gen -1)) branch'.
611
+			'       FROM `##maj_sosa`'.
612
+			'       WHERE majs_gedcom_id = :tree_id AND majs_user_id = :user_id'.
613
+			'           AND majs_gen >= :gen'.
614
+			'   ) indistat'.
615
+			'   GROUP BY i_id'.
616
+			') grouped'.
617
+			' GROUP BY branches')
618
+			->execute(array(
619
+				'tree_id' => $this->tree->getTreeId(), 
620
+				'user_id' => $this->user->getUserId(),
621
+				'gen' => $gen
622
+			))->fetchAssoc() ?: array();
623
+	}
624
+    
625
+	/**
626
+	 * Return an array of the most duplicated root Sosa ancestors.
627
+	 * The number of ancestors to return is limited by the parameter $limit.
628
+	 * If several individuals are tied when reaching the limit, none of them are returned,
629
+	 * which means that there can be less individuals returned than requested.
630
+	 * 
631
+	 * Format: 
632
+	 *  - key : root Sosa individual
633
+	 *  - value: number of duplications of the ancestor (e.g. 3 if it appears 3 times)
634
+	 * 
635
+	 * @param number $limit Maximum number of individuals to return
636
+	 * @return array 
637
+	 */
638
+	public function getTopMultiSosaAncestorsNoTies($limit) {
639
+		if(!$this->is_setup) return array();
640
+		return Database::prepare(
641
+			'SELECT sosa_i_id, sosa_count FROM ('.
642
+			'   SELECT'.
643
+			'       top_sosa.sosa_i_id, top_sosa.sosa_count, top_sosa.sosa_min,'.
644
+			'       @keep := IF(@prev_count = 0 OR sosa_count = @prev_count, @keep, 1) AS keep,'.
645
+			'       @prev_count := top_sosa.sosa_count AS prev_count'.
646
+			'   FROM ('.
647
+			'       SELECT'.
648
+			'           sosa.majs_i_id sosa_i_id,'.
649
+			'           COUNT(sosa.majs_sosa) sosa_count,'.
650
+			'           MIN(sosa.majs_sosa) sosa_min'.
651
+			'       FROM ##maj_sosa AS sosa'.
652
+			'       LEFT JOIN ##maj_sosa AS sosa_fat ON sosa_fat.majs_sosa = 2 * sosa.majs_sosa'.   // Link to sosa's father
653
+			'           AND sosa.majs_gedcom_id = sosa_fat.majs_gedcom_id'.
654
+			'           AND sosa.majs_user_id = sosa_fat.majs_user_id'.
655
+			'       LEFT JOIN ##maj_sosa AS sosa_mot on sosa_mot.majs_sosa = (2 * sosa.majs_sosa + 1)'.  // Link to sosa's mother
656
+			'           AND sosa.majs_gedcom_id = sosa_fat.majs_gedcom_id'.
657
+			'           AND sosa.majs_user_id = sosa_fat.majs_user_id'.
658
+			'       WHERE sosa.majs_gedcom_id = :tree_id'.
659
+			'       AND sosa.majs_user_id = :user_id'.
660
+			'       AND sosa_fat.majs_sosa IS NULL'.    // We keep only root individuals, i.e. those with no father or mother
661
+			'       AND sosa_mot.majs_sosa IS NULL'. 
662
+			'       GROUP BY sosa.majs_i_id'.
663
+			'       HAVING COUNT(sosa.majs_sosa) > 1'.   // Limit to the duplicate sosas.
664
+			'       ORDER BY COUNT(sosa.majs_sosa) DESC'.
665
+			'       LIMIT ' . ($limit + 1) . // We want to select one more than required
666
+			'   ) AS top_sosa,'.
667
+			'   (SELECT @prev_count := 0, @keep := 0) x'.
668
+			'   ORDER BY top_sosa.sosa_count ASC'.
669
+			' ) top_sosa_list'.
670
+			' WHERE keep = 1'.
671
+			' ORDER BY sosa_count DESC, sosa_min ASC'
672
+			)->execute(array(
673
+				'tree_id' => $this->tree->getTreeId(),
674
+				'user_id' => $this->user->getUserId()
675
+			))->fetchAssoc() ?: array();
676
+	}
677 677
     
678 678
                
679 679
 }
Please login to merge, or discard this patch.
Spacing   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -84,18 +84,18 @@  discard block
 block discarded – undo
84 84
      * @param User $user
85 85
      */
86 86
     public function __construct(Tree $tree, User $user = null) {
87
-        if(self::$default_user === null) 
87
+        if (self::$default_user === null) 
88 88
             self::$default_user = User::find(-1);
89 89
         
90 90
         $this->tree = $tree;
91 91
         $this->user = $user;
92 92
         $this->is_setup = true;
93
-        if($this->user === null) $this->user = Auth::user();
94
-        if(strlen($this->user->getUserId()) == 0) $this->user = self::$default_user;
93
+        if ($this->user === null) $this->user = Auth::user();
94
+        if (strlen($this->user->getUserId()) == 0) $this->user = self::$default_user;
95 95
         
96 96
         // Check if the user, or the default user, has a root already setup;
97
-        if(empty($this->getRootIndiId())) {
98
-            if($this->user == self::$default_user) {  // If the default user is not setup
97
+        if (empty($this->getRootIndiId())) {
98
+            if ($this->user == self::$default_user) {  // If the default user is not setup
99 99
                 $this->is_setup = false;
100 100
             }
101 101
             else {
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
      */
128 128
     public function getRootIndi() {
129 129
         $root_indi_id = $this->getRootIndiId();
130
-        if(!empty($root_indi_id)) {
130
+        if (!empty($root_indi_id)) {
131 131
             return Individual::getInstance($root_indi_id, $this->tree);
132 132
         }
133 133
         return null;
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
      * Remove all Sosa entries related to the gedcom file and user
142 142
      */
143 143
     public function deleteAll() {
144
-        if(!$this->is_setup) return;
144
+        if (!$this->is_setup) return;
145 145
         Database::prepare(
146 146
             'DELETE FROM `##maj_sosa`'.
147 147
             ' WHERE majs_gedcom_id= :tree_id and majs_user_id = :user_id ')
@@ -157,12 +157,12 @@  discard block
 block discarded – undo
157 157
      * @param int $sosa
158 158
      */
159 159
     public function deleteAncestors($sosa) {
160
-        if(!$this->is_setup) return;
160
+        if (!$this->is_setup) return;
161 161
         $gen = Functions::getGeneration($sosa);
162 162
         Database::prepare(
163 163
             'DELETE FROM `##maj_sosa`'.
164
-            ' WHERE majs_gedcom_id=:tree_id and majs_user_id = :user_id' .
165
-            ' AND majs_gen >= :gen' .
164
+            ' WHERE majs_gedcom_id=:tree_id and majs_user_id = :user_id'.
165
+            ' AND majs_gen >= :gen'.
166 166
             ' AND FLOOR(majs_sosa / (POW(2, (majs_gen - :gen)))) = :sosa'
167 167
         )->execute(array(
168 168
             'tree_id' => $this->tree->getTreeId(), 
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
      * @param array $sosa_records
178 178
      */
179 179
     public function insertOrUpdate($sosa_records) {
180
-        if(!$this->is_setup) return;
180
+        if (!$this->is_setup) return;
181 181
         
182 182
         $treeid = $this->tree->getTreeId();
183 183
         $userid = $this->user->getUserId();
@@ -185,9 +185,9 @@  discard block
 block discarded – undo
185 185
         $values_table = array();
186 186
         
187 187
         $i = 0;
188
-        foreach  ($sosa_records as $row) {
188
+        foreach ($sosa_records as $row) {
189 189
             $gen = Functions::getGeneration($row['sosa']);
190
-            if($gen <= self::MAX_DB_GENERATIONS) {
190
+            if ($gen <= self::MAX_DB_GENERATIONS) {
191 191
                 $questionmarks_table[] = 
192 192
                     '(:tree_id'.$i.', :user_id'.$i.', :sosa'.$i.', :indi_id'.$i.', :gen'.$i.', :byear'.$i.', :byearest'.$i.', :dyear'.$i.', :dyearest'.$i.')';
193 193
                 $values_table = array_merge(
@@ -208,9 +208,9 @@  discard block
 block discarded – undo
208 208
             $i++;
209 209
         }
210 210
         
211
-        $sql = 'REPLACE INTO `##maj_sosa`' .
212
-            ' (majs_gedcom_id, majs_user_id, majs_sosa, majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)' .
213
-            ' VALUES '. implode(',', $questionmarks_table);
211
+        $sql = 'REPLACE INTO `##maj_sosa`'.
212
+            ' (majs_gedcom_id, majs_user_id, majs_sosa, majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)'.
213
+            ' VALUES '.implode(',', $questionmarks_table);
214 214
         Database::prepare($sql)->execute($values_table);
215 215
     }
216 216
     
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
      * @return array Array of sosa numbers
227 227
      */
228 228
     public function getSosaNumbers(Individual $indi) {
229
-        if(!$this->is_setup) return array();
229
+        if (!$this->is_setup) return array();
230 230
         return Database::prepare(
231 231
                 'SELECT majs_sosa, majs_gen FROM `##maj_sosa`'.
232 232
                 ' WHERE majs_i_id=:indi_id AND majs_gedcom_id=:tree_id AND majs_user_id=:user_id'
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
      * @return number Last generation if found, 1 otherwise
244 244
      */
245 245
     public function getLastGeneration() {
246
-        if(!$this->is_setup) return;
246
+        if (!$this->is_setup) return;
247 247
         return Database::prepare(
248 248
                 'SELECT MAX(majs_gen) FROM `##maj_sosa`'.
249 249
                 ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
      *
263 263
      * @return array Associative array of Sosa ancestors, with their generation, comma separated
264 264
      */
265
-    public function getAllSosaWithGenerations(){
266
-        if(!$this->is_setup) return array();
265
+    public function getAllSosaWithGenerations() {
266
+        if (!$this->is_setup) return array();
267 267
         return Database::prepare(
268
-            'SELECT majs_i_id AS indi,' .
269
-            ' GROUP_CONCAT(DISTINCT majs_gen ORDER BY majs_gen ASC SEPARATOR ",") AS generations' .
270
-            ' FROM `##maj_sosa`' .
271
-            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id' .
268
+            'SELECT majs_i_id AS indi,'.
269
+            ' GROUP_CONCAT(DISTINCT majs_gen ORDER BY majs_gen ASC SEPARATOR ",") AS generations'.
270
+            ' FROM `##maj_sosa`'.
271
+            ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
272 272
             ' GROUP BY majs_i_id'
273 273
         )->execute(array(
274 274
             'tree_id' => $this->tree->getTreeId(),
@@ -282,13 +282,13 @@  discard block
 block discarded – undo
282 282
      * @param number $gen Generation
283 283
      * @return array Array of Sosa individuals
284 284
      */
285
-    public function getSosaListAtGeneration($gen){
286
-        if(!$this->is_setup) return array();
287
-        if(!$this->sosa_list_by_gen)
285
+    public function getSosaListAtGeneration($gen) {
286
+        if (!$this->is_setup) return array();
287
+        if (!$this->sosa_list_by_gen)
288 288
             $this->sosa_list_by_gen = array();
289 289
         
290
-        if($gen){
291
-            if(!isset($this->sosa_list_by_gen[$gen])){
290
+        if ($gen) {
291
+            if (!isset($this->sosa_list_by_gen[$gen])) {
292 292
                 $this->sosa_list_by_gen[$gen] = Database::prepare(
293 293
                     'SELECT majs_sosa AS sosa, majs_i_id AS indi'.
294 294
                     ' FROM `##maj_sosa`'.
@@ -313,13 +313,13 @@  discard block
 block discarded – undo
313 313
      * @param number $gen Generation
314 314
      * @return array Array of Sosa families
315 315
      */
316
-    public function getFamilySosaListAtGeneration($gen){
317
-        if(!$this->is_setup) return array();
318
-        if(!$this->sosa_fam_list_by_gen)
316
+    public function getFamilySosaListAtGeneration($gen) {
317
+        if (!$this->is_setup) return array();
318
+        if (!$this->sosa_fam_list_by_gen)
319 319
             $this->sosa_fam_list_by_gen = array();
320 320
         
321
-        if($gen){
322
-            if(!isset($this->sosa_fam_list_by_gen[$gen])){
321
+        if ($gen) {
322
+            if (!isset($this->sosa_fam_list_by_gen[$gen])) {
323 323
                 $this->sosa_fam_list_by_gen[$gen] = Database::prepare(
324 324
                     'SELECT s1.majs_sosa AS sosa, f_id AS fam'.
325 325
                     ' FROM `##families`'.
@@ -349,9 +349,9 @@  discard block
 block discarded – undo
349 349
      * @param number $gen Generation
350 350
      * @return array Array of Sosa individuals
351 351
      */
352
-    public function getMissingSosaListAtGeneration($gen){
353
-        if(!$this->is_setup) return array();    
354
-        if($gen){
352
+    public function getMissingSosaListAtGeneration($gen) {
353
+        if (!$this->is_setup) return array();    
354
+        if ($gen) {
355 355
             return $this->sosa_list_by_gen[$gen] = Database::prepare(
356 356
                 'SELECT schild.majs_sosa sosa, schild.majs_i_id indi, sfat.majs_sosa IS NOT NULL has_father, smot.majs_sosa IS NOT NULL has_mother'.
357 357
                 ' FROM `##maj_sosa` schild'.
@@ -390,10 +390,10 @@  discard block
 block discarded – undo
390 390
      * @return array Statistics array
391 391
      */
392 392
     public function getStatisticsByGeneration() {
393
-        if(!$this->is_setup) return array();
394
-        if(!$this->statistics_tab) {
393
+        if (!$this->is_setup) return array();
394
+        if (!$this->statistics_tab) {
395 395
             $this->statistics_tab = array();
396
-            if($maxGeneration = $this->getLastGeneration()) {
396
+            if ($maxGeneration = $this->getLastGeneration()) {
397 397
                 for ($gen = 1; $gen <= $maxGeneration; $gen++) {
398 398
                     $birthStats = $this->getStatsBirthYearInGeneration($gen);
399 399
                     $this->statistics_tab[$gen] = array(
@@ -418,9 +418,9 @@  discard block
 block discarded – undo
418 418
 	 * @return int
419 419
 	 */
420 420
 	public function getTotalIndividuals() {
421
-	    if(!$this->is_setup) return 0;
421
+	    if (!$this->is_setup) return 0;
422 422
 	    return Database::prepare(
423
-	        'SELECT COUNT(*) FROM `##individuals`' .
423
+	        'SELECT COUNT(*) FROM `##individuals`'.
424 424
 	        ' WHERE i_file = :tree_id')
425 425
 	        ->execute(array('tree_id' => $this->tree->getTreeId()))
426 426
 	        ->fetchOne() ?: 0;
@@ -431,10 +431,10 @@  discard block
 block discarded – undo
431 431
      *
432 432
      * @return number Number of Sosas
433 433
      */
434
-    public function getSosaCount(){
435
-        if(!$this->is_setup) return 0;
434
+    public function getSosaCount() {
435
+        if (!$this->is_setup) return 0;
436 436
         return Database::prepare(
437
-            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
437
+            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`'.
438 438
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
439 439
             ->execute(array(
440 440
                 'tree_id' => $this->tree->getTreeId(), 
@@ -448,10 +448,10 @@  discard block
 block discarded – undo
448 448
      * @param number $gen Generation
449 449
      * @return number Number of Sosas in generation
450 450
      */
451
-    public function getSosaCountAtGeneration($gen){
452
-        if(!$this->is_setup) return 0;
451
+    public function getSosaCountAtGeneration($gen) {
452
+        if (!$this->is_setup) return 0;
453 453
         return Database::prepare(
454
-            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
454
+            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`'.
455 455
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
456 456
             ' AND majs_gen= :gen')
457 457
         ->execute(array(
@@ -467,10 +467,10 @@  discard block
 block discarded – undo
467 467
      * @param number $gen Generation
468 468
      * @return number Total number of Sosas up to generation
469 469
      */
470
-    public function getSosaCountUpToGeneration($gen){
471
-        if(!$this->is_setup) return 0;
470
+    public function getSosaCountUpToGeneration($gen) {
471
+        if (!$this->is_setup) return 0;
472 472
         return Database::prepare(
473
-            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
473
+            'SELECT COUNT(majs_sosa) FROM `##maj_sosa`'.
474 474
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
475 475
             ' AND majs_gen <= :gen')
476 476
         ->execute(array(
@@ -485,10 +485,10 @@  discard block
 block discarded – undo
485 485
      *
486 486
      * @return number Total number of distinct individual
487 487
      */
488
-    public function getDifferentSosaCount(){
489
-        if(!$this->is_setup) return 0;
488
+    public function getDifferentSosaCount() {
489
+        if (!$this->is_setup) return 0;
490 490
         return Database::prepare(
491
-            'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
491
+            'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`'.
492 492
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
493 493
         ->execute(array(
494 494
                 'tree_id' => $this->tree->getTreeId(), 
@@ -502,10 +502,10 @@  discard block
 block discarded – undo
502 502
      * @param number $gen Generation
503 503
      * @return number Number of distinct Sosa individuals up to generation
504 504
      */
505
-    public function getDifferentSosaCountUpToGeneration($gen){
506
-        if(!$this->is_setup) return 0;
505
+    public function getDifferentSosaCountUpToGeneration($gen) {
506
+        if (!$this->is_setup) return 0;
507 507
         return Database::prepare(
508
-            'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
508
+            'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`'.
509 509
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
510 510
             ' AND majs_gen <= :gen')
511 511
         ->execute(array(
@@ -527,8 +527,8 @@  discard block
 block discarded – undo
527 527
      * @param number $gen Generation
528 528
      * @return array Birth statistics array
529 529
      */
530
-    public function getStatsBirthYearInGeneration($gen){
531
-        if(!$this->is_setup) return array('first' => 0, 'first_est' => 0, 'avg' => 0, 'last' => 0, 'last_est' => 0);
530
+    public function getStatsBirthYearInGeneration($gen) {
531
+        if (!$this->is_setup) return array('first' => 0, 'first_est' => 0, 'avg' => 0, 'last' => 0, 'last_est' => 0);
532 532
         return Database::prepare(
533 533
             'SELECT'.
534 534
             ' MIN(majs_birth_year) AS first, MIN(majs_birth_year_est) AS first_est,'.
@@ -549,26 +549,26 @@  discard block
 block discarded – undo
549 549
      *
550 550
      * @return number|NULL Mean generation time
551 551
      */
552
-    public function getMeanGenerationTime(){
553
-        if(!$this->is_setup) return;
554
-        if(!$this->statistics_tab){
552
+    public function getMeanGenerationTime() {
553
+        if (!$this->is_setup) return;
554
+        if (!$this->statistics_tab) {
555 555
             $this->getStatisticsByGeneration();
556 556
         }
557 557
         //Linear regression on x=generation and y=birthdate
558 558
         $sum_xy = 0;
559
-        $sum_x=0;
560
-        $sum_y=0;
561
-        $sum_x2=0;
562
-        $n=count($this->statistics_tab);
563
-        foreach($this->statistics_tab as $gen=>$stats){
564
-            $sum_xy+=$gen*$stats['avgBirth'];
565
-            $sum_x+=$gen;
566
-            $sum_y+=$stats['avgBirth'];
567
-            $sum_x2+=$gen*$gen;
559
+        $sum_x = 0;
560
+        $sum_y = 0;
561
+        $sum_x2 = 0;
562
+        $n = count($this->statistics_tab);
563
+        foreach ($this->statistics_tab as $gen=>$stats) {
564
+            $sum_xy += $gen * $stats['avgBirth'];
565
+            $sum_x += $gen;
566
+            $sum_y += $stats['avgBirth'];
567
+            $sum_x2 += $gen * $gen;
568 568
         }
569
-        $denom=($n*$sum_x2)-($sum_x*$sum_x);
570
-        if($denom!=0){
571
-            return -(($n*$sum_xy)-($sum_x*$sum_y))/($denom);
569
+        $denom = ($n * $sum_x2) - ($sum_x * $sum_x);
570
+        if ($denom != 0) {
571
+            return -(($n * $sum_xy) - ($sum_x * $sum_y)) / ($denom);
572 572
         }
573 573
         return null;
574 574
     }
@@ -596,14 +596,14 @@  discard block
 block discarded – undo
596 596
      * @return array
597 597
      */
598 598
     public function getAncestorDispersionForGen($gen) {
599
-        if(!$this->is_setup || $gen > 11) return array();  // Going further than 11 gen will be out of range in the query
599
+        if (!$this->is_setup || $gen > 11) return array(); // Going further than 11 gen will be out of range in the query
600 600
         return Database::prepare(
601 601
             'SELECT branches, count(i_id)'.
602 602
             ' FROM ('.
603 603
             '   SELECT i_id,'.
604 604
             '       CASE'.
605 605
             '           WHEN CEIL(LOG2(SUM(branch))) = LOG2(SUM(branch)) THEN SUM(branch)'.
606
-            '           ELSE -1'.   // We put all ancestors shared between some branches in the same bucket
606
+            '           ELSE -1'.// We put all ancestors shared between some branches in the same bucket
607 607
             '       END branches'.
608 608
             '   FROM ('.
609 609
             '       SELECT DISTINCT majs_i_id i_id,'.
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
      * @return array 
637 637
      */
638 638
     public function getTopMultiSosaAncestorsNoTies($limit) {
639
-        if(!$this->is_setup) return array();
639
+        if (!$this->is_setup) return array();
640 640
         return Database::prepare(
641 641
             'SELECT sosa_i_id, sosa_count FROM ('.
642 642
             '   SELECT'.
@@ -649,20 +649,20 @@  discard block
 block discarded – undo
649 649
             '           COUNT(sosa.majs_sosa) sosa_count,'.
650 650
             '           MIN(sosa.majs_sosa) sosa_min'.
651 651
             '       FROM ##maj_sosa AS sosa'.
652
-            '       LEFT JOIN ##maj_sosa AS sosa_fat ON sosa_fat.majs_sosa = 2 * sosa.majs_sosa'.   // Link to sosa's father
652
+            '       LEFT JOIN ##maj_sosa AS sosa_fat ON sosa_fat.majs_sosa = 2 * sosa.majs_sosa'.// Link to sosa's father
653 653
             '           AND sosa.majs_gedcom_id = sosa_fat.majs_gedcom_id'.
654 654
             '           AND sosa.majs_user_id = sosa_fat.majs_user_id'.
655
-            '       LEFT JOIN ##maj_sosa AS sosa_mot on sosa_mot.majs_sosa = (2 * sosa.majs_sosa + 1)'.  // Link to sosa's mother
655
+            '       LEFT JOIN ##maj_sosa AS sosa_mot on sosa_mot.majs_sosa = (2 * sosa.majs_sosa + 1)'.// Link to sosa's mother
656 656
             '           AND sosa.majs_gedcom_id = sosa_fat.majs_gedcom_id'.
657 657
             '           AND sosa.majs_user_id = sosa_fat.majs_user_id'.
658 658
             '       WHERE sosa.majs_gedcom_id = :tree_id'.
659 659
             '       AND sosa.majs_user_id = :user_id'.
660
-            '       AND sosa_fat.majs_sosa IS NULL'.    // We keep only root individuals, i.e. those with no father or mother
660
+            '       AND sosa_fat.majs_sosa IS NULL'.// We keep only root individuals, i.e. those with no father or mother
661 661
             '       AND sosa_mot.majs_sosa IS NULL'. 
662 662
             '       GROUP BY sosa.majs_i_id'.
663
-            '       HAVING COUNT(sosa.majs_sosa) > 1'.   // Limit to the duplicate sosas.
663
+            '       HAVING COUNT(sosa.majs_sosa) > 1'.// Limit to the duplicate sosas.
664 664
             '       ORDER BY COUNT(sosa.majs_sosa) DESC'.
665
-            '       LIMIT ' . ($limit + 1) . // We want to select one more than required
665
+            '       LIMIT '.($limit + 1).// We want to select one more than required
666 666
             '   ) AS top_sosa,'.
667 667
             '   (SELECT @prev_count := 0, @keep := 0) x'.
668 668
             '   ORDER BY top_sosa.sosa_count ASC'.
Please login to merge, or discard this patch.
Braces   +77 added lines, -30 removed lines patch added patch discarded remove patch
@@ -84,21 +84,25 @@  discard block
 block discarded – undo
84 84
      * @param User $user
85 85
      */
86 86
     public function __construct(Tree $tree, User $user = null) {
87
-        if(self::$default_user === null) 
88
-            self::$default_user = User::find(-1);
87
+        if(self::$default_user === null) {
88
+                    self::$default_user = User::find(-1);
89
+        }
89 90
         
90 91
         $this->tree = $tree;
91 92
         $this->user = $user;
92 93
         $this->is_setup = true;
93
-        if($this->user === null) $this->user = Auth::user();
94
-        if(strlen($this->user->getUserId()) == 0) $this->user = self::$default_user;
94
+        if($this->user === null) {
95
+        	$this->user = Auth::user();
96
+        }
97
+        if(strlen($this->user->getUserId()) == 0) {
98
+        	$this->user = self::$default_user;
99
+        }
95 100
         
96 101
         // Check if the user, or the default user, has a root already setup;
97 102
         if(empty($this->getRootIndiId())) {
98 103
             if($this->user == self::$default_user) {  // If the default user is not setup
99 104
                 $this->is_setup = false;
100
-            }
101
-            else {
105
+            } else {
102 106
                 $this->user = self::$default_user;
103 107
                 $this->is_setup = $this->getRootIndiId() === null;
104 108
             }            
@@ -141,7 +145,9 @@  discard block
 block discarded – undo
141 145
      * Remove all Sosa entries related to the gedcom file and user
142 146
      */
143 147
     public function deleteAll() {
144
-        if(!$this->is_setup) return;
148
+        if(!$this->is_setup) {
149
+        	return;
150
+        }
145 151
         Database::prepare(
146 152
             'DELETE FROM `##maj_sosa`'.
147 153
             ' WHERE majs_gedcom_id= :tree_id and majs_user_id = :user_id ')
@@ -157,7 +163,9 @@  discard block
 block discarded – undo
157 163
      * @param int $sosa
158 164
      */
159 165
     public function deleteAncestors($sosa) {
160
-        if(!$this->is_setup) return;
166
+        if(!$this->is_setup) {
167
+        	return;
168
+        }
161 169
         $gen = Functions::getGeneration($sosa);
162 170
         Database::prepare(
163 171
             'DELETE FROM `##maj_sosa`'.
@@ -177,7 +185,9 @@  discard block
 block discarded – undo
177 185
      * @param array $sosa_records
178 186
      */
179 187
     public function insertOrUpdate($sosa_records) {
180
-        if(!$this->is_setup) return;
188
+        if(!$this->is_setup) {
189
+        	return;
190
+        }
181 191
         
182 192
         $treeid = $this->tree->getTreeId();
183 193
         $userid = $this->user->getUserId();
@@ -226,7 +236,9 @@  discard block
 block discarded – undo
226 236
      * @return array Array of sosa numbers
227 237
      */
228 238
     public function getSosaNumbers(Individual $indi) {
229
-        if(!$this->is_setup) return array();
239
+        if(!$this->is_setup) {
240
+        	return array();
241
+        }
230 242
         return Database::prepare(
231 243
                 'SELECT majs_sosa, majs_gen FROM `##maj_sosa`'.
232 244
                 ' WHERE majs_i_id=:indi_id AND majs_gedcom_id=:tree_id AND majs_user_id=:user_id'
@@ -243,7 +255,9 @@  discard block
 block discarded – undo
243 255
      * @return number Last generation if found, 1 otherwise
244 256
      */
245 257
     public function getLastGeneration() {
246
-        if(!$this->is_setup) return;
258
+        if(!$this->is_setup) {
259
+        	return;
260
+        }
247 261
         return Database::prepare(
248 262
                 'SELECT MAX(majs_gen) FROM `##maj_sosa`'.
249 263
                 ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'
@@ -263,7 +277,9 @@  discard block
 block discarded – undo
263 277
      * @return array Associative array of Sosa ancestors, with their generation, comma separated
264 278
      */
265 279
     public function getAllSosaWithGenerations(){
266
-        if(!$this->is_setup) return array();
280
+        if(!$this->is_setup) {
281
+        	return array();
282
+        }
267 283
         return Database::prepare(
268 284
             'SELECT majs_i_id AS indi,' .
269 285
             ' GROUP_CONCAT(DISTINCT majs_gen ORDER BY majs_gen ASC SEPARATOR ",") AS generations' .
@@ -283,9 +299,12 @@  discard block
 block discarded – undo
283 299
      * @return array Array of Sosa individuals
284 300
      */
285 301
     public function getSosaListAtGeneration($gen){
286
-        if(!$this->is_setup) return array();
287
-        if(!$this->sosa_list_by_gen)
288
-            $this->sosa_list_by_gen = array();
302
+        if(!$this->is_setup) {
303
+        	return array();
304
+        }
305
+        if(!$this->sosa_list_by_gen) {
306
+                    $this->sosa_list_by_gen = array();
307
+        }
289 308
         
290 309
         if($gen){
291 310
             if(!isset($this->sosa_list_by_gen[$gen])){
@@ -314,9 +333,12 @@  discard block
 block discarded – undo
314 333
      * @return array Array of Sosa families
315 334
      */
316 335
     public function getFamilySosaListAtGeneration($gen){
317
-        if(!$this->is_setup) return array();
318
-        if(!$this->sosa_fam_list_by_gen)
319
-            $this->sosa_fam_list_by_gen = array();
336
+        if(!$this->is_setup) {
337
+        	return array();
338
+        }
339
+        if(!$this->sosa_fam_list_by_gen) {
340
+                    $this->sosa_fam_list_by_gen = array();
341
+        }
320 342
         
321 343
         if($gen){
322 344
             if(!isset($this->sosa_fam_list_by_gen[$gen])){
@@ -350,7 +372,9 @@  discard block
 block discarded – undo
350 372
      * @return array Array of Sosa individuals
351 373
      */
352 374
     public function getMissingSosaListAtGeneration($gen){
353
-        if(!$this->is_setup) return array();    
375
+        if(!$this->is_setup) {
376
+        	return array();
377
+        }
354 378
         if($gen){
355 379
             return $this->sosa_list_by_gen[$gen] = Database::prepare(
356 380
                 'SELECT schild.majs_sosa sosa, schild.majs_i_id indi, sfat.majs_sosa IS NOT NULL has_father, smot.majs_sosa IS NOT NULL has_mother'.
@@ -390,7 +414,9 @@  discard block
 block discarded – undo
390 414
      * @return array Statistics array
391 415
      */
392 416
     public function getStatisticsByGeneration() {
393
-        if(!$this->is_setup) return array();
417
+        if(!$this->is_setup) {
418
+        	return array();
419
+        }
394 420
         if(!$this->statistics_tab) {
395 421
             $this->statistics_tab = array();
396 422
             if($maxGeneration = $this->getLastGeneration()) {
@@ -418,7 +444,9 @@  discard block
 block discarded – undo
418 444
 	 * @return int
419 445
 	 */
420 446
 	public function getTotalIndividuals() {
421
-	    if(!$this->is_setup) return 0;
447
+	    if(!$this->is_setup) {
448
+	    	return 0;
449
+	    }
422 450
 	    return Database::prepare(
423 451
 	        'SELECT COUNT(*) FROM `##individuals`' .
424 452
 	        ' WHERE i_file = :tree_id')
@@ -432,7 +460,9 @@  discard block
 block discarded – undo
432 460
      * @return number Number of Sosas
433 461
      */
434 462
     public function getSosaCount(){
435
-        if(!$this->is_setup) return 0;
463
+        if(!$this->is_setup) {
464
+        	return 0;
465
+        }
436 466
         return Database::prepare(
437 467
             'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
438 468
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
@@ -449,7 +479,9 @@  discard block
 block discarded – undo
449 479
      * @return number Number of Sosas in generation
450 480
      */
451 481
     public function getSosaCountAtGeneration($gen){
452
-        if(!$this->is_setup) return 0;
482
+        if(!$this->is_setup) {
483
+        	return 0;
484
+        }
453 485
         return Database::prepare(
454 486
             'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
455 487
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
@@ -468,7 +500,9 @@  discard block
 block discarded – undo
468 500
      * @return number Total number of Sosas up to generation
469 501
      */
470 502
     public function getSosaCountUpToGeneration($gen){
471
-        if(!$this->is_setup) return 0;
503
+        if(!$this->is_setup) {
504
+        	return 0;
505
+        }
472 506
         return Database::prepare(
473 507
             'SELECT COUNT(majs_sosa) FROM `##maj_sosa`' .
474 508
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
@@ -486,7 +520,9 @@  discard block
 block discarded – undo
486 520
      * @return number Total number of distinct individual
487 521
      */
488 522
     public function getDifferentSosaCount(){
489
-        if(!$this->is_setup) return 0;
523
+        if(!$this->is_setup) {
524
+        	return 0;
525
+        }
490 526
         return Database::prepare(
491 527
             'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
492 528
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id')
@@ -503,7 +539,9 @@  discard block
 block discarded – undo
503 539
      * @return number Number of distinct Sosa individuals up to generation
504 540
      */
505 541
     public function getDifferentSosaCountUpToGeneration($gen){
506
-        if(!$this->is_setup) return 0;
542
+        if(!$this->is_setup) {
543
+        	return 0;
544
+        }
507 545
         return Database::prepare(
508 546
             'SELECT COUNT(DISTINCT majs_i_id) FROM `##maj_sosa`' .
509 547
             ' WHERE majs_gedcom_id=:tree_id AND majs_user_id=:user_id'.
@@ -528,7 +566,9 @@  discard block
 block discarded – undo
528 566
      * @return array Birth statistics array
529 567
      */
530 568
     public function getStatsBirthYearInGeneration($gen){
531
-        if(!$this->is_setup) return array('first' => 0, 'first_est' => 0, 'avg' => 0, 'last' => 0, 'last_est' => 0);
569
+        if(!$this->is_setup) {
570
+        	return array('first' => 0, 'first_est' => 0, 'avg' => 0, 'last' => 0, 'last_est' => 0);
571
+        }
532 572
         return Database::prepare(
533 573
             'SELECT'.
534 574
             ' MIN(majs_birth_year) AS first, MIN(majs_birth_year_est) AS first_est,'.
@@ -550,7 +590,9 @@  discard block
 block discarded – undo
550 590
      * @return number|NULL Mean generation time
551 591
      */
552 592
     public function getMeanGenerationTime(){
553
-        if(!$this->is_setup) return;
593
+        if(!$this->is_setup) {
594
+        	return;
595
+        }
554 596
         if(!$this->statistics_tab){
555 597
             $this->getStatisticsByGeneration();
556 598
         }
@@ -596,7 +638,10 @@  discard block
 block discarded – undo
596 638
      * @return array
597 639
      */
598 640
     public function getAncestorDispersionForGen($gen) {
599
-        if(!$this->is_setup || $gen > 11) return array();  // Going further than 11 gen will be out of range in the query
641
+        if(!$this->is_setup || $gen > 11) {
642
+        	return array();
643
+        }
644
+        // Going further than 11 gen will be out of range in the query
600 645
         return Database::prepare(
601 646
             'SELECT branches, count(i_id)'.
602 647
             ' FROM ('.
@@ -636,7 +681,9 @@  discard block
 block discarded – undo
636 681
      * @return array 
637 682
      */
638 683
     public function getTopMultiSosaAncestorsNoTies($limit) {
639
-        if(!$this->is_setup) return array();
684
+        if(!$this->is_setup) {
685
+        	return array();
686
+        }
640 687
         return Database::prepare(
641 688
             'SELECT sosa_i_id, sosa_count FROM ('.
642 689
             '   SELECT'.
Please login to merge, or discard this patch.