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

Categories::formUrl()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 8
nop 0
dl 0
loc 11
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
use CMSFactory\Events;
4
use core\models\Route;
5
use core\models\RouteQuery;
6
use template_manager\classes\TemplateManager;
7
8
if (!defined('BASEPATH')) {
9
    exit('No direct script access allowed');
10
}
11
12
/**
13
 * @property Cms_admin cms_admin
14
 * @property Lib_admin lib_admin
15
 * @property Lib_category lib_category
16
 * @property Cms_base cms_base
17
 */
18
class Categories 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
    /**
22
     * @var array
23
     */
24
    public $categories;
25
26
    /**
27
     * @var int
28
     */
29
    protected $level = -1;
30
31
    /**
32
     * @var bool
33
     */
34
    protected $multi = false;
35
36
    /**
37
     * @var array
38
     */
39
    protected $path = [];
40
41
    /**
42
     * @var array
43
     */
44
    protected $pathIds = [];
45
46
    /**
47
     * @var array
48
     */
49
    private $temp_cats = [];
50
51
    /**
52
     * Categories constructor.
53
     */
54 View Code Duplication
    public function __construct() {
55
        parent::__construct();
56
57
        $this->load->library('DX_Auth');
58
        admin_or_redirect();
59
        $this->load->library('lib_admin');
60
        $this->load->library('lib_category');
61
        $this->lib_admin->init_settings();
62
    }
63
64
    /**
65
     * Create or update new category
66
     * @param string $action
67
     * @param int $cat_id
68
     */
