Passed
Push — master ( eb013e...37f747 )
by Jonathan
04:35
created

AdminConfigController::edit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * webtrees-lib: MyArtJaub library for webtrees
4
 *
5
 * @package MyArtJaub\Webtrees
6
 * @subpackage GeoDispersion
7
 * @author Jonathan Jaubart <[email protected]>
8
 * @copyright Copyright (c) 2009-2016, Jonathan Jaubart
9
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3
10
 */
11
namespace MyArtJaub\Webtrees\Module\GeoDispersion;
12
13
use Fisharebest\Webtrees\Auth;
14
use Fisharebest\Webtrees\Controller\PageController;
15
use Fisharebest\Webtrees\Filter;
16
use Fisharebest\Webtrees\FlashMessages;
17
use Fisharebest\Webtrees\I18N;
18
use Fisharebest\Webtrees\Log;
19
use Fisharebest\Webtrees\Module;
20
use Fisharebest\Webtrees\Module\AbstractModule;
21
use Fisharebest\Webtrees\Theme;
22
use Fisharebest\Webtrees\Theme\AdministrationTheme;
23
use Fisharebest\Webtrees\Tree;
24
use MyArtJaub\Webtrees\Controller\JsonController;
25
use MyArtJaub\Webtrees\Globals;
26
use MyArtJaub\Webtrees\Module\GeoDispersion\Model\GeoAnalysis;
27
use MyArtJaub\Webtrees\Module\GeoDispersion\Model\GeoAnalysisProvider;
28
use MyArtJaub\Webtrees\Module\GeoDispersion\Model\OutlineMap;
29
use MyArtJaub\Webtrees\Mvc\Controller\MvcController;
30
use MyArtJaub\Webtrees\Mvc\View\ViewBag;
31
use MyArtJaub\Webtrees\Mvc\View\ViewFactory;
32
use Rhumsaa\Uuid\Uuid;
33
34
/**
35
 * Controller for GeoDispersion AdminConfig
36
 */
37
class AdminConfigController extends MvcController
38
{    
39
    /**
40
     * GeoAnalysis Provider
41
     * @var GeoAnalysisProvider $provider
42
     */
43
    protected $provider;    
44
    
45
    /**
46
     * Constructor for Admin Config controller
47
     * @param AbstractModule $module
48
     */
49
    public function __construct(AbstractModule $module) {
50
        parent::__construct($module);
51
        
52
        $this->provider = $this->module->getProvider();
53
    }    
54
    
55
    /**
56
     * Pages
57
     */
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());
69
        
70
        $data = new ViewBag();
71
        $data->set('title', $controller->getPageTitle());
72
        $data->set('tree', $wt_tree);
73
        
74
        $data->set('root_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig');
75
                
76
        $table_id = 'table-geoanalysis-' . Uuid::uuid4();
77
        $data->set('table_id', $table_id);
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);
84
        
85
        $data->set('places_hierarchy', $this->provider->getPlacesHierarchy());
86
        
87
        $controller
88
            ->addExternalJavascript(WT_JQUERY_DATATABLES_JS_URL)
89
            ->addExternalJavascript(WT_DATATABLES_BOOTSTRAP_JS_URL)
