Completed
Push — development ( cfd391...deed4d )
by Andrij
12:03
created

Pages::add()   F

Complexity

Conditions 14
Paths 268

Size

Total Lines 121
Code Lines 77

Duplication

Lines 6
Ratio 4.96 %

Importance

Changes 0
Metric Value
cc 14
eloc 77
nc 268
nop 0
dl 6
loc 121
rs 3.7522
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
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
 * @property Tags tags
16
 * @property Cms_base cms_base
17
 */
18
class Pages extends BaseAdminController
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
19
{
20
21
    public $_Config = ['per_page' => 20];
22
23 View Code Duplication
    public function __construct() {
24
25
        parent::__construct();
26
27
        $this->load->library('DX_Auth');
28
        admin_or_redirect();
29
30
        $this->load->library('lib_admin');
31
        $this->load->library('lib_category');
32
        $this->load->library('pagination');
33
        $this->load->library('lib_seo');
34
        $this->lib_admin->init_settings();
35
    }
36
37
    public function index() {
38
39
        // Set roles
40
        $locale = $this->cms_admin->get_default_lang();
41
        $locale = $locale['identif'];
42
43
        $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 . "'");
44
        $this->template->assign('roles', $query->result_array());
45
46
        $uri_segs = $this->uri->uri_to_assoc(2);
47
48
        $this->template->add_array(
49
            [
50
             'tree'     => $this->lib_category->build(), // Load category tree
51
             'cur_time' => date('H:i:s'),
52
             'cur_date' => date('Y-m-d'),
53
             'sel_cat'  => $uri_segs['category'],
54
            ]
55
        );
56
        /** Init Event. Pre Create Page */
57
        Events::create()->registerEvent('', 'BaseAdminPage:preCreate');
58
        Events::runFactory();
59
60
        $this->template->show('add_page', FALSE);
61
    }
62
63
    /*     * **************************************************
64
     * PAGE EVENTS
65
     * ************************************************* */
66
67
    /**
68
     * Validation for template name field
69
     * @param string $tpl
70
     * @return bool
71
     */
72 View Code Duplication
    public function tpl_validation($tpl) {
73
74
        if (preg_match('/^[A-Za-z\_\.]{0,50}$/', $tpl)) {
75
            return TRUE;
76
        }
77
        $this->form_validation->set_message('tpl_validation', lang('The %s field can only contain Latin characters', 'admin'));
78
        return FALSE;
79
    }
80
81
    /**
82
     * Add new page
83
     * Language default
84
     */
