Menu::_get_real_tpl()   F
last analyzed

Complexity

Conditions 20
Paths 189

Size

Total Lines 96

Duplication

Lines 21
Ratio 21.88 %

Importance

Changes 0
Metric Value
cc 20
nc 189
nop 2
dl 21
loc 96
rs 3.425
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
if (!defined('BASEPATH')) {
4
    exit('No direct script access allowed');
5
}
6
7
/**
8
 * Image CMS
9
 *
10
 * Menu module
11
 */
12
class Menu extends MY_Controller
13
{
14
15
    /*     * ***** Это можно редактировать *********** */
16
    private $tpl_folder_prefix = 'level_';
17
18
    /**
19
     *
20
     * @var array
21
     */
22
    private $tpl_file_names = [
23
                               'container'           => 'container',
24
                               'item_default'        => 'item_default',
25
                               'item_default_active' => 'item_default_active',
26
                               'item_first'          => 'item_first',
27
                               'item_first_active'   => 'item_first_active',
28
                               'item_last'           => 'item_last',
29
                               'item_last_active'    => 'item_last_active',
30
                               'item_one'            => 'item_one',
31
                               'item_one_active'     => 'item_one_active',
32
                              ];
33
34
    /*     * ***** То что ниже редактируйте осторожно, вдумчиво :) *********** */
35
    private $current_uri = '';
36
37
    private $tpl_folder = '';
38
39
    private $stack = [];
40
41
    private $errors = [];
42
43
    public $menu_array = []; // the root of the menu tree
44
45
    public $sub_menu_array = []; // the list of menu items
46
47
    public $select_hidden = FALSE;
48
49
    public $arranged_menu_array = [];
50
51
    public $activate_by_sub_urls = TRUE;
52
53
    private $expand = []; // items id to expand
54
55
    private $cache_key = '';
56
57
    public $menu_template_vars = [];
58
59
    private $cur_level = 0;
60
61
    public static $IS_ADMIN_PART = FALSE;
62
63
    public function __construct() {
64
        parent::__construct();
65
        $this->load->module('core');
66
        $this->cache_key = 'menu_data_';
67
        $this->cache_key = $this->cache_key . $this->dx_auth->get_role_id();
68
        $lang = new MY_Lang();
69
        $lang->load('menu');
70
        $this->setAdminPart();
71
        $this->load->helper('string');
72
    }
73
74
    public function index() {
75
        redirect();
76
    }
77
78
    public function autoload() {
79
        $this->load->helper('menu');
80
81
        $this->prepare_current_uri();
82
        //$this->current_uri = site_url( $this->uri->uri_string() );
83
    }
84
85
    /**
86
     * Prepare and set $this->current_uri value
87
     *
88
     * @access private
89
     */
90
    private function prepare_current_uri() {
91
        $lang_id = $this->config->item('cur_lang');
92
        $this->db->select('identif');
93
        $query = $this->db->get_where('languages', ['id' => $lang_id])->result();
94
95
        if ($query) {
96
            if ($this->uri->segment(1) == $query[0]->identif) {
97
                $segment_array = $this->uri->segment_array();
98
                array_shift($segment_array); // убираем первый элемент ( идентификатор языка ) массива сегментов uri
99
                $this->current_uri = site_url($segment_array);
0 ignored issues
show
Documentation introduced by
$segment_array is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
100
            } else {
101
                $this->current_uri = site_url($this->uri->uri_string());
102
            }
103
        } else {
104
            // что-то не в порядке с таблицей languages или функцией $this->config->item
105
            return false;
106
        }
107
        return true;
108
    }
109
110
    /**
111
     * Prepare and display menu
112
     *
113
     * @param string $menu menu name
114
     * @access public
115
     */
116
    public function render($menu) {
117
        $this->clear();
118
119
        $this->prepare_current_uri(); // правильно определяет текущий uri, фикс бага многоязычности
120
121
        $this->prepare_menu_array($menu);
122
123
        $array_keys = array_keys($this->menu_array);
124
        $start_index = $array_keys[0];
125
        $this->tpl_folder = $this->menu_array[$start_index]['tpl'];
126
127
        $this->prepare_menu_recursion(); // Инициализируем первый элемент для начала итераций
128
129
        $this->display_menu($this->menu_array);
130
131
        if ($this->errors) {
132
            $data = [
133
                     'menu'       => $menu,
134
                     'errors'     => array_unique($this->errors),
135
                     'tpl_folder' => $this->tpl_folder,
136
                    ];
137
            $this->display_tpl('error', $data);
138
        } else {
139
            echo $this->arranged_menu_array[-1]['html'];
140
        }
141
    }
142
143
    private function prepare_menu_recursion() {
144
        array_push($this->stack, -1);
145
        $this->arranged_menu_array[-1]['html'] = FALSE;
146
        $this->arranged_menu_array[-1]['level'] = -1;
147
    }
148
149
    private function clear() {
150
        $this->current_uri = '';
151
        $this->tpl_folder = '';
152
        $this->menu_array = [];
153
        $this->errors = [];
154
        $this->sub_menu_array = [];
155
        $this->select_hidden = FALSE;
156
        $this->activate_by_sub_urls = TRUE;
157
        $this->expand = [];
158
        $this->arranged_menu_array = [];
159
        $this->stack = [];
160
        $this->menu_template_vars = [];
161
        $this->cur_level = 0;
162
    }
163
164
    /**
165
     * Recursive function to display menu ul list
166
     * TODO: Rewrite this part of code to display valid html list
167
     *
168
     * @param array $menu_array
169
     * @access public
170
     */
171
    public function display_menu($menu_array) {
172
173
        $array_keys = array_keys($menu_array);
174
        $start_index = $array_keys[0];
175
        $end_index = $array_keys[count($array_keys) - 1];
176
177
        foreach ($menu_array as $item) {
178
            if (!$item['hidden']) {
179
180
                $arranged_items_count = count($this->arranged_menu_array);
181
                $this->arranged_menu_array[$arranged_items_count]['level'] = $this->cur_level;
182
                $this->arranged_menu_array[$arranged_items_count]['tpl'] = $item['tpl'];
183
184
                // Translate title
185
                if (isset($item['lang_title_' . $this->config->item('cur_lang')])) {
186
                    $item['title'] = $item['lang_title_' . $this->config->item('cur_lang')];
187
                }
188
189
                if ($item['item_type'] != 'url') {
190
                    $site_url = site_url($item['link']);
191
                } else {
192
                    $site_url = $item['link'];
193
                }
194
195
                if ($this->activate_by_sub_urls === TRUE) {
196
                    $exp = explode('/', trim_slashes($this->uri->uri_string()));
197
                    $exp2 = explode('/', trim_slashes($item['link']));
198
199
                    $matches = 0;
200
                    foreach ($exp2 as $k => $v) {
201
                        if ($v == $exp[$k]) {
202
                            $matches++;
203
                        }
204
                    }
205
206
                    if ($matches == count($exp2)) {
207
                        $active_cur = TRUE;
208
                    } else {
209
                        $active_cur = FALSE;
210
                    }
211
                }
212
213
                if ($this->cur_level < ($item['expand_level'])) {
214
                    $this->expand[$item['id']] = TRUE; // to expand tree
215
                }
216
                if ($site_url == $this->current_uri OR $active_cur === TRUE) {
217
                    $this->expand[$item['id']] = TRUE;
218
                    $is_active = TRUE;
0 ignored issues
show
Unused Code introduced by
$is_active is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
219
                    $this->arranged_menu_array[$arranged_items_count]['is_active'] = TRUE;
220
                } else {
221
                    // Make link active if link is / and no segments in url
222
                    // if ($item['link'] == '/' AND $this->uri->total_segments() == 0) {
223
                    if ($item['link'] == '/' AND get_main_lang('identif') == $this->uri->segment(1) AND $this->uri->total_segments() == 1 or $item['link'] == '/' AND get_main_lang('identif') != $this->uri->segment(1) AND $this->uri->total_segments() == 0 or $item['item_type'] == 'url' AND $item['link'] != '/' AND strstr($this->input->server('REQUEST_URI'), $item['link'])) {
224
                        $is_active = TRUE;
0 ignored issues
show
Unused Code introduced by
$is_active is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
225
                        $this->arranged_menu_array[$arranged_items_count]['is_active'] = TRUE;
226
                    } else {
227
                        $is_active = FALSE;
0 ignored issues
show
Unused Code introduced by
$is_active is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
228
                        $this->arranged_menu_array[$arranged_items_count]['is_active'] = FALSE;
229
                    }
230
                }
231
232
                //$item['item_type'] == 'url' ? $href = $item['link'] : $href = site_url($item['link']);
233
                //echo $item['item_type'];
234
                if ($item['item_type'] == 'url' && strstr($item['link'], 'http://') or $item['item_type'] == 'url' && strstr($item['link'], 'www')) {
235
                    $href = $item['link'];
236
                } else {
237
                    $href = rtrim(site_url($item['link']), '/');
238
                }
239
240
                $this->arranged_menu_array[$arranged_items_count]['link'] = $href;
241
                $this->arranged_menu_array[$arranged_items_count]['id'] = $item['id'];
242
                $this->arranged_menu_array[$arranged_items_count]['title'] = $item['title'];
243
                $this->arranged_menu_array[$arranged_items_count]['image'] = $item['image'];
244
                if (!is_array($item['add_data'])) {
245
                    $item['add_data'] = unserialize($item['add_data']);
246
                    $item['add_data']['newpage'] == '1' ? $this->arranged_menu_array[$arranged_items_count]['target'] = 'target="_blank"' : $this->arranged_menu_array[$arranged_items_count]['target'] = 'target="_self"';
247
                } else {
248
                    $item['add_data']['newpage'] == '1' ? $this->arranged_menu_array[$arranged_items_count]['target'] = 'target="_blank"' : $this->arranged_menu_array[$arranged_items_count]['target'] = 'target="_self"';
249
                }
250
251 View Code Duplication
                if (($menu_array[$start_index]['position'] != $item['position']) AND ($menu_array[$end_index]['position'] != $item['position'])) {
252
                    $this->arranged_menu_array[$arranged_items_count]['edge'] = 'default';
253
                }
254
255 View Code Duplication
                if (($menu_array[$start_index]['position'] == $item['position']) AND ($menu_array[$end_index]['position'] != $item['position'])) {
256
                    $this->arranged_menu_array[$arranged_items_count]['edge'] = 'first';
257
                }
258
259 View Code Duplication
                if (($menu_array[$start_index]['position'] != $item['position']) AND ($menu_array[$end_index]['position'] == $item['position'])) {
260
                    $this->arranged_menu_array[$arranged_items_count]['edge'] = 'last';
261
                }
262
263 View Code Duplication
                if (($menu_array[$start_index]['position'] == $item['position']) AND ($menu_array[$end_index]['position'] == $item['position'])) {
264
                    $this->arranged_menu_array[$arranged_items_count]['edge'] = 'one';
265
                }
266
267
                $sub_menus = $this->_get_sub_menus($item['id']);
268
269
                $this->arranged_menu_array[$arranged_items_count]['has_childs'] = count($sub_menus) > 0 ? 1 : 0;
270
271
                if (isset($this->expand[$item['id']]) AND $this->expand[$item['id']] == TRUE AND count($sub_menus) > 0) {
272
                    $this->cur_level++;
273
                    array_push($this->stack, $arranged_items_count);
274
275
                    $this->display_menu($sub_menus);
276
                } else {
277
                    $this->_prepare_item_tpl($arranged_items_count);
278
                }
279
            }
280
        }
281
282
        $wrapper = '';
283
        $stack_item = array_pop($this->stack);
284
        for ($i = $stack_item + 1; $i <= $arranged_items_count; $i++) {
285
            if ($this->arranged_menu_array[$i]['level'] <= $this->arranged_menu_array[$stack_item]['level'] + 1) {
286
                $wrapper .= $this->arranged_menu_array[$i]['html'] . "\n";
287
            }
288
        }
289
290
        $this->_prepare_item_tpl($stack_item, $wrapper);
291
292
        $this->cur_level--;
293
    }
294
295
    /**
296
     * Натягивает шаблон на данные и запихивает всю эту красоту в this->arranged_menu_array[$arranged_items_count]['html']. версия для элемента списка
297
     *
298
     * @param integer $index номер элемента для натягивания шаблона
299
     * @param string $wrapper натянутые шаблоны на всех всех наследников
300
     * @access private
301
     * @return string|false
302
     */
303
    private function _prepare_container_tpl($index = 0, $wrapper = FALSE) {
304
        $data = ['wrapper' => $wrapper];
305
306
        $tpl_path = $this->_get_real_tpl($index, 'container');
307
        if ($tpl_path) {
308
            return $this->fetch_tpl($tpl_path, $data);
309
        } else {
310
            return FALSE;
311
        }
312
    }
313
314
    /**
315
     * Натягивает данные на шаблон и запихивает всю эту красоту в this->arranged_menu_array[$arranged_items_count]['html']. версия для элемента списка
316
     *
317
     * @param integer $index номер элемента для натягивания шаблона
318
     * @param string $wrapper натянутые шаблоны на всех всех наследников
319
     * @access private
320
     * @return TRUE
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
321
     */
322
    private function _prepare_item_tpl($index = 0, $wrapper = FALSE) {
323
        if ($wrapper == TRUE) {
324
            $wrapper = $this->_prepare_container_tpl($index, $wrapper);
325
        }
326
327
        $is_active_hard = $this->arranged_menu_array[$index]['link'] == $this->current_uri ? 1 : 0;
328
329
        $data = [
330
                 'id'             => $this->arranged_menu_array[$index]['id'],
331
                 'title'          => $this->arranged_menu_array[$index]['title'],
332
                 'link'           => $this->arranged_menu_array[$index]['link'],
333
                 'image'          => $this->arranged_menu_array[$index]['image'],
334
                 'wrapper'        => $wrapper,
335
                 'target'         => $this->arranged_menu_array[$index]['target'],
336
                 'has_childs'     => $this->arranged_menu_array[$index]['has_childs'],
337
                 'is_active_hard' => $is_active_hard,
338
                ];
339
340
        if ($index == -1) {
341
            $this->arranged_menu_array[$index]['html'] = $wrapper;
342
        } else {
343
            $tpl_path = $this->_get_real_tpl($index);
344
            if ($tpl_path) {
345
                $this->arranged_menu_array[$index]['html'] = $this->fetch_tpl($tpl_path, $data);
346
            }
347
        }
348
349
        return TRUE;
350
    }
351
352
    /**
353
     * Find sub menus
354
     *
355
     * @param integer $id
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
356
     * @access public
357
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string|false.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
358
     */
359
    private function _get_real_tpl($index = 0, $mode = 'item') {
360
        if ($mode == 'item') {
361
            $is_active = $this->arranged_menu_array[$index]['is_active'];
362
            $edge = $this->arranged_menu_array[$index]['edge'];
363
364
            switch ($edge) {
365
                case 'first':
366
                    $item_active_tpl = $this->tpl_file_names['item_first_active'];
367
                    $item_tpl = $this->tpl_file_names['item_first'];
368
                    break;
369
                case 'last':
370
                    $item_active_tpl = $this->tpl_file_names['item_last_active'];
371
                    $item_tpl = $this->tpl_file_names['item_last'];
372
                    break;
373
                case 'one':
374
                    $item_active_tpl = $this->tpl_file_names['item_one_active'];
375
                    $item_tpl = $this->tpl_file_names['item_one'];
376
                    break;
377
                default:
378
                    // ничего вроде не надо...
379
                    break;
380
            }
381
382
            /*             * *** дефолтный шаблон ***** */
383
            $default_item_active_tpl = $this->tpl_file_names['item_default_active'];
384
            $default_item_tpl = $this->tpl_file_names['item_default'];
385
            $is_good = FALSE;
386
387
            for ($level = $this->arranged_menu_array[$index]['level']; $level >= 0; $level--) {
388
                if ($is_active) {
389 View Code Duplication
                    if ($item_active_tpl) {
390
                        $tpl = $this->tpl_folder_prefix . $level . '/' . $this->tpl_file_names[$item_active_tpl];
391
                        if ($this->test_tpl($tpl)) {
392
                            $is_good = TRUE;
393
                            break;
394
                        }
395
                    }
396 View Code Duplication
                    if ($item_tpl) {
397
                        $tpl = $this->tpl_folder_prefix . $level . '/' . $this->tpl_file_names[$item_tpl];
398
                        if ($this->test_tpl($tpl)) {
399
                            $is_good = TRUE;
400
                            break;
401
                        }
402
                    }
403
404
                    $tpl = $this->tpl_folder_prefix . $level . '/' . $this->tpl_file_names[$default_item_active_tpl];
405
                    if ($this->test_tpl($tpl)) {
406
                        $is_good = TRUE;
407
                        break;
408
                    }
409
410
                    $tpl = $this->tpl_folder_prefix . $level . '/' . $this->tpl_file_names[$default_item_tpl];
411
                    if ($this->test_tpl($tpl)) {
412
                        $is_good = TRUE;
413
                        break;
414
                    }
415
                } else {
416 View Code Duplication
                    if ($item_tpl) {
417
                        $tpl = $this->tpl_folder_prefix . $level . '/' . $this->tpl_file_names[$item_tpl];
418
                        if ($this->test_tpl($tpl)) {
419
                            $is_good = TRUE;
420
                            break;
421
                        }
422
                    }
423
                    $tpl = $this->tpl_folder_prefix . $level . '/' . $this->tpl_file_names[$default_item_tpl];
424
                    if ($this->test_tpl($tpl)) {
425
                        $is_good = TRUE;
426
                        break;
427
                    }
428
                }
429
            }
430
        } else {
431
            for ($level = $this->arranged_menu_array[$index]['level'] + 1; $level >= 0; $level--) {
432
                $tpl = $this->tpl_folder_prefix . $level . '/' . $this->tpl_file_names['container'];
433
                if ($this->test_tpl($tpl)) {
434
                    $is_good = TRUE;
435
                    break;
436
                }
437
            }
438
        }
439
440
        if ($is_good) {
441
            return $tpl;
442
        } else {
443
            //передача управления сюда означает что один из необходимых файлов шаблона меню не найден в указанной папке
444
445
            if ($this->tpl_folder) {
446
                $err_data = ['user_template' => $this->tpl_folder . '/' . $tpl . '.tpl'];
447
            } else {
448
                $err_data = ['system_template' => './application/' . getModContDirName('menu') . '/menu/templates/public/' . $tpl . '.tpl'];
449
            }
450
451
            $this->errors[] = $err_data;
452
            return FALSE;
453
        }
454
    }
455
456
    /**
457
     * Find sub menus
458
     *
459
     * @param integer $id
460
     * @access public
461
     * @return array|false
462
     */
463
    public function _get_sub_menus($id) {
464
        $sub_menus = [];
465
466
        foreach ($this->sub_menu_array as $sub_menu) {
467
            if ($sub_menu['parent_id'] == $id) {
468
                array_push($sub_menus, $sub_menu);
469
470
                if (site_url($item['link']) == $this->current_uri) {
471
                    $this->expand[$item['id']] == TRUE;
0 ignored issues
show
Bug introduced by
The variable $item does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
472
                }
473
            }
474
        }
475
476
        if (count($sub_menus > 0)) {
477
            return $sub_menus;
478
        } else {
479
            return FALSE;
480
        }
481
    }
482
483
    /**
484
     * Select menu data from DB and separate menus is two arrays: root and submenus.
485
     *
486
     * @param string $menu - menu name
487
     * @access public
488
     */
489
    public function prepare_menu_array($menu) {
490
        $menu_cache_key = $this->cache_key . $menu . self::getCurrentLocale();
491
        if (($menu_data = $this->cache->fetch($menu_cache_key, 'menus')) !== FALSE) {
492
            $this->menu_array = $menu_data['menu_array'];
493
            $this->sub_menu_array = $menu_data['sub_menu_array'];
494
        } else {
495
            $this->db->select('menus.name', FALSE);
496
            $this->db->select('menus.tpl AS tpl', FALSE);
497
            $this->db->select('menus.expand_level AS expand_level', FALSE);
498
            //$this->db->select('menus.main_title', FALSE);
499
            $this->db->select('menus_data.id AS id', FALSE);
500
            $this->db->select('menus_data.menu_id AS menu_id', FALSE);
501
            $this->db->select('menus_data.item_type AS item_type', FALSE);
502
            $this->db->select('menus_data.item_id AS item_id', FALSE);
503
            $this->db->select('menus_data.title AS title', FALSE);
504
            $this->db->select('menus_data.hidden AS hidden', FALSE);
505
            $this->db->select('menus_data.position AS position', FALSE);
506
            $this->db->select('menus_data.roles AS roles', FALSE);
507
            $this->db->select('menus_data.parent_id AS parent_id', FALSE);
508
            $this->db->select('menus_data.description AS description', FALSE);
509
            $this->db->select('menus_data.add_data AS add_data', FALSE);
510
            $this->db->select('menus_data.item_image AS image', FALSE);
511
512
            $this->db->join('menus_data', 'menus_data.menu_id = menus.id');
513
            $this->db->where('menus.name', $menu);
514
            $this->db->where('menus_data.hidden', 0);
515
            $this->db->order_by('position', 'asc');
516
517
            // Select hidden items
518
            if ($this->select_hidden == TRUE) {
519
                $this->db->or_where('menus_data.hidden', 1);
520
                $this->db->where('menus.name', $menu);
521
            }
522
523
            $menus = $this->db->get('menus');
524
525
            if ($menus->num_rows() == 0) {
526
                //echo 'Ошибка загрузки меню '.$menu;
527
                return FALSE;
528
            } else {
529
                $menus = $menus->result_array();
530
            }
531
532
            // detect roles
533
            $cnt = count($menus);
534
            for ($i = 0; $i < $cnt; $i++) {
535
                if ($menus[$i]['roles'] != FALSE) {
536
                    $access = $this->_check_roles(unserialize($menus[$i]['roles']));
537
                    if ($access == FALSE) {
538
                        unset($menus[$i]);
539
                    }
540
                }
541
            }
542
543
            $this->cur_menu_id = $menus[0]['menu_id'];
544
            $this->load->model('menu_model', 'item');
545
546
            $menus = array_values($menus);
547
548
            $langs = $this->db->get('languages');
549
550
            if ($langs->num_rows() > 0) {
551
                $langs = $langs->result_array();
552
            } else {
553
                $langs = FALSE;
554
            }
555
556
            // Create links
557
            $cnt = count($menus);
558
            for ($i = 0; $i < $cnt; $i++) {
559
                switch ($menus[$i]['item_type']) {
560
                    case 'page':
561
562
                        $url = $this->item->get_page_url($menus[$i]['item_id']);
563
                        $menus[$i]['link'] = $url['cat_url'] . '/' . $url['url'];
564
                        break;
565
566
                    case 'category':
567
                        $category = $this->lib_category->get_category($menus[$i]['item_id']);
568
                        $menus[$i]['link'] = $category['path_url'];
569
                        break;
570
571
                    case 'module':
572
                        $mod_info = unserialize($menus[$i]['add_data']);
573
                        $mod_url = $this->item->get_module_link($mod_info['mod_name']);
574
575
                        if ($menus[$i]['add_data'] != NULL) {
576
                            $method = $mod_info['method'];
577
578
                            if (substr($method, 0, 1) == '/') {
579
                                $url = $mod_url . $method;
580
                            } else {
581
                                $url = $mod_url . '/' . $method;
582
                            }
583
                        }
584
585
                        $menus[$i]['link'] = $url;
586
                        break;
587
588
                    case 'url':
589
                        $menus[$i]['add_data'] = unserialize($menus[$i]['add_data']);
590
                        $menus[$i]['link'] = $menus[$i]['add_data']['url'];
591
                        break;
592
                }
593
594
                if ($langs != FALSE) {
595
                    foreach ($langs as $lang) {
596
597
                        if (self::getCurrentLocale($lang)) {
598
                            $this->db->where('item_id', $menus[$i]['id']);
599
                            $this->db->where('lang_id', $lang['id']);
600
                            $t_query = $this->db->get('menu_translate');
601
602
                            if ($t_query->num_rows() == 1) {
603
                                $n_title = $t_query->row_array();
604
                                if ($n_title['title']) {
605
                                    $menus[$i]['title'] = $n_title['title'];
606
                                }
607
                            }
608
                        }
609
                    }
610
                }
611
612
                if ($menus[$i]['parent_id'] == 0) {
613
                    $this->menu_array[$menus[$i]['id']] = $menus[$i];
614
                } else {
615
                    $this->sub_menu_array[$menus[$i]['id']] = $menus[$i];
616
                }
617
            }
618
619
            $data = [
620
                     'menu_array'     => $this->menu_array,
621
                     'sub_menu_array' => $this->sub_menu_array,
622
                    ];
623
624
            $this->cache->store($menu_cache_key, $data, FALSE, 'menus');
625
        }
626
    }
627
628
    /**
629
     * Get current locale for menu module
630
     * @param $language
631
     * @return string|boolean
632
     */
633
    public static function getCurrentLocale($language = NULL) {
634
        if ($language == null) {
635
            return self::$IS_ADMIN_PART ? MY_Controller::defaultLocale() : MY_Controller::getCurrentLocale();
636
        }
637
638
        if (self::$IS_ADMIN_PART && $language['identif'] == MY_Controller::defaultLocale()) {
639
            return TRUE;
640
        }
641
642
        if (!self::$IS_ADMIN_PART && $language['identif'] == MY_Controller::getCurrentLocale()) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !self::$IS_ADMIN_...er::getCurrentLocale();.
Loading history...
643
            return TRUE;
644
        }
645
646
        return FALSE;
647
    }
