Completed
Push — development ( 67765c...7029e6 )
by Andrij
18:12
created

Pages::delete_pages()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 8
nop 0
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
use CMSFactory\Events;
4
use core\models\Route;
5
6
if (!defined('BASEPATH')) {
7
    exit('No direct script access allowed');
8
}
9
10
/**
11
 * @property Lib_admin $lib_admin
12
 * @property Cms_admin $cms_admin
13
 * @property Lib_category $lib_category
14
 * @property Lib_seo $lib_seo
15
 */
16
class Pages extends BaseAdminController
17
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
18
19
    public $_Config = ['per_page' => 20];
20
21 View Code Duplication
    public function __construct() {
22
23
        parent::__construct();
24
25
        $this->load->library('DX_Auth');
26
        admin_or_redirect();
27
28
        $this->load->library('lib_admin');
29
        $this->load->library('lib_category');
30
        $this->load->library('pagination');
31
        $this->load->library('lib_seo');
32
        $this->lib_admin->init_settings();
33
    }
34
35
    public function index() {
36
37
        // Set roles
38
        $locale = $this->cms_admin->get_default_lang();
39
        $locale = $locale['identif'];
40
41
        $query = $this->db->query("SELECT * FROM `shop_rbac_roles` JOIN `shop_rbac_roles_i18n` ON shop_rbac_roles.id=shop_rbac_roles_i18n.id WHERE `locale`='" . $locale . "'");
42
        $this->template->assign('roles', $query->result_array());
43
44
        $uri_segs = $this->uri->uri_to_assoc(2);
45
46
        $this->template->add_array(
47
            [
48
             'tree'     => $this->lib_category->build(), // Load category tree
49
             'cur_time' => date('H:i:s'),
50
             'cur_date' => date('Y-m-d'),
51
             'sel_cat'  => $uri_segs['category'],
52
            ]
53
        );
54
        /** Init Event. Pre Create Page */
55
        Events::create()->registerEvent('', 'BaseAdminPage:preCreate');
56
        Events::runFactory();
57
58
        $this->template->show('add_page', FALSE);
59
    }
60
61
    /*     * **************************************************
62
     * PAGE EVENTS
63
     * ************************************************* */
64
65
    /**
66
     * Validation for template name field
67
     * @param string $tpl
68
     * @return bool
69
     */
70 View Code Duplication
    public function tpl_validation($tpl) {
71
72
        if (preg_match('/^[A-Za-z\_\.]{0,50}$/', $tpl)) {
73
            return TRUE;
74
        }
75
        $this->form_validation->set_message('tpl_validation', lang('The %s field can only contain Latin characters', 'admin'));
76
        return FALSE;
77
    }
78
79
    /**
80
     * Add new page
81
     * Language default
82
     */