85
    public function add() {
86
87
        $this->form_validation->set_rules('page_title', lang('Title', 'admin'), 'trim|required|min_length[1]|max_length[500]');
88
        $this->form_validation->set_rules('page_url', lang('URL', 'admin'), 'alpha_dash|least_one_symbol|max_length[255]');
89
        $this->form_validation->set_rules('prev_text', lang('Preliminary contents', 'admin'), 'trim|required');
90
        $this->form_validation->set_rules('page_description', lang('Description ', 'admin'), 'trim');
91
        $this->form_validation->set_rules('full_tpl', lang('Page template', 'admin'), 'trim|max_length[150]|min_length[2]|callback_tpl_validation');
92
        $this->form_validation->set_rules('create_date', lang('Creation date', 'admin'), 'required');
93
        $this->form_validation->set_rules('create_time', lang('Creation time', 'admin'), 'required');
94
        $this->form_validation->set_rules('publish_date', lang('Publication date', 'admin'), 'required');
95
        $this->form_validation->set_rules('publish_time', lang('Publication time', 'admin'), 'required');
96
97
        $this->form_validation->set_rules('main_tpl', lang('Main page template', 'admin'), 'trim|max_length[50]|min_length[2]|callback_tpl_validation');
98
99
        $url = $this->input->post('page_url') ?: $this->createUrl($this->input->post('page_title'));
100
101
        if ($url) {
102
            $this->form_validation->set_rules('page_url', lang('URL', 'admin'), 'alpha_dash|least_one_symbol|max_length[255]');
103
        } else {
104
            $this->form_validation->set_rules('page_url', lang('URL', 'admin'), 'required|alpha_dash|least_one_symbol|max_length[255]');
105
        }
106
107
        if ($this->form_validation->run() == FALSE) {
108
            $error = $this->form_validation->error_string('<p>', '</p>');
109
110
            showMessage(lang('From validation error: <br />', 'admin') . $error, false, 'r');
111
        } else {
112
            // load site settings
113
            $settings = $this->cms_admin->get_settings();
114
115
            $def_lang = $this->cms_admin->get_default_lang();
116
            // check if we have existing module with entered URL
117
            $this->db->where('name', $url);
118
            $query = $this->db->get('components');
119
120
            if ($query->num_rows() > 0) {
121
                showMessage(lang('Reserved the same name module', 'admin'), false, 'r');
122
                return;
123
            }
124
            // check if we have existing category with entered URL
125
            // end module check
126
            $this->db->where('url', $url);
127
            $query = $this->db->get('route', 1);
128
129
            if ($query->num_rows() > 0) {
130
                showMessage(lang('This URL is already in use!'), false, 'r');
131
                return;
132
            }
133
            $full_url = $this->lib_category->GetValue($this->input->post('category'), 'path_url');
134
135
            if ($full_url == FALSE) {
136
                $full_url = '';
137
            }
138
139
            $keywords = $this->lib_admin->db_post('page_keywords');
140
            $description = $this->lib_admin->db_post('page_description');
141
142
            // create keywords
143 View Code Duplication
            if ($keywords == '' AND $settings['create_keywords'] == 'auto') {
0 ignored issues
show
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected and, but found AND.
Loading history...
144
                $keywords = $this->lib_seo->get_keywords($this->input->post('prev_text') . ' ' . $this->input->post('full_text'));
145
            }
146
147
            // create description
148 View Code Duplication
            if ($description == '' AND $settings['create_description'] == 'auto') {
0 ignored issues
show
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected and, but found AND.
Loading history...
149
                $description = $this->lib_seo->get_description($this->input->post('prev_text') . ' ' . $this->input->post('full_text'));
150
            }
151
152
            mb_substr($keywords, -1) == ',' ? $keywords = mb_substr($keywords, 0, -1) : TRUE;
153
154
            $publish_date = $this->input->post('publish_date') . ' ' . $this->input->post('publish_time');
155
            $create_date = $this->input->post('create_date') . ' ' . $this->input->post('create_time');
156
157
            /** @var array $category_default_comments */
158
            $category_default_comments = $this->lib_category->get_category($this->input->post('category'));
159
160
            $data = [
161
                     'title'           => trim($this->input->post('page_title')),
162
                     'meta_title'      => trim($this->input->post('meta_title')),
163
                     'url'             => str_replace('.', '', trim($url)), //Delete dots from url
164
                     'cat_url'         => $full_url,
165
                     'keywords'        => $keywords,
166
                     'description'     => $description,
167
                     'full_text'       => trim($this->input->post('full_text')),
168
                     'prev_text'       => trim($this->lib_admin->db_post('prev_text')),
169
                     'category'        => $this->input->post('category'),
170
                     'full_tpl'        => $this->input->post('full_tpl'),
171
                     'main_tpl'        => $this->input->post('main_tpl'),
172
                     'comments_status' => $category_default_comments['comments_default'] ?: 0,
173
                     'post_status'     => $this->input->post('post_status'),
174
                     'author'          => $this->dx_auth->get_username(),
175
                     'publish_date'    => strtotime($publish_date),
176
                     'created'         => strtotime($create_date),
177
                     'lang'            => $def_lang['id'],
178
                    ];
179
180
            $page_id = $this->cms_admin->add_page($data);
181
182
            $data['id'] = $page_id;
183
184
            $this->load->module('cfcm')->save_item_data($page_id, 'page');
185
186
            $this->cache->delete_all();
187
188
            $this->on_page_add($data);
189
190
            $this->lib_admin->log(
191
                lang('Created a page', 'admin') .
192
                " <a href='/admin/pages/edit/$page_id'>{$data['title']}</a>"
193
            );
194
195
            $action = $this->input->post('action');
196
            $path = '/admin/pages/GetPagesByCategory';
197
198
            if ($action == 'edit') {
199
                $path = '/admin/pages/edit/' . $page_id;
200
            }
201
202
            showMessage(lang('Page has been created', 'admin'));
203
            pjax($path);
204
        }
205
    }
206
207
    /**
208
     * Crete url with at least one symbol
209
     * @param $str
0 ignored issues
show
introduced by
Missing parameter type
Loading history...
210
     * @return string
211
     */
212
    private function createUrl($str) {
213
214
        $this->load->helper('translit');
215
        is_numeric($str) && $str = 'p' . $str;
216
        return translit_url($str);
217
    }
218
219
    /*     * **************************************************
220
     * END PAGE EVENTS
221
     * ************************************************* */
222
223
    /**
224
     * This event occurs right after page inserted in DB
225
     */
226
    private function on_page_add($page) {
227
228
        $this->load->module('cfcm')->save_item_data($page['id'], 'page');
229
230
        /** Set page roles */
231
        $this->_set_page_roles($page['id'], $this->input->post('roles'));
232
233
        /** Set page tags */
234
        $this->load->module('tags')->_set_page_tags($this->input->post('search_tags'), $page['id']);
235
236
        /** Init CMS Events system */
237
        Events::create()->registerEvent($page, 'Page:create');
238
    }
239
240
    /**
241
     * Set roles for page
242
     * @param integer $page_id
243
     * @param array $roles
244
     * @return bool
245
     */
246
    public function _set_page_roles($page_id, $roles) {
247
248
        if ($roles[0] != '') {
249
            $page_roles = [];
250
251
            foreach ($roles as $k) {
252
                $data = ['role_id' => $k];
253
                array_push($page_roles, $data);
254
            }
255
256
            $n_data = [
257
                       'page_id' => $page_id,
258
                       'data'    => serialize($page_roles),
259
                      ];
260
261
            // Delete page roles
262
            $this->db->where('page_id', $page_id);
263
            $this->db->delete('content_permissions');
264
265
            // Insert new page roles
266
            $this->db->insert('content_permissions', $n_data);
267
        } else {
268
269
            if ($this->db->get_where('content_permissions', ['page_id' => $page_id])->num_rows() > 0) {
270
                $this->db->where('page_id', $page_id);
271
                $this->db->delete('content_permissions');
272
            }
273
        }
274
275
        return TRUE;
276
    }