90
            ->addInlineJavascript('
91
				jQuery.fn.dataTableExt.oSort["text-asc"] = textCompareAsc;
92
				jQuery.fn.dataTableExt.oSort["text-desc"] = textCompareDesc;
93
                
94
				var geoAnalysisTable = jQuery("#'.$table_id.'")
95
                .on("draw.dt", function ( e, settings, json, xhr ) {
96
                    jQuery("[data-toggle=\'tooltip\']").tooltip();
97
                }).DataTable({
98
					'.I18N::datatablesI18N().',			
99
					sorting: [[3, "asc"], [4, "asc"]],
100
					pageLength: 10,
101
                    processing: true,
102
                    serverSide : true,
103
					ajax : {
104
						url : "module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@jsonGeoAnalysisList&ged='. $wt_tree->getNameUrl().'",
105
                        type : "POST"
106
					},
107
                    columns: [
108
						/* 0 Edit		 	*/ { sortable: false, className: "text-center"},
109
                        /* 1 ID             */ { sortable: false, visible: false},
110
						/* 2 Enabled 		*/ { sortable: false, className: "text-center"  },
111
						/* 3 Description	*/ { type: "text" },
112
						/* 4 Analysis Level	*/ { type: "text", dataSort: 5, className: "text-center" },
113
						/* 5 ANAL_LEVEL_SORT*/ { type: "num", visible: false },
114
						/* 6 Map 	        */ { type: "text", sortable: false, className: "text-center" },
115
						/* 7 Map Top Level 	*/ { type: "text", sortable: false, className: "text-center" },
116
						/* 8 Use Flags     	*/ { type: "text", sortable: false, className: "text-center" },					
117
						/* 9 Place Details	*/ { type: "text", sortable: false, className: "text-center" }
118
					],
119
				});
120
                
121
                ')
122
                ->addInlineJavascript('				
123
                    function set_geoanalysis_status(ga_id, status, gedcom) {
124
                		jQuery.ajax({
125
                            url: "module.php", 
126
                            type: "GET",
127
                            data: {
128
                			    mod: "' . $this->module->getName() .'",
129
                                mod_action:  "GeoAnalysis@setStatus",
130
                			    ga_id: ga_id,
131
                			    ged: typeof gedcom === "undefined" ? WT_GEDCOM : gedcom,
132
                                status: status
133
                            },
134
                            error: function(result, stat, error) {
135
                                var err = typeof result.responseJSON === "undefined" ? error : result.responseJSON.error;
136
                                alert("' . I18N::translate('An error occured while editing this analysis:') . '" + err);
137
                            },
138
                            complete: function(result, stat) {
139
                                geoAnalysisTable.ajax.reload(null, false);
140
                            }                            
141
                		});
142
                    }
143
                    
144
                    function delete_geoanalysis(ga_id, status, gedcom) {
145
                		jQuery.ajax({
146
                            url: "module.php", 
147
                            type: "GET",
148
                            data: {
149
                			    mod: "' . $this->module->getName() .'",
150
                                mod_action:  "GeoAnalysis@delete",
151
                			    ga_id: ga_id,
152
                			    ged: typeof gedcom === "undefined" ? WT_GEDCOM : gedcom
153
                            },
154
                            error: function(result, stat, error) {
155
                                var err = typeof result.responseJSON === "undefined" ? error : result.responseJSON.error;
156
                                alert("' . I18N::translate('An error occured while deleting this analysis:') . '" + err);
157
                            },
158
                            complete: function(result, stat) {
159
                                geoAnalysisTable.ajax.reload(null, false);
160
                            }                            
161
                		});
162
                    }
163
                ');
164
        
165
        
166
        ViewFactory::make('AdminConfig', $this, $controller, $data)->render();
167
    }
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));
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'];
0 ignored issues
show
Bug Best Practice introduced by
The expression $search of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
181
        $start  = Filter::postInteger('start');
182
        $length = Filter::postInteger('length');
183
        $order  = Filter::postArray('order');
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
        }
197
        
198
        /** @var GeoAnalysisProvider $provider */
199
        $provider = $this->module->getProvider();
200
        
201
        $list = $provider->getFilteredGeoAnalysisList($search, $order, $start, $length);
0 ignored issues
show
Bug introduced by
It seems like $search can also be of type string[]; however, parameter $search of MyArtJaub\Webtrees\Modul...lteredGeoAnalysisList() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

201
        $list = $provider->getFilteredGeoAnalysisList(/** @scrutinizer ignore-type */ $search, $order, $start, $length);
Loading history...
202
        $recordsFiltered = count($list);
203
        $recordsTotal = $this->provider->getGeoAnalysisCount();
204
        
205
        $data = array();
206
        $place_hierarchy = $this->provider->getPlacesHierarchy();