69
    public function create($action, $cat_id = 0) {
70
        $url = $this->formUrl();
71
72
        $this->form_validation->set_rules('name', lang('Title', 'admin'), 'trim|required|min_length[1]|max_length[160]|xss_clean');
73
74
        /** Добавил необходимое условие так как если передать спец символы url не генерирует */
75
76
        $urlRule = 'trim|min_length[1]|max_length[255]|alpha_dash|least_one_symbol';
77
        $this->form_validation->set_rules('url', lang('URL categories', 'admin'), $url ? $urlRule : 'required|' . $urlRule);
78
        $this->form_validation->set_rules('image', lang('Image', 'admin'), 'max_length[250]');
79
        $this->form_validation->set_rules('parent_id', lang('Parent', 'admin'), 'trim|required|integer|max_length[160]');
80
        $this->form_validation->set_rules('description', lang('Description ', 'admin'), 'trim');
81
        $this->form_validation->set_rules('keywords', lang('Keywords', 'admin'), 'trim');
82
        $this->form_validation->set_rules('short_desc', lang('Short description', 'admin'), 'trim');
83
        $this->form_validation->set_rules('title', lang('Meta Title', 'admin'), 'trim|max_length[250]');
84
        $this->form_validation->set_rules('tpl', lang('Template', 'admin'), 'trim|max_length[50]');
85
        $this->form_validation->set_rules('page_tpl', lang('Page template', 'admin'), 'trim|max_length[50]|callback_tpl_validation');
86
        $this->form_validation->set_rules('main_tpl', lang('Main template', 'admin'), 'trim|max_length[50]|callback_tpl_validation');
87
        $this->form_validation->set_rules('per_page', lang('Posts on page', 'admin'), 'required|trim|integer|max_length[4]|min_length[1]|is_natural_no_zero');
88
        if ($cat_id) {
89
            $cat = $this->cms_admin->get_category($cat_id);
90
            $groupId = (int) $cat['category_field_group'];
91
            $groupId_POST = (int) $this->input->post('category_field_group');
92
93
            if ($groupId != -1 && $groupId_POST != -1) {
94
                ($hook = get_hook('cfcm_set_rules')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'cfcm_set_rules'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
95
            }
96
        }
97
        if ($this->form_validation->run($this) == FALSE) {
98
            ($hook = get_hook('admin_create_cat_val_failed')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_create_cat_val_failed'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
99
100
            showMessage(validation_errors(), false, 'r');
101
        } else {
102
103
            $fetch_pages = $this->input->post('fetch_pages');
104
105
            if (count($fetch_pages) > 0) {
106
                $fetch_pages = serialize($fetch_pages);
107
            }
108
            $settings = [
109
                         'category_apply_for_subcats' => $this->input->post('category_apply_for_subcats'),
110
                         'apply_for_subcats'          => $this->input->post('apply_for_subcats'),
111
                        ];
112
            $data = [
113
                     'name'             => $this->input->post('name'),
114
                     'url'              => $url,
115
                     'image'            => $this->lib_admin->db_post('image'),
116
                     'short_desc'       => $this->lib_admin->db_post('short_desc'),
117
                     'parent_id'        => $this->input->post('parent_id'),
118
                     'description'      => $this->lib_admin->db_post('description'),
119
                     'keywords'         => $this->lib_admin->db_post('keywords'),
120
                     'title'            => $this->lib_admin->db_post('title'),
121
                     'tpl'              => $this->lib_admin->db_post('tpl'),
122
                     'main_tpl'         => $this->lib_admin->db_post('main_tpl'),
123
                     'page_tpl'         => $this->lib_admin->db_post('page_tpl'),
124
                     'per_page'         => $this->lib_admin->db_post('per_page'),
125
                     'order_by'         => $this->lib_admin->db_post('order_by'),
126
                     'sort_order'       => $this->lib_admin->db_post('sort_order'),
127
                     'comments_default' => $this->lib_admin->db_post('comments_default'),
128
                     'fetch_pages'      => $fetch_pages,
129
                     'settings'         => serialize($settings),
130
                     'updated'          => time(),
131
                     'route_id'         => $cat['route_id'],
132
                    ];
133
134
            $parent = $this->lib_category->get_category($data['parent_id']);
135
136 View Code Duplication
            if ($parent != 'NULL') {
137
                $full_path = $parent['path_url'] . $data['url'] . '/';
138
            } else {
139
                $full_path = $data['url'] . '/';
140
            }
141
142 View Code Duplication
            if (($this->category_exists($full_path) == TRUE) AND ($action != 'update') AND ($data['url'] != 'core')) {
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...
143
                $data['url'] .= time();
144
            }
145
146
            switch ($action) {
147
                case 'new':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
148
149
                    if ($this->url_exists($data['url'])) {
150
                        $data['url'] .= time();
151
                    }
152
153
                    $data['created'] = time();
154
                    ($hook = get_hook('admin_create_category')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_create_category'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
155
156
                    $id = $this->cms_admin->create_category($data);
157
158
                    $this->lib_admin->log(
159
                        lang('Category has been created', 'admin') .
160
                        " <a href='$BASE_URL/admin/categories/edit/$id'>{$data['name']}</a>"
0 ignored issues
show
Bug introduced by
The variable $BASE_URL does not exist. Did you forget to declare it?

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

Loading history...
161
                    );
162
163
                    /** Init Event. Create new Category */
164
                    Events::create()->raiseEvent(array_merge($data, ['id' => $id, 'userId' => $this->dx_auth->get_user_id()]), 'Categories:create');
165
166
                    /** End init Event. Create new Page */
167
                    showMessage(lang('Pages category created', 'admin'));
168
169
                    $act = $this->input->post('action');
170
                    if ($act == 'close') {
171
                        pjax('/admin/categories/cat_list');
172
                    } else {
173
                        pjax('/admin/categories/edit/' . $id);
174
                    }
175
                    break;
176
177
                case 'update':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
178
179
                    /** Init Event. Pre Create Category */
180
                    Events::create()->raiseEvent(['pageId' => $cat_id, 'url' => $cat['url']], 'Categories:preUpdate');
181
182
                    if ($this->url_exists($data['url'], $cat_id)) {
183
                        $data['url'] .= time();
184
                    }
185
186
                    ($hook = get_hook('admin_update_category')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_update_category'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
187
                    $this->cms_admin->update_category($data, $cat_id);
188
189
                    $this->load->module('cfcm')->save_item_data($cat_id, 'category');
190
191
                    $this->cache->delete_all();
192
193
                    // Clear lib_category data
194
                    $this->lib_category->categories = [];
195
                    $this->lib_category->level = 0;
196
                    $this->lib_category->path = [];
197
                    $this->lib_category->unsorted_arr = FALSE;
198
                    $this->lib_category->unsorted = FALSE;
199
200
                    $this->lib_category->build();
201
202
                    $this->update_urls();
203
204
                    $this->lib_admin->log(
205
                        lang('Changed the category', 'admin') .
206
                        " <a href='$BASE_URL/admin/categories/edit/$cat_id'>{$data['name']}</a>"
207
                    );
208
209
                    /** Init Event. Create new Category */
210
                    Events::create()->raiseEvent(array_merge($data, ['id' => $cat_id, 'userId' => $this->dx_auth->get_user_id()]), 'Categories:update');
211
212
                    showMessage(lang('Changes saved', 'admin'));
213
                    $act = $this->input->post('action');
214
                    if ($act == 'close') {
215
                        pjax('/admin/categories/cat_list');
216
                    } else {
217
                        pjax('/admin/categories/edit/' . $cat_id);
218
                    }
219
220
                    break;
221
            }
222
223
            $this->cache->delete_all();
224
        }
225
    }
226
227
    public function url_exists($url, $id = null) {
228
229
        $segment = end(explode('/', $url));
0 ignored issues
show
Bug introduced by
explode('/', $url) cannot be passed to end() as the parameter $array expects a reference.
Loading history...
230
231
        if ($id) {
232
            $this->db->where('entity_id <>', $id);
233
        }
234
        $query = $this->db->where('url', $segment)->get('route');
235
236
        return $query->num_rows() > 0;
237
238
    }
239
240
    /**
241
     * Form url from POST
242
     * @return string
243
     */
244
    private function formUrl() {
245
        // Create category URL
246
        if ($this->input->post('url') == null || $this->input->post('url') == '') {
247
            $url = $this->createUrl($this->input->post('name'));
248
        } else {
249
            $url = $this->input->post('url');
250
        }
251
        $url = mb_strlen($url) === 1 ? str_repeat($url, 2) : $url;
252
253
        return $url ?: time();
254
    }
255
256
    /**
257
     * @param string $str
258
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be false|array? Also, consider making the array more specific, something like array<String>, or String[].

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.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
259
     */
260
    public function category_exists($str) {
261
        return $this->lib_category->get_category_by('path_url', $str);
262
    }
263
264
    public function update_urls() {
265
        $categories = $this->lib_category->unsorted();
266
267
        foreach ($categories as $category) {
268
            $this->db->where('category', $category['id']);
269
            $this->db->update('content', ['cat_url' => $category['path_url']]);
270
        }
271
        $this->cache->delete_all();
272
    }
273
274
    /**
275
     * Display create category form
276
     * @param null $parent_id
277
     */
278
    public function create_form($parent_id = NULL) {
279
        $this->template->assign('tree', $this->lib_category->build());
280
        $this->template->assign('parent_id', $parent_id);
281
        $this->template->assign('include_cats', $this->sub_cats($this->lib_category->build()));
282
        $this->template->assign('template_files', $this->getTemplateFiles());
283
284
        /** Init Event. Pre Create Category */
285
        Events::create()->registerEvent('', 'BaseAdminCategory:preCreate');
286
        Events::runFactory();
287
288
        $this->template->show('create_cat', FALSE);
289
    }
290
291
    /**
292
     * @param array $array
293
     * @return array
294
     */
295
    public function sub_cats(array $array = []) {
296
        foreach ($array as $item) {
297
            $this->temp_cats[] = $item;
298
            if (count($item['subtree']) > 0) {
299
                $this->sub_cats($item['subtree']);
300
            }
301
        }
302
        return $this->temp_cats;
303
    }
304
305
    /**
306
     * Return template files names for main, page or category template
307
     * @return array
308
     */
309
    public function getTemplateFiles() {
310
        $currentTemplate = TemplateManager::getInstance()->getCurentTemplate()->name;
311
        $pathToFind = TEMPLATES_PATH . $currentTemplate;
312
313
        $files = [];
314
        foreach (new DirectoryIterator($pathToFind) as $entity) {
315
            if ($entity->isFile() & !$entity->isDot() & $entity->getExtension() == 'tpl') {
316
                $files[] = array_shift(explode('.', $entity->getFilename()));
0 ignored issues
show
Bug introduced by
explode('.', $entity->getFilename()) cannot be passed to array_shift() as the parameter $array expects a reference.
Loading history...
317
            }
318
        }
319
        return $files;
320
    }
321
322
    /**
323
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be false|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...
324
     */
325
    public function create_tpl() {
326
        $file = trim($this->input->post('filename'));
327
328
        $this->form_validation->set_rules('filename', lang('Template name', 'admin'), 'required|alpha_numeric|min_length[1]|max_length[250]');
329
330
        if ($this->form_validation->run() == FALSE) {
331
            $responce = showMessage(validation_errors(), false, 'r', true);
332
            $result = false;
333
            echo json_encode(['responce' => $responce, 'result' => $result]);
334
            return FALSE;
335
        }
336
337
        $currentTemplate = TemplateManager::getInstance()->getCurentTemplate()->name;
338
        $file = TEMPLATES_PATH . $currentTemplate . '/' . $file . '.tpl';
339
340
        if (!file_exists($file)) {
341
            $fp = fopen($file, 'w');
342
            if ($fp) {
343
                $responce = showMessage(lang('The file has been successfully created', 'admin'), '', '', true);
344
                $result = true;
345
            } else {
346
                $responce = showMessage(lang('Could not create file', 'admin'), '', 'r', true);
347
                $result = false;
348
            }
349
            fwrite($fp, '/* new ImageCMS Tpl file */');
350
            fclose($fp);
351
            echo json_encode(['responce' => $responce, 'result' => $result]);
352
        } else {
353
            $responce = showMessage(lang('File with the same name is already exist.'), '', 'r', true);
354
            $result = false;
355
            echo json_encode(['responce' => $responce, 'result' => $result]);
356
            return FALSE;
357
        }
358
    }
359
360
    /**
361
     * Delete category and its pages
362
     * @access public
363
     */
364
    public function delete() {
365
366
        foreach ($this->input->post('ids') as $p) {
367
368
            $cat_id = $p;
369
370
            if ($this->db->get('category')->num_rows() == 1) {
371
                showMessage(lang('You can not delete the last category from the list', 'admin'), lang('Error', 'admin'), 'r');
372
                return;
373
            }
374
375
            $settings = $this->cms_admin->get_settings();
376
377
            if ($settings['main_page_cat'] == $cat_id && 'category' == $settings['main_type']) {
378
                showMessage(lang('Can not delete main category', 'admin'), lang('Error', 'admin'), 'r');
379
                if (count($this->input->post('ids')) > 1) {
380
                    continue;
381
                } else {
382
                    return;
383
                }
384
            }
385
386
            ($hook = get_hook('admin_category_delete')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_category_delete'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
387
388
            // Delete Category
389
            $this->db->limit(1);
390
            $this->db->where('id', $cat_id);
391
            $this->db->delete('category');
392
393
            Events::create()->raiseEvent(['id' => $cat_id], 'Categories:delete');
394
395
            $this->lib_admin->log(lang('Deleted ID category or ID category has been deleted', 'admin') . ' ' . $cat_id);
396
397
            // Delete translates
398
            $this->db->where('alias', $cat_id);
399
            $this->db->delete('category_translate');
400
401
            // Delete pages
402
            $this->db->where('category', $cat_id);
403
            $pages = $this->db->get('content');
404
405 View Code Duplication
            if ($pages->num_rows() > 0) {
406
                $this->load->module('admin/pages', 'pages');
407
                foreach ($pages->result_array() as $page) {
408
                    $this->pages->delete($page['id'], FALSE);
409
                }
410
            }
411
412
            // Delete sub cats
413
            $this->sub_cats = [];
414
            $this->categories = $this->db->get('category')->result_array();
415
            $this->_get_sub_cats($cat_id);
416
417
            if (count($this->sub_cats) > 0) {
418
                foreach ($this->sub_cats as $key => $cat_id) {
419
420
                    ($hook = get_hook('admin_sub_category_delete')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_sub_category_delete'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
421
422
                    // Delete Category
423
                    $this->db->limit(1);
424
                    $this->db->where('id', $cat_id);
425
                    $this->db->delete('category');
426
427
                    Events::create()->raiseEvent(['id' => $cat_id], 'Categories:delete');
428
429
                    $this->lib_admin->log(lang('Deleted ID category or ID category has been deleted', 'admin') . ' ' . $cat_id);
430
431
                    // Delete translates
432
                    $this->db->where('alias', $cat_id);
433
                    $this->db->delete('category_translate');
434
435
                    // Delete pages
436
                    $this->db->where('category', $cat_id);
437
                    $pages = $this->db->get('content');
438
439 View Code Duplication
                    if ($pages->num_rows() > 0) {
440
                        $this->load->module('admin/pages', 'pages');
441
                        foreach ($pages->result_array() as $page) {
442
                            $this->pages->delete($page['id'], FALSE);
443
                        }
444
                    }
445
                }
446
            }
447
        }
448
449
        $CI = &get_instance();
450
451
        if ($CI->db->get_where('components', ['name' => 'sitemap'])->row()) {
452
            $CI->load->module('sitemap')->ping_google($this);
453
        }
454
455
        $this->cache->delete_all();
456
457 View Code Duplication
        if (count($this->input->post('ids')) > 1) {
458
            showMessage(lang('Pages categories deleted', 'admin'));
459
        } else {
460
            showMessage(lang('Pages category deleted', 'admin'));
461
        }
462
463
        return TRUE;
464
    }
465
466
    /**
467
     * @param int $id
468
     */
469
    public function _get_sub_cats($id) {
470
        foreach ($this->categories as $cat) {
471
            if ($cat['parent_id'] == $id) {
472
                $this->sub_cats[] = $cat['id'];
473
                $this->_get_sub_cats($cat['id']);
474
            }
475
        }
476
    }
477
478
    /**
479
     * Show edit category window
480
     * @access public
481
     * @param int $id
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
482
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be null|false?

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...
483
     */
484
    public function edit($id) {
485
        $cat = $this->cms_admin->get_category($id);
486
487
        /** Init Event. Pre Create Category */
488
        Events::create()->registerEvent(['pageId' => $id, 'url' => $cat['url']], 'Categories:preUpdate');
489
        Events::runFactory();
490
491
        ($hook = get_hook('admin_edit_category')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_edit_category'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
492
493
        if ($cat !== FALSE) {
494
            // Get langs
495
            $langs = $this->cms_base->get_langs();
496
            $this->template->assign('langs', $langs);
497
            $settings = unserialize($cat['settings']);
498
            $cat['fetch_pages'] = unserialize($cat['fetch_pages']);
499
            $this->template->add_array($cat);
500
501
            $categories = $this->lib_category->build();
502
503
            $this->template->assign('tree', $categories);
504
            $this->template->assign('template_files', $this->getTemplateFiles());
505
            $this->template->assign('include_cats', $this->sub_cats($this->lib_category->build()));
506
            $this->template->assign('settings', $settings);
507
            ($hook = get_hook('admin_show_category_edit')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_show_category_edit'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
508
509
            $this->template->show('category_edit', FALSE);
510
        } else {
511
            return FALSE;
512
        }
513
    }
514
515
    /**
516
     * @param string $action
517
     */
518
    public function fast_add($action = '') {
519
520
        $this->template->add_array(
521
            [
522
             'tree' => $this->lib_category->build(),
523
            ]
524
        );
525
526
        if ($action == '') {
527
            $this->template->show('fast_cat_add', FALSE);
528
        }
529
530
        if ($action == 'create') {
531
            $this->form_validation->set_rules('name', lang('Title', 'admin'), 'trim|required|min_length[1]|max_length[160]');
532
            $this->form_validation->set_rules('parent_id', lang('Parent', 'admin'), 'trim|required|integer|max_length[160]');
533
534
            if ($this->form_validation->run($this) == FALSE) {
535
                showMessage(validation_errors(), false, 'r');
536
            } else {
537
                $url = $this->formUrl();
538
                $fetch_pages = '';
539
540
                $data = [
541
                         'name'             => $this->input->post('name'),
542
                         'url'              => $url,
543
                         'position'         => '0',
544
                         'short_desc'       => '',
545
                         'parent_id'        => $this->input->post('parent_id'),
546
                         'description'      => '',
547
                         'keywords'         => '',
548
                         'title'            => '',
549
                         'tpl'              => '',
550
                         'main_tpl'         => '',
551
                         'page_tpl'         => '',
552
                         'per_page'         => 15,
553
                         'order_by'         => 'publish_date',
554
                         'sort_order'       => 'desc',
555
                         'comments_default' => '1',
556
                         'fetch_pages'      => $fetch_pages,
557
                        ];
558
559
                $parent = $this->lib_category->get_category($data['parent_id']);
560
561 View Code Duplication
                if ($parent != 'NULL') {
562
                    $full_path = $parent['path_url'] . $data['url'] . '/';
563
                } else {
564
                    $full_path = $data['url'] . '/';
565
                }
566
567 View Code Duplication
                if (($this->category_exists($full_path) == TRUE) AND ($action != 'update') AND ($data['url'] != 'core')) {
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...
568
                    $data['url'] .= time();
569
                }
570
571
                $id = $this->cms_admin->create_category($data);
572
573
                Events::create()->raiseEvent(
574
                    array_merge($data, ['id' => $id, 'userId' => $this->dx_auth->get_user_id()]),
575
                    'Categories:create'
576
                );
577
578
                $this->cache->delete_all();
579
580
                $this->lib_admin->log(
581
                    lang('Category has been created or created a category', 'admin') .
582
                    " <a href='$BASE_URL/admin/categories/edit/$id'>{$data['name']}</a>"
0 ignored issues
show
Bug introduced by
The variable $BASE_URL does not exist. Did you forget to declare it?

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

Loading history...
583
                );
584
585
                $this->template->add_array(
586
                    [
587
                     'tree'    => $this->lib_category->build(),
588
                     'sel_cat' => $id,
589
                    ]
590
                );
591
592
                $this->template->show('cats_select', FALSE);
593
            }
594
        }
595
    }
596
597
    /**
598
     * @param int $id
599
     */
600
    public function get_comments_status($id) {
601
        $this->db->select('comments_default');
602
        $this->db->where('id', $id);
603
        $query = $this->db->get('category')->row_array();
604
605
        echo json_encode($query);
606
    }
607
608
    public function index() {
609
        $this->cat_list();
610
    }
611
612
    public function cat_list() {
613
        $this->config->set_item('cur_lang', $this->load->module('core')->def_lang[0]['id']);
614
615
        $tree = $this->lib_category->_build();
616
617
        $this->template->add_array(
618
            [
619
             'tree'        => $tree,
620
             'catTreeHTML' => $this->renderCatList($tree),
621
            ]
622
        );
623
624
        $this->template->show('category_list', FALSE);
625
    }
626
627
    /**
628
     * @param array $tree
629
     * @return string
630
     */
631
    private function renderCatList(array $tree) {
632
        $html = '';
633
        foreach ($tree as $item) {
634
            $html .= '<div>';
635
            $html .= $this->template->fetch('_catlistitem', ['item' => $item]);
636
            if (count($item['subtree'])) {
637
                $html .= '<div class="frame_level sortable" style="display:none;">';
638
                $html .= $this->renderCatList($item['subtree']);
639
                $html .= '</div>';
640
            }
641
            $html .= '</div>';
642
        }
643
        return $html;
644
    }
645
646
    public function save_positions() {
647
        $positions = $this->input->post('positions');
648
649
        if (count($positions) == 0) {
650
            return false;
651
        }
652
653
        if ($this->input->post('positions')) {
654
            foreach ($this->input->post('positions') as $pos => $id) {
655
                $this->db->where('id', (int) $id);
656
                $this->db->set('position', $pos);
657
                $this->db->update('category');
658
            }
659
660
            showMessage(lang('The position has been successfully saved', 'admin'));
661
        }
662
    }
663
664
    /**
665
     * Validation for template name field
666
     * @param string $tpl
667
     * @return bool
668
     */
669 View Code Duplication
    public function tpl_validation($tpl) {
670
        if (preg_match('/^[0-9A-Za-z\_\.]{0,50}$/', $tpl)) {
671
            return TRUE;
672
        }
673
        $this->form_validation->set_message('tpl_validation', lang('The %s field can only contain Latin characters', 'admin'));
674
        return FALSE;
675
    }
676
677
    /**
678
     * @param int $id
679
     * @param string $lang
680
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be null|false?

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...
681
     */
682
    public function translate($id, $lang) {
683
        $cat = $this->cms_admin->get_category($id);
684
685
        ($hook = get_hook('admin_on_translate_cat')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_on_translate_cat'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
686
687
        if ($this->input->post()) {
688
            $this->load->library('form_validation');
689
690
            $this->form_validation->set_rules('name', lang('Title', 'admin'), 'trim|required|min_length[1]|max_length[160]');
691
            $this->form_validation->set_rules('image', lang('Image', 'admin'), 'max_length[250]');
692
            $this->form_validation->set_rules('description', lang('Description ', 'admin'), 'trim');
693
            $this->form_validation->set_rules('keywords', lang('Keywords', 'admin'), 'trim');
694
            $this->form_validation->set_rules('short_desc', lang('Short description', 'admin'), 'trim');
695
            $this->form_validation->set_rules('title', lang('Meta title', 'admin'), 'trim|max_length[250]');
696
697
            ($hook = get_hook('admin_set_cat_translate_rules')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_set_cat_translate_rules'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
698
699
            if ($this->form_validation->run($this) == FALSE) {
700
                showMessage(validation_errors(), false, 'r');
701
            } else {
702
                $data = [];
703
                $data['alias'] = $id;
704
                $data['lang'] = $lang;
705
                $data['name'] = $this->input->post('name');
706
                $data['image'] = $this->input->post('image');
707
                $data['description'] = $this->input->post('description');
708
                $data['keywords'] = $this->input->post('keywords');
709
                $data['short_desc'] = $this->input->post('short_desc');
710
                $data['title'] = $this->input->post('title');
711
712
                $this->db->where('alias', $id);
713
                $this->db->where('lang', $lang);
714
                $query = $this->db->get('category_translate');
715
716
                if ($query->num_rows() == 0) {
717
                    $this->lib_admin->log(
718
                        lang('Translated the category', 'admin') .
719
                        " <a href='$BASE_URL/admin/categories/edit/{$cat['id']}'>{$cat['name']}</a>"
0 ignored issues
show
Bug introduced by
The variable $BASE_URL does not exist. Did you forget to declare it?

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

Loading history...
720
                    );
721
722
                    ($hook = get_hook('admin_insert_cat_translation')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_insert_cat_translation'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
723
724
                    $this->db->insert('category_translate', $data);
725
                } else {
726
                    $this->lib_admin->log(
727
                        lang('Changed the category translation', 'admin') .
728
                        " <a href='$BASE_URL/admin/categories/edit/{$cat['id']}'>{$cat['name']}</a>"
729
                    );
730
731
                    ($hook = get_hook('admin_update_cat_translation')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_update_cat_translation'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
732
733
                    $this->db->where('alias', $id);
734
                    $this->db->where('lang', $lang);
735
                    $this->db->update('category_translate', $data);
736
                }
737
738
                $this->cache->delete_all();
739
                showMessage(lang('Category translation updated', 'admin'));
740
741
                $active = $this->input->post('action');
742
743
                if ($active == 'close') {
744
                    pjax('/admin/categories/translate/' . $id . '/' . $lang);
745
                } else {
746
                    pjax('/admin/categories/edit/' . $id);
747
                }
748
            }
749
750
            exit;
751
        }
752
753
        if ($cat !== FALSE) {
754
            // Get translated category
755
            $this->db->where('alias', $id);
756
            $this->db->where('lang', $lang);
757
            $query = $this->db->get('category_translate');
758
759
            // Get langs
760
            $langs = $this->cms_base->get_langs();
761
            $this->template->assign('langs', $langs);
762
763
            if ($query->num_rows() > 0) {
764
                $this->template->add_array(
765
                    [
766
                     'cat' => $query->row_array(),
767
                    ]
768
                );
769
            }
770
771
            $this->template->add_array(
772
                [
773
                 'orig_cat' => $cat,
774
                 'lang'     => $lang,
775
                ]
776
            );
777
778
            ($hook = get_hook('admin_show_cat_translate')) ? eval($hook) : NULL;
0 ignored issues
show
Unused Code introduced by
The call to get_hook() has too many arguments starting with 'admin_show_cat_translate'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
779
780
            $this->template->show('cat_translate_edit', FALSE);
781
        } else {
782
            return FALSE;
783
        }
784
    }
785
786
    /**
787
     * Refresh categories in sidebar
788
     */
789
    public function update_block() {
790
        $this->template->assign('tree', $this->lib_category->build());
791
        $this->template->show('cats_sidebar', FALSE);
792
    }
793
794
    /**
795
     * @param string $sel_id
796
     */
797
    public function update_fast_block($sel_id) {
798
        $this->template->add_array(
799
            [
800
             'tree'    => $this->lib_category->build(),
801
             'sel_cat' => $sel_id,
802
            ]
803
        );
804
805
        echo lang('Category', 'admin') . ' <select name="category" ONCHANGE="change_comments_status();" id="category_selectbox">
806
                <option value="0">' . lang('No', 'admin') . '</option>';
807
808
        $this->template->show('cats_select', FALSE);
809
810
        echo '</select>';
811
    }
812
813
    /**
814
     * Crete url with at least one symbol
815
     * @param $str
0 ignored issues
show
introduced by
Missing parameter type
Loading history...
816
     * @return string
817
     */
818
    private function createUrl($str) {
819
        $this->load->helper('translit');
820
        is_numeric($str) && $str = 'p' . $str;
821
        return translit_url($str);
822
    }
823
824
}
825
826
/* End of categories.php */