277
278
    /**
279
     * Show edit_page form
280
     *
281
     * @access public
282
     * @param integer $page_id
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
283
     * @param int $lang
284
     */
285
    public function edit($page_id, $lang = 0) {
286
        $this->cms_base->setLocaleId($lang);
287
288
        if ($this->cms_admin->get_page($page_id) == FALSE) {
289
            showMessage(lang('Page', 'admin') . $page_id . lang('Not found', 'admin'), false, 'r');
290
            return;
291
        }
292
293
        $select = 'content.* , route.url, if( route.parent_url <> "", concat(route.parent_url, "/"), "") as cat_url';
294
295
        // Get page data
296
        $data = $this->db
297
            ->select($select, false)
298
            ->join('route', 'route.id = content.route_id')
299
            ->get_where('content', ['content.id' => $page_id])
300
            ->row_array();
301
302
        if ($data['lang_alias'] != 0) {
303
            redirect('/admin/pages/edit/' . $data['lang_alias'] . '/' . $data['lang']);
304
        }
305
306
        if ($lang != 0 AND $lang != $data['lang']) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected and, but found AND.
Loading history...
307
            $data = $this->db
308
                ->select($select, false)
309
                ->join('route', 'route.id = content.route_id')
310
                ->get_where('content', ['lang_alias' => $page_id, 'lang' => $lang]);
311
312
            if ($data->num_rows() > 0) {
313
                $data = $data->row_array();
314
            } else {
315
                $data = FALSE;
316
            }
317
        }
318
319
        /** Init Event. Pre Edit Page */
320
        Events::create()->registerEvent(['pageId' => $page_id, 'url' => $data['url']], 'BaseAdminPage:preUpdate');
321
        Events::runFactory();
322
323
        $pageExists = 1;
324
        if (!$data) {
325
            $defpage = $this->cms_admin->get_page($page_id);
326
            $defpage['author'] = $this->dx_auth->get_username();
327
            $defpage['lang'] = $lang;
328
            $defpage['title'] = '';
329
            $defpage['keywords'] = '';
330
            $defpage['description'] = '';
331
            $defpage['prev_text'] = '';
332
            $defpage['full_text'] = '';
333
            $defpage['meta_title'] = '';
334
            $data = $defpage;
335
            $pageExists = 0;
336
        }
337
338
        if ($data) {
339
            $this->template->assign('page_id', $page_id);
340
            $this->template->assign('update_page_id', $data['id']);
341
342
            $this->template->add_array($data);
343
344
            $this->load->module('tags');
345
346
            $tags = $this->tags->get_page_tags($data['id']);
347
348
            $tags = array_column($tags, 'value');
349
350
            $this->template->assign('tags', $tags);
351
352
            // Roles
353
            $this->db->where('page_id', $page_id);
354
            $query = $this->db->get('content_permissions', 1);
355
            $page_roles = $query->row_array();
356
            $page_roles = unserialize($page_roles['data']);
357
358
            // Set roles
359
            $locale = MY_Controller::defaultLocale();
360
            $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'");
361
            $roles = $g_query->result_array();
362
363
            if ($roles != FALSE) {
364
                for ($i = 0, $cnt = count($roles); $i < $cnt; $i++) {
365
                    for ($i2 = 0, $cnt2 = count($page_roles); $i2 < $cnt2; $i2++) {
366
                        if ($page_roles[$i2]['role_id'] == $roles[$i]['id']) {
367
                            $roles[$i]['selected'] = 'selected="true"';
368
                        }
369
                        if ($page_roles[$i2]['role_id'] == '0') {
370
                            $this->template->assign('all_selected', 'selected="true"');
371
                        }
372
                    }
373
                }
374
            }
375
376
            $this->template->assign('roles', $roles);
377
            // roles
378
            // explode publush_date to date and time
379
            $this->template->assign('publish_date', date('Y-m-d', $data['publish_date']));
380
            $this->template->assign('publish_time', date('H:i:s', $data['publish_date']));
381
            $this->template->assign('create_date', date('Y-m-d', $data['created']));
382
            $this->template->assign('create_time', date('H:i:s', $data['created']));
383
            // end
384
            // set langs
385
            $langs = $this->cms_admin->get_langs();
386
387
            if (count($langs) > 1) {
388
                $this->template->assign('show_langs', 1);
389
            }
390
391
            // Load category
392
            $category = $this->lib_category->get_category($data['category']);
393
394
            $pagesPagination = $this->session->userdata('pages_pag_url');
395
            $pagesPagination = $pagesPagination ?: null;
396
397
            $this->template->add_array(
398
                [
399
                 'page_lang'       => $data['lang'],
400
                 'page_identif'    => $data['identif'],
401
                 'tree'            => $this->lib_category->build(),
402
                 'parent_id'       => $data['category'],
403
                 'langs'           => $langs,
404
                 'defLang'         => MY_Controller::getDefaultLanguage()['id'], //??
405
                 'category'        => $category,
406
                 'pageExists'      => $pageExists,
407
                 'pagesPagination' => $pagesPagination,
408
                ]
409
            );
410
411
            if ($data['lang_alias'] != 0) {
412
                $orig_page = $this->cms_admin->get_page($data['lang_alias']);
413
414
                $this->template->assign('orig_page', $orig_page);
415
            }
416
417
            $this->template->show('edit_page', FALSE);
418
        }
