Completed
Push — development ( eb9524...db4517 )
by Andrij
28:49 queued 02:09
created

Permitions::scanControllers()   C

Complexity

Conditions 10
Paths 96

Size

Total Lines 50
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 50
rs 5.7647
cc 10
eloc 38
nc 96
nop 2

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
if (!defined('BASEPATH')) {
4
    exit('No direct script access allowed');
5
}
6
7
class Permitions
8
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
9
10
    private static $shop_controllers_path;  //define shop admin controllers path
11
12
    private static $base_controllers_path;       //define base admin controllers path
13
14
    private static $modules_controllers_path = '/application/modules/';          //define modules path
15
16
    private static $rbac_roles_table = 'shop_rbac_roles';                       //define rbac roles table name
17
18
    private static $rbac_privileges_table = 'shop_rbac_privileges';             //define privileges table name
19
20
    private static $rbac_group_table = 'shop_rbac_group';                       //define group table
21
22
    private static $rbac_roles_privileges_table = 'shop_rbac_roles_privileges'; //define roles privileges table
23
24
    private static $controller_types = ['shop', 'base', 'module'];         //define controllers types
25
26
    private static $installed_modules = [];         //define installed modules
27
28
    public function __construct() {
29
        $ci = &get_instance();
30
        $ci->load->library('DX_Auth');
31
        self::$shop_controllers_path = getModulePath('shop') . 'admin/';
32
        self::$base_controllers_path = getModulePath('admin');
33
    }
34
35
    /**
36
     * runs in BaseAdminController and ShopAdminController __construct()
37
     */
38
    public static function checkPermitions() {
39
        self::checkUrl();
40
        self::checkModuleInstall();
41
    }
42
43
    /**
44
     * Check module install by requested url
45
     */
46
    private static function checkModuleInstall() {
47
        $for_check = CI::$APP->uri->segment(2);
48
49
        if ($for_check == 'components') {
50
            if (in_array(CI::$APP->uri->segment(3), ['init_window', 'run', 'cp'])) {
51
                $module = CI::$APP->uri->segment(4);
52
            }
53
        }
54
55
        if ($module) {
56
            self::getInstalledMudules();
57
            if (!self::$installed_modules[$module]) {
58
                redirect('admin/rbac/not_installed_module_error');
59
            }
60
        }
61
    }
62
63
    /**
64
     * Get installed modules array
65
     * @return array
66
     */
67
    private static function getInstalledMudules() {
68
        if (!self::$installed_modules) {
69
            $modules = CI::$APP->db->select('id, name')->get('components')->result_array();
70
            foreach ($modules as $key => $module) {
71
                $modules[$module['name']] = $module;
72
                unset($modules[$key]);
73
            }
74
            self::$installed_modules = $modules;
75
        }
76
        return self::$installed_modules;
77
    }
78
79
    /**
80
     *
81
     * @param string $adminClassName
82
     * @param string $adminMethod
83
     * @return boolean|null
84
     */
85
    private static function checkAllPermitions($adminClassName, $adminMethod) {
86
        $ci = &get_instance();
87
88
        //check if user is loged in
89
        if ($ci->dx_auth->is_logged_in()) {
90
            //creating string for search in rbac privileges table
91
            $privilege = $adminClassName . '::' . $adminMethod;
92
93
            //searching privilege
94
            $privilege = $ci->db->where('name', $privilege)->get(self::$rbac_privileges_table)->row();
95
96
            //searching user by id to get his role id
97
            $userProfile = $ci->db->where('id', $ci->dx_auth->get_user_id())->get('users')->row();
98
99
            //if user exists!
100
            if (!empty($userProfile)) {
101
                //get user role
102
                $userRole = $ci->db->where('id', $userProfile->role_id)->get(self::$rbac_roles_table)->row();
103
            }
104
105
            //if privilege found
106
            if (!empty($privilege)) {
107
                //check if role exists
108
                if (!empty($userRole)) {
109
                    //check if user has needed privilege
110
                    $userPrivilege = $ci->db->where(['role_id' => (int) $userRole->id, 'privilege_id' => (int) $privilege->id])->get(self::$rbac_roles_privileges_table)->result();
111
                    if (!empty($userPrivilege)) {
112
                        //yes, current user has needed privilege
113
                        return TRUE;
114
                    } else {
115
                        //no, permission denied
116
                        redirect('admin/rbac/permition_denied');
117
                    }
118
                }
119
            } else {
120
                //if privilege not found in base check if user is admin
121
                if ($userRole->name != 'Administrator' AND $adminMethod != 'permition_denied') {
122
                    redirect('admin/rbac/permition_denied');
123
                }
124
            }
125
        } else {
126
            //user always has access to admin/login page
127
            if ($adminClassName != 'Login') {
128
                $loginUrl = '/admin/login';
129
                if ($ci->input->is_ajax_request()) {
130
                    ajax_redirect($loginUrl);
131
                    exit;
132
                } else {
133
                    $_SESSION['redirect_after_login'] = $ci->uri->uri_string;
134
                    redirect($loginUrl);
135
                }
136
            }
137
        }
138
    }
139
140
    /**
141
     * parsing url to get needed parameters
142
     * @param string|bool $checkLink
143
     * @param string $link
144
     * @return array with class name and class method
0 ignored issues
show
Documentation introduced by
Should the return type not be array|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...
145
     */
