Completed
Push — development ( a150a5...f82eb6 )
by Andrij
17:01
created

Core::use_def_language()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
use CMSFactory\Events;
4
5
if (!defined('BASEPATH')) {
6
    exit('No direct script access allowed');
7
}
8
9
/**
10
 * TODO COMPLETED:
11
 * remove _prepare_content method
12
 * remove bridge
13
 * simplify language url segment
14
 *
15
 *
16
 * Image CMS
0 ignored issues
show
introduced by
There must be exactly one blank line between descriptions in a doc comment
Loading history...
17
 *
18
 * core.php
19
 * @property Cms_base $cms_base
20
 * @property Lib_category $lib_category
21
 * @property Cfcm $cfcm
22
 * @property Lib_seo lib_seo
23
 */
24
class Core extends MY_Controller
25
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
26
27
    /**
28
     * @var string
29
     */
30
    public $action = ''; // Langs array
31
32
    /**
33
     * @var bool
34
     */
35
    public $by_pages = FALSE; // Default language array
36
37
    /**
38
     * @var array
39
     */
40
    public $cat_content = []; // Page data
41
42
    /**
43
     * @var int
44
     */
45
    public $cat_page = 0; // Category data
46
47
    /**
48
     * @var array
49
     */
50
    public $core_data = ['data_type' => null]; // Site settings
51
52
    /**
53
     * @var array
54
     */
55
    public $def_lang = []; // Modules array
56
57
    /**
58
     * @var array
59
     */
60
    public $langs = [];
61
62
    /**
63
     * @var array
64
     */
65
    public $modules = [];
66
67
    /**
68
     * @var array
69
     */
70
    public $page_content = [];
71
72
    /**
73
     * @var array
74
     */
75
    public $settings = [];
76
77
    /**
78
     * @var array
79
     */
80
    public $tpl_data = [];
81
82
    public function __construct() {
83
84
        parent::__construct();
85
        $this->_load_languages();
86
        Modules::$registry['core'] = $this;
87
        $lang = new MY_Lang();
88
        $lang->load('core');
89
        $this->load->module('cfcm');
90
    }
91
92
    public function index() {
93
94
        //module url segment
95
        $mod_segment = 1;
96
        $data_type = '';
97
98
        $cat_path = $this->uri->uri_string();
99
        $this->settings = $this->cms_base->get_settings();
100
101
        // Set site main template
102
        $this->config->set_item('template', $this->settings['site_template']);
103
        $this->load->library('template');
104
105
        if (($this->input->get() || strstr($this->input->server('REQUEST_URI'), '?')) && $this->uri->uri_string() == '') {
106
            $this->template->registerCanonical(site_url());
107
        }
108
109
        /* Show Analytic codes if some value inserted in admin panel */
110
        $this->load->library('lib_seo');
111
        $this->lib_seo->init($this->settings);
112
113
        if ($uri_lang = $this->detectLanguage($cat_path)) {
114
            $cat_path = substr($cat_path, strlen($uri_lang) + 1);
115
            $mod_segment = 2;
116
        }
117
118
        $this->load_functions_file($this->settings['site_template']);
119
120
        $this->checkOffline();
121
122
        $this->correctDefaultLangUrl();
123
124
        $this->load->library('lib_category');
125
        $this->lib_category->setLocaleId($this->config->item('cur_lang'));
126
        $categories = $this->lib_category->build();
127
        $this->tpl_data['categories'] = $categories;
128
        $cats_unsorted = $this->lib_category->unsorted();
129
130
        $this->initModules();
131
132
        $this->load->library('DX_Auth');
133
134
        if ($cat_path == FALSE) {
135
            $data_type = 'main';
136
        }
137
138
        $last_element = key($this->uri->uri_to_assoc(0));
139
140
        //is pagination page
141
        if (is_numeric($last_element)) {
142
            $cat_path = $this->_prepCatPath($cat_path);
143
            $this->by_pages = TRUE;
144
            $this->cat_page = $last_element;
0 ignored issues
show
Documentation Bug introduced by
It seems like $last_element can also be of type double or string. However, the property $cat_page is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
145
        }
146
147
        foreach ($cats_unsorted as $cat) {
148
            if ($cat['path_url'] == $cat_path . '/') {
149
                $this->cat_content = $cat;
150
                $data_type = 'category';
151
                break;
152
            }
153
        }
154
155
        if ($data_type != 'main' AND $data_type != 'category') {
156
157
            if ($this->findPage($cat_path, $last_element, $cats_unsorted)) {
158
                $data_type = 'page';
159
            } else {
160
                $data_type = '404';
161
            }
162
163
        }
164
165
        // Possible values: page/category/main/404
166
        $this->core_data['data_type'] = $data_type;
167
168
        $this->assignTemplateData();
169
170
        // Assign template variables and load modules
171
        $this->_process_core_data();
172
173
        // Check url segments
174
        $this->_check_url();
175
176
        // on every page load
177
        Events::create()->registerEvent(NULL, 'Core:pageLoaded');
178
179
        // If module than exit from core and load module
180
        if ($this->is_module($mod_segment) == TRUE) {
181
            return;
182
        }
183
184
        $this->display();
185
186
    }