419
    }
420
421
    /**
422
     * Update existing page by ID
423
     *
424
     * @access public
425
     * @param integer $page_id
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
426
     */
427
    public function update($page_id) {
428
429
        $pagesPagination = $this->session->userdata('pages_pag_url');
430
        $pagesPagination = $pagesPagination ?: null;
431
432
        //cp_check_perm('page_edit');
433
434
        $data = $this->db->get_where('content', ['id' => $page_id]);
435
436
        if ($data->num_rows() > 0) {
437
            $data = $data->row_array();
438
        } else {
439
            $data = FALSE;
440
        }
441
        /** Init Event. Pre Edit Page */
442
        Events::create()->registerEvent(['pageId' => $page_id, 'url' => $data['url']], 'BaseAdminPage:preUpdate');
443
        Events::runFactory();
444
445
        $this->form_validation->set_rules('page_title', lang('Title', 'admin'), 'trim|required|min_length[1]|max_length[500]');
446
        $this->form_validation->set_rules('page_keywords', lang('Keywords', 'admin'), 'trim');
447
        $this->form_validation->set_rules('prev_text', lang('Preliminary contents', 'admin'), 'trim|required');
448
        $this->form_validation->set_rules('page_description', lang('Description ', 'admin'), 'trim');
449
        $this->form_validation->set_rules('full_tpl', lang('Page template', 'admin'), 'trim|max_length[50]|min_length[2]|callback_tpl_validation');
450
        $this->form_validation->set_rules('main_tpl', lang('Main page template ', 'admin'), 'trim|max_length[50]|min_length[2]|callback_tpl_validation');
451
        $this->form_validation->set_rules('create_date', lang('Creation date', 'admin'), 'required');
452
        $this->form_validation->set_rules('create_time', lang('Creation time', 'admin'), 'required');
453
        $this->form_validation->set_rules('publish_date', lang('Publication date', 'admin'), 'required');
454
        $this->form_validation->set_rules('publish_time', lang('Publication time', 'admin'), 'required');
455
456
        $url = $this->input->post('page_url') ?: $this->createUrl($this->input->post('page_title'));
457
        $urlValidation = $url ? '' : '|required';
458
        $this->form_validation->set_rules('page_url', lang('URL', 'admin'), 'alpha_dash|least_one_symbol|max_length[255]' . $urlValidation);
459
460
        $page_category = $this->cms_admin->get_category($data['category']);
461
462
        if ($page_category['field_group'] != -1 && $page_category) {
463
            $groupId = $page_category['field_group'];
464
            $fields = $this->db
465
                ->where("content_fields.data like '%required%'")
466
                ->or_where("content_fields.data like '%validation%'")
467
                ->where('group_id', $groupId)
468
                ->join('content_fields', 'content_fields.field_name = content_fields_groups_relations.field_name')
469
                ->get('content_fields_groups_relations')
470
                ->result_array();
471
472
            foreach ($fields as $field) {
473
                if ($groupId == $field['group_id']) {
474
                    $data = unserialize($field['data']);
475
                    $str = '';
476
                    if ($data['required']) {
477
                        $str .= 'required|';
478
                    }
479
                    if ($data['validation']) {
480
                        $str .= $data['validation'];
481
                    }
482
483
                    $this->form_validation->set_rules($field['field_name'], $data['label'], $str);
484
                }
485
            }
486
        }
487
488
        if ($this->form_validation->run($this) == FALSE) {
489
            showMessage(validation_errors(), false, 'r');
490
        } else {
491
492
            // check if we have existing module with entered URL
493
            $this->db->where('name', $url);
494
            $query = $this->db->get('components');
495
496
            if ($query->num_rows() > 0) {
497
                showMessage(lang('Reserved the same name module', 'admin'), false, 'r');
498
                return;
499
            }
500
            // end module check
501
            // check if we have existing category with entered URL
502
            $b_page = $this->cms_admin->get_page($page_id);
503
504
            $originId = $b_page['lang_alias'] ?: $b_page['id'];
505
            $this->db->where('url', $url)
506
                ->where('entity_id !=', $originId);
507
            $query = $this->db->get('route', 1);
508
509
            if ($query->num_rows() > 0) {
510
                showMessage(lang('This URL is already in use!'), false, 'r');
511
                return;
512
            }
513
            // end check
514
515
            $full_url = $this->lib_category->GetValue($this->input->post('category'), 'path_url');
516
517
            if ($full_url == FALSE) {
518
                $full_url = '';
519
            }
520
521
            $keywords = $this->lib_admin->db_post('page_keywords');
522
            $description = $this->lib_admin->db_post('page_description');
523
524
            $publish_date = $this->input->post('publish_date') . ' ' . $this->input->post('publish_time');
525
            $create_date = $this->input->post('create_date') . ' ' . $this->input->post('create_time');
526
527
            $data = [
528
                     'title'           => trim($this->input->post('page_title')),
529
                     'meta_title'      => trim($this->input->post('meta_title')),
530
                     'url'             => str_replace('.', '', trim($url)), //Delete dots from url
531
                     'cat_url'         => $full_url,
532
                     'keywords'        => $keywords,
533
                     'description'     => $description,
534
                     'full_text'       => trim($this->input->post('full_text')),
535
                     'prev_text'       => trim($this->lib_admin->db_post('prev_text')),
536
                     'category'        => $this->input->post('category'),
537
                     'full_tpl'        => $this->input->post('full_tpl'),
538
                     'main_tpl'        => $this->input->post('main_tpl'),
539
                     'comments_status' => $this->input->post('comments_status'),
540
                     'post_status'     => $this->input->post('post_status'),
541
                     'publish_date'    => strtotime($publish_date),
542
                     'created'         => strtotime($create_date),
543
                     'updated'         => time(),
544
                     'route_id'        => $b_page['route_id'],
545
                    ];
546
547
            $data['id'] = $page_id;
548
549
            if ($b_page['lang_alias'] != 0) {
550
                $data['url'] = $b_page['url'];
551
            }
552
553
            $this->on_page_update($data);
554
555
            $last_id = $this->cms_admin->update_page($page_id, $data);
556
557
            if ($last_id >= 1) {
558
                $this->load->module('cfcm')->save_item_data($last_id, 'page');
559
560
                $this->cache->delete_all();
561
562
                $this->lib_admin->log(
563
                    lang('Changed the page', 'admin') .
564
                    " <a href='/admin/pages/edit/$page_id>'{$data['title']}</a>"
565
                );
566
567
                $action = $this->input->post('action');
568
                $path = '/admin/pages/GetPagesByCategory/all/' . $pagesPagination;
569
570
                if ($action == 'edit') {
571
                    $path = "/admin/pages/edit/$page_id";
572
                }
573
574
                showMessage(lang('Page contents have been updated', 'admin'));
575
576
                $page = $this->cms_admin->get_page($page_id);
577
                if ($page) {
578
                    $page_id = $page['lang_alias'] ? $page['lang_alias'] : $page_id;
579
                    $lang_id = $this->input->post('lang_id');
580
                    if ($action == 'edit') {
581
                        $path = "/admin/pages/edit/$page_id/$lang_id";
582
                    }
583
                }
584
585
                pjax($path);
586
            } else {
587
                showMessage('Error', false, 'r');
588
            }
589
        }
590
    }