83
    public function add() {
84
85
        $this->form_validation->set_rules('page_title', lang('Title', 'admin'), 'trim|required|min_length[1]|max_length[500]');
86
        $this->form_validation->set_rules('page_url', lang('URL', 'admin'), 'alpha_dash|least_one_symbol|max_length[255]');
87
        $this->form_validation->set_rules('prev_text', lang('Preliminary contents', 'admin'), 'trim|required');
88
        $this->form_validation->set_rules('page_description', lang('Description ', 'admin'), 'trim');
89
        $this->form_validation->set_rules('full_tpl', lang('Page template', 'admin'), 'trim|max_length[150]|min_length[2]|callback_tpl_validation');
90
        $this->form_validation->set_rules('create_date', lang('Creation date', 'admin'), 'required');
91
        $this->form_validation->set_rules('create_time', lang('Creation time', 'admin'), 'required');
92
        $this->form_validation->set_rules('publish_date', lang('Publication date', 'admin'), 'required');
93
        $this->form_validation->set_rules('publish_time', lang('Publication time', 'admin'), 'required');
94
95
        $this->form_validation->set_rules('main_tpl', lang('Main page template', 'admin'), 'trim|max_length[50]|min_length[2]|callback_tpl_validation');
96
97
        if ($this->form_validation->run($this) == FALSE) {
98
            $error = $this->form_validation->error_string('<p>', '</p>');
99
100
            showMessage(lang('From validation error: <br />', 'admin') . $error, false, 'r');
101
        } else {
102
            // load site settings
103
            $settings = $this->cms_admin->get_settings();
104
105
            $def_lang = $this->cms_admin->get_default_lang();
106
107 View Code Duplication
            if ($this->input->post('page_url') == '' or $this->input->post('page_url') == NULL) {
108
                $url = $this->createUrl($this->input->post('page_title'));
109
            } else {
110
                $url = $this->input->post('page_url');
111
            }
112
113
            // check if we have existing module with entered URL
114
            $this->db->where('name', $url);
115
            $query = $this->db->get('components');
116
117
            if ($query->num_rows() > 0) {
118
                showMessage(lang('Reserved the same name module', 'admin'), false, 'r');
119
                return;
120
            }
121
            // check if we have existing category with entered URL
122
            // end module check
123
            $this->db->where('url', $url);
124
            $query = $this->db->get('route', 1);
125
126
            if ($query->num_rows() > 0) {
127
                showMessage(lang('This URL is already in use!'), false, 'r');
128
                return;
129
            }
130
            $full_url = $this->lib_category->GetValue($this->input->post('category'), 'path_url');
131
132
            if ($full_url == FALSE) {
133
                $full_url = '';
134
            }
135
136
            $keywords = $this->lib_admin->db_post('page_keywords');
137
            $description = $this->lib_admin->db_post('page_description');
138
139
            // create keywords
140 View Code Duplication
            if ($keywords == '' AND $settings['create_keywords'] == 'auto') {
141
                $keywords = $this->lib_seo->get_keywords($this->input->post('prev_text') . ' ' . $this->input->post('full_text'));
142
            }
143
144
            // create description
145 View Code Duplication
            if ($description == '' AND $settings['create_description'] == 'auto') {
146
                $description = $this->lib_seo->get_description($this->input->post('prev_text') . ' ' . $this->input->post('full_text'));
147
            }
148
149
            mb_substr($keywords, -1) == ',' ? $keywords = mb_substr($keywords, 0, -1) : TRUE;
150
151
            $publish_date = $this->input->post('publish_date') . ' ' . $this->input->post('publish_time');
152
            $create_date = $this->input->post('create_date') . ' ' . $this->input->post('create_time');
153
154
            /** @var array $category_default_comments */
155
            $category_default_comments = $this->lib_category->get_category($this->input->post('category'));
156
157
            $data = [
158
                     'title'           => trim($this->input->post('page_title')),
159
                     'meta_title'      => trim($this->input->post('meta_title')),
160
                     'url'             => str_replace('.', '', trim($url)), //Delete dots from url
161
                     'cat_url'         => $full_url,
162
                     'keywords'        => $keywords,
163
                     'description'     => $description,
164
                //'full_text' => htmlspecialchars(trim($this->input->post('full_text'))),
165
                     'full_text'       => trim($this->input->post('full_text')),
166
                     'prev_text'       => trim($this->lib_admin->db_post('prev_text')),
167
                //'prev_text' => htmlspecialchars(trim($this->lib_admin->db_post('prev_text'))),
168
                     'category'        => $this->input->post('category'),
169
                     'full_tpl'        => $this->input->post('full_tpl'),
170
                     'main_tpl'        => $this->input->post('main_tpl'),
171
                     'comments_status' => $category_default_comments['comments_default'] ?: 0,
172
                     'post_status'     => $this->input->post('post_status'),
173
                     'author'          => $this->dx_auth->get_username(),
174
                     'publish_date'    => strtotime($publish_date),
175
                     'created'         => strtotime($create_date),
176
                     'lang'            => $def_lang['id'],
177
                    ];
178
179
            $page_id = $this->cms_admin->add_page($data);
180
181
            $data['id'] = $page_id;
182
183
            $this->load->module('cfcm')->save_item_data($page_id, 'page');
184
185
            $this->cache->delete_all();
186
187
            $this->on_page_add($data);
188
189
            $this->lib_admin->log(
190
                lang('Created a page', 'admin') .
191
                " <a href='/admin/pages/edit/$page_id'>{$data['title']}</a>"
192
            );
193
194
            $action = $this->input->post('action');
195
            $path = '/admin/pages/GetPagesByCategory';
196
197
            if ($action == 'edit') {
198
                $path = '/admin/pages/edit/' . $page_id;
199
            }
200
201
            showMessage(lang('Page has been created', 'admin'));
202
            pjax($path);
203
        }
204
    }
205
206
    /**
207
     * Crete url with at least one symbol
208
     * @param $str
0 ignored issues
show
introduced by
Missing parameter type
Loading history...
209
     * @return string
210
     */
211
    private function createUrl($str) {
212
213
        $this->load->helper('translit');
214
        is_numeric($str) && $str = 'p' . $str;
215
        return translit_url($str);
216
    }
217
218
    /*     * **************************************************
219
     * END PAGE EVENTS
220
     * ************************************************* */
221
222
    /**
223
     * This event occurs right after page inserted in DB
224
     */
225
    private function on_page_add($page) {
226
227
        $this->load->module('cfcm')->save_item_data($page['id'], 'page');
228
229
        /** Set page roles */
230
        $this->_set_page_roles($page['id'], $this->input->post('roles'));
231
232
        /** Set page tags */
233
        $this->load->module('tags')->_set_page_tags($this->input->post('search_tags'), $page['id']);
234
235
        /** Init CMS Events system */
236
        Events::create()->registerEvent($page, 'Page:create');
237
    }
238
239
    /**
240
     * Set roles for page
241
     * @param integer $page_id
242
     * @param array $roles
243
     * @return bool
244
     */
245
    public function _set_page_roles($page_id, $roles) {
246
247
        if ($roles[0] != '') {
248
            $page_roles = [];
249
250
            foreach ($roles as $k) {
251
                $data = ['role_id' => $k];
252
                array_push($page_roles, $data);
253
            }
254
255
            $n_data = [
256
                       'page_id' => $page_id,
257
                       'data'    => serialize($page_roles),
258
                      ];
259
260
            // Delete page roles
261
            $this->db->where('page_id', $page_id);
262
            $this->db->delete('content_permissions');
263
264
            // Insert new page roles
265
            $this->db->insert('content_permissions', $n_data);
266
        } else {
267
268
            if ($this->db->get_where('content_permissions', ['page_id' => $page_id])->num_rows() > 0) {
269
                $this->db->where('page_id', $page_id);
270
                $this->db->delete('content_permissions');
271
            }
272
        }
273
274
        return TRUE;
275
    }