146
    private static function checkUrl($checkLink = FALSE, $link = '') {
147
        $ci = &get_instance();
148
149
        if ($checkLink AND $link != '') {
150
            $uri_array = explode('/', $link);
151
            $for_check = $uri_array[1];
152
        } else {
153
            $for_check = $ci->uri->segment(2);
154
        }
155
156
        if ($for_check == 'components') {
157
            if (in_array($ci->uri->segment(3), ['init_window', 'run', 'cp']) OR in_array($uri_array[2], ['init_window', 'run', 'cp'])) {
158
                $classNamePrep = 'Admin';
159
                $controller_segment = 4;
160
                $controller_method = 5;
161
            } else {
162
                $controller_segment = 2;
163
                $controller_method = 3;
164
                $classNamePrep = 'Base';
165
            }
166
            if ($ci->uri->segment(4) == 'shop' OR $uri_array[3] == 'shop') {
167
                $classNamePrep = 'ShopAdmin';
168
                $controller_segment = 5;
169
                $controller_method = 6;
170
            }
171
        } else {
172
            $controller_segment = 2;
173
            $controller_method = 3;
174
            $classNamePrep = 'Base';
175
        }
176
177
        if ($checkLink AND $link != '') {
178
            $adminController = $uri_array[$controller_segment - 1];
179
        } else {
180
            $adminController = $ci->uri->segment($controller_segment);
181
        }
182
183
        switch ($classNamePrep) {
184
            case 'ShopAdmin':
185
                $adminClassName = 'ShopAdmin' . ucfirst($adminController);
186
                $adminClassFile = self::$shop_controllers_path . $adminController . '.php';
0 ignored issues
show
Unused Code introduced by
$adminClassFile 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...
187
                break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
188
            case 'Admin':
189
                $adminClassName = $adminController;
190
                $adminClassFile = self::$modules_controllers_path . $adminController . '/admin.php';
0 ignored issues
show
Unused Code introduced by
$adminClassFile 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...
191
                break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
192
            case 'Base':
193
                $adminClassName = ucfirst($adminController);
194
                $adminClassFile = self::$base_controllers_path . $adminController . '.php';
0 ignored issues
show
Unused Code introduced by
$adminClassFile 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...
195
                break;
196
        }
197
        if ($checkLink AND $link != '') {
198
            $adminMethod = $uri_array[$controller_method - 1];
199
        } else {
200
            $adminMethod = $ci->uri->segment($controller_method);
201
        }
202
203
        if (!$adminMethod) {
204
            $adminMethod = 'index';
205
        }
206
207
        if ($checkLink AND $link != '') {
208
            return ['adminClassName' => $adminClassName, 'adminMethod' => $adminMethod];
209
        } else {
210
            self::checkAllPermitions($adminClassName, $adminMethod);
211
        }
212
    }
213
214
    /**
215
     * scans all admin controllers
216
     */
217
    private static function processRbacPrivileges() {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
218
        $ci = &get_instance();
219
        $controllerFolders = self::$controller_types;
220
        foreach ($controllerFolders as $folder) {
221
            if ($folder == 'base') {
222
                $adminControllersDir = self::$base_controllers_path;
223
            }
224
            if ($folder == 'shop') {
225
                $adminControllersDir = self::$shop_controllers_path;
226
            }
227
            if ($folder == 'module') {
228
                $adminControllersDir = self::$modules_controllers_path;
229
                $ci->load->helper('directory');
230
                $controllers = directory_map($adminControllersDir, true);
231
                foreach ($controllers as $c) {
232
                    if (file_exists($adminControllersDir . $c . '/admin.php') AND !in_array($c, ['shop', 'admin'])) {
233
                        $result[] = $adminControllersDir . $c . '/admin.php';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = 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...
234
                    }
235
                }
236
                $controllers = $result;
237
            }
238
            $fileExtension = EXT;
239
240
            if ($handle = opendir($adminControllersDir)) {
241
                //list of the admin controllers
242
                if (!$controllers) {
243
                    $controllers = glob($adminControllersDir . "*$fileExtension");
244
                }
245
                foreach ($controllers as $controller) {
246
247
                    self::scanControllers($controller, $folder);
248
                }
249
                $controllers = false;
250
                closedir($handle);
251
            }
252
        }
253
        showMessage('Успех');
254
    }
255
256
    /**
257
     * scans needed controller for public methods and write them into privileges table
258
     * @param string $controller
259
     * @param string $folder
260
     */