648
649
    private function setAdminPart() {
650
        return $this->uri->segment(1) === 'admin' ? TRUE : FALSE;
651
    }
652
653
    /**
654
     *
655
     * @param array $roles
656
     * @return boolean
657
     */
658
    private function _check_roles($roles = []) {
659
        $access = FALSE;
660
661
        foreach ($roles as $role_id) {
662
            $my_role = $this->dx_auth->get_role_id();
663
664
            // admin
665
            if ($this->dx_auth->is_admin() === TRUE) {
666
                $access = TRUE;
667
            }
668
669
            // all users
670
            if ($role_id == 0) {
671
                $access = TRUE;
672
            }
673
674
            if ($role_id == $my_role) {
675
                $access = TRUE;
676
            }
677
        }
678
679
        return $access;
680
    }
681
682 View Code Duplication
    public function get_all_menus() {
683
        $this->db->select('name, main_title');
684
        $query = $this->db->get('menus');
685
686
        if ($query->num_rows() > 0) {
687
            return $query->result_array();
688
        } else {
689
            return FALSE;
690
        }
691
    }
692
693
    /**
694
     * Display template file
695
     */
696
    private function display_tpl($file = '', $data = []) {
697
        if (count($data) > 0) {
698
            $this->template->add_array($data);
699
        }
700
701
        $file = realpath(__DIR__) . '/templates/public/' . $file . '.tpl';
702
703
        $this->template->display('file:' . $file);
704
    }