276
277
    /**
278
     * Show edit_page form
279
     *
280
     * @access public
281
     * @param integer $page_id
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
282
     * @param int $lang
283
     */
284
    public function edit($page_id, $lang = 0) {
285
        $this->cms_base->setLocaleId($lang);
286
287
        if ($this->cms_admin->get_page($page_id) == FALSE) {
288
            showMessage(lang('Page', 'admin') . $page_id . lang('Not found', 'admin'), false, 'r');
289
            return;
290
        }
291
292
        // Get page data
293
        $data = $this->db
294
            ->select('content.* , route.url, if( route.parent_url <> "", concat(route.parent_url, "/"),"" )  as cat_url', false)
295
            ->join('route', 'route.id = content.route_id')
296
            ->get_where('content', ['content.id' => $page_id])
297
            ->row_array();
298
299
        if ($data['lang_alias'] != 0) {
300
            redirect('/admin/pages/edit/' . $data['lang_alias'] . '/' . $data['lang']);
301
        }
302
303
        if ($lang != 0 AND $lang != $data['lang']) {
304
            $data = $this->db
305
                ->select('content.* , route.url')
306
                ->join('route', 'route.id = content.route_id')
307
                ->get_where('content', ['lang_alias' => $page_id, 'lang' => $lang]);
308
309
            if ($data->num_rows() > 0) {
310
                $data = $data->row_array();
311
            } else {
312
                $data = FALSE;
313
            }
314
        }
315
        /** Init Event. Pre Edit Page */
316
        Events::create()->registerEvent(['pageId' => $page_id, 'url' => $data['url']], 'BaseAdminPage:preUpdate');
317
        Events::runFactory();
318
319
        $pageExists = 1;
320
        if (!$data) {
321
            $defpage = $this->cms_admin->get_page($page_id);
322
            $defpage['author'] = $this->dx_auth->get_username();
323
            $defpage['lang'] = $lang;
324
            $defpage['title'] = '';
325
            $defpage['keywords'] = '';
326
            $defpage['description'] = '';
327
            $defpage['prev_text'] = '';
328
            $defpage['full_text'] = '';
329
            $defpage['meta_title'] = '';
330
            $data = $defpage;
331
            $pageExists = 0;
332
        }
333
334
        if ($data) {
335
            $this->template->assign('page_id', $page_id);
336
            $this->template->assign('update_page_id', $data['id']);
337
338
            $this->template->add_array($data);
339
340
            $this->load->module('tags');
341
342
            $tags = $this->tags->get_page_tags($data['id']);
343
344
            $tags = array_column($tags, 'value');
345
346
            $this->template->assign('tags', $tags);
347
348
            // Roles
349
            $this->db->where('page_id', $page_id);
350
            $query = $this->db->get('content_permissions', 1);
351
            $page_roles = $query->row_array();
352
            $page_roles = unserialize($page_roles['data']);
353
354
            // Set roles
355
            $locale = MY_Controller::defaultLocale();
356
            $g_query = $this->db->query("SELECT * FROM `shop_rbac_roles` JOIN `shop_rbac_roles_i18n` ON shop_rbac_roles.id=shop_rbac_roles_i18n.id WHERE locale='$locale'");
357
            $roles = $g_query->result_array();
358
359
            if ($roles != FALSE) {
360
                for ($i = 0, $cnt = count($roles); $i < $cnt; $i++) {
361
                    for ($i2 = 0, $cnt2 = count($page_roles); $i2 < $cnt2; $i2++) {
362
                        if ($page_roles[$i2]['role_id'] == $roles[$i]['id']) {
363
                            $roles[$i]['selected'] = 'selected="true"';
364
                        }
365
                        if ($page_roles[$i2]['role_id'] == '0') {
366
                            $this->template->assign('all_selected', 'selected="true"');
367
                        }
368
                    }
369
                }
370
            }
371
372
            $this->template->assign('roles', $roles);
373
            // roles
374
            // explode publush_date to date and time
375
            $this->template->assign('publish_date', date('Y-m-d', $data['publish_date']));
376
            $this->template->assign('publish_time', date('H:i:s', $data['publish_date']));
377
            $this->template->assign('create_date', date('Y-m-d', $data['created']));
378
            $this->template->assign('create_time', date('H:i:s', $data['created']));
379
            // end
380
            // set langs
381
            $langs = $this->cms_admin->get_langs();
382
383
            if (count($langs) > 1) {
384
                $this->template->assign('show_langs', 1);
385
            }
386
387
            // Load category
388
            $category = $this->lib_category->get_category($data['category']);
389
390
            $pagesPagination = $this->session->userdata('pages_pag_url');
391
            $pagesPagination = $pagesPagination ? $pagesPagination : null;
392
393
            $this->template->add_array(
394
                [
395
                 'page_lang'       => $data['lang'],
396
                 'page_identif'    => $data['identif'],
397
                 'tree'            => $this->lib_category->build(),
398
                 'parent_id'       => $data['category'],
399
                 'langs'           => $langs,
400
                 'defLang'         => MY_Controller::getDefaultLanguage()['id'], //??
401
                 'category'        => $category,
402
                 'pageExists'      => $pageExists,
403
                 'pagesPagination' => $pagesPagination,
404
                ]
405
            );
406
407
            if ($data['lang_alias'] != 0) {
408
                $orig_page = $this->cms_admin->get_page($data['lang_alias']);
409
410
                $this->template->assign('orig_page', $orig_page);
411
            }
412
413
            $this->template->show('edit_page', FALSE);
414
        }
415
    }