261
    private static function scanControllers($controller, $folder) {
262
        $locale = MY_Controller::getCurrentLocale();
263
        $ci = &get_instance();
264
        $fileExtension = EXT;
265
        if ($folder == 'module') {
266
            $arr = explode('/', $controller);
267
            $text = file_get_contents($controller);
268
            $text = str_replace('class Admin', 'class ' . $arr[2], $text);
269
            write_file(str_replace('admin.php', $arr[2] . 'temp' . $fileExtension, $controller), $text);
270
            $controller = str_replace('admin.php', $arr[2] . 'temp' . $fileExtension, $controller);
271
        }
272
273
        include_once $controller;
274
        $controllerName = str_replace('temp', '', basename($controller, $fileExtension));
275
        switch ($folder) {
276
            case 'base':
277
                $controllerClassName = ucfirst($controllerName);
278
                break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
279
            case 'module':
280
                $controllerClassName = $arr[2];
281
                break;
0 ignored issues
show
Coding Style introduced by
Case breaking statements must be followed by a single blank line
Loading history...
282
            case 'shop':
283
                $controllerClassName = 'ShopAdmin' . ucfirst($controllerName);
284
                break;
285
        }
286
287
        $class = new ReflectionClass($controllerClassName);
288
289
        $controllerMethods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
290
291
        foreach ($controllerMethods as $controllerMethod) {
292
            if ($controllerMethod->class == $controllerClassName) {
293
                $privilegeName = $controllerMethod->class . '::' . $controllerMethod->name;
294
                $dbPrivilege = $ci->db->where('name', $privilegeName)->get(self::$rbac_privileges_table)->row();
295
                $group = $ci->db->where('name', ucfirst($controllerClassName))->get(self::$rbac_group_table)->row();
296
                if (empty($group)) {
297
                    $ci->db->insert(self::$rbac_group_table, ['name' => ucfirst($controllerClassName), 'type' => $folder]);
298
                    $ci->db->insert(self::$rbac_group_table . '_i18n', ['id' => $ci->db->insert_id(), 'description' => '', 'locale' => $locale]);
299
                    $group = $ci->db->where('name', ucfirst($controllerClassName))->get(self::$rbac_group_table)->row();
300
                }
301
                if (empty($dbPrivilege)) {
302
                    $ci->db->insert(self::$rbac_privileges_table, ['name' => $privilegeName, 'group_id' => $group->id]);
303
                    $ci->db->insert(self::$rbac_privileges_table . '_i18n', ['id' => $ci->db->insert_id(), 'title' => '', 'description' => '', 'locale' => $locale]);
304
                }
305
            }
306
        }
307
        if ($folder == 'module') {
308
            unlink($controller);
309
        }
310
    }
311
312
    /**
313
     * check if user with id = 1 exists and has all privileges
314
     * @return null|boolean
315
     */
316
    private static function checkSuperAdmin() {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
317
        $ci = &get_instance();
318
        $superAdmin = $ci->db->where('id', 1)->get('users')->row();
319
        if (empty($superAdmin)) {
320
            die('Супер администратор не найден');
321
        } else {
322
            $role_id = $superAdmin->role_id;
323
            $privileges = $ci->db->get(self::$rbac_privileges_table)->result();
324
            if (!empty($privileges)) {
325
                $countAllPermitions = count($privileges);
326
                $countUserPermitions = 0;
327
                foreach ($privileges as $privilege) {
328
                    if ($ci->db->where(['privilege_id' => $privilege->id, 'role_id' => $role_id])->get(self::$rbac_roles_privileges_table)->num_rows() > 0) {
329
                        $countUserPermitions++;
330
                    }
331
                }
332
                if ($countAllPermitions == $countUserPermitions) {
333
                    return true;
334
                } else {
335
                    die('Суперадмин не найден');
336
                }
337
            }
338
        }
339
    }
340
341
    /**
342
     * add all privileges to superadmin role
343
     */
344
    private static function createSuperAdmin() {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
345
        $ci = &get_instance();
346
        $superAdmin = $ci->db->where('id', 1)->get('users')->row();
347
        if (empty($superAdmin)) {
348
            die('Супер администратор не найден');
349
        } else {
350
            $role_id = $superAdmin->role_id;
351
            $privileges = $ci->db->get(self::$rbac_privileges_table)->result();
352
            if (!empty($privileges)) {
353
                foreach ($privileges as $privilege) {
354
                    if ($ci->db->where(['privilege_id' => $privilege->id, 'role_id' => $role_id])->get(self::$rbac_roles_privileges_table)->num_rows() == 0) {
355
                        $ci->db->insert(self::$rbac_roles_privileges_table, ['role_id' => $role_id, 'privilege_id' => $privilege->id]);
356
                    }
357
                }
358
            }
359
        }
360
    }
361
362
    /*     * *************  RBAC privileges groups  ************** */
363
364
    /**
365
     * create a RBAC privileges group
366
     *
367
     * @access public
368
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
369
     */
370
    public function groupCreate() {
371
372
        $this->form_validation->set_rules('Name', 'Name', 'required');
0 ignored issues
show
Bug introduced by
The property form_validation does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
373
374
        if ($this->input->post()) {
375
            if ($this->form_validation->run($this) == FALSE) {
376
                showMessage(validation_errors(), '', 'r');
377
            } else {
378
379
                $sql = 'INSERT INTO shop_rbac_group (type, name) VALUES(' . $this->db->escape($this->input->post('type')) . ',' . $this->db->escape($this->input->post('Name')) . ')';
0 ignored issues
show
Bug introduced by
The property db does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property input does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
380
                $this->db->query($sql);
381
382
                $idNewGroup = $this->db->insert_id();
383
384
                $sql = 'INSERT INTO  shop_rbac_group_i18n (id, description, locale) VALUES(' . $idNewGroup . ', ' . $this->db->escape($this->input->post('Description')) . ", '" . MY_Controller::getCurrentLocale() . "' ) ";
385
386
                $this->db->query($sql);
387
388 View Code Duplication
                if ($this->input->post('Privileges')) {
389
                    $idPrivilege = implode(',', $this->input->post('Privileges'));
390
                    $sql = 'UPDATE shop_rbac_privileges SET group_id = ' . $idNewGroup . ' WHERE id IN(' . $idPrivilege . ')';
391
                    $this->db->query($sql);
392
                }
393
394
                showMessage('Группа создана');
395
                if ($this->input->post('action') == 'tomain') {
396
                    pjax('/admin/rbac/groupEdit/' . $idNewGroup);
397
                }
398
                if ($this->input->post('action') == 'tocreate') {
399
                    pjax('/admin/rbac/groupCreate');
400
                }
401
                if ($this->input->post('action') == 'toedit') {
402
                    pjax('/admin/rbac/groupEdit/' . $idNewGroup);
403
                }
404
            }
405 View Code Duplication
        } else {
406
407
            $sqlModel = 'SELECT SRP.id, SRP.name, SRP.group_id, SRPI.title, SRPI.description
408
            FROM shop_rbac_privileges SRP
409
            INNER JOIN shop_rbac_privileges_i18n SRPI ON SRPI.id = SRP.id WHERE SRPI.locale = "' . MY_Controller::getCurrentLocale() . '"  ORDER BY SRP.name ASC';
410
            $model = $this->db->query($sqlModel);
411
412
            $this->template->add_array(
0 ignored issues
show
Bug introduced by
The property template does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
413
                [
414
                    'model' => $model,
415
                    'privileges' => $model->result(),
416
                ]
417
            );
418
419
            $this->template->show('groupCreate', FALSE);
420
        }
421
    }