591
592
    /**
593
     * This event occurs right after page updated
594
     * @param array $page
595
     */
596
    private function on_page_update($page) {
597
598
        /** Update page roles */
599
        $this->_set_page_roles($page['id'], $this->input->post('roles'));
600
601
        /** Update page tags */
602
        $this->load->module('tags')->_set_page_tags($this->input->post('search_tags'), (int) $page['id']);
603
604
        /** Init CMS Events system */
605
        Events::create()->registerEvent($page, 'Page:update');
606
    }
607
608
    /**
609
     * Translit title to url
610
     */
611
    public function ajax_translit() {
612
613
        echo $this->createUrl($this->input->post('str'));
614
    }
615
616
    public function save_positions() {
617
618
        foreach ($this->input->post('pages_pos') as $k => $v) {
619
            $item = explode('_', substr($v, 4));
620
621
            $data = ['position' => $k];
622
            $this->db->where('id', $item[0]);
623
            //            $this->db->or_where('lang_alias', $item[1]);
624
            $this->db->update('content', $data);
625
        }
626
    }
627
628
    public function delete_pages() {
629
630
        $ids = $this->input->post('pages');
631
632
        if (count($ids) > 0) {
633
            foreach ($ids as $v) {
634
                $page_id = substr($v, 5);
635
                $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...
636
            }
637
        }
638
639
        if (in_array(false, $res)) {
640
            showMessage(lang('Can not delete main page', 'admin'), lang('Message'), 'r');
641
        }
642
        if (in_array(true, $res)) {
643
            showMessage(lang('Successful delete', 'admin'));
644
        }
645
        pjax($this->input->server('HTTP_REFERER'));
646
    }
647
648
    /**
649
     * Delete page
650
     *
651
     * @access public
652
     * @param string $page_id
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
653
     * @param bool $show_messages
654
     * @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...
655
     */