416
417
    /**
418
     * Update existing page by ID
419
     *
420
     * @access public
421
     * @param integer $page_id
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
422
     */
423
    public function update($page_id) {
424
425
        $pagesPagination = $this->session->userdata('pages_pag_url');
426
        $pagesPagination = $pagesPagination ? $pagesPagination : null;
427
428
        //cp_check_perm('page_edit');
429
430
        $data = $this->db->get_where('content', ['id' => $page_id]);
431
432
        if ($data->num_rows() > 0) {
433
            $data = $data->row_array();
434
        } else {
435
            $data = FALSE;
436
        }
437
        /** Init Event. Pre Edit Page */
438
        Events::create()->registerEvent(['pageId' => $page_id, 'url' => $data['url']], 'BaseAdminPage:preUpdate');
439
        Events::runFactory();
440
441
        $this->form_validation->set_rules('page_title', lang('Title', 'admin'), 'trim|required|min_length[1]|max_length[500]');
442
        $this->form_validation->set_rules('page_url', lang('URL', 'admin'), 'alpha_dash|least_one_symbol|max_length[255]');
443
        $this->form_validation->set_rules('page_keywords', lang('Keywords', 'admin'), 'trim');
444
        $this->form_validation->set_rules('prev_text', lang('Preliminary contents', 'admin'), 'trim|required');
445
        $this->form_validation->set_rules('page_description', lang('Description ', 'admin'), 'trim');
446
        $this->form_validation->set_rules('full_tpl', lang('Page template', 'admin'), 'trim|max_length[50]|min_length[2]|callback_tpl_validation');
447
        $this->form_validation->set_rules('main_tpl', lang('Main page template ', 'admin'), 'trim|max_length[50]|min_length[2]|callback_tpl_validation');
448
        $this->form_validation->set_rules('create_date', lang('Creation date', 'admin'), 'required');
449
        $this->form_validation->set_rules('create_time', lang('Creation time', 'admin'), 'required');
450
        $this->form_validation->set_rules('publish_date', lang('Publication date', 'admin'), 'required');
451
        $this->form_validation->set_rules('publish_time', lang('Publication time', 'admin'), 'required');
452
453
        $page_category = $this->cms_admin->get_category($data['category']);
454
455
        if ($page_category['field_group'] != -1 && $page_category) {
456
            $groupId = $page_category['field_group'];
457
            $fields = $this->db
458
                ->where("content_fields.data like '%required%'")
459
                ->or_where("content_fields.data like '%validation%'")
460
                ->where('group_id', $groupId)
461
                ->join('content_fields', 'content_fields.field_name = content_fields_groups_relations.field_name')
462
                ->get('content_fields_groups_relations')
463
                ->result_array();
464
465
            foreach ($fields as $field) {
466
                if ($groupId == $field['group_id']) {
467
                    $data = unserialize($field['data']);
468
                    $str = '';
469
                    if ($data['required']) {
470
                        $str .= 'required|';
471
                    }
472
                    if ($data['validation']) {
473
                        $str .= $data['validation'];
474
                    }
475
476
                    $this->form_validation->set_rules($field['field_name'], $data['label'], $str);
477
                }
478
            }
479
        }
480
481
        if ($this->form_validation->run($this) == FALSE) {
482
            showMessage(validation_errors(), false, 'r');
483
        } else {
484 View Code Duplication
            if ($this->input->post('page_url') == '' or $this->input->post('page_url') == NULL) {
485
                $url = $this->createUrl($this->input->post('page_title'));
486
            } else {
487
                $url = $this->input->post('page_url');
488
            }
489
490
            // check if we have existing module with entered URL
491
            $this->db->where('name', $url);
492
            $query = $this->db->get('components');
493
494
            if ($query->num_rows() > 0) {
495
                showMessage(lang('Reserved the same name module', 'admin'), false, 'r');
496
                return;
497
            }
498
            // end module check
499
            // check if we have existing category with entered URL
500
            $b_page = $this->cms_admin->get_page($page_id);
501
502
            $originId = $b_page['lang_alias'] ?: $b_page['id'];
503
            $this->db->where('url', $url)
504
                ->where('entity_id !=', $originId);
505
            $query = $this->db->get('route', 1);
506
507
            if ($query->num_rows() > 0) {
508
                showMessage(lang('This URL is already in use!'), false, 'r');
509
                return;
510
            }
511
            // end check
512
513
            $full_url = $this->lib_category->GetValue($this->input->post('category'), 'path_url');
514
515
            if ($full_url == FALSE) {
516
                $full_url = '';
517
            }
518
519
            $keywords = $this->lib_admin->db_post('page_keywords');
520
            $description = $this->lib_admin->db_post('page_description');
521
522
            $publish_date = $this->input->post('publish_date') . ' ' . $this->input->post('publish_time');
523
            $create_date = $this->input->post('create_date') . ' ' . $this->input->post('create_time');
524
525
            $data = [
526
                     'title'           => trim($this->input->post('page_title')),
527
                     'meta_title'      => trim($this->input->post('meta_title')),
528
                     'url'             => str_replace('.', '', trim($url)), //Delete dots from url
529
                     'cat_url'         => $full_url,
530
                     'keywords'        => $keywords,
531
                     'description'     => $description,
532
                     'full_text'       => trim($this->input->post('full_text')),
533
                     'prev_text'       => trim($this->lib_admin->db_post('prev_text')),
534
                     'category'        => $this->input->post('category'),
535
                     'full_tpl'        => $this->input->post('full_tpl'),
536
                     'main_tpl'        => $this->input->post('main_tpl'),
537
                     'comments_status' => $this->input->post('comments_status'),
538
                     'post_status'     => $this->input->post('post_status'),
539
                     'author'          => $this->dx_auth->get_username(),
540
                     'publish_date'    => strtotime($publish_date),
541
                     'created'         => strtotime($create_date),
542
                     'updated'         => time(),
543
                     'route_id'        => $b_page['route_id'],
544
                    ];
545
546
            $data['id'] = $page_id;
547
548
            if ($b_page['lang_alias'] != 0) {
549
                $data['url'] = $b_page['url'];
550
            }
551
552
            $this->on_page_update($data);
553
554
            $last_id = $this->cms_admin->update_page($page_id, $data);
555
556
            if ($last_id >= 1) {
557
                $this->load->module('cfcm')->save_item_data($last_id, 'page');
558
559
                $this->cache->delete_all();
560
561
                $this->lib_admin->log(
562
                    lang('Changed the page', 'admin') .
563
                    " <a href='/admin/pages/edit/$page_id>'{$data['title']}</a>"
564
                );
565
566
                $action = $this->input->post('action');
567
                $path = '/admin/pages/GetPagesByCategory/all/' . $pagesPagination;
568
569
                if ($action == 'edit') {
570
                    $path = "/admin/pages/edit/$page_id";
571
                }
572
573
                showMessage(lang('Page contents have been updated', 'admin'));
574
575
                $page = $this->cms_admin->get_page($page_id);
576
                if ($page) {
577
                    $page_id = $page['lang_alias'] ? $page['lang_alias'] : $page_id;
578
                    $lang_id = $this->input->post('lang_id');
579
                    if ($action == 'edit') {
580
                        $path = "/admin/pages/edit/$page_id/$lang_id";
581
                    }
582
                }
583
584
                pjax($path);
585
            } else {
586
                showMessage('Error', false, 'r');
587
            }
588
        }
589
    }