705
706
    /**
707
     * Fetch template file
708
     */
709
    private function fetch_tpl($file = '', $data = []) {
710
        if (count($data) > 0) {
711
            $this->template->add_array($data);
712
        }
713
714 View Code Duplication
        if ($this->tpl_folder) {
715
            $file = $this->template->template_dir . $this->tpl_folder . '/' . $file . '.tpl';
716
        } else {
717
            $file = realpath(__DIR__) . '/templates/public/' . $file . '.tpl';
718
        }
719
720
        return $this->template->fetch('file:' . $file);
721
    }
722
723
    private function test_tpl($file = '') {
724 View Code Duplication
        if ($this->tpl_folder) {
725
            $file = $this->template->template_dir . $this->tpl_folder . '/' . $file . '.tpl';
726
        } else {
727
            $file = realpath(__DIR__) . '/templates/public/' . $file . '.tpl';
728
        }
729
730
        if (file_exists($file)) {
0 ignored issues
show
Coding Style introduced by
The if-else statement can be simplified to return file_exists($file);.
Loading history...
731
            return TRUE;
732
        } else {
733
            return FALSE;
734
        }
735
    }
736
737
    public function _install() {
738
        $this->db->where('name', 'menu');
739
        $this->db->update('components', ['autoload' => 1]);
740
    }
741
742
}