187
188
    private function display() {
189
        if ($this->core_data['data_type'] == 'main') {
190
            switch ($this->settings['main_type']) {
191
                case 'page':
192
                    $main_id = $this->settings['main_page_id'];
193
                    break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
194
                case 'category':
195
                    $main_id = $this->settings['main_page_cat'];
196
                    break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
197
                case 'module':
198
                    $main_id = $this->settings['main_page_module'];
199
                    break;
200
            }
201
            $this->core->core_data['id'] = $main_id;
202
            $this->_mainpage();
203
        } elseif ($this->core_data['data_type'] == 'category') {
204
            $this->core->core_data['id'] = $this->cat_content['id'];
205
            $this->_display_category($this->cat_content);
206
        } elseif ($this->core_data['data_type'] == 'page') {
207
            $this->check_page_access($this->page_content['roles']);
208
            $this->core->core_data['id'] = $this->page_content['id'];
209
            $this->_display_page_and_cat($this->page_content, $this->cat_content);
210
        } elseif ($this->core_data['data_type'] == '404') {
211
            $this->error_404();
212
        }
213
    }
214
215
    /**
216
     * @return string|null
217
     */
218
    private function detectLanguage() {
219
220
        $haveSegments = $this->uri->total_segments() >= 1;
221
        $languageExists = array_key_exists($this->uri->segment(1), $this->langs);
222
        if ($haveSegments && $languageExists) {
223
224
            $uri_lang = $this->uri->segment(1);
225
            $this->setLanguage($this->langs[$uri_lang]);
226
            // Reload template settings
227
            $this->template->set_config_value('tpl_path', TEMPLATES_PATH . $this->settings['site_template'] . '/');
228
            $this->template->load();
229
230
            // Add language identifier to base_url
231
            $this->config->set_item('base_url', base_url() . $uri_lang);
232
233
            return $uri_lang;
234
        }
235
236
        $this->setLanguage($this->def_lang[0]);
237
    }
238
239
    /**
240
     * @param array $language
241
     */
242
    private function setLanguage(array $language) {
243
244
        $this->config->set_item('language', $language['folder']);
245
        // Load Language
246
        $this->lang->load('main', $language['folder']);
247
        // Set current language variable
248
        $this->config->set_item('cur_lang', $language['id']);
249
    }
250
251
    /**
252
     * Show offline page if site in offline mode
253
     */
254
    private function checkOffline() {
255
        $isMainSaasRequest = 0 === strpos($this->input->server('PATH_INFO'), '/mainsaas');
256
        $siteIsOffline = $this->settings['site_offline'] == 'yes';
257
        $isAdmin = $this->session->userdata('DX_role_id') == 1;
258
        if ($siteIsOffline && !$isMainSaasRequest && !$isAdmin) {
259
            header('HTTP/1.1 503 Service Unavailable');
260
            $this->template->display('offline');
261
            exit;
262
        }
263
    }
264
265
    /**
266
     * redirect to url without default lang segment
267
     */
268
    private function correctDefaultLangUrl() {
269
        if ($this->uri->segment(1) == $this->def_lang[0]['identif']) {
270
            $get = $this->input->server('QUERY_STRING') ? '?' . $this->input->server('QUERY_STRING') : '';
271
            $url = implode('/', array_slice($this->uri->segment_array(), 1));
272
            header('Location:/' . $url . $get);
273
            exit;
274
        }
275
    }
276
277
    /**
278
     * Load site languages
279
     *
280
     * move to model
0 ignored issues
show
introduced by
Doc comment long description must start with a capital letter
Loading history...
281
     */
282
    public function _load_languages() {
283
284
        // Load languages
285
286
        if (($langs = $this->cache->fetch('main_site_langs')) === FALSE) {
287
            $langs = $this->cms_base->get_langs(TRUE);
288
            $this->cache->store('main_site_langs', $langs);
289
        }
290
291
        foreach ($langs as $lang) {
292
            $this->langs[$lang['identif']] = [
293
                                              'id'       => $lang['id'],
294
                                              'name'     => $lang['lang_name'],
295
                                              'folder'   => $lang['folder'],
296
                                              'template' => $lang['template'],
297
                                              'image'    => $lang['image'],
298
                                             ];
299
300
            if ($lang['default'] == 1) {
301
                $this->def_lang = [$lang];
302
            }
303
        }
304
    }