590
591
    /**
592
     * This event occurs right after page updated
593
     * @param array $page
594
     */
595
    private function on_page_update($page) {
596
597
        /** Update page roles */
598
        $this->_set_page_roles($page['id'], $this->input->post('roles'));
599
600
        /** Update page tags */
601
        $this->load->module('tags')->_set_page_tags($this->input->post('search_tags'), (int) $page['id']);
602
603
        /** Init CMS Events system */
604
        Events::create()->registerEvent($page, 'Page:update');
605
    }
606
607
    /**
608
     * Translit title to url
609
     */
610
    public function ajax_translit() {
611
612
        echo $this->createUrl($this->input->post('str'));
613
    }
614
615
    public function save_positions() {
616
617
        foreach ($this->input->post('pages_pos') as $k => $v) {
618
            $item = explode('_', substr($v, 4));
619
620
            $data = ['position' => $k];
621
            $this->db->where('id', $item[0]);
622
            //            $this->db->or_where('lang_alias', $item[1]);
623
            $this->db->update('content', $data);
624
        }
625
    }
626
627
    public function delete_pages() {
628
629
        $ids = $this->input->post('pages');
630
631
        if (count($ids) > 0) {
632
            foreach ($ids as $v) {
633
                $page_id = substr($v, 5);
634
                $res[$page_id] = $this->delete($page_id, FALSE);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$res was never initialized. Although not strictly required by PHP, it is generally a good practice to add $res = 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...
635
            }
636
        }
637
638
        if (in_array(false, $res)) {
639
            showMessage(lang('Can not delete main page', 'admin'), lang('Message'), 'r');
640
        }
641
        if (in_array(true, $res)) {
642
            showMessage(lang('Successful delete', 'admin'));
643
        }
644
        pjax($this->input->server('HTTP_REFERER'));
645
    }
646
647
    /**
648
     * Delete page
649
     *
650
     * @access public
651
     * @param string $page_id
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
652
     * @param bool $show_messages
653
     * @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...
654
     */