656
    public function delete($page_id, $show_messages = TRUE) {
657
658
        //cp_check_perm('page_delete');
659
660
        $settings = $this->cms_admin->get_settings();
661
662
        if ($settings['main_page_id'] == $page_id AND $settings['main_type'] == 'page') {
0 ignored issues
show
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected and, but found AND.
Loading history...
663
            return FALSE;
664
        }
665
666
        $this->db->where('id', $page_id);
667
        $query = $this->db->get('content', 1);
668
        $page = $query->row_array();
669
670
        if ($page['lang_alias'] == 0) {
671
            $this->db->where('id', $page['id']);
672
            $this->db->delete('content');
673
674
            $this->db->where('lang_alias', $page['id']);
675
            $this->db->delete('content');
676
677
            $this->on_page_delete($page['id']);
678
679
            if ($show_messages == TRUE) {
680
                showMessage(lang('Page has been deleted.', 'admin'));
681
                updateDiv('page', site_url('admin/pages/GetPagesByCategory/' . $page['category']));
682
            }
683
            return TRUE;
684
        }
685
686
        $root_page = $this->cms_admin->get_page($page['lang_alias']);
687
688
        //         delete page
689
        $this->db->where('id', $page['id']);
690
        $this->db->delete('content');
691
692
        $this->on_page_delete($page_id);
693
694
        if ($show_messages == TRUE) {
695
            showMessage(lang('Page has been deleted.', 'admin'));
696
            updateDiv('page', site_url('admin/pages/edit/' . $root_page['id'] . '/' . $root_page['lang']));
697
        }
698
    }
699
700
    /**
701
     * This event occurs right after page deleted
702
     * @param integer $page_id
703
     */
704
    private function on_page_delete($page_id) {
705
706
        $this->db->where('item_id', $page_id);
707
        $this->db->where('item_type', 'page');
708
        $this->db->delete('content_fields_data');
709
        $this->cache->delete('cfcm_field_' . $page_id . 'page');
710
711
        $this->lib_admin->log(lang('Deleted ID page', 'admin') . ' ' . $page_id);
712
713
        // Delete content_permissions
714
        $this->db->where('page_id', $page_id);
715
        $this->db->delete('content_permissions');
716
717
        // Delete page tags
718
        $this->load->module('tags')->_remove_orphans($page_id);
719
720
        /** Init CMS Events system */
721
        Events::create()->raiseEvent(['pageId' => $page_id, 'userId' => $this->dx_auth->get_user_id()], 'Page:delete');
722
    }
723
724
    /**
725
     * @param string $action
726
     */
727
    public function move_pages($action) {
728
729
        $ids = $this->input->post('pages');
730
        $ids_key = array_flip($this->input->post('pages'));
731
732
        $this->db->select('category');
733
        $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...
734
735
        if ((int) $this->input->post('new_cat') > 0) {
736
            $category = $this->lib_category->get_category($this->input->post('new_cat'));
737
        } else {
738
            $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...
739
            $category['path_url'] = '';
740
        }
741
742
        if (count($ids) > 0) {
743
            foreach ($ids as $v) {
744
                $page_id = substr($v, 5);
745
746
                $data = [
747
                         'category' => $category['id'],
748
                        ];
749
                $route = [
750
                          'parent_url' => trim($category['path_url'], '/'),
751
                         ];
752
753
                switch ($action) {
754
                    case 'move':
755
                        $this->db->where('id', $page_id);
756
                        $this->db->update('content', $data);
757
758
                        $this->db->where('lang_alias', $page_id);
759
                        $this->db->update('content', $data);
760
761
                        $this->db->where('entity_id', $page_id);
762
                        $this->db->update('route', $route);
763
764
                        break;
765
766
                    case 'copy':
767
                        $page = $this->db
768
                            ->select('content.*, route.url, route.parent_url')
769
                            ->join('route', 'route.id = content.route_id')
770
                            ->get_where('content', ['content.id' => $page_id])->row_array();
771
                        $page['category'] = $data['category'];
772
                        $page['lang_alias'] = 0;
773
                        $page['comments_count'] = 0;
774
                        $url = $page['url'];
775
                        $parentUrl = $page['parent_url'];
776
777
                        $this->db->like('url', $url);
778
                        $new_url = $url . ($this->db->get('route')->num_rows() + 1);
779
780
                        unset($page['id'], $page['url'], $page['parent_url']);
781
782
                        $this->db->insert('content', $page);
783
                        $new_id = $this->db->insert_id();
784
785
                        $route = new Route();
786
                        $route->setParentUrl($parentUrl);
787
                        $route->setUrl($new_url);
788
                        $route->setType(Route::TYPE_PAGE);
789
                        $route->setEntityId($new_id);
790
                        $route->save();
791
792
                        $this->db->update('content', ['route_id' => $route->getId()], ['id' => $new_id]);
793
794
                        $this->_copy_content_fields($page_id, $new_id);
795
796
                        // Copy page to other languages
797
                        $pages = $this->db->get_where('content', ['lang_alias' => $page_id])->result_array();
798
799
                        foreach ($pages as $page) {
800
                            unset($page['id']);
801
                            $page['category'] = $data['category'];
802
                            $page['comments_count'] = 0;
803
                            $page['lang_alias'] = $new_id;
804
                            $this->db->insert('content', $page);
805
                            $this->_copy_content_fields($page_id, $this->db->insert_id());
806
                        }
807
808
                        break;
809
                }
810
            }
811
            $catName = $category['name'] ? ' -> ' . $category['name'] : '';
812
            if ($action == 'copy') {
813
                showMessage(lang('Page successfuly copied', 'admin'));
814
                $this->lib_admin->log(lang('Pages was copied', 'admin') . '. Id: ' . implode(', ', $ids_key) . '' . $catName);
815
            } else if ($action == 'move') {
0 ignored issues
show
introduced by
Use "elseif" in place of "else if"
Loading history...
816
                showMessage(lang('Successfull moving', 'admin'));
817
                $this->lib_admin->log(lang('Pages was moving', 'admin') . '. Id: ' . implode(', ', $ids_key) . '' . $catName);
818
            }
819
            pjax($this->input->server('HTTP_REFERER'));
820
        } else {
821
            showMessage(lang('The operation error', 'admin'));
822
        }
823
    }