422
423
    public function groupEdit($groupId) {
424
425
        $sqlModel = 'SELECT SRG.id, SRG.name, SRGI.description
426
            FROM shop_rbac_group SRG
427
            INNER JOIN shop_rbac_group_i18n SRGI ON SRGI.id = SRG.id WHERE SRG.id = "' . $groupId . '" AND SRGI.locale = "' . MY_Controller::getCurrentLocale() . '"  ORDER BY SRG.name ASC';
428
        $model = $this->db->query($sqlModel);
429
430
        if ($model === null) {
431
            $this->error404('Группа не найдена');
0 ignored issues
show
Bug introduced by
The method error404() does not seem to exist on object<Permitions>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
432
        }
433
434
        if ($this->input->post()) {
435
436
            $sql = 'UPDATE shop_rbac_group SET name = ' . $this->db->escape($this->input->post('Name')) .
437
                ' WHERE id = ' . $groupId;
438
            $this->db->query($sql);
439
440
            $sql = 'UPDATE shop_rbac_group_i18n SET description = ' . $this->db->escape($this->input->post('Description')) . ' WHERE id = ' . $groupId . " AND locale = '" . MY_Controller::getCurrentLocale() . "'";
441
            $this->db->query($sql);
442
443 View Code Duplication
            if ($this->input->post('Privileges')) {
444
                $idPrivilege = implode(',', $this->input->post('Privileges'));
445
                $sql = 'UPDATE shop_rbac_privileges SET group_id = ' . $groupId . ' WHERE id IN(' . $idPrivilege . ')';
446
                $this->db->query($sql);
447
            }
448
            showMessage('Изменения сохранены');
449
            if ($this->input->post('action') == 'tomain') {
450
                pjax('/admin/rbac/groupEdit/' . $groupId);
451
            }
452
            if ($this->input->post('action') == 'tocreate') {
453
                pjax('/admin/rbac/groupCreate');
454
            }
455
            if ($this->input->post('action') == 'toedit') {
456
                pjax('/admin/rbac/groupEdit/' . $groupId);
457
            }
458
        } else {
459
460
            $sqlPrivilege = $this->db->select(['id', 'name', 'group_id'])->get('shop_rbac_privileges')->result();
461
462
            $this->template->add_array(
463
                [
464
                    'model' => $model->row(),
465
                    'privileges' => $sqlPrivilege
466
                ]
467
            );
468
469
            $this->template->show('groupEdit', FALSE);
470
        }
471
    }
472
473
    public function groupList() {
474
475
        $sql = 'SELECT SRG.id, SRG.name, SRGI.description
476
            FROM shop_rbac_group SRG
477
            INNER JOIN shop_rbac_group_i18n SRGI ON SRGI.id = SRG.id WHERE SRGI.locale = "' . MY_Controller::getCurrentLocale() . '" ORDER BY name ASC';
478
        $query = $this->db->query($sql);
479
480
        $this->template->add_array(
481
            [
482
                'model' => $query->result()
483
            ]
484
        );
485
486
        $this->template->show('groupList', FALSE);
487
    }
488
489
    /**
490
     * delete a RBAC privileges group
491
     *
492
     * @access public
493
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
494
     */
495
    public function groupDelete() {
496
        $groupId = $this->input->post('ids');
497
498
        if ($groupId != null) {
499
            foreach ($groupId as $id) {
500
                $this->db->delete('shop_rbac_group', ['id' => $id]);
501
                $this->db->delete('shop_rbac_group_i18n', ['id' => $id]);
502
            }
503
            showMessage('Успех', 'Группа(ы) успешно удалены');
504
            pjax('/admin/rbac/groupList');
505
        }
506
    }
507
508
    /*     * *************  RBAC roles  ************** */
509
510
    /**
511
     * create a RBAC role
512
     *
513
     * @access public
514
     * @return     void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
515
     */