655
    public function delete($page_id, $show_messages = TRUE) {
656
657
        //cp_check_perm('page_delete');
658
659
        $settings = $this->cms_admin->get_settings();
660
661
        if ($settings['main_page_id'] == $page_id AND $settings['main_type'] == 'page') {
662
            return FALSE;
663
        }
664
665
        $this->db->where('id', $page_id);
666
        $query = $this->db->get('content', 1);
667
        $page = $query->row_array();
668
669
        if ($page['lang_alias'] == 0) {
670
            $this->db->where('id', $page['id']);
671
            $this->db->delete('content');
672
673
            $this->db->where('lang_alias', $page['id']);
674
            $this->db->delete('content');
675
676
            $this->on_page_delete($page['id']);
677
678
            if ($show_messages == TRUE) {
679
                showMessage(lang('Page has been deleted.', 'admin'));
680
                updateDiv('page', site_url('admin/pages/GetPagesByCategory/' . $page['category']));
681
            }
682
            return TRUE;
683
        }
684
685
        $root_page = $this->cms_admin->get_page($page['lang_alias']);
686
687
        //         delete page
688
        $this->db->where('id', $page['id']);
689
        $this->db->delete('content');
690
691
        $this->on_page_delete($page_id);
692
693
        if ($show_messages == TRUE) {
694
            showMessage(lang('Page has been deleted.', 'admin'));
695
            updateDiv('page', site_url('admin/pages/edit/' . $root_page['id'] . '/' . $root_page['lang']));
696
        }
697
    }
698
699
    /**
700
     * This event occurs right after page deleted
701
     * @param integer $page_id
702
     */
703
    private function on_page_delete($page_id) {
704
705
        $this->db->where('item_id', $page_id);
706
        $this->db->where('item_type', 'page');
707
        $this->db->delete('content_fields_data');
708
        $this->cache->delete('cfcm_field_' . $page_id . 'page');
709
710
        $this->lib_admin->log(lang('Deleted ID page', 'admin') . ' ' . $page_id);
711
712
        // Delete content_permissions
713
        $this->db->where('page_id', $page_id);
714
        $this->db->delete('content_permissions');
715
716
        // Delete page tags
717
        $this->load->module('tags')->_remove_orphans($page_id);
718
719
        /** Init CMS Events system */
720
        Events::create()->raiseEvent(['pageId' => $page_id, 'userId' => $this->dx_auth->get_user_id()], 'Page:delete');
721
    }
722
723
    /**
724
     * @param string $action
725
     */
726
    public function move_pages($action) {
727
728
        $ids = $this->input->post('pages');
729
        $ids_key = array_flip($this->input->post('pages'));
730
731
        $this->db->select('category');
732
        $page = $this->db->get_where('content', ['id' => substr($this->input->post('pages')[0], 5)])->row_array();
0 ignored issues
show
Unused Code introduced by
$page 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...
733
734
        if ((int) $this->input->post('new_cat') > 0) {
735
            $category = $this->lib_category->get_category($this->input->post('new_cat'));
736
        } else {
737
            $category['id'] = 0;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$category was never initialized. Although not strictly required by PHP, it is generally a good practice to add $category = 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...
738
            $category['path_url'] = '';
739
        }
740
741
        if (count($ids) > 0) {
742
            foreach ($ids as $v) {
743
                $page_id = substr($v, 5);
744
745
                $data = [
746
                         'category' => $category['id'],
747
                        ];
748
                $route = [
749
                          'parent_url' => trim($category['path_url'], '/'),
750
                         ];
751
752
                switch ($action) {
753
                    case 'move':
754
                        $this->db->where('id', $page_id);
755
                        $this->db->update('content', $data);
756
757
                        $this->db->where('lang_alias', $page_id);
758
                        $this->db->update('content', $data);
759
760
                        $this->db->where('entity_id', $page_id);
761
                        $this->db->update('route', $route);
762
763
                        break;
764
765
                    case 'copy':
766
                        $page = $this->db
767
                            ->select('content.*, route.url, route.parent_url')
768
                            ->join('route', 'route.id = content.route_id')
769
                            ->get_where('content', ['content.id' => $page_id])->row_array();
770
                        $page['category'] = $data['category'];
771
                        $page['lang_alias'] = 0;
772
                        $page['comments_count'] = 0;
773
                        $url = $page['url'];
774
                        $parentUrl = $page['parent_url'];
775
776
                        $this->db->like('url', $url);
777
                        $new_url = $url . ($this->db->get('route')->num_rows() + 1);
778
779
                        unset($page['id'], $page['url'], $page['parent_url']);
780
781
                        $this->db->insert('content', $page);
782
                        $new_id = $this->db->insert_id();
783
784
                        $route = new Route();
785
                        $route->setParentUrl($parentUrl);
786
                        $route->setUrl($new_url);
787
                        $route->setType(Route::TYPE_PAGE);
788
                        $route->setEntityId($new_id);
789
                        $route->save();
790
791
                        $this->db->update('content', ['route_id' => $route->getId()], ['id' => $new_id]);
792
793
                        $this->_copy_content_fields($page_id, $new_id);
794
795
                        // Copy page to other languages
796
                        $pages = $this->db->get_where('content', ['lang_alias' => $page_id])->result_array();
797
798
                        foreach ($pages as $page) {
799
                            unset($page['id']);
800
                            $page['category'] = $data['category'];
801
                            $page['comments_count'] = 0;
802
                            $page['lang_alias'] = $new_id;
803
                            $this->db->insert('content', $page);
804
                            $this->_copy_content_fields($page_id, $this->db->insert_id());
805
                        }
806
807
                        break;
808
                }
809
            }
810
            $catName = $category['name'] ? ' -> ' . $category['name'] : '';
811
            if ($action == 'copy') {
812
                showMessage(lang('Page successfuly copied', 'admin'));
813
                $this->lib_admin->log(lang('Pages was copied', 'admin') . '. Id: ' . implode(', ', $ids_key) . '' . $catName);
814
            } else if ($action == 'move') {
0 ignored issues
show
introduced by
Use "elseif" in place of "else if"
Loading history...
815
                showMessage(lang('Successfull moving', 'admin'));
816
                $this->lib_admin->log(lang('Pages was moving', 'admin') . '. Id: ' . implode(', ', $ids_key) . '' . $catName);
817
            }
818
            pjax($this->input->server('HTTP_REFERER'));
819
        } else {
820
            showMessage(lang('The operation error', 'admin'));
821
        }
822
    }