824
825
    /**
826
     * Copy content field on page copy
827
     * @param $page_id
0 ignored issues
show
introduced by
Missing parameter type
Loading history...
828
     * @param string $original_id
829
     */
830
    protected function _copy_content_fields($original_id, $new_id) {
831
832
        $fields = $this->db->get_where('content_fields_data', ['item_id' => $original_id, 'item_type' => 'page'])->result_array();
833
834
        foreach ($fields as $field) {
835
            unset($field['id']);
836
            $field['item_id'] = $new_id;
837
            $this->db->insert('content_fields_data', $field);
838
        }
839
    }
840
841
    /**
842
     * Display window to move pages to some category
843
     * @param string $action
844
     */
845
    public function show_move_window($action = 'move') {
846
847
        $this->template->assign('action', $action);
848
        $this->template->assign('tree', $this->lib_category->build());
849
        $this->template->show('move_pages', FALSE);
850
    }
851
852
    /**
853
     * Return tags in JSON
854
     */
855
    public function json_tags() {
856
857
        $this->load->module('tags');
858
        $new_tags = [];
859
860
        $search = $this->input->post('search_tags');
861
862
        if (mb_strlen($search) > 1) {
863
            $tags = $this->tags->search_tags($search);
864
865
            foreach ($tags as $tag) {
866
                $new_tags[] = $tag['value'];
867
            }
868
869
            echo json_encode(array_unique($new_tags));
870
        }
871
    }
872
873
    /**
874
     * Create keywords
875
     */
876
    public function ajax_create_keywords() {
877
878
        $text = $this->input->post('keys');
879
880
        if ($text == '') {
881
            echo lang('Zero-length string', 'admin');
882
            return;
883
        }
884
885
        $keywords = $this->lib_seo->get_keywords($text, TRUE);
886
887
        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...
888
            if ($val < 3) {
889
                $size = 14 + $val;
890
            }
891
892
            if ($val == 1) {
893
                $size = 12;
894
            }
895
896
            if ($val == 4) {
897
                $size = 13;
898
            }
899
900
            if ($val > 3) {
901
                $size = 22;
902
            }
903
904
            $append = $key . ', ';
905
            echo '<a class="underline" onclick="$(\'#page_keywords\').append(\'' . $append . '\' );" style="font-size:' . $size . 'px">' . $key . '</a> &nbsp;';
906
        }
907
    }
908
909
    /**
910
     * Create description
911
     */
912
    public function ajax_create_description() {
913
914
        $desc = $this->lib_seo->get_description($this->input->post('text'));
915
        echo $desc;
916
    }
917
918
    /**
919
     * Change page post_status
920
     */
921
    public function ajax_change_status($page_id) {
922
923
        $exsists = true;
924
        $page = $this->cms_admin->get_page($page_id);
925
926
        switch ($page['post_status']) {
927 View Code Duplication
            case 'publish':
928
                //$data = array('post_status' => 'pending');
929
                $data = $page;
930
                $data['post_status'] = 'draft';
931
                $this->cms_admin->update_page($page['id'], $data, $exsists);
932
                break;
933
934 View Code Duplication
            case 'pending':
935
                $data = $page;
936
                $data['post_status'] = 'publish';
937
                $this->cms_admin->update_page($page['id'], $data, $exsists);
938
939
                break;
940
941 View Code Duplication
            case 'draft':
942
                $data = $page;
943
                $data['post_status'] = 'publish';
944
                $this->cms_admin->update_page($page['id'], $data, $exsists);
945
946
                break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
947 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...
948
                $data = $page;
949
                $data['post_status'] = 'publish';
950
                $this->cms_admin->update_page($page['id'], $data, $exsists);
951
                break;
952
        }
953
        showMessage(lang('Status change success', 'admin'));
954
    }
955
956
    /**
957
     * Display pages by Category ID
958
     *
959
     * @access public
960
     * @param string $cat_id
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
961
     * @param null|int $pagination
962
     */