305
306
    /**
307
     * @param string $tpl_name
308
     */
309
    private function load_functions_file($tpl_name) {
310
311
        $full_path = './templates/' . $tpl_name . '/functions.php';
312
313
        if (file_exists($full_path)) {
314
            include $full_path;
315
        }
316
    }
317
318
    /**
319
     *
320
     * @param string $cat_path
321
     * @return string
322
     */
323
    public function _prepCatPath($cat_path) {
324
        // Delete page number from path
325
        $cat_path = substr($cat_path, 0, strrpos($cat_path, '/'));
326
        return $cat_path;
327
    }
328
329
    private function user_browser() {
330
331
        $this->load->library('user_agent');
332
        $browserIn = [
333
                      '0' => $this->agent->browser(),
334
                      '1' => $this->agent->version(),
335
                     ];
336
        return $browserIn;
337
    }
338
339
    private function _process_core_data() {
340
341
        SHOP_INSTALLED && class_exists('ShopCore') && ShopCore::initEnviroment();
342
        $this->template->add_array($this->tpl_data);
343
        $this->load_modules();
344
    }
345
346
    /**
347
     * Load and run modules
348
     */
349
    private function load_modules() {
350
351
        foreach ($this->modules as $module) {
352
            if ($module['autoload'] == 1) {
353
                $mod_name = $module['name'];
354
355
                $this->load->module($mod_name);
356
                if (method_exists($mod_name, 'autoload') === TRUE) {
357
                    $this->core_data['module'] = $mod_name;
358
                    $this->$mod_name->autoload();
359
                    /** @todo why? */
360
                    self::$detect_load[$mod_name] = 1;
361
                }
362
            }
363
        }
364
    }
365
366
    /**
367
     * todo: check error method and remove
368
     * Deny access to modules install/deinstall/rules/etc/ methods
369
     */
370
    private function _check_url() {
371
372
        $fullUrl = explode('?', $this->input->server('HTTP_HOST') . $this->input->server('REQUEST_URI'));
373
        $urlWithoutGet = $fullUrl[0];
374
        if (strstr($urlWithoutGet, '//')) {
375
            $this->error_404();
376
        }
377
378
        $CI = &get_instance();
379
380
        $not_permitted = [
381
                          '_install',
382
                          '_deinstall',
383
                          '_install_rules',
384
                          'autoload',
385
                          '__construct',
386
                         ];
387
388
        $url_segs = $CI->uri->segment_array();
389
390
        // Deny uri access to all methods like _somename
391
        if (count(explode('/_', $CI->uri->uri_string())) > 1) {
392
            $this->error_404();
393
        }
394
395
        if (count($url_segs) > 0) {
396
            foreach ($url_segs as $segment) {
397
                if (in_array($segment, $not_permitted) == TRUE) {
398
                    $this->error_404();
399
                }
400
            }
401
        }
402
    }
403
404
    /**
405
     * Display error template end exit
406
     * @param string $text
407
     * @param bool $back
408
     */
409
    public function error($text, $back = TRUE) {
410
411
        $this->template->add_array(
412
            [
413
             'content' => $this->template->read('error', ['error_text' => $text, 'back_button' => $back]),
414
            ]
415
        );
416
417
        $this->template->show();
418
        exit;
419
    }
420
421
    /**
422
     * Page not found
423
     * Show 404 error
424
     */
425
    public function error_404() {
426
427
        header('HTTP/1.1 404 Not Found');
428
        $this->set_meta_tags(lang('Page not found', 'core'));
429
        $this->template->assign('error_text', lang('Page not found.', 'core'));
430
        $this->template->show('404');
431
        exit;
432
    }
433
434
    /**
435
     * Set meta tags for pages
436
     * @param string $title
437
     * @param string $keywords
438
     * @param string $description
439
     * @param string $page_number
440
     * @param int $showsitename
441
     * @param string $category
442
     */