823
824
    /**
825
     * Copy content field on page copy
826
     * @param $page_id
0 ignored issues
show
introduced by
Missing parameter type
Loading history...
827
     * @param string $original_id
828
     */
829
    protected function _copy_content_fields($original_id, $new_id) {
830
831
        $fields = $this->db->get_where('content_fields_data', ['item_id' => $original_id, 'item_type' => 'page'])->result_array();
832
833
        foreach ($fields as $field) {
834
            unset($field['id']);
835
            $field['item_id'] = $new_id;
836
            $this->db->insert('content_fields_data', $field);
837
        }
838
    }
839
840
    /**
841
     * Display window to move pages to some category
842
     * @param string $action
843
     */
844
    public function show_move_window($action = 'move') {
845
846
        $this->template->assign('action', $action);
847
        $this->template->assign('tree', $this->lib_category->build());
848
        $this->template->show('move_pages', FALSE);
849
    }
850
851
    /**
852
     * Return tags in JSON
853
     */
854
    public function json_tags() {
855
856
        $this->load->module('tags');
857
        $new_tags = [];
858
859
        $search = $this->input->post('search_tags');
860
861
        if (mb_strlen($search) > 1) {
862
            $tags = $this->tags->search_tags($search);
863
864
            foreach ($tags as $tag) {
865
                $new_tags[] = $tag['value'];
866
            }
867
868
            echo json_encode(array_unique($new_tags));
869
        }
870
    }
871
872
    /**
873
     * Create keywords
874
     */
875
    public function ajax_create_keywords() {
876
877
        $text = $this->input->post('keys');
878
879
        if ($text == '') {
880
            echo lang('Zero-length string', 'admin');
881
            return;
882
        }
883
884
        $keywords = $this->lib_seo->get_keywords($text, TRUE);
885
886
        foreach ($keywords as $key => $val) {
0 ignored issues
show
Bug introduced by
The expression $keywords of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
887
            if ($val < 3) {
888
                $size = 14 + $val;
889
            }
890
891
            if ($val == 1) {
892
                $size = 12;
893
            }
894
895
            if ($val == 4) {
896
                $size = 13;
897
            }
898
899
            if ($val > 3) {
900
                $size = 22;
901
            }
902
903
            $append = $key . ', ';
904
            echo '<a class="underline" onclick="$(\'#page_keywords\').append(\'' . $append . '\' );" style="font-size:' . $size . 'px">' . $key . '</a> &nbsp;';
905
        }
906
    }
907
908
    /**
909
     * Create description
910
     */
911
    public function ajax_create_description() {
912
913
        $desc = $this->lib_seo->get_description($this->input->post('text'));
914
        echo $desc;
915
    }
916
917
    /**
918
     * Change page post_status
919
     */
920
    public function ajax_change_status($page_id) {
921
922
        $exsists = true;
923
        $page = $this->cms_admin->get_page($page_id);
924
925
        switch ($page['post_status']) {
926 View Code Duplication
            case 'publish':
927
                //$data = array('post_status' => 'pending');
928
                $data = $page;
929
                $data['post_status'] = 'draft';
930
                $this->cms_admin->update_page($page['id'], $data, $exsists);
931
                break;
932
933 View Code Duplication
            case 'pending':
934
                $data = $page;
935
                $data['post_status'] = 'publish';
936
                $this->cms_admin->update_page($page['id'], $data, $exsists);
937
938
                break;
939
940 View Code Duplication
            case 'draft':
941
                $data = $page;
942
                $data['post_status'] = 'publish';
943
                $this->cms_admin->update_page($page['id'], $data, $exsists);
944
945
                break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
946 View Code Duplication
            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement
Loading history...
947
                $data = $page;
948
                $data['post_status'] = 'publish';
949
                $this->cms_admin->update_page($page['id'], $data, $exsists);
950
                break;
951
        }
952
        showMessage(lang('Status change success', 'admin'));
953
    }
954
955
    /**
956
     * Display pages by Category ID
957
     *
958
     * @access public
959
     * @cat_id int
960
     * @cur_page int
961
     */