963
    public function GetPagesByCategory($cat_id = 'all', $pagination = null) {
964
965
        //////**********  Pagination pages **********\\\\\\\
966 View Code Duplication
        if ($pagination) {
967
            $paginationSession = ['pages_pag_url' => $pagination];
968
            $this->session->set_userdata($paginationSession);
969
        } else {
970
            $this->session->unset_userdata('pages_pag_url');
971
        }
972
973
        $def_lang = $this->cms_admin->get_default_lang();
974
        $this->config->set_item('cur_lang', $def_lang['id']);
975
        if ($cat_id != 'all') {
976
            $db_where = [
977
                         'category' => $cat_id,
978
                //'lang_alias' => 0,
979
                         'lang'     => (int) $def_lang['id'],
980
                        ];
981
        } else {
982
            //$this->db->select('content.*, category.name as cat_name');
983
            $db_where = [
984
                         'category >=' => 0,
985
                //'lang_alias' => 0,
986
                         'lang'        => (int) $def_lang['id'],
987
                        ];
988
        }
989
        $main_settings = $this->cms_base->get_settings();
990
991
        $offset = $this->uri->segment(5);
992
        $offset == FALSE ? $offset = 0 : TRUE;
993
994
        $row_count = $this->_Config['per_page'];
995
996
        if ($cat_id != 'all') {
997
            $category = $this->lib_category->get_category($cat_id);
998
        }
999
1000
        //$this->db->order_by('category', 'asc');
1001
        $this->db->order_by('content.position', 'asc');
1002
        $this->db->order_by('content.id', 'desc');
1003
1004
        //filter
1005
        if ($this->input->post('id')) {
1006
            $this->db->where('content.id', $this->input->post('id'));
1007
            $flagPOST = true;
1008
        }
1009 View Code Duplication
        if ($this->input->post('title')) {
1010
            $this->db->where('content.title LIKE ', '%' . $this->input->post('title') . '%');
1011
            $flagPOST = true;
1012
        }
1013 View Code Duplication
        if ($this->input->post('url')) {
1014
            $this->db->where('route.url LIKE ', '%' . $this->input->post('url') . '%');
1015
1016
            $flagPOST = true;
1017
        }
1018
1019
        if ($cat_id == NULL) {
1020
            $this->db->join('category', 'category.id = content.category');
1021
        }
1022
1023
        $this->db->join('route', 'route.id = content.route_id');
1024
1025
        $this->db->select('content.*, route.url, if(route.parent_url <> "", concat(route.parent_url, "/") , "") as cat_url ', false);
1026
        if (!$flagPOST) {
1027
            $query = $this->db->get_where('content', $db_where, $row_count, $offset);
1028
        } else {
1029
            $query = $this->db->get_where('content', $db_where);
1030
        }
1031
        $this->db->where($db_where);
1032
        $this->db->from('content');
1033
        $total_pages = $this->db->count_all_results();
1034
1035
        if ($query->num_rows > 0) {
1036
            // При пагинации при поиске ломался поиск.
1037
            if (!$flagPOST) {
1038
                // Begin pagination
1039
                $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...
1040
                $config['container'] = 'page';
1041
                $config['uri_segment'] = 5;
1042
                $config['total_rows'] = $total_pages;
1043
                $config['per_page'] = $this->_Config['per_page'];
1044
1045
                $config['separate_controls'] = true;
1046
                $config['full_tag_open'] = '<div class="pagination pull-left"><ul>';
1047
                $config['full_tag_close'] = '</ul></div>';
1048
                $config['controls_tag_open'] = '<div class="pagination pull-right"><ul>';
1049
                $config['controls_tag_close'] = '</ul></div>';
1050
                $config['next_link'] = lang('Next', 'admin') . '&nbsp;&gt;';
1051
                $config['prev_link'] = '&lt;&nbsp;' . lang('Prev', 'admin');
1052
                $config['cur_tag_open'] = '<li class="btn-primary active"><span>';
1053
                $config['cur_tag_close'] = '</span></li>';
1054
                $config['prev_tag_open'] = '<li>';
1055
                $config['prev_tag_close'] = '</li>';
1056
                $config['next_tag_open'] = '<li>';
1057
                $config['next_tag_close'] = '</li>';
1058
                $config['num_tag_close'] = '</li>';
1059
                $config['num_tag_open'] = '<li>';
1060
                $config['num_tag_close'] = '</li>';
1061
1062
                $this->pagination->num_links = 5;
1063
                $this->pagination->initialize($config);
1064
                // End pagination
1065
            }
1066
1067
            $pages = $query->result_array();
1068
1069
            $catsQuery = $this->db->get('category');
1070
            $allCats = $catsQuery->result_array();
1071
1072
            $this->template->add_array(
1073
                [
1074
                 'paginator'     => $this->pagination->create_links_ajax(),
1075
                 'total_pages'   => $total_pages,
1076
                 'pages'         => $pages,
1077
                 'cat_id'        => $cat_id,
1078
                 'category'      => $category,
1079
                 'cats'          => $allCats,
1080
                 'tree'          => $this->lib_category->build(),
1081
                 'show_cat_list' => $main_settings['cat_list'],
1082
                ]
1083
            );
1084
            $this->template->show('pages_list', FALSE);
1085
        } else {
1086
1087
            $this->template->add_array(
1088
                [
1089
                 'no_pages'      => TRUE,
1090
                 'category'      => $category,
1091
                 'total_pages'   => $total_pages,
1092
                 'tree'          => $this->lib_category->build(),
1093
                 'cat_id'        => $cat_id,
1094
                 'show_cat_list' => $main_settings['cat_list'],
1095
                ]
1096
            );
1097
1098
            $this->template->show('pages_list', FALSE);
1099
        }
1100
    }
1101
1102
}