443
    public function set_meta_tags($title = '', $keywords = '', $description = '', $page_number = '', $showsitename = 0, $category = '') {
444
445
        if ($this->core_data['data_type'] == 'main') {
446
            $this->template->add_array(
447
                [
448
                 'site_title'       => empty($this->settings['site_title']) ? $title : $this->settings['site_title'],
449
                 'site_description' => empty($this->settings['site_description']) ? $description : $this->settings['site_description'],
450
                 'site_keywords'    => empty($this->settings['site_keywords']) ? $keywords : $this->settings['site_keywords'],
451
                ]
452
            );
453
        } else {
454
            if (($page_number > 1) && ($page_number != '')) {
455
                $title = lang('Page', 'core') . ' №' . $page_number . ' - ' . $title;
456
            }
457
458
            if ($description != '') {
459
                if ($page_number > 1 && $page_number != '') {
460
                    $description = "$page_number - $description {$this->settings['delimiter']} {$this->settings['site_short_title']}";
461
                } else {
462
                    $description = "$description {$this->settings['delimiter']} {$this->settings['site_short_title']}";
463
                }
464
            }
465
466
            if ($this->settings['add_site_name_to_cat']) {
467
                if ($category != '') {
468
                    $title .= ' - ' . $category;
469
                }
470
            }
471
472
            if ($this->core_data['data_type'] == 'page' AND $this->page_content['category'] != 0 AND $this->settings['add_site_name_to_cat']) {
473
                $title .= ' ' . $this->settings['delimiter'] . ' ' . $this->cat_content['name'];
474
            }
475
476
            if (is_array($title)) {
477
                $n_title = '';
478
                foreach ($title as $k => $v) {
479
                    $n_title .= $v;
480
481
                    if ($k < count($title) - 1) {
482
                        $n_title .= ' ' . $this->settings['delimiter'] . ' ';
483
                    }
484
                }
485
                $title = $n_title;
486
            }
487
488
            if ($this->settings['add_site_name'] == 1 && $showsitename != 1) {
489
                $title .= ' ' . $this->settings['delimiter'] . ' ' . $this->settings['site_short_title'];
490
            }
491
492
            if ($this->settings['create_description'] == 'empty') {
493
                $description = '';
494
            }
495
            if ($this->settings['create_keywords'] == 'empty') {
496
                $keywords = '';
497
            }
498
499
            $page_number = $page_number ?: (int) $this->pagination->cur_page;
500
            $this->template->add_array(
501
                [
502
                 'site_title'       => $title,
503
                 'site_description' => htmlspecialchars($description),
504
                 'site_keywords'    => htmlspecialchars($keywords),
505
                 'page_number'      => $page_number,
506
                ]
507
            );
508
        }
509
    }
510
511
    /**
512
     * Run module
513
     * @access private
514
     * @param integer $n
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
515
     * @return bool
516
     */
517
    private function is_module($n) {
518
519
        $segment = $this->uri->segment($n);
520
        $found = FALSE;
521
522
        foreach ($this->modules as $k) {
523
            if ($k['identif'] === $segment AND $k['enabled'] == 1) {
524
                $found = TRUE;
525
                $mod_name = $k['identif'];
526
            }
527
        }
528
529
        if ($found == TRUE) {
530
            $mod_function = $this->uri->segment($n + 1);
531
532
            if ($mod_function == FALSE) {
533
                $mod_function = 'index';
534
            }
535
536
            $file = getModulePath($mod_name) . $mod_function . EXT;
537
538
            $this->core_data['module'] = $mod_name;
539
540
            if (file_exists($file)) {
541
                // Run module
542
                $func = $this->uri->segment($n + 2);
543
                if ($func == FALSE) {
544
                    $func = 'index';
545
                }
546
547
                $args = $this->grab_variables($n + 3);
548
549
                $this->load->module($mod_name . '/' . $mod_function);
550
551 View Code Duplication
                if (method_exists($mod_function, $func)) {
552
                    echo modules::run($mod_name . '/' . $mod_function . '/' . $func, $args);
553
                } else {
554
                    $this->error_404();
555
                }
556
            } else {
557
                $args = $this->grab_variables($n + 2);
558
                $this->load->module($mod_name);
559 View Code Duplication
                if (method_exists($mod_name, $mod_function)) {
560
                    echo modules::run($mod_name . '/' . $mod_name . '/' . $mod_function, $args);
561
                } else {
562
                    // If method not found display 404 error.
563
                    $this->error_404();
564
                }
565
            }
566
567
            return TRUE;
568
        }
569
        return FALSE;
570
    }
571
572
    /**
573
     * Grab uri segments to args array
574
     * @access public
575
     * @param integer $n
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
576
     * @return array
577
     */
578
    public function grab_variables($n) {
579
580
        $args = [];
581
582
        foreach ($this->uri->uri_to_assoc($n) as $k => $v) {
583
            if (isset($k)) {
584
                array_push($args, $k);
585
            }
586
            if (isset($v)) {
587
                array_push($args, $v);
588
            }
589
        }
590
591
        $count = count($args);
592
        for ($i = 0, $cnt = $count; $i < $cnt; $i++) {
593
            if ($args[$i] === FALSE) {
594
                unset($args[$i]);
595
            }
596
        }
597
598
        return $args;
599
    }
600
601
    /**
602
     * Display main page
603
     */