962
    public function GetPagesByCategory($cat_id = 'all', $pagination = null) {
963
964
        //////**********  Pagination pages **********\\\\\\\
965 View Code Duplication
        if ($pagination) {
966
            $paginationSession = ['pages_pag_url' => $pagination];
967
            $this->session->set_userdata($paginationSession);
968
        } else {
969
            $this->session->unset_userdata('pages_pag_url');
970
        }
971
972
        $def_lang = $this->cms_admin->get_default_lang();
973
        CI::$APP->config->set_item('cur_lang', $def_lang['id']);
974
        if ($cat_id != 'all') {
975
            $db_where = [
976
                         'category' => $cat_id,
977
                //'lang_alias' => 0,
978
                         'lang'     => (int) $def_lang['id'],
979
                        ];
980
        } else {
981
            //$this->db->select('content.*, category.name as cat_name');
982
            $db_where = [
983
                         'category >=' => 0,
984
                //'lang_alias' => 0,
985
                         'lang'        => (int) $def_lang['id'],
986
                        ];
987
        }
988
        $main_settings = $this->cms_base->get_settings();
989
990
        $offset = $this->uri->segment(5);
991
        $offset == FALSE ? $offset = 0 : TRUE;
992
993
        $row_count = $this->_Config['per_page'];
994
995
        if ($cat_id != 'all') {
996
            $category = $this->lib_category->get_category($cat_id);
997
        }
998
999
        //$this->db->order_by('category', 'asc');
1000
        $this->db->order_by('content.position', 'asc');
1001
        $this->db->order_by('content.id', 'desc');
1002
1003
        //filter
1004
        if ($this->input->post('id')) {
1005
            $this->db->where('content.id', $this->input->post('id'));
1006
            $flagPOST = true;
1007
        }
1008 View Code Duplication
        if ($this->input->post('title')) {
1009
            $this->db->where('content.title LIKE ', '%' . $this->input->post('title') . '%');
1010
            $flagPOST = true;
1011
        }
1012 View Code Duplication
        if ($this->input->post('url')) {
1013
            $this->db->where('route.url LIKE ', '%' . $this->input->post('url') . '%');
1014
1015
            $flagPOST = true;
1016
        }
1017
1018
        if ($cat_id == NULL) {
1019
            $this->db->join('category', 'category.id = content.category');
1020
        }
1021
1022
        $this->db->join('route', 'route.id = content.route_id');
1023
1024
        $this->db->select('content.*, route.url, if(route.parent_url <> "", concat(route.parent_url, "/") , "") as cat_url ', false);
1025
        if (!$flagPOST) {
1026
            $query = $this->db->get_where('content', $db_where, $row_count, $offset);
1027
        } else {
1028
            $query = $this->db->get_where('content', $db_where);
1029
        }
1030
        $this->db->where($db_where);
1031
        $this->db->from('content');
1032
        $total_pages = $this->db->count_all_results();
1033
1034
        if ($query->num_rows > 0) {
1035
            // При пагинации при поиске ломался поиск.
1036
            if (!$flagPOST) {
1037
                // Begin pagination
1038
                $config['base_url'] = site_url('admin/pages/GetPagesByCategory/' . $cat_id . '/');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = 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...
1039
                $config['container'] = 'page';
1040
                $config['uri_segment'] = 5;
1041
                $config['total_rows'] = $total_pages;
1042
                $config['per_page'] = $this->_Config['per_page'];
1043
1044
                $config['separate_controls'] = true;
1045
                $config['full_tag_open'] = '<div class="pagination pull-left"><ul>';
1046
                $config['full_tag_close'] = '</ul></div>';
1047
                $config['controls_tag_open'] = '<div class="pagination pull-right"><ul>';
1048
                $config['controls_tag_close'] = '</ul></div>';
1049
                $config['next_link'] = lang('Next', 'admin') . '&nbsp;&gt;';
1050
                $config['prev_link'] = '&lt;&nbsp;' . lang('Prev', 'admin');
1051
                $config['cur_tag_open'] = '<li class="btn-primary active"><span>';
1052
                $config['cur_tag_close'] = '</span></li>';
1053
                $config['prev_tag_open'] = '<li>';
1054
                $config['prev_tag_close'] = '</li>';
1055
                $config['next_tag_open'] = '<li>';
1056
                $config['next_tag_close'] = '</li>';
1057
                $config['num_tag_close'] = '</li>';
1058
                $config['num_tag_open'] = '<li>';
1059
                $config['num_tag_close'] = '</li>';
1060
1061
                $this->pagination->num_links = 5;
1062
                $this->pagination->initialize($config);
1063
                // End pagination
1064
            }
1065
1066
            $pages = $query->result_array();
1067
1068
            $catsQuery = $this->db->get('category');
1069
            $allCats = $catsQuery->result_array();
1070
1071
            $this->template->add_array(
1072
                [
1073
                 'paginator'     => $this->pagination->create_links_ajax(),
1074
                 'total_pages'   => $total_pages,
1075
                 'pages'         => $pages,
1076
                 'cat_id'        => $cat_id,
1077
                 'category'      => $category,
1078
                 'cats'          => $allCats,
1079
                 'tree'          => $this->lib_category->build(),
1080
                 'show_cat_list' => $main_settings['cat_list'],
1081
                ]
1082
            );
1083
            $this->template->show('pages_list', FALSE);
1084
        } else {
1085
1086
            $this->template->add_array(
1087
                [
1088
                 'no_pages'      => TRUE,
1089
                 'category'      => $category,
1090
                 'total_pages'   => $total_pages,
1091
                 'tree'          => $this->lib_category->build(),
1092
                 'cat_id'        => $cat_id,
1093
                 'show_cat_list' => $main_settings['cat_list'],
1094
                ]
1095
            );
1096
1097
            $this->template->show('pages_list', FALSE);
1098
        }
1099
    }
1100
1101
}