207
        foreach($list as $ga) {
208
            /** @var GeoAnalysis $ga */
209
            
210
            $datum = array();
211
            $options= $ga->getOptions();
212
            
213
            $datum[0] = '
214
                <div class="btn-group">
215
                    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
216
                        <i class="fa fa-pencil"></i><span class="caret"></span>
217
                    </button>
218
                    <ul class="dropdown-menu" role="menu">
219
                       <li>
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')) . '
222
                            </a>
223
                       </li>
224
                        <li>
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') . '
227
                            </a>
228
                       </li>
229
                       <li class="divider" />
230
                       <li>
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') . '
233
                            </a>
234
                       </li>
235
                    </ul>
236
                </div>';
237
		    $datum[1] = $ga->getId();
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>';
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
				'<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>';
270
		    $datum[9] = $options->getMaxDetailsInGen() > 0 ? $options->getMaxDetailsInGen() : I18N::translate('All');
271
		    
272
		    $data[] = $datum;
273
        }
274
        
275
        $controller->pageHeader();
276
        
277
        $controller->encode(array(
278
            'draw'            => Filter::getInteger('draw'),
279
            'recordsTotal'    => $recordsTotal,
280
            'recordsFiltered' => $recordsFiltered,
281
            'data'            => $data
282
        ));
283
        
284
    }
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);
292
        
293
        $this->renderEdit($ga);
294
    }
295
    
296
    /**
297
     * AdminConfig@add
298
     */
299
    public function add() {
300
        $this->renderEdit(null);
301
    }
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
         );
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');
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));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map_file does not seem to be defined for all execution paths leading up to this point.
Loading history...
337
                        $options->setMapLevel($map_top_level + 1);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $map_top_level does not seem to be defined for all execution paths leading up to this point.
Loading history...
338
                    }
339
                    else {
340
                        $options->setMap(null);
341
                    }
342
                }
343
				
344
				$res = $this->provider->updateGeoAnalysis($ga);
345
				if($res) {
346
					FlashMessages::addMessage(I18N::translate('The geographical dispersion analysis “%s” has been successfully updated', $res->getTitle()), 'success');
347
					Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'.$res->getId().'” has been updated.');
348
					$ga = $res;
349
					$success = true;
350
				}
351
				else {
352
					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.');
354
				}
355
            }
356
        } else {
357
			$ga = $this->provider->createGeoAnalysis(
358
				$description,
359
				$analysislevel + 1,
360
				$use_map ? $map_file : null,
361
				$use_map ? $map_top_level + 1 : null,
362
				$use_flags,
363
				$gen_details
364
			);
365
			if($ga) {
366
				FlashMessages::addMessage(I18N::translate('The geographical dispersion analysis “%s” has been successfully added.', $ga->getTitle()), 'success');
367
				Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis ID “'.$ga->getId().'” has been added.');
368
				$success = true;
369
			}
370
			else {
371
				FlashMessages::addMessage(I18N::translate('An error occured while adding the geographical dispersion analysis “%s”', $description), 'danger');
372
				Log::addConfigurationLog('Module '.$this->module->getName().' : Geo Analysis “'.$description.'” could not be added. See error log.');
373
			}
374
        }
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);
386
        
387
    }
388
     
389
	/**
390
	 * Renders the edit form, whether it is an edition of an existing GeoAnalysis, or the addition of a new one.
391
	 * 
392
	 * @param (GeoAnalysis!null) $ga GeoAnalysis to edit
0 ignored issues
show
Documentation Bug introduced by
The doc comment (GeoAnalysis!null) at position 1 could not be parsed: Unknown type name 'GeoAnalysis!null' at position 1 in (GeoAnalysis!null).
Loading history...
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('
401
                function toggleMapOptions() {
402
                    if($("input:radio[name=\'use_map\']:checked").val() == 1) {
403
                        $("#map_options").show();
404
                    }
405
                    else {
406
                        $("#map_options").hide();
407
                    }
408
                }
409
        
410
                $("[name=\'use_map\']").on("change", toggleMapOptions);
411
                toggleMapOptions();
412
            ');
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
        }
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());
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);
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);
440
    
441
        ViewFactory::make('GeoAnalysisEdit', $this, $controller, $data)->render();
442
    }
443
    
444
}