604
    public function _mainpage() {
605
606
        /** Register event 'Core:_mainpage' */
607
        Events::create()->registerEvent(NULL, 'Core:_mainPage')->runFactory();
608
609
        switch ($this->settings['main_type']) {
610
            // Load main page
611
            case 'page':
612
                $main_page_id = $this->settings['main_page_id'];
613
614
                $this->db->where('lang', $this->config->item('cur_lang'));
615
                $this->db->where('id', $main_page_id);
616
                $query = $this->db->get('content', 1);
617
618
                if ($query->num_rows() == 0) {
619
                    $this->db->where('lang', $this->config->item('cur_lang'));
620
                    $this->db->where('lang_alias', $main_page_id);
621
                    $query = $this->db->get('content', 1);
622
623
                }
624
625
                if ($query->num_rows() > 0) {
626
                    $page = $query->row_array();
627
                } else {
628
                    $this->error_404(lang('Home page not found.', 'core'));
629
630
                }
631
632
                // Set page template file
633
                if ($page['full_tpl'] == NULL) {
634
                    $page_tpl = 'page_full';
635
                } else {
636
                    $page_tpl = $page['full_tpl'];
637
                }
638
639
                if ($page['full_text'] == '') {
640
                    $page['full_text'] = $page['prev_text'];
641
                }
642
643
                $page = $this->cfcm->connect_fields($page, 'page');
644
645
                $this->template->assign('content', $this->template->read($page_tpl, ['page' => $page]));
646
647
                $this->set_meta_tags($page['meta_title'] == NULL ? $page['title'] : $page['meta_title'], $page['keywords'], $page['description']);
648
649
                if (empty($page['main_tpl'])) {
650
                    $this->template->show();
651
                } else {
652
                    $this->template->display($page['main_tpl']);
653
                }
654
                break;
655
656
            // Category
657
            case 'category':
658
                $m_category = $this->lib_category->get_category($this->settings['main_page_cat']);
659
                $this->_display_category($m_category);
660
                break;
661
662
            // Run module as main page
663
            case 'module':
664
                $modName = $this->settings['main_page_module'] . '';
665
                $module = $this->load->module($modName);
666
                if (is_object($module) && method_exists($module, 'index')) {
667
                    $module->index();
668
                } else {
669
                    $this->error(lang('Module uploading or loading  error', 'core') . $modName);
670
                }
671
672
                break;
673
        }
674
    }
675
676
    /**
677
     * Display category
678
     * @param array $category
679
     */