516
    public function roleCreate() {
517
        if ($this->input->post()) {
518
            $this->form_validation->set_rules('Name', lang('Title'), 'required');
519
            $this->form_validation->set_rules('Importance', lang('Важность'), 'numeric');
520
            if ($this->form_validation->run($this) == FALSE) {
521
                showMessage(validation_errors(), '', 'r');
522
            } else {
523
                if ($this->db->where('name', $this->input->post('Name'))->get(self::$rbac_roles_table)->num_rows() == 0) {
524
                    $sql = 'INSERT INTO shop_rbac_roles(name, importance) VALUES(' . $this->db->escape($this->input->post('Name')) . ', ' . $this->db->escape($this->input->post('Importance')) .
525
                        ')';
526
                    $this->db->query($sql);
527
                    $idCreate = $this->db->insert_id();
528
                    $languages = $this->db->get('languages')->result_array();
529
                    foreach ($languages as $lang) {
530
                        $sql = 'INSERT INTO shop_rbac_roles_i18n(id, alt_name, locale, description) VALUES(' . $idCreate . ', ' . $this->db->escape($this->input->post('Name')) .
531
                            ",  '" . $lang['identif'] . "',  "
532
                            . $this->db->escape($this->input->post('Description')) . ')';
533
                        $this->db->query($sql);
534
                    }
535
536 View Code Duplication
                    if ($this->input->post('Privileges')) {
537
                        foreach ($this->input->post('Privileges') as $idPrivilege) {
538
                            $sqlPrivilege = 'INSERT INTO shop_rbac_roles_privileges (role_id, privilege_id) VALUES(' . $idCreate . ', ' . $this->db->escape($idPrivilege) . ')';
539
                            $this->db->query($sqlPrivilege);
540
                        }
541
                    }
542
543
                    $last_role_id = $this->db->order_by('id', 'desc')->get('shop_rbac_roles')->row()->id;
544
                    $this->lib_admin->log(lang('The role is created') . '. Id: ' . $last_role_id);
0 ignored issues
show
Bug introduced by
The property lib_admin does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
545
                    showMessage(lang('Changes have been saved'));
546
                    if ($this->input->post('action') == 'new') {
547
                        pjax('/admin/rbac/roleEdit/' . $idCreate);
548
                    } else {
549
                        pjax('/admin/rbac/roleList');
550
                    }
551
                } else {
552
                    showMessage('Такое имя для роли уже занято');
553
                }
554
            }
555
        } else {
556
            //preparing array of controller types
557
            $types = $this->db->query('SELECT DISTINCT `type` FROM ' . self::$rbac_group_table)->result_array();
558
            foreach ($types as $item) {
559
                $controller_types[] = $item['type'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$controller_types was never initialized. Although not strictly required by PHP, it is generally a good practice to add $controller_types = 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...
560
            }
561
562
            //preparing groups
563
564
            $locale = MY_Controller::defaultLocale();
565
            $res = $this->db->select('id')->get_where(self::$rbac_group_table . '_i18n', ['locale' => $locale])->result_array();
566
            if (count($res) < 1) {
567
                $locale = 'en';
568
            }
569
570
            $result = self::makeRolesArray($controller_types, $locale);
571
572
            $this->template->add_array(
573
                [
574
                    'types' => $result
575
                ]
576
            );
577
578
            $this->template->show('roleCreate', FALSE);
579
        }
580
    }
581
582
    public function translateRole($id, $lang) {
583
584
        $sqlModel = 'SELECT id, alt_name, locale, description
585
            FROM  shop_rbac_roles_i18n
586
            WHERE id = "' . $id . '" AND locale = "' . $lang . '"';
587
588
        $queryModel = $this->db->query($sqlModel)->row();
589
590
        if ($this->input->post()) {
591
            if (empty($queryModel)) {
592
593
                $sql = 'INSERT INTO shop_rbac_roles_i18n(id, alt_name, locale, description) VALUES(' . $id . ', ' . $this->db->escape($this->input->post('alt_name')) .
594
                    ",  '" . $lang . "',  "
595
                    . $this->db->escape($this->input->post('Description')) . ')';
596
                $this->db->query($sql);
597
            } else {
598
                $sqlI = 'UPDATE shop_rbac_roles_i18n SET alt_name = ' . $this->db->escape($this->input->post('alt_name')) . ", locale = '" . $lang . "', description = " . $this->db->escape($this->input->post('Description')) . " WHERE id = '" . $id . "' AND locale = '" . $lang . "'";
599
                $this->db->query($sqlI);
600
            }
601
602
            showMessage(lang('Changes have been saved'));
603
            if ($this->input->post('action') == 'edit') {
604
                pjax('/admin/rbac/translateRole/' . $id . '/' . $lang);
605
            } else {
606
                pjax('/admin/rbac/roleList');
607
            }
608
        } else {
609
610
            $this->template->add_array(
611
                [
612
                    'model' => $queryModel,
613
                    'idRole' => $id,
614
                    'lang_sel' => $lang
615
                ]
616
            );
617
            $this->template->show('translateRole', FALSE);
618
        }
619
    }
620
621
    /**
622
     * edit a RBAC role
623
     *
624
     * @access    public
625
     * @param    integer $roleId
0 ignored issues
show
introduced by
Paramater tags must be grouped together in a doc commment
Loading history...
626
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
627
     */
628
    public function roleEdit($roleId) {
629
        $sqlModel = 'SELECT SRR.id, SRR.name, SRR.importance, SRRI.alt_name, SRRI.description
630
            FROM shop_rbac_roles SRR
631
            LEFT JOIN shop_rbac_roles_i18n SRRI ON SRRI.id = SRR.id  AND SRRI.locale = "' . MY_Controller::getCurrentLocale() . '" WHERE SRR.id = "' . $roleId . '" ORDER BY SRR.name ASC';
632
633
        $queryModel = $this->db->query($sqlModel);
634
        $queryModel->row();
635
636
        if ($queryModel === null) {
637
            $this->error404(lang('Role not found'));
0 ignored issues
show
Bug introduced by
The method error404() does not seem to exist on object<Permitions>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
638
        }
639
640
        if ($this->input->post()) {
641
            $this->form_validation->set_rules('alt_name', lang('Title'), 'required');
642
643
            if ($this->form_validation->run($this) == FALSE) {
644
                showMessage(validation_errors(), '', 'r');
645
            } else {
646
647
                $sql = 'UPDATE shop_rbac_roles SET importance = ' . $this->db->escape($this->input->post('Importance')) .
648
                    " WHERE id   =   '" . $roleId . "'";
649
                $this->db->query($sql);
650
651
                $sqlI = 'UPDATE `shop_rbac_roles_i18n` SET `alt_name` = ' .
652
                    $this->db->escape($this->input->post('alt_name')) . ', `description` = ' .
653
                    $this->db->escape($this->input->post('Description')) . " WHERE id = '" .
654
                    $roleId . "' AND locale = '" . MY_Controller::getCurrentLocale() . "'";
655
                $this->db->query($sqlI);
656
657
                //$this->db->where('id',$roleId)->update('shop_rbac_roles',array('name', $this->input->post('Name')));
658
659
                $privileges = $this->input->post('Privileges') ?: [];
660
661
                if (MY_Controller::isProCMS()) {
662
                    $privilegesPOSTIds = $this->filterShopPrivileges();
0 ignored issues
show
Bug introduced by
The method filterShopPrivileges() does not seem to exist on object<Permitions>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
663
                } else {
664
                    $privilegesPOSTIds = $privileges;
665
                }
666
667
                    $idForDelete = implode(', ', $privilegesPOSTIds);
668
669
                    $sqlDelete = 'DELETE FROM `shop_rbac_roles_privileges` WHERE `role_id`=' . $roleId;
670
671
                    count($privileges) > 0 && $sqlDelete .= ' AND `privilege_id` NOT IN (' . $idForDelete . ')';
672
673
                    $this->db->query($sqlDelete);
674
675
                foreach ($privilegesPOSTIds as $idPrivilege) {
676
                    if (!$this->db->where(['role_id' => $roleId, 'privilege_id' => (int) $idPrivilege])->get(self::$rbac_roles_privileges_table)->num_rows()) {
677
                        $sqlPrivilege = 'INSERT INTO shop_rbac_roles_privileges (role_id, privilege_id) VALUES(' . $this->db->escape($roleId) . ', ' . $this->db->escape($idPrivilege) . ')';
678
                        $this->db->query($sqlPrivilege);
679
                    }
680
                }
681
                $this->lib_admin->log(lang('Role was edited') . '. Id: ' . $roleId);
682
                showMessage(lang('Changes have been saved'));
683
                pjax('/admin/rbac/roleEdit/' . $roleId);
684
                if ($this->input->post('action') != 'edit') {
685
                    pjax('/admin/rbac/roleList');
686
                }
687
            }
688
        } else {
689
            //preparing array of privileges ids which belong to currenc role
690
            $sql = 'SELECT `privilege_id`
691
            FROM `shop_rbac_roles_privileges` WHERE `role_id` = ' . $roleId;
692
            $queryPrivilegeR = $this->db->query($sql)->result_array();
693
            $role_privileges = [];
694
            foreach ($queryPrivilegeR as $item) {
695
                $role_privileges[] = (int) $item['privilege_id'];
696
            }
697
698
            //preparing array of controller types
699
            $types = $this->db->query('SELECT DISTINCT `type` FROM ' . self::$rbac_group_table)->result_array();
700
            foreach ($types as $item) {
701
                $controller_types[] = $item['type'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$controller_types was never initialized. Although not strictly required by PHP, it is generally a good practice to add $controller_types = 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...
702
            }
703
704
            //preparing groups
705
706
            $locale = MY_Controller::defaultLocale();
707
            $res = $this->db->select('id')->get_where(self::$rbac_group_table . '_i18n', ['locale' => $locale])->result_array();
708
            if (count($res) < 1) {
709
                $locale = 'en';
710
            }
711
712
            $result = self::makeRolesArray($controller_types, $locale);
713
714
            $sqlLangSel = 'SELECT lang_sel FROM settings';
715
            $Lang = $this->db->query($sqlLangSel)->row();
716
            $this->template->add_array(
717
                [
718
                    'model' => $queryModel->row(),
719
                    'lang_sel' => $Lang,
720
                    'types' => $result,
721
                    'privilegeCheck' => $role_privileges
722
                ]
723
            );
724
725
            $this->template->show('roleEdit', FALSE);
726
        }
727
    }
728
729
    /**
730
     * display a list of RBAC roles
731
     *
732
     * @access public
733
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
734
     */
735
    public static function roleList() {
736
        CI::$APP->template->add_array(
737
            [
738
                'model' => self::getRoles()
739
            ]
740
        );
741
742
        CI::$APP->template->show('roleList', FALSE);
743
    }
744
745
    /**
746
     * @return mixed
747
     */
748
    public static function getRoles() {
749
        $sql = 'SELECT SRR.id, SRR.name, SRR.importance, SRRI.alt_name, SRRI.description
750
            FROM shop_rbac_roles SRR
751
            INNER JOIN shop_rbac_roles_i18n SRRI ON SRRI.id = SRR.id WHERE SRRI.locale = "' . MY_Controller::getCurrentLocale() . '" ORDER BY SRR.id ASC';
752
        return CI::$APP->db->query($sql)->result();
753
    }
754
755
    /**
756
     * delete a RBAC privileges group
757
     *
758
     * @access public
759
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
760
     */
761
    public function roleDelete() {
762
        $groupId = $this->input->post('ids');
763
764
        if ($groupId != null) {
765
            foreach ($groupId as $id) {
766
                $this->db->delete('shop_rbac_roles', ['id' => $id]);
767
                $this->db->delete('shop_rbac_roles_i18n', ['id' => $id]);
768
                $this->db->delete('shop_rbac_roles_privileges', ['role_id' => $id]);
769
            }
770
771
            $this->lib_admin->log(lang('Role was deleted') . '. Id: ' . implode(', ', $groupId));
772
773
            showMessage(lang('Role(s) successfully deleted'));
774
            //            showMessage('Роль(и) успешно удалена(ы)');
775
            pjax('/admin/rbac/roleList');
776
        }
777
    }
778
779
    /*     * *************  RBAC privileges  ************** */
780
781
    /**
782
     * create a RBAC privilege
783
     *
784
     * @access public
785
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
786
     */
787
    public function privilegeCreate() {
788
789
        if ($this->input->post()) {
790
791
            $this->form_validation->set_rules('Name', 'Name', 'required');
792
793
            if ($this->form_validation->run($this) == FALSE) {
794
                showMessage(validation_errors(), '', 'r');
795
            } else {
796
797
                $sql = 'INSERT INTO shop_rbac_privileges(name, group_id) VALUES(' . $this->db->escape($this->input->post('Name')) .
798
                    ',  ' . $this->db->escape($this->input->post('GroupId')) . ')';
799
                $this->db->query($sql);
800
801
                $idNewPrivilege = $this->db->insert_id();
802
803
                $sqlI = 'INSERT INTO shop_rbac_privileges_i18n(id, title, description, locale) VALUES('
804
                    . $idNewPrivilege .
805
                    ', ' . $this->db->escape($this->input->post('Title')) .
806
                    ', ' . $this->db->escape($this->input->post('Description')) .
807
                    ", '" . MY_Controller::getCurrentLocale() . "')";
808
                $this->db->query($sqlI);
809
810
                showMessage(lang('Privilege created'));
811
812
                if ($this->input->post('action') == 'close') {
813
                    pjax('/admin/rbac/privilegeCreate');
814
                } else {
815
                    pjax('/admin/rbac/privilegeList');
816
                }
817
            }
818
        } else {
819
            $sql = 'SELECT SRG.id, SRGI.description
820
            FROM shop_rbac_group SRG
821
            INNER JOIN  shop_rbac_group_i18n SRGI ON SRGI.id = SRG.id WHERE SRGI.locale = "' . MY_Controller::getCurrentLocale() . '"';
822
            $queryRBACGroup = $this->db->query($sql)->result();
823
824
            $this->template->add_array(
825
                [
826
                    'groups' => $queryRBACGroup
827
                ]
828
            );
829
830
            $this->template->show('privilegeCreate', FALSE);
831
        }
832
    }
833
834
    /**
835
     * edit a RBAC privilege
836
     *
837
     * @param integer $privilegeId
838
     * @access public
839
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
840
     */
841
    public function privilegeEdit($privilegeId) {
842
        //        $queryRBACPrivilege = $this->db->get_where('shop_rbac_privileges', array('id' => $privilegeId))->row();
843
844
        $sqlPr = 'SELECT SRP.id, SRP.name, SRP.group_id, SRPI.title, SRPI.description
845
            FROM shop_rbac_privileges SRP
846
            INNER JOIN   shop_rbac_privileges_i18n SRPI ON SRPI.id = SRP.id WHERE SRPI.locale = "' . MY_Controller::getCurrentLocale() . '" AND SRP.id = ' . $privilegeId;
847
        $queryRBACPrivilege = $this->db->query($sqlPr)->row();
848
849
        if ($queryRBACPrivilege === null AND FALSE) {
850
            $this->error404(lang('The privilege is not found'));
0 ignored issues
show
Bug introduced by
The method error404() does not seem to exist on object<Permitions>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
851
        }
852
853
        if ($this->input->post()) {
854
855
            $sql = 'UPDATE shop_rbac_privileges SET name = ' . $this->db->escape($this->input->post('Name')) . ',  description  =  ' . $this->db->escape($this->input->post('Description')) . ', group_id = ' . $this->db->escape($this->input->post('GroupId')) .
856
                ' WHERE id = ' . $privilegeId;
857
            $this->db->query($sql);
858
859
            showMessage(lang('Changes have been saved'));
860
861
            if ($this->input->post('action') == 'close') {
862
                pjax('/admin/rbac/privilegeEdit/' . $privilegeId);
863
            } else {
864
                pjax('/admin/rbac/privilegeList');
865
            }
866 View Code Duplication
        } else {
867
            $sql = 'SELECT SRG.id, SRGI.description
868
            FROM shop_rbac_group SRG
869
            INNER JOIN  shop_rbac_group_i18n SRGI ON SRGI.id = SRG.id WHERE SRGI.locale = "' . MY_Controller::getCurrentLocale() . '"';
870
            $queryRBACGroup = $this->db->query($sql)->result();
871
872
            $this->template->add_array(
873
                [
874
                    'model' => $queryRBACPrivilege,
875
                    'groups' => $queryRBACGroup
876
                ]
877
            );
878
879
            $this->template->show('privilegeEdit', FALSE);
880
        }
881
    }
882
883
    /**
884
     * display a list of RBAC privileges
885
     *
886
     * @access public
887
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
888
     */
889
    public function privilegeList() {
890
891
        $sql = 'SELECT SRG.id, SRG.name, SRGI.description
892
            FROM shop_rbac_group SRG
893
            INNER JOIN shop_rbac_group_i18n SRGI ON SRGI.id = SRG.id WHERE SRGI.locale = "' . MY_Controller::getCurrentLocale() . '"';
894
        $queryGroups = $this->db->query($sql)->result();
895
        foreach ($queryGroups as $key => $value) {
896
            $sqlPriv = 'SELECT SRP.id, SRP.name, SRP.group_id, SRPI.title, SRPI.description
897
            FROM shop_rbac_privileges SRP
898
            INNER JOIN  shop_rbac_privileges_i18n SRPI ON SRPI.id = SRP.id WHERE SRPI.locale = "' . MY_Controller::getCurrentLocale() . '" AND SRP.group_id = ' . $value->id;
899
            $queryGroupsPrivilege = $this->db->query($sqlPriv)->result();
900
901
            $queryGroups[$key]->privileges = $queryGroupsPrivilege;
902
        }
903
904
        $queryRBACGroup = $this->db->select(['id', 'name'])->get('shop_rbac_privileges')->result();
905
906
        $this->template->add_array(
907
            [
908
                'model' => $queryRBACGroup,
909
                'groups' => $queryGroups
910
            ]
911
        );
912
913
        $this->template->show('privilegeList', FALSE);
914
    }
915
916
    /**
917
     * delete a RBAC privilege
918
     *
919
     * @access public
920
     * @return    void
0 ignored issues
show
introduced by
If there is no return value for a function, there must not be a @return tag.
Loading history...
921
     */
922
    public function privilegeDelete() {
923
        $privilegeId = $this->input->post('id');
924
        $model = ShopRbacPrivilegesQuery::create()
925
            ->findPks($privilegeId);
926
927
        if ($model != null) {
928
            $model->delete();
929
            showMessage('Успех', 'Привилегии успешно удалены');
930
            pjax('/admin/components/run/shop/rbac/privilege_list');
931
        }
932
    }
933
934
    public static function checkControlPanelAccess($role_id) {
935
        if ($role_id != null) {
936
            $ci = &get_instance();
937
            $r = $ci->db->query(
938
                'SELECT * FROM `' . self::$rbac_roles_privileges_table . '`
939
                        JOIN `' . self::$rbac_privileges_table . '` ON ' . self::$rbac_roles_privileges_table . '.privilege_id = ' . self::$rbac_privileges_table . '.id
940
                        WHERE ' . self::$rbac_roles_privileges_table . '.role_id = ' . $role_id . " AND `name` = 'Admin::__construct'"
941
            )->num_rows();
942
            if ($r > 0) {
943
                return 'admin';
944
            } else {
945
                return '';
946
            }
947
        } else {
948
            return '';
949
        }
950
    }
951
952
    public function deletePermition($id = null) {
953
        if (!$id) {
954
            return false;
955
        } else {
956
            $this->db->where('id', $id)->delete(self::$rbac_privileges_table . '_i18n');
957
            $this->db->where('id', $id)->delete(self::$rbac_privileges_table);
958
            showMessage('Привилегия удалена');
959
            pjax('/admin/rbac/roleEdit/1');
960
        }
961
    }
962
963
    public function makeRolesArray($controller_types, $locale) {
964
        /* @var $ci MY_Controller */
965
        $ci = &get_instance();
966
        foreach ($controller_types as $controller_type) {
967
            $result[$controller_type] = $ci->db->query(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = 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...
968
                'SELECT *, ' . self::$rbac_group_table . '.id as id FROM ' . self::$rbac_group_table . '
969
                    LEFT JOIN `' . self::$rbac_group_table . '_i18n` ON ' . self::$rbac_group_table . '.id=' . self::$rbac_group_table . "_i18n.id AND `locale` = '$locale'
970
                        WHERE `type`='$controller_type'"
971
            )->result_array();
972
            if (!empty($result[$controller_type])) {
973
                foreach ($result[$controller_type] as $key => $group) {
974
                    $result[$controller_type][$key]['privileges'] = $ci->db->query(
975
                        'SELECT *, ' . self::$rbac_privileges_table . '.id as id FROM ' . self::$rbac_privileges_table . '
976
                            LEFT JOIN ' . self::$rbac_privileges_table . '_i18n ON ' . self::$rbac_privileges_table . '.id=' . self::$rbac_privileges_table . "_i18n.id AND `locale` = '$locale'
977
                                WHERE `group_id`=" . (int) $group['id']
978
                    )->result_array();
979
                }
980
            }
981
        }
982
983
        //array sort
984
        foreach ($controller_types as $controller_type) {
985
            //foreach ($result[$controller_type] as $key => $value) {
986
            $controller_type_count = count($result[$controller_type]);
987
            for ($j = 0; $j < $controller_type_count; $j++) {
988
                for ($i = 0; $i < $controller_type_count - $j; $i++) {
989
                    if ($result[$controller_type][$i + 1]) {
990
                        if (count($result[$controller_type][$i + 1]['privileges']) < count($result[$controller_type][$i]['privileges'])) {
991
                            $temp = $result[$controller_type][$i];
992
                            $result[$controller_type][$i] = $result[$controller_type][$i + 1];
993
                            $result[$controller_type][$i + 1] = $temp;
994
                        }
995
                    }
996
                }
997
            }
998
        }
999
1000
        return $result;
1001
    }
1002
1003
}