680
    public function _display_category(array $category = []) {
681
682
        /** Register event 'Core:_displayCategory' */
683
        Events::create()->registerEvent($this->cat_content, 'Core:_displayCategory')->runFactory();
684
685
        $category['fetch_pages'] = unserialize($category['fetch_pages']);
686
687
        $content = '';
0 ignored issues
show
Unused Code introduced by
$content 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...
688
689
        preg_match('/^\d+$/', $this->uri->segment($this->uri->total_segments()), $matches);
690
        if (!empty($matches)) {
691
            $offset = $this->uri->segment($this->uri->total_segments());
692
            $segment = $this->uri->total_segments();
693
        } else {
694
            $offset = 0;
695
            $segment = $this->uri->total_segments() + 1;
696
        }
697
698
        $offset == FALSE ? $offset = 0 : TRUE;
699
        $row_count = $category['per_page'];
700
701
        $pages = $this->_get_category_pages($category, $row_count, $offset);
702
703
        if (count($pages) == 0 && $offset > 0) {
704
            $this->error_404();
705
        }
706
707
        // Count total pages for pagination
708
        $category['total_pages'] = $this->_get_category_pages($category, 0, 0, TRUE);
709
710
        if ($category['total_pages'] > $category['per_page']) {
711
            $this->load->library('Pagination');
712
713
            if (array_key_exists($this->uri->segment(1), $this->langs)) {
714
                $paginationConfig['base_url'] = '/' . $this->uri->segment(1) . '/' . $category['path_url'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$paginationConfig was never initialized. Although not strictly required by PHP, it is generally a good practice to add $paginationConfig = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
715
            } else {
716
                $paginationConfig['base_url'] = '/' . $category['path_url'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$paginationConfig was never initialized. Although not strictly required by PHP, it is generally a good practice to add $paginationConfig = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
717
            }
718
719
            $paginationConfig['total_rows'] = $category['total_pages'];
720
            $paginationConfig['per_page'] = $category['per_page'];
721
            $paginationConfig['uri_segment'] = $segment;
722
            include_once "./templates/{$this->config->item('template')}/paginations.php";
723
            $paginationConfig['page_query_string'] = false;
724
725
            $this->pagination->initialize($paginationConfig);
726
            $this->template->assign('pagination', $this->pagination->create_links());
727
        }
728
        // End pagination
729
730
        $this->template->assign('category', $category);
731
732
        $cnt = count($pages);
733
734
        if ($category['tpl'] == '') {
735
            $cat_tpl = 'category';
736
        } else {
737
            $cat_tpl = $category['tpl'];
738
        }
739
740
        if ($cnt > 0) {
741
            // Locate category tpl file
742
            if (!file_exists($this->template->template_dir . $cat_tpl . '.tpl')) {
743
                show_error(lang("Can't locate category template file."));
744
            }
745
746
            $content = $this->template->read($cat_tpl, ['pages' => $pages]);
747
        } else {
748
            $content = $this->template->read($cat_tpl, ['no_pages' => lang('In the category has no pages.', 'core')]);
749
        }
750
751
        $category['title'] == NULL ? $category['title'] = $category['name'] : TRUE;
752
753
        $category['description'] = $this->_makeDescription($category['description']);
754
755
        $category['keywords'] = $this->_makeKeywords($category['keywords'], $category['short_desc']);
756
757
        // adding page number for pages with pagination (from second page)
758
        $curPage = $this->pagination->cur_page;
759
        if ($curPage > 1) {
760
            $title = $category['title'] . ' - ' . $curPage;
761
            $description = $category['description'] . ' - ' . $curPage;
762
763
            $this->set_meta_tags($title, $category['keywords'], $description);
764
        } else {
765
            $this->set_meta_tags($category['title'], $category['keywords'], $category['description']);
766
        }
767
768
        $this->template->assign('content', $content);
769
770
        Events::create()->registerEvent($this->cat_content, 'pageCategory:load');
771
        Events::runFactory();
772
773
        if (!$category['main_tpl']) {
774
            $this->core->core_data['id'] = $category['id'];
775
            $this->template->show();
776
        } else {
777
            $this->core->core_data['id'] = $category['id'];
778
            $this->template->display($category['main_tpl']);
779
        }
780
    }
781
782
    /**
783
     * Select or count pages in category
784
     * @param array $category
785
     * @param int $row_count
786
     * @param int $offset
787
     * @param bool|FALSE $count
788
     * @return array|string
789
     */
790
    public function _get_category_pages(array $category = [], $row_count = 0, $offset = 0, $count = FALSE) {
791
792
        $this->db->where('post_status', 'publish');
793
        $this->db->where('publish_date <=', time());
794
        $this->db->where('lang', $this->config->item('cur_lang'));
795
796 View Code Duplication
        if (count($category['fetch_pages']) > 0) {
797
            $category['fetch_pages'][] = $category['id'];
798
            $this->db->where_in('category', $category['fetch_pages']);
799
        } else {
800
            $this->db->where('category', $category['id']);
801
        }
802
803
        $this->db->select('content.*');
804
        $this->db->select('CONCAT_WS("", content.cat_url, content.url) as full_url', FALSE);
805
        $this->db->order_by($category['order_by'], $category['sort_order']);
806
807
        if ($count === FALSE) {
808 View Code Duplication
            if ($row_count > 0) {
809
                $query = $this->db->get('content', (int) $row_count, (int) $offset);
810
            } else {
811
                $query = $this->db->get('content');
812
            }
813
        } else {
814
            $this->db->from('content');
815
            return $this->db->count_all_results();
816
        }
817
818
        $pages = $query->result_array();
819
820
        if (count($pages) > 0 AND is_array($pages)) {
821
            $n = 0;
822
            foreach ($pages as $p) {
823
                $pages[$n] = $this->cfcm->connect_fields($p, 'page');
824
                $n++;
825
            }
826
        }
827
828
        return $pages;
829
    }
830
831
    /**
832
     *
833
     * @param string $description
834
     * @param null|string $text
835
     * @return string
836
     */
837
    public function _makeDescription($description, $text = null) {
838
839
        if ($this->settings['create_description'] == 'auto' && !$description) {
840
            $description = $this->lib_seo->get_description($text);
841
        }
842
843
        return $description;
844
    }
845
846
    /**
847
     *
848
     * @param string $keywords
849
     * @param string $text
850
     * @return string
851
     */
852
    public function _makeKeywords($keywords, $text) {
853
854
        if ($this->settings['create_keywords'] == 'auto' && !$keywords) {
855
            $keywords = $this->lib_seo->get_keywords($text, TRUE);
856
857
            $keywords = implode(', ', array_keys($keywords));
858
        }
859
860
        return $keywords;
861
    }
862
863
    /**
864
     * Check user access for page
865
     * @param array $roles
866
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

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...
867
     */
868
    public function check_page_access($roles) {
869
870
        if ($roles == FALSE OR count($roles) == 0) {
871
            return TRUE;
872
        }
873
874
        $access = FALSE;
875
        $logged = $this->dx_auth->is_logged_in();
876
        $my_role = $this->dx_auth->get_role_id();
877
878
        if ($this->dx_auth->is_admin() === TRUE) {
879
            $access = TRUE;
880
        }
881
882
        // Check roles access
883
        if ($access != TRUE) {
884
            foreach ($roles as $role) {
885
                if ($role['role_id'] == $my_role) {
886
                    $access = TRUE;
887
                }
888
889
                if ($role['role_id'] == 1 AND $logged == TRUE) {
890
                    $access = TRUE;
891
                }
892
893
                if ($role['role_id'] == '0') {
894
                    $access = TRUE;
895
                }
896
            }
897
        }
898
899
        if ($access == FALSE) {
900
            $this->dx_auth->deny_access('deny');
901
            exit;
902
        }
903
    }
904
905
    /**
906
     * Display page
907
     * @param array $page
908
     * @param array $category
909
     */
910
    public function _display_page_and_cat($page = [], array $category = []) {
911
912
        /** Register event 'Core:_displayPage' */
913
        Events::create()->registerEvent($this->page_content, 'Core:_displayPage')->runFactory();
914
915
        if (empty($page['full_text'])) {
916
            $page['full_text'] = $page['prev_text'];
917
        }
918
919
        if (count($category) > 0) {
920
            // Set page template file
921
            if ($page['full_tpl'] == NULL) {
922
                $page_tpl = $category['page_tpl'];
923
            } else {
924
                $page_tpl = $page['full_tpl'];
925
            }
926
927
            $tpl_name = $category['main_tpl'];
928
        } else {
929
            if ($page['full_tpl']) {
930
                $page_tpl = $page['full_tpl'];
931
            }
932
            $tpl_name = False;
933
        }
934
935
        empty($page_tpl) ? $page_tpl = 'page_full' : TRUE;
936
937
        $this->template->add_array(
938
            [
939
             'page'     => $page,
940
             'category' => $category,
941
            ]
942
        );
943
944
        if ($this->input->get()) {
945
            $this->template->registerCanonical(site_url());
946
        }
947
948
        $this->template->assign('content', $this->template->read($page_tpl));
949
950
        $page['description'] = $this->_makeDescription($page['description'], $page['full_text']);
951
952
        $page['keywords'] = $this->_makeKeywords($page['keywords'], $page['prev_text']);
953
        $this->set_meta_tags($page['meta_title'] == NULL ? $page['title'] : $page['meta_title'], $page['keywords'], $page['description']);
954
955
        $this->db->set('showed', 'showed + 1', FALSE);
956
        $this->db->where('id', $page['id']);
957
        $this->db->limit(1);
958
        $this->db->update('content');
959
960
        Events::create()->registerEvent($this->page_content, 'page:load');
961
        Events::runFactory();
962
963
        if (!empty($page['main_tpl'])) {
964
            $tpl_name = $page['main_tpl'];
965
        }
966
967
        if (!$tpl_name) {
968
            $this->core->core_data['id'] = $page['id'];
969
            $this->template->show();
970
        } else {
971
            $this->template->display($tpl_name);
972
        }
973
    }
974
975
    public function robots() {
976
977
        $robotsSettings = $this->db->select('robots_settings,robots_settings_status,robots_status')->get('settings');
978
        if ($robotsSettings) {
979
            $robotsSettings = $robotsSettings->row();
980
        }
981
982
        header('Content-type: text/plain');
983
        if ($robotsSettings->robots_status == '1') {
984
            if ($robotsSettings->robots_settings_status == '1') {
985
                if (trim($robotsSettings->robots_settings)) {
986
                    echo $robotsSettings->robots_settings;
987
                    exit;
988 View Code Duplication
                } else {
989
                    header('Content-type: text/plain');
990
                    echo "User-agent: * \r\nDisallow: /";
991
                    echo "\r\nHost: " . $this->input->server('HTTP_HOST');
992
                    echo "\r\nSitemap: " . site_url('sitemap.xml');
993
                    exit;
994
                }
995 View Code Duplication
            } else {
996
997
                header('Content-type: text/plain');
998
                echo "User-agent: * \r\nDisallow: ";
999
                echo "\r\nHost: " . $this->input->server('HTTP_HOST');
1000
                echo "\r\nSitemap: " . site_url('sitemap.xml');
1001
                exit;
1002
            }
1003 View Code Duplication
        } else {
1004
            header('Content-type: text/plain');
1005
            echo "User-agent: * \r\nDisallow: /";
1006
            echo "\r\nHost: " . $this->input->server('HTTP_HOST');
1007
            echo "\r\nSitemap: " . site_url('sitemap.xml');
1008
            exit;
1009
        }
1010
    }
1011
1012
    /**
1013
     *
1014
     * @param int $LastModified_unix
1015
     * @return void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
1016
     */
1017
    public function setLastModified($LastModified_unix) {
1018
1019
        if ($LastModified_unix < time() - 60 * 60 * 24 * 4 or $LastModified_unix > time()) {
1020
            if (in_array(date('D', time()), ['Mon', 'Tue', 'Wen'])) {
1021
                $LastModified_unix = strtotime('last sunday', time());
1022
            } else {
1023
                $LastModified_unix = strtotime('last thursday', time());
1024
            }
1025
        }
1026
1027
        $LastModified = date('D, d M Y H:i:s \G\M\T', $LastModified_unix);
1028
        $IfModifiedSince = false;
1029
1030
        if ($this->input->server('HTTP_IF_MODIFIED_SINCE')) {
1031
            $IfModifiedSince = strtotime(substr($this->input->server('HTTP_IF_MODIFIED_SINCE'), 5));
1032
        }
1033
        if ($IfModifiedSince && $IfModifiedSince >= $LastModified_unix) {
1034
            header($this->input->server('SERVER_PROTOCOL') . ' 304 Not Modified');
1035
            return;
1036
        }
1037
        header('Last-Modified: ' . $LastModified);
1038
    }
1039
1040
    private function initModules() {
1041
1042
        $query = $this->cms_base->get_modules();
1043
1044
        if ($query->num_rows() > 0) {
1045
            $this->modules = $query->result_array();
1046
1047
            foreach ($this->modules as $k) {
1048
                $com_links[$k['name']] = '/' . $k['identif'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$com_links was never initialized. Although not strictly required by PHP, it is generally a good practice to add $com_links = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1049
            }
1050
1051
            $this->tpl_data['modules'] = $com_links;
1052
        }
1053
    }
1054
1055
    private function assignTemplateData() {
1056
        // Assign user data
1057
        if ($this->dx_auth->is_logged_in() == TRUE) {
1058
            $this->tpl_data['is_logged_in'] = TRUE;
1059
            $this->tpl_data['username'] = $this->dx_auth->get_username();
1060
        }
1061
        $this->template->add_array(['agent' => $this->user_browser()]);
1062
1063
        //Assign captcha type
1064
        if ($this->dx_auth->use_recaptcha) {
1065
            $this->tpl_data['captcha_type'] = 'recaptcha';
1066
        } else {
1067
            $this->tpl_data['captcha_type'] = 'captcha';
1068
        }
1069
    }
1070
1071
    private function findPage($cat_path, $last_element, $cats_unsorted) {
1072
        $without_cat = FALSE;
1073
        $cat_path_url = substr($cat_path, 0, strrpos($cat_path, '/') + 1);
1074
1075
        // Select page permissions and page data
1076
        $this->db->select('content.*');
1077
        $this->db->select('CONCAT(content.cat_url,content.url ) as full_url');
1078
        $this->db->select('content_permissions.data as roles', FALSE);
1079
        $this->db->where('url', $last_element);
1080
        $this->db->where('post_status', 'publish');
1081
        $this->db->where('publish_date <=', time());
1082
        $this->db->where('lang', $this->config->item('cur_lang'));
1083
        $this->db->join('content_permissions', 'content_permissions.page_id = content.id', 'left');
1084
1085
        if ($this->db->table_exists('comments')) {
1086
            $this->db->select('count(comments.id) as comments_count');
1087
            $this->db->join('comments', "comments.item_id = content.id AND comments.module='core' AND comments.status=0", 'left');
1088
        }
1089
1090
        $withoutCategory = ($cat_path == $last_element);
1091
        // Search page without category
1092
        if ($withoutCategory) {
1093
            $this->db->where('content.category', 0);
1094
            $without_cat = TRUE;
1095
        } else {
1096
            $this->db->where('content.cat_url', $cat_path_url);
1097
        }
1098
1099
        $query = $this->db->get('content', 1);
1100
1101
        $page_info = $query->num_rows() > 0 ? $query->row_array() : NULL;
1102
1103
        if ($page_info['id']) {
1104
1105
            $cat_path = $this->_prepCatPath($cat_path);
1106
1107
            $page_info['roles'] = unserialize($page_info['roles']);
1108
            if ($without_cat == FALSE) {
1109
                // load page and category
1110
                foreach ($cats_unsorted as $cat) {
1111
                    if (($cat['path_url'] == $cat_path . '/') AND ($cat['id'] == $page_info['category'])) {
1112
                        $this->page_content = $page_info;
1113
                        $this->cat_content = $cat;
1114
                        $this->page_content = $this->cfcm->connect_fields($this->page_content, 'page');
1115
                        break;
1116
                    }
1117
                }
1118
            } else {
1119
                // display page without category
1120
                $this->page_content = $page_info;
1121
                $this->page_content = $this->cfcm->connect_fields($this->page_content, 'page');
1122
            }
1123
            return true;
1124
        }
1125
    }
1126
1127
}
1128
1129
/* End of file core.php */