Passed
Push — development ( fce7d0...df4c91 )
by Nils
04:58
created

prepareEmaiItemPath()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
c 1
b 0
f 0
nc 6
nop 3
dl 0
loc 26
rs 8.5806
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 4404 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * @file          items.queries.php
4
 * @author        Nils Laumaillé
5
 * @version       2.1.27
6
 * @copyright     (c) 2009-2017 Nils Laumaillé
7
 * @licensing     GNU GPL-3.0
8
 * @link          http://www.teampass.net
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
require_once 'SecureHandler.php';
15
session_start();
16
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] === false || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
17
    die('Hacking attempt...');
18
}
19
20
// Load config
21
if (file_exists('../includes/config/tp.config.php')) {
22
    require_once '../includes/config/tp.config.php';
23
} elseif (file_exists('./includes/config/tp.config.php')) {
24
    require_once './includes/config/tp.config.php';
25
} else {
26
    throw new Exception("Error file '/includes/config/tp.config.php' not exists", 1);
27
}
28
29
// Do checks
30
require_once $SETTINGS['cpassman_dir'].'/includes/config/include.php';
31
require_once $SETTINGS['cpassman_dir'].'/sources/checks.php';
32
if (checkUser($_SESSION['user_id'], $_SESSION['key'], 'home') === false) {
33
    // Not allowed page
34
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED;
35
    include $SETTINGS['cpassman_dir'].'/error.php';
36
    exit();
37
}
38
39
/**
40
 * Define Timezone
41
**/
42
if (isset($SETTINGS['timezone']) === true) {
43
    date_default_timezone_set($SETTINGS['timezone']);
44
} else {
45
    date_default_timezone_set('UTC');
46
}
47
48
require_once $SETTINGS['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
49
require_once $SETTINGS['cpassman_dir'].'/includes/config/settings.php';
50
header('Content-type: text/html; charset=utf-8');
51
header('Cache-Control: no-cache, must-revalidate');
52
require_once 'main.functions.php';
53
54
// Ensure Complexity levels are translated
55
if (isset($SETTINGS_EXT['pwComplexity']) === false) {
56
    $SETTINGS_EXT['pwComplexity'] = array(
57
        0=>array(0, $LANG['complex_level0']),
58
        25=>array(25, $LANG['complex_level1']),
59
        50=>array(50, $LANG['complex_level2']),
60
        60=>array(60, $LANG['complex_level3']),
61
        70=>array(70, $LANG['complex_level4']),
62
        80=>array(80, $LANG['complex_level5']),
63
        90=>array(90, $LANG['complex_level6'])
64
    );
65
}
66
67
// Connect to mysql server
68
require_once $SETTINGS['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
69
$pass = defuse_return_decrypted($pass);
70
DB::$host = $server;
71
DB::$user = $user;
72
DB::$password = $pass;
73
DB::$dbName = $database;
74
DB::$port = $port;
75
DB::$encoding = $encoding;
76
DB::$error_handler = true;
77
$link = mysqli_connect($server, $user, $pass, $database, $port);
78
$link->set_charset($encoding);
79
80
// Class loader
81
require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';
82
83
//Load Tree
84
$tree = new SplClassLoader('Tree\NestedTree', '../includes/libraries');
85
$tree->register();
86
$tree = new Tree\NestedTree\NestedTree(prefix_table("nested_tree"), 'id', 'parent_id', 'title');
87
88
// phpcrypt
89
require_once $SETTINGS['cpassman_dir'].'/includes/libraries/phpcrypt/phpCrypt.php';
90
use PHP_Crypt\PHP_Crypt as PHP_Crypt;
91
92
// Prepare POST variables
93
$post_page = filter_input(INPUT_POST, 'page', FILTER_SANITIZE_STRING);
94
$post_type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING);
95
$post_data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
96
$post_key = filter_input(INPUT_POST, 'key', FILTER_SANITIZE_STRING);
97
$post_label = filter_input(INPUT_POST, 'label', FILTER_SANITIZE_STRING);
98
$post_status = filter_input(INPUT_POST, 'status', FILTER_SANITIZE_STRING);
99
$post_cat = filter_input(INPUT_POST, 'cat', FILTER_SANITIZE_STRING);
100
$post_receipt = filter_input(INPUT_POST, 'receipt', FILTER_SANITIZE_STRING);
101
$post_item_id = filter_input(INPUT_POST, 'item_id', FILTER_SANITIZE_NUMBER_INT);
102
$post_id_tree = filter_input(INPUT_POST, 'id_tree', FILTER_SANITIZE_NUMBER_INT);
103
$post_folder_id = filter_input(INPUT_POST, 'folder_id', FILTER_SANITIZE_NUMBER_INT);
104
$post_id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
105
$post_destination = filter_input(INPUT_POST, 'destination', FILTER_SANITIZE_NUMBER_INT);
106
$post_source = filter_input(INPUT_POST, 'source', FILTER_SANITIZE_NUMBER_INT);
107
$post_user_id = filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_NUMBER_INT);
108
$post_iFolderId = filter_input(INPUT_POST, 'iFolderId', FILTER_SANITIZE_NUMBER_INT);
109
110
// Do asked action
111
if (null !== $post_type) {
112
    switch ($post_type) {
113
        /*
114
        * CASE
115
        * creating a new ITEM
116
        */
117
        case "new_item":
118
            // Check KEY and rights
119
            if ($post_key !== $_SESSION['key']) {
120
                echo prepareExchangedData(array("error" => "ERR_KEY_NOT_CORRECT"), "encode");
121
                break;
122
            }
123
124
            // decrypt and retreive data in JSON format
125
            $dataReceived = prepareExchangedData(
126
                $post_data,
127
                "decode"
128
            );
129
130
            // Prepare variables
131
            $label = filter_var(htmlspecialchars_decode($dataReceived['label']), FILTER_SANITIZE_STRING);
132
            $url = filter_var(htmlspecialchars_decode($dataReceived['url']), FILTER_SANITIZE_STRING);
133
            $pw = htmlspecialchars_decode($dataReceived['pw']);
134
            $login = filter_var(htmlspecialchars_decode($dataReceived['login']), FILTER_SANITIZE_STRING);
135
            $tags = htmlspecialchars_decode($dataReceived['tags']);
136
137
            // is author authorized to create in this folder
138
            if (count($_SESSION['list_folders_limited']) > 0) {
139
                if (!in_array($dataReceived['categorie'], array_keys($_SESSION['list_folders_limited']))
140
                    && !in_array($dataReceived['categorie'], $_SESSION['groupes_visibles'])
141
                    && !in_array($dataReceived['categorie'], $_SESSION['personal_visible_groups_list'])
142
                ) {
143
                    echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
144
                    break;
145
                }
146
            } else {
147
                if (!in_array($dataReceived['categorie'], $_SESSION['groupes_visibles'])) {
148
                    echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
149
                    break;
150
                }
151
            }
152
153
            // perform a check in case of Read-Only user creating an item in his PF
154
            if ($_SESSION['user_read_only'] === true &&
155
                in_array($dataReceived['categorie'], $_SESSION['personal_folders']) === false
156
            ) {
157
                echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
158
                break;
159
            }
160
161
162
163
164
165
            // is pwd empty?
166
            if (empty($pw) &&
167
                isset($_SESSION['user_settings']['create_item_without_password']) &&
168
                $_SESSION['user_settings']['create_item_without_password'] !== '1'
169
            ) {
170
                echo prepareExchangedData(array("error" => "ERR_PWD_EMPTY"), "encode");
171
                break;
172
            }
173
174
            // Check length
175
            if (strlen($pw) > $SETTINGS['pwd_maximum_length']) {
176
                echo prepareExchangedData(array("error" => "ERR_PWD_TOO_LONG"), "encode");
177
                break;
178
            }
179
            // check if element doesn't already exist
180
            $itemExists = 0;
181
            $newID = "";
182
            $data = DB::queryfirstrow(
183
                "SELECT * FROM ".prefix_table("items")."
184
                WHERE label = %s AND inactif = %i",
185
                $label,
186
                0
187
            );
188
            $counter = DB::count();
189
            if ($counter != 0) {
190
                $itemExists = 1;
191
            } else {
192
                $itemExists = 0;
193
            }
194
195
            // Manage case where item is personal.
196
            // In this case, duplication is allowed
197
            if (isset($SETTINGS['duplicate_item'])
198
                && $SETTINGS['duplicate_item'] === '0'
199
                && $dataReceived['salt_key_set'] === '1'
200
                && isset($dataReceived['salt_key_set'])
201
                && $dataReceived['is_pf'] === '1'
202
                && isset($dataReceived['is_pf'])
203
            ) {
204
                $itemExists = 0;
205
            }
206
207
            if ((isset($SETTINGS['duplicate_item']) && $SETTINGS['duplicate_item'] === '0' && $itemExists === 0)
208
                ||
209
                (isset($SETTINGS['duplicate_item']) && $SETTINGS['duplicate_item'] === '1')
210
            ) {
211
                // Handle case where pw is empty
212
                // if not allowed then warn user
213
                if ((isset($_SESSION['user_settings']['create_item_without_password'])
214
                    && $_SESSION['user_settings']['create_item_without_password'] !== '1'
215
                    ) ||
216
                    empty($pw) === false
217
                ) {
218
                    // encrypt PW
219
                    if ($dataReceived['salt_key_set'] === '1' &&
220
                        isset($dataReceived['salt_key_set']) &&
221
                        $dataReceived['is_pf'] === '1' &&
222
                        isset($dataReceived['is_pf'])
223
                    ) {
224
                        $passwd = cryption(
225
                            $pw,
226
                            $_SESSION['user_settings']['session_psk'],
227
                            "encrypt"
228
                        );
229
                        $restictedTo = $_SESSION['user_id'];
230
                    } else {
231
                        $passwd = cryption(
232
                            $pw,
233
                            "",
234
                            "encrypt"
235
                        );
236
                    }
237
                } else {
238
                    $passwd['string'] = '';
239
                }
240
241
                if (empty($passwd["error"]) === false) {
242
                    echo prepareExchangedData(array("error" => "ERR_ENCRYPTION", "msg" => $passwd["error"]), "encode");
243
                    break;
244
                }
245
246
                // ADD item
247
                DB::insert(
248
                    prefix_table("items"),
249
                    array(
250
                        'label' => $label,
251
                        'description' => $dataReceived['description'],
252
                        'pw' => $passwd['string'],
253
                        'pw_iv' => "",
254
                        'email' => noHTML($dataReceived['email']),
255
                        'url' => noHTML($url),
256
                        'id_tree' => $dataReceived['categorie'],
257
                        'login' => noHTML($login),
258
                        'inactif' => '0',
259
                        'restricted_to' => isset($dataReceived['restricted_to']) ? $dataReceived['restricted_to'] : '0',
260
                        'perso' => (isset($dataReceived['salt_key_set']) && $dataReceived['salt_key_set'] === '1' && isset($dataReceived['is_pf']) && $dataReceived['is_pf'] === '1') ? '1' : '0',
261
                        'anyone_can_modify' => (isset($dataReceived['anyone_can_modify']) && $dataReceived['anyone_can_modify'] === "on") ? '1' : '0',
262
                        'complexity_level' => $dataReceived['complexity_level']
263
                        )
264
                );
265
                $newID = DB::insertId();
266
                $pw = $passwd['string'];
267
268
                // update fields
269
                if (isset($SETTINGS['item_extra_fields']) && $SETTINGS['item_extra_fields'] === '1') {
270
                    foreach (explode("_|_", $dataReceived['fields']) as $field) {
271
                        $field_data = explode("~~", $field);
272
                        if (count($field_data) > 1 && empty($field_data[1]) === false) {
273
                            // should we encrypt the data
274
                            $dataTmp = DB::queryFirstRow(
275
                                "SELECT encrypted_data
276
                                FROM ".prefix_table("categories")."
277
                                WHERE id = %i",
278
                                $field_data[0]
279
                            );
280
                            if ($dataTmp['encrypted_data'] === '1') {
281
                                $encrypt = cryption(
282
                                    $field_data[1],
283
                                    "",
284
                                    "encrypt"
285
                                );
286
                                $enc_type = "defuse";
287
                            } else {
288
                                $encrypt['string'] = $field_data[1];
289
                                $enc_type = "not_set";
290
                            }
291
292
293
                            DB::insert(
294
                                prefix_table('categories_items'),
295
                                array(
296
                                    'item_id' => $newID,
297
                                    'field_id' => $field_data[0],
298
                                    'data' => $encrypt['string'],
299
                                    'data_iv' => "",
300
                                    'encryption_type' => $enc_type
301
                                )
302
                            );
303
                        }
304
                    }
305
                }
306
307
                // If automatic deletion asked
308
                if ($dataReceived['to_be_deleted'] != 0 && empty($dataReceived['to_be_deleted']) === false) {
309
                    $date_stamp = dateToStamp($dataReceived['to_be_deleted']);
310
                    DB::insert(
311
                        prefix_table('automatic_del'),
312
                        array(
313
                            'item_id' => $newID,
314
                            'del_enabled' => 1, /* Possible values: 0=deactivated;1=activated */
315
                            'del_type' => $date_stamp !== false ? 2 : 1, /* Possible values:  1=counter;2=date */
316
                            'del_value' => $date_stamp !== false ? $date_stamp : $dataReceived['to_be_deleted']
317
                            )
318
                    );
319
                }
320
321
                // Manage retriction_to_roles
322
                if (isset($dataReceived['restricted_to_roles'])) {
323
                    foreach (array_filter(explode(';', $dataReceived['restricted_to_roles'])) as $role) {
324
                        DB::insert(
325
                            prefix_table('restriction_to_roles'),
326
                            array(
327
                                'role_id' => $role,
328
                                'item_id' => $newID
329
                                )
330
                        );
331
                    }
332
                }
333
                // log
334
                logItems($newID, $label, $_SESSION['user_id'], 'at_creation', $_SESSION['login']);
335
                // Add tags
336
                $tags = explode(' ', $tags);
337
                foreach ($tags as $tag) {
338
                    if (empty($tag) === false) {
339
                        DB::insert(
340
                            prefix_table('tags'),
341
                            array(
342
                                'item_id' => $newID,
343
                                'tag' => strtolower($tag)
344
                                )
345
                        );
346
                    }
347
                }
348
                // Check if any files have been added
349
                if (empty($dataReceived['random_id_from_files']) === false) {
350
                    $rows = DB::query(
351
                        "SELECT id
352
                        FROM ".prefix_table("files")."
353
                        WHERE id_item = %s",
354
                        $dataReceived['random_id_from_files']
355
                    );
356
                    foreach ($rows as $record) {
357
                        // update item_id in files table
358
                        DB::update(
359
                            prefix_table('files'),
360
                            array(
361
                                'id_item' => $newID
362
                                ),
363
                            "id=%i",
364
                            $record['id']
365
                        );
366
                    }
367
                }
368
369
                // Announce by email?
370
                if (empty($dataReceived['diffusion']) === false) {
371
                    // get links url
372
                    if (empty($SETTINGS['email_server_url'])) {
373
                        $SETTINGS['email_server_url'] = $SETTINGS['cpassman_url'];
374
                    }
375
376
                    // Get path
377
                    $path = prepareEmaiItemPath(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $path is correct as prepareEmaiItemPath($dat...e'], $label, $SETTINGS) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
378
                        $dataReceived['categorie'],
379
                        $label,
380
                        $SETTINGS
381
                    );
382
383
                    // send email
384
                    foreach (explode(';', $dataReceived['diffusion']) as $emailAddress) {
385
                        if (empty($emailAddress) === false) {
386
                            // send it
387
                            sendEmail(
388
                                $LANG['email_subject'],
389
                                str_replace(
390
                                    array("#label", "#link"),
391
                                    array($path, $SETTINGS['email_server_url'].'/index.php?page=items&group='.$dataReceived['categorie'].'&id='.$newID.$txt['email_body3']),
392
                                    $LANG['new_item_email_body']
393
                                ),
394
                                $emailAddress,
395
                                $LANG,
396
                                $SETTINGS,
397
                                str_replace(
398
                                    array("#label", "#link"),
399
                                    array($path, $SETTINGS['email_server_url'].'/index.php?page=items&group='.$dataReceived['categorie'].'&id='.$newID.$txt['email_body3']),
400
                                    $LANG['new_item_email_body']
401
                                )
402
                            );
403
                        }
404
                    }
405
                }
406
                // Get Expiration date
407
                $expirationFlag = '';
408
                if ($SETTINGS['activate_expiration'] === '1') {
409
                    $expirationFlag = '<i class="fa fa-flag mi-green"></i>&nbsp;';
410
                }
411
                // Prepare full line
412
                $html = '<li class="item_draggable'
413
                .'" id="'.$newID.'" style="margin-left:-30px;">'
414
                .'<span style="cursor:hand;" class="grippy"><i class="fa fa-sm fa-arrows mi-grey-1"></i>&nbsp;</span>'
415
                .$expirationFlag.'<i class="fa fa-sm fa-warning mi-yellow"></i>&nbsp;'.
416
                '&nbsp;<a id="fileclass'.$newID.'" class="file" onclick="AfficherDetailsItem(\''.$newID.'\', \'0\', \'\', \'\', \'\', \'\', \'\')" ondblclick="AfficherDetailsItem(\''.$newID.'\', \'0\', \'\', \'\', \'\', true, \'\')">'.
417
                stripslashes($dataReceived['label']);
418
                if (empty($dataReceived['description']) === false && isset($SETTINGS['show_description']) && $SETTINGS['show_description'] === '1') {
419
                    $html .= '&nbsp;<font size=2px>['.strip_tags(stripslashes(substr(cleanString($dataReceived['description']), 0, 30))).']</font>';
420
                }
421
                $html .= '</a><span style="float:right;margin:2px 10px 0px 0px;">';
422
                // mini icon for collab
423
                if (isset($SETTINGS['anyone_can_modify']) && $SETTINGS['anyone_can_modify'] === '1') {
424
                    if ($dataReceived['anyone_can_modify'] === '1') {
425
                        $itemCollab = '<i class="fa fa-pencil fa-sm mi-grey-1 pointer tip" title="'.$LANG['item_menu_collab_enable'].'" ondblclick="AfficherDetailsItem(\''.$newID.'\', \'0\', \'\', \'\', \'\', true, \'\')"></i>&nbsp;&nbsp;';
426
                    }
427
                }
428
                // display quick icon shortcuts ?
429
                if (isset($SETTINGS['copy_to_clipboard_small_icons']) && $SETTINGS['copy_to_clipboard_small_icons'] === '1') {
430
                    $itemLogin = $itemPw = "";
431
432
                    if (empty($dataReceived['login']) === false) {
433
                        $itemLogin = '<span id="iconlogin_'.$newID.'" class="copy_clipboard tip" title="'.$LANG['item_menu_copy_login'].'"><i class="fa fa-sm fa-user mi-black"></i>&nbsp;</span>';
434
                    }
435
                    if (empty($dataReceived['pw']) === false) {
436
                        $itemPw = '<span id="iconpw_'.$newID.'" class="copy_clipboard tip" title="'.$LANG['item_menu_copy_login'].'"><i class="fa fa-sm fa-lock mi-black"></i>&nbsp;</span>';
437
                    }
438
                    $html .= $itemLogin.'&nbsp;'.$itemPw;
439
                }
440
                // Prepare make Favorite small icon
441
                $html .= '&nbsp;<span id="quick_icon_fav_'.$newID.'" title="Manage Favorite" class="cursor">';
442
                if (in_array($newID, $_SESSION['favourites'])) {
443
                    $html .= '<i class="fa fa-sm fa-star mi-yellow" onclick="ActionOnQuickIcon('.$newID.',0)" class="tip"></i>';
444
                } else {
445
                    $html .= '<i class="fa fa-sm fa-star-o mi-black" onclick="ActionOnQuickIcon('.$newID.',1)" class="tip"></i>';
446
                }
447
448
                $html .= '</span></li>';
449
                // Build array with items
450
                $itemsIDList = array($newID, $dataReceived['pw'], $login);
451
452
                $returnValues = array(
453
                    "item_exists" => $itemExists,
454
                    "error" => "no",
455
                    "new_id" => $newID,
456
                    "new_pw" => $dataReceived['pw'],
457
                    "new_login" => $login,
458
                    "new_entry" => $html,
459
                    "array_items" => $itemsIDList,
460
                    "show_clipboard_small_icons" => (isset($SETTINGS['copy_to_clipboard_small_icons']) && $SETTINGS['copy_to_clipboard_small_icons'] === '1') ? 1 : 0
461
                    );
462
            } elseif (isset($SETTINGS['duplicate_item']) && $SETTINGS['duplicate_item'] === '0' && (int) $itemExists === 1) {
463
                // Encrypt data to return
464
                echo prepareExchangedData(array("error" => "item_exists"), "encode");
465
                break;
466
            }
467
468
            // Add item to CACHE table if new item has been created
469
            if (isset($newID) === true) {
470
                updateCacheTable("add_value", $newID);
471
            }
472
473
            // Encrypt data to return
474
            echo prepareExchangedData($returnValues, "encode");
475
            break;
476
477
        /*
478
        * CASE
479
        * update an ITEM
480
        */
481
        case "update_item":
482
            // Check KEY and rights
483
            if ($post_key !== $_SESSION['key']) {
484
                echo prepareExchangedData(array("error" => "ERR_KEY_NOT_CORRECT"), "encode");
485
                break;
486
            }
487
488
            // init
489
            $reloadPage = false;
490
            $returnValues = array();
491
            // decrypt and retreive data in JSON format
492
            $dataReceived = prepareExchangedData(
493
                $post_data,
494
                "decode"
495
            );
496
497
            if (count($dataReceived) > 0) {
498
                // Prepare variables
499
                $label = filter_var(($dataReceived['label']), FILTER_SANITIZE_STRING);
500
                $url = filter_var(htmlspecialchars_decode($dataReceived['url']), FILTER_SANITIZE_STRING);
501
                $pw = $original_pw = $sentPw = htmlspecialchars_decode($dataReceived['pw']);
502
                $login = filter_var(htmlspecialchars_decode($dataReceived['login']), FILTER_SANITIZE_STRING);
503
                $tags = htmlspecialchars_decode($dataReceived['tags']);
504
                $email = filter_var(htmlspecialchars_decode($dataReceived['email']), FILTER_SANITIZE_STRING);
505
                $post_category = filter_var(htmlspecialchars_decode($dataReceived['categorie']), FILTER_SANITIZE_NUMBER_INT);
506
507
                // perform a check in case of Read-Only user creating an item in his PF
508
                if ($_SESSION['user_read_only'] === true && (!in_array($dataReceived['categorie'], $_SESSION['personal_folders']) || $dataReceived['is_pf'] !== '1')) {
509
                    echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
510
                    break;
511
                }
512
513
                // Get all informations for this item
514
                $dataItem = DB::queryfirstrow(
515
                    "SELECT *
516
                    FROM ".prefix_table("items")." as i
517
                    INNER JOIN ".prefix_table("log_items")." as l ON (l.id_item = i.id)
518
                    WHERE i.id=%i AND l.action = %s",
519
                    $dataReceived['id'],
520
                    "at_creation"
521
                );
522
                // check that actual user can access this item
523
                $restrictionActive = true;
524
                $restrictedTo = array_filter(explode(';', $dataItem['restricted_to']));
525
                if (in_array($_SESSION['user_id'], $restrictedTo)) {
526
                    $restrictionActive = false;
527
                }
528
                if (empty($dataItem['restricted_to'])) {
529
                    $restrictionActive = false;
530
                }
531
532
                // perform a check in case of Read-Only user creating an item in his PF
533
                if ($_SESSION['user_read_only'] === true && !in_array($dataReceived['categorie'], $_SESSION['personal_folders'])) {
534
                    echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
535
                    break;
536
                }
537
538
                if ((
539
                        in_array($dataItem['id_tree'], $_SESSION['groupes_visibles'])
540
                        && ($dataItem['perso'] === '0' || ($dataItem['perso'] === '1' && $dataItem['id_user'] == $_SESSION['user_id']))
541
                        && $restrictionActive === false
542
                    )
543
                    ||
544
                    (
545
                        isset($SETTINGS['anyone_can_modify'])
546
                        && $SETTINGS['anyone_can_modify'] === '1'
547
                        && $dataItem['anyone_can_modify'] === '1'
548
                        && (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1')
549
                        && $restrictionActive === false
550
                    )
551
                    ||
552
                    (null !== $post_folder_id
553
                    && isset($_SESSION['list_restricted_folders_for_items'][$post_folder_id])
554
                    && in_array($post_id, $_SESSION['list_restricted_folders_for_items'][$post_folder_id])
555
                    && $post_restricted === '1'
556
                    && $restrictionActive === false)
557
                ) {
558
                    // Is pwd empty?
559
                    if (empty($pw) && isset($_SESSION['user_settings']['create_item_without_password']) && $_SESSION['user_settings']['create_item_without_password'] !== '1') {
560
                        echo prepareExchangedData(array("error" => "ERR_PWD_EMPTY"), "encode");
561
                        break;
562
                    }
563
564
                    // Check length
565
                    if (strlen($pw) > $SETTINGS['pwd_maximum_length']) {
566
                        echo prepareExchangedData(array("error" => "ERR_PWD_TOO_LONG"), "encode");
567
                        break;
568
                    }
569
                    // Get existing values
570
                    $data = DB::queryfirstrow(
571
                        "SELECT i.id as id, i.label as label, i.description as description, i.pw as pw, i.url as url, i.id_tree as id_tree, i.perso as perso, i.login as login,
572
                        i.inactif as inactif, i.restricted_to as restricted_to, i.anyone_can_modify as anyone_can_modify, i.email as email, i.notification as notification,
573
                        u.login as user_login, u.email as user_email
574
                        FROM ".prefix_table("items")." as i
575
                        INNER JOIN ".prefix_table("log_items")." as l ON (i.id=l.id_item)
576
                        INNER JOIN ".prefix_table("users")." as u ON (u.id=l.id_user)
577
                        WHERE i.id=%i",
578
                        $dataReceived['id']
579
                    );
580
581
                    // encrypt PW
582
                    if ((isset($_SESSION['user_settings']['create_item_without_password']) && $_SESSION['user_settings']['create_item_without_password'] !== '1') || empty($pw) === false) {
583
                        if ($dataReceived['salt_key_set'] === '1' && isset($dataReceived['salt_key_set'])
584
                            && in_array($post_category, $_SESSION['personal_folders']) === true
585
                        ) {
586
                            $sentPw = $pw;
587
                            $passwd = cryption(
588
                                $pw,
589
                                $_SESSION['user_settings']['session_psk'],
590
                                "encrypt"
591
                            );
592
                            $restictedTo = $_SESSION['user_id'];
593
                        } else {
594
                            $passwd = cryption(
595
                                $pw,
596
                                "",
597
                                "encrypt"
598
                            );
599
                        }
600
601
                        if (empty($passwd["error"]) === false) {
602
                            echo prepareExchangedData(array("error" => $passwd["error"]), "encode");
603
                            break;
604
                        }
605
                    } else {
606
                        $passwd['string'] = "";
607
                    }
608
609
                    // ---Manage tags
610
                    // deleting existing tags for this item
611
                    DB::delete($pre."tags", "item_id = %i", $dataReceived['id']);
612
613
                    // Add new tags
614
                    $return_tags = "";
615
                    $tags = explode(' ', $tags);
616
                    foreach ($tags as $tag) {
617
                        if (empty($tag) === false) {
618
                            // save in DB
619
                            DB::insert(
620
                                prefix_table('tags'),
621
                                array(
622
                                    'item_id' => $dataReceived['id'],
623
                                    'tag' => strtolower($tag)
624
                                )
625
                            );
626
                            // prepare display
627
                            if (empty($tags)) {
628
                                $return_tags = "<span class='round-grey pointer tip' title='".addslashes($LANG['list_items_with_tag'])."' onclick='searchItemsWithTags(\"".strtolower($tag)."\")'><i class='fa fa-tag fa-sm'></i>&nbsp;<span class=\"item_tag\">".strtolower($tag)."</span></span>";
629
                            } else {
630
                                $return_tags .= "&nbsp;&nbsp;<span class='round-grey pointer tip' title='".addslashes($LANG['list_items_with_tag'])."' onclick='searchItemsWithTags(\"".strtolower($tag)."\")'><i class='fa fa-tag fa-sm'></i>&nbsp;<span class=\"item_tag\">".strtolower($tag)."</span></span>";
631
                            }
632
                        }
633
                    }
634
635
                    // update item
636
                    DB::update(
637
                        prefix_table("items"),
638
                        array(
639
                            'label' => $label,
640
                            'description' => $dataReceived['description'],
641
                            'pw' => $passwd['string'],
642
                            'pw_iv' => "",
643
                            'email' => $email,
644
                            'login' => $login,
645
                            'url' => $url,
646
                            'id_tree' => (!isset($dataReceived['categorie']) || $dataReceived['categorie'] === "undefined") ? $dataItem['id_tree'] : $dataReceived['categorie'],
647
                            'restricted_to' => isset($dataReceived['restricted_to']) ? $dataReceived['restricted_to'] : '0',
648
                            'anyone_can_modify' => (isset($dataReceived['anyone_can_modify']) && $dataReceived['anyone_can_modify'] === "on") ? '1' : '0',
649
                            'complexity_level' => $dataReceived['complexity_level']
650
                            ),
651
                        "id=%i",
652
                        $dataReceived['id']
653
                    );
654
                    // update fields
655
                    if (isset($SETTINGS['item_extra_fields']) && $SETTINGS['item_extra_fields'] === '1') {
656
                        foreach (explode("_|_", $dataReceived['fields']) as $field) {
657
                            $field_data = explode("~~", $field);
658
                            if (count($field_data) > 1 && empty($field_data[1]) === false) {
659
                                $dataTmpCat = DB::queryFirstRow(
660
                                    "SELECT c.title AS title, i.data AS data, i.data_iv AS data_iv, i.encryption_type AS encryption_type, c.encrypted_data AS encrypted_data
661
                                    FROM ".prefix_table("categories_items")." AS i
662
                                    INNER JOIN ".prefix_table("categories")." AS c ON (i.field_id=c.id)
663
                                    WHERE i.field_id = %i AND i.item_id = %i",
664
                                    $field_data[0],
665
                                    $dataReceived['id']
666
                                );
667
                                // store Field text in DB
668
                                if (count($dataTmpCat['title']) === 0) {
669
                                    // get info about this custom field
670
                                    $dataTmpCat = DB::queryFirstRow(
671
                                        "SELECT title, encrypted_data
672
                                        FROM ".prefix_table("categories")."
673
                                        WHERE id = %i",
674
                                        $field_data[0]
675
                                    );
676
677
                                    // should we encrypt the data
678
                                    if ($dataTmpCat['encrypted_data'] === '1') {
679
                                        $encrypt = cryption(
680
                                            $field_data[1],
681
                                            "",
682
                                            "encrypt"
683
                                        );
684
                                        $enc_type = "defuse";
685
                                    } else {
686
                                        $encrypt['string'] = $field_data[1];
687
                                        $enc_type = "not_set";
688
                                    }
689
690
                                    // store field text
691
                                    DB::insert(
692
                                        prefix_table('categories_items'),
693
                                        array(
694
                                            'item_id' => $dataReceived['id'],
695
                                            'field_id' => $field_data[0],
696
                                            'data' => $encrypt['string'],
697
                                            'data_iv' => "",
698
                                            'encryption_type' => $enc_type
699
                                        )
700
                                    );
701
702
                                    // update LOG
703
                                    logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_field : '.$dataTmpCat['title'].' : '.$field_data[1]);
704
                                } else {
705
                                    // compare the old and new value
706
                                    if ($dataTmpCat['encryption_type'] === "defuse") {
707
                                        $oldVal = cryption(
708
                                            $dataTmpCat['data'],
709
                                            "",
710
                                            "decrypt"
711
                                        );
712
                                    } else {
713
                                        $oldVal['string'] = $dataTmpCat['data'];
714
                                    }
715
716
                                    if ($field_data[1] !== $oldVal['string']) {
717
                                        // should we encrypt the data
718
                                        if ($dataTmpCat['encrypted_data'] === '1') {
719
                                            $encrypt = cryption(
720
                                                $field_data[1],
721
                                                "",
722
                                                "encrypt"
723
                                            );
724
                                            $enc_type = "defuse";
725
                                        } else {
726
                                            $encrypt['string'] = $field_data[1];
727
                                            $enc_type = "not_set";
728
                                        }
729
730
                                        // update value
731
                                        DB::update(
732
                                            prefix_table('categories_items'),
733
                                            array(
734
                                                'data' => $encrypt['string'],
735
                                                'data_iv' => "",
736
                                                'encryption_type' => $enc_type
737
                                            ),
738
                                            "item_id = %i AND field_id = %i",
739
                                            $dataReceived['id'],
740
                                            $field_data[0]
741
                                        );
742
743
                                        // update LOG
744
                                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_field : '.$dataTmpCat['title'].' => '.$oldVal['string']);
745
                                    }
746
                                }
747
                            } else {
748
                                if (empty($field_data[1])) {
749
                                    DB::delete(
750
                                        $pre."categories_items",
751
                                        "item_id = %i AND field_id = %s",
752
                                        $dataReceived['id'],
753
                                        $field_data[0]
754
                                    );
755
                                }
756
                            }
757
                        }
758
                    }
759
760
                    // Update automatic deletion - Only by the creator of the Item
761
                    if (isset($SETTINGS['enable_delete_after_consultation']) && $SETTINGS['enable_delete_after_consultation'] === '1') {
762
                        // check if elem exists in Table. If not add it or update it.
763
                        DB::query("SELECT * FROM ".prefix_table("automatic_del")." WHERE item_id = %i", $dataReceived['id']);
764
                        if (DB::count() === 0) {
765
                            // No automatic deletion for this item
766
                            if (empty($dataReceived['to_be_deleted']) === false || ($dataReceived['to_be_deleted'] > 0 && is_numeric($dataReceived['to_be_deleted']))) {
767
                                // Automatic deletion to be added
768
                                DB::insert(
769
                                    prefix_table('automatic_del'),
770
                                    array(
771
                                        'item_id' => $dataReceived['id'],
772
                                        'del_enabled' => 1,
773
                                        'del_type' => is_numeric($dataReceived['to_be_deleted']) ? 1 : 2,
774
                                        'del_value' => is_numeric($dataReceived['to_be_deleted']) ? $dataReceived['to_be_deleted'] : dateToStamp($dataReceived['to_be_deleted'])
775
                                        )
776
                                );
777
                                // update LOG
778
                                logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_automatic_del : '.$dataReceived['to_be_deleted']);
779
                            }
780
                        } else {
781
                            // Automatic deletion exists for this item
782
                            if (empty($dataReceived['to_be_deleted']) === false || ($dataReceived['to_be_deleted'] > 0 && is_numeric($dataReceived['to_be_deleted']))) {
783
                                // Update automatic deletion
784
                                DB::update(
785
                                    $pre."automatic_del",
786
                                    array(
787
                                        'del_type' => is_numeric($dataReceived['to_be_deleted']) ? 1 : 2,
788
                                        'del_value' => is_numeric($dataReceived['to_be_deleted']) ? $dataReceived['to_be_deleted'] : dateToStamp($dataReceived['to_be_deleted'])
789
                                        ),
790
                                    "item_id = %i",
791
                                    $dataReceived['id']
792
                                );
793
                            } else {
794
                                // delete automatic deleteion for this item
795
                                DB::delete($pre."automatic_del", "item_id = %i", $dataReceived['id']);
796
                            }
797
                            // update LOG
798
                            logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_automatic_del : '.$dataReceived['to_be_deleted']);
799
                        }
800
                    }
801
802
                    // get readable list of restriction
803
                    $listOfRestricted = $oldRestrictionList = "";
804
                    if (empty($dataReceived['restricted_to']) === false && $SETTINGS['restricted_to'] === '1') {
805
                        foreach (explode(';', $dataReceived['restricted_to']) as $userRest) {
806
                            if (empty($userRest) === false) {
807
                                $dataTmp = DB::queryfirstrow("SELECT login FROM ".prefix_table("users")." WHERE id= %i", $userRest);
808
                                if (empty($listOfRestricted)) {
809
                                    $listOfRestricted = $dataTmp['login'];
810
                                } else {
811
                                    $listOfRestricted .= ";".$dataTmp['login'];
812
                                }
813
                            }
814
                        }
815
                    }
816
                    if ($data['restricted_to'] != $dataReceived['restricted_to'] && $SETTINGS['restricted_to'] === '1') {
817
                        if (empty($data['restricted_to']) === false) {
818
                            foreach (explode(';', $data['restricted_to']) as $userRest) {
819
                                if (empty($userRest) === false) {
820
                                    $dataTmp = DB::queryfirstrow("SELECT login FROM ".prefix_table("users")." WHERE id= ".$userRest);
821
                                    if (empty($oldRestrictionList)) {
822
                                        $oldRestrictionList = $dataTmp['login'];
823
                                    } else {
824
                                        $oldRestrictionList .= ";".$dataTmp['login'];
825
                                    }
826
                                }
827
                            }
828
                        }
829
                    }
830
                    // Manage retriction_to_roles
831
                    if (isset($dataReceived['restricted_to_roles']) && $SETTINGS['restricted_to_roles'] === '1') {
832
                        // get values before deleting them
833
                        $rows = DB::query(
834
                            "SELECT t.title
835
                            FROM ".prefix_table("roles_title")." as t
836
                            INNER JOIN ".prefix_table("restriction_to_roles")." as r ON (t.id=r.role_id)
837
                            WHERE r.item_id = %i
838
                            ORDER BY t.title ASC",
839
                            $dataReceived['id']
840
                        );
841
                        foreach ($rows as $record) {
842
                            if (empty($oldRestrictionList)) {
843
                                $oldRestrictionList = $record['title'];
844
                            } else {
845
                                $oldRestrictionList .= ";".$record['title'];
846
                            }
847
                        }
848
                        // delete previous values
849
                        DB::delete(prefix_table("restriction_to_roles"), "item_id = %i", $dataReceived['id']);
850
                        // add roles for item
851
                        foreach (array_filter(explode(';', $dataReceived['restricted_to_roles'])) as $role) {
852
                            $role = explode("role_", $role);
853
                            if (count($role) > 1) {
854
                                $role = $role[1];
855
                            } else {
856
                                $role = $role[0];
857
                            }
858
                            DB::insert(
859
                                prefix_table('restriction_to_roles'),
860
                                array(
861
                                    'role_id' => $role,
862
                                    'item_id' => $dataReceived['id']
863
                                    )
864
                            );
865
                            $dataTmp = DB::queryfirstrow("SELECT title FROM ".prefix_table("roles_title")." WHERE id= ".$role);
866
                            if (empty($listOfRestricted)) {
867
                                $listOfRestricted = $dataTmp['title'];
868
                            } else {
869
                                $listOfRestricted .= ";".$dataTmp['title'];
870
                            }
871
                        }
872
                    }
873
                    // Update CACHE table
874
                    updateCacheTable("update_value", $dataReceived['id']);
875
                    // Log all modifications done
876
                    /*LABEL */
877
                    if ($data['label'] != $label) {
878
                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_label : '.$data['label'].' => '.$label);
879
                    }
880
                    /*LOGIN */
881
                    if ($data['login'] != $login) {
882
                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_login : '.$data['login'].' => '.$login);
883
                    }
884
                    /*EMAIL */
885
                    if ($data['email'] != $dataReceived['email']) {
886
                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_email : '.$data['email'].' => '.$dataReceived['email']);
887
                    }
888
                    /*URL */
889
                    if ($data['url'] != $url && $url != "http://") {
890
                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_url : '.$data['url'].' => '.$url);
891
                    }
892
                    /*DESCRIPTION */
893
                    if ($data['description'] != $dataReceived['description']) {
894
                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_description');
895
                    }
896
                    /*FOLDER */
897
                    if ($data['id_tree'] != $dataReceived['categorie']) {
898
                        // Get name of folders
899
                        $dataTmp = DB::query("SELECT title FROM ".prefix_table("nested_tree")." WHERE id IN %li", array($data['id_tree'],$dataReceived['categorie']));
900
901
                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_category : '.$dataTmp[0]['title'].' => '.$dataTmp[1]['title']);
902
                        // ask for page reloading
903
                        $reloadPage = true;
904
                    }
905
                    /*PASSWORD */
906
                    if ($dataReceived['salt_key_set'] === '1' && isset($dataReceived['salt_key_set']) && $dataReceived['is_pf'] === '1' && isset($dataReceived['is_pf'])) {
907
                        $oldPw = $data['pw'];
908
                        $oldPwClear = cryption(
909
                            $oldPw,
910
                            $_SESSION['user_settings']['session_psk'],
911
                            "decrypt"
912
                        );
913
                    } else {
914
                        $oldPw = $data['pw'];
915
                        $oldPwClear = cryption(
916
                            $oldPw,
917
                            "",
918
                            "decrypt"
919
                        );
920
                    }
921
                    if ($sentPw != $oldPwClear['string']) {
922
                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_pw :'.$oldPw, "", "defuse");
923
                    }
924
                    /*RESTRICTIONS */
925
                    if ($data['restricted_to'] != $dataReceived['restricted_to']) {
926
                        logItems($dataReceived['id'], $label, $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_restriction : '.$oldRestrictionList.' => '.$listOfRestricted);
927
                    }
928
                    // Reload new values
929
                    $dataItem = DB::queryfirstrow(
930
                        "SELECT *
931
                        FROM ".prefix_table("items")." as i
932
                        INNER JOIN ".prefix_table("log_items")." as l ON (l.id_item = i.id)
933
                        WHERE i.id = %i AND l.action = %s",
934
                        $dataReceived['id'],
935
                        "at_creation"
936
                    );
937
                    // Reload History
938
                    $history = "";
939
                    $rows = DB::query(
940
                        "SELECT l.date as date, l.action as action, l.raison as raison, u.login as login
941
                        FROM ".prefix_table("log_items")." as l
942
                        LEFT JOIN ".prefix_table("users")." as u ON (l.id_user=u.id)
943
                        WHERE l.action <> %s AND id_item=%s",
944
                        "at_shown",
945
                        $dataReceived['id']
946
                    );
947
                    foreach ($rows as $record) {
948
                        $reason = explode(':', $record['raison']);
949
                        if (empty($history)) {
950
                            $history = date($SETTINGS['date_format']." ".$SETTINGS['time_format'], $record['date'])." - ".$record['login']." - ".$LANG[$record['action']].
951
                            " - ".(empty($record['raison']) === false ? (count($reason) > 1 ? $LANG[trim($reason[0])].' : '.$reason[1] : $LANG[trim($reason[0])]) : '');
952
                        } else {
953
                            $history .= "<br />".date($SETTINGS['date_format']." ".$SETTINGS['time_format'], $record['date'])." - ".
954
                            $record['login']." - ".$LANG[$record['action']]." - ".
955
                            (empty($record['raison']) === false ? (count($reason) > 1 ? $LANG[trim($reason[0])].' => '.$reason[1] : ($record['action'] != "at_manual" ? $LANG[trim($reason[0])] : trim($reason[0]))) : '');
956
                        }
957
                    }
958
                    // decrypt PW
959
                    if (empty($dataReceived['salt_key'])) {
960
                        $encrypt = cryption(
961
                            $dataItem['pw'],
962
                            "",
963
                            "encrypt"
964
                        );
965
                    } else {
966
                        $encrypt = cryption(
967
                            $dataItem['pw'],
968
                            $_SESSION['user_settings']['session_psk'],
969
                            "encrypt"
970
                        );
971
                    }
972
973
                    $pw = cleanString($encrypt['string']);
974
                    // generate 2d key
975
                    $_SESSION['key_tmp'] = bin2hex(PHP_Crypt::createKey(PHP_Crypt::RAND, 16));
976
977
                    // Prepare files listing
978
                    $files = $filesEdit = "";
979
                    // launch query
980
                    $rows = DB::query("SELECT id, name, file, extension FROM ".prefix_table("files")." WHERE id_item=%i", $dataReceived['id']);
981
                    foreach ($rows as $record) {
982
                        // get icon image depending on file format
983
                        $iconImage = fileFormatImage($record['extension']);
984
985
                        // If file is an image, then prepare lightbox. If not image, then prepare donwload
986
                        if (in_array($record['extension'], $SETTINGS_EXT['image_file_ext'])) {
987
                            $files .= '<i class=\'fa fa-file-image-o\' /></i>&nbsp;<a class="image_dialog" href="#'.$record['id'].'" title="'.$record['name'].'">'.$record['name'].'</a><br />';
988
                        } else {
989
                            $files .= '<i class=\'fa fa-file-text-o\' /></i>&nbsp;<a href=\'sources/downloadFile.php?name='.urlencode($record['name']).'&type=sub&key='.$_SESSION['key'].'&key_tmp='.$_SESSION['key_tmp'].'&fileid='.$record['id'].'\' target=\'_blank\'>'.$record['name'].'</a><br />';
990
                        }
991
                        // Prepare list of files for edit dialogbox
992
                        $filesEdit .= '<span id="span_edit_file_'.$record['id'].'"><span class="fa fa-'.$iconImage.'"></span>&nbsp;<span class="fa fa-eraser tip" style="cursor:pointer;"  onclick="delete_attached_file(\"'.$record['id'].'\")" title="'.$LANG['at_delete'].'"></span>&nbsp;'.$record['name']."</span><br />";
993
                    }
994
                    // Send email
995
                    if (empty($dataReceived['diffusion']) === false) {
996
                        foreach (explode(';', $dataReceived['diffusion']) as $emailAddress) {
997
                            if (empty($emailAddress) === false) {
998
                                sendEmail(
999
                                    $LANG['email_subject_item_updated'],
1000
                                    str_replace(
1001
                                        array("#item_label#", "#item_category#", "#item_id#", "#url#"),
1002
                                        array($label, $dataReceived['categorie'], $dataReceived['id'], $SETTINGS['cpassman_url']),
1003
                                        $LANG['email_body_item_updated']
1004
                                    ),
1005
                                    $emailAddress,
1006
                                    $LANG,
1007
                                    $SETTINGS,
1008
                                    str_replace("#item_label#", $label, $LANG['email_bodyalt_item_updated'])
1009
                                );
1010
                            }
1011
                        }
1012
                    }
1013
1014
                    // send email to user that whant to be notified
1015
                    if ($dataItem['notification'] !== null && empty($dataItem['notification']) === false) {
1016
                        $users_to_be_notified = array_filter(explode(";", $dataItem['notification']));
1017
1018
                        // perform query to get emails
1019
                        $users_email = DB::QUERY(
1020
                            "SELECT id, email
1021
                            FROM ".prefix_table("users")."
1022
                            WHERE id IN %li",
1023
                            $users_to_be_notified
1024
                        );
1025
1026
                        // build emails list
1027
                        $mailing = "";
1028
                        foreach ($users_email as $record) {
1029
                            if (empty($mailing)) {
1030
                                $mailing = $record['email'];
1031
                            } else {
1032
                                $mailing = ",".$record['email'];
1033
                            }
1034
                        }
1035
1036
                        // send email
1037
                        DB::insert(
1038
                            prefix_table('emails'),
1039
                            array(
1040
                                'timestamp' => time(),
1041
                                'subject' => $LANG['email_subject_item_updated'],
1042
                                'body' =>
1043
                                    str_replace(
1044
                                        array("#item_label#", "#item_category#", "#item_id#", "#url#"),
1045
                                        array($label, $dataReceived['categorie'], $dataReceived['id'], $SETTINGS['cpassman_url']),
1046
                                        $LANG['email_body_item_updated']
1047
                                    ),
1048
                                'receivers' => $mailing,
1049
                                'status' => ''
1050
                                )
1051
                        );
1052
                    }
1053
1054
                    // Prepare some stuff to return
1055
                    $arrData = array(
1056
                        "files" => $files,
1057
                        "history" => str_replace('"', '&quot;', $history),
1058
                        "files_edit" => $filesEdit,
1059
                        "id_tree" => $dataItem['id_tree'],
1060
                        "id" => $dataItem['id'],
1061
                        "reload_page" => $reloadPage,
1062
                        "restriction_to" => $dataReceived['restricted_to'].$dataReceived['restricted_to_roles'],
1063
                        "list_of_restricted" => $listOfRestricted,
1064
                        "tags" => $return_tags,
1065
                        "error" => ""
1066
                        );
1067
                } else {
1068
                    echo prepareExchangedData(array("error" => "ERR_NOT_ALLOWED_TO_EDIT"), "encode");
1069
                    break;
1070
                }
1071
            } else {
1072
                // an error appears on JSON format
1073
                $arrData = array("error" => "ERR_JSON_FORMAT");
1074
            }
1075
            // return data
1076
            echo prepareExchangedData($arrData, "encode");
1077
            break;
1078
1079
        /*".."
1080
          * CASE
1081
          * Copy an Item
1082
        */
1083
        case "copy_item":
1084
            // Check KEY and rights
1085
            if ($post_key !== $_SESSION['key']) {
1086
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "1'.addslashes($LANG['error_not_allowed_to']).'"}]';
1087
                echo $returnValues;
1088
                break;
1089
            }
1090
1091
            // Prepare POST variables
1092
            $post_source_id = filter_input(INPUT_POST, 'source_id', FILTER_SANITIZE_NUMBER_INT);
1093
            $post_dest_id = filter_input(INPUT_POST, 'dest_id', FILTER_SANITIZE_NUMBER_INT);
1094
1095
            // perform a check in case of Read-Only user creating an item in his PF
1096
            if ($_SESSION['user_read_only'] === '1'
1097
                && (!in_array($post_source_id, $_SESSION['personal_folders'])
1098
                    || !in_array($post_dest_id, $_SESSION['personal_folders']))
1099
            ) {
1100
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
1101
                echo $returnValues;
1102
                break;
1103
            }
1104
1105
            $returnValues = $pw = "";
1106
            $is_perso = 0;
1107
1108
            if (empty($post_item_id) === false
1109
                && empty($post_dest_id) === false
1110
            ) {
1111
                // load the original record into an array
1112
                $originalRecord = DB::queryfirstrow(
1113
                    "SELECT * FROM ".prefix_table("items")."
1114
                    WHERE id=%i",
1115
                    $post_item_id
1116
                );
1117
1118
                // Check if the folder where this item is, is accessible to the user
1119
                if (in_array($originalRecord['id_tree'], $_SESSION['groupes_visibles']) === false) {
1120
                    $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
1121
                    echo $returnValues;
1122
                    break;
1123
                }
1124
1125
                // Load the destination folder record into an array
1126
                $dataDestination = DB::queryfirstrow(
1127
                    "SELECT personal_folder FROM ".prefix_table("nested_tree")."
1128
                    WHERE id=%i",
1129
                    $post_dest_id
1130
                );
1131
1132
                // previous is personal folder and public one
1133
                if ($originalRecord['perso'] === '1' && $dataDestination['personal_folder'] === '0') {
1134
                    // decrypt and re-encrypt password
1135
                    $decrypt = cryption(
1136
                        $originalRecord['pw'],
1137
                        mysqli_escape_string($link, stripslashes($_SESSION['user_settings']['session_psk'])),
1138
                        "decrypt"
1139
                    );
1140
                    $encrypt = cryption(
1141
                        $decrypt['string'],
1142
                        "",
1143
                        "encrypt"
1144
                    );
1145
1146
                    // reaffect pw
1147
                    $originalRecord['pw'] = $encrypt['string'];
1148
1149
                    // this item is now public
1150
                    $is_perso = 0;
1151
                // previous is public folder and personal one
1152
                } elseif ($originalRecord['perso'] === '0' && $dataDestination['personal_folder'] === '1') {
1153
                    // check if PSK is set
1154
                    if (!isset($_SESSION['user_settings']['session_psk']) || empty($_SESSION['user_settings']['session_psk'])) {
1155
                        $returnValues = '[{"error" : "no_psk"}, {"error_text" : "'.addslashes($LANG['alert_message_personal_sk_missing']).'"}]';
1156
                        echo $returnValues;
1157
                        break;
1158
                    }
1159
1160
                    // decrypt and re-encrypt password
1161
                    $decrypt = cryption(
1162
                        $originalRecord['pw'],
1163
                        "",
1164
                        "decrypt"
1165
                    );
1166
                    $encrypt = cryption(
1167
                        $decrypt['string'],
1168
                        mysqli_escape_string($link, stripslashes($_SESSION['user_settings']['session_psk'])),
1169
                        "encrypt"
1170
                    );
1171
1172
                    // reaffect pw
1173
                    $originalRecord['pw'] = $encrypt['string'];
1174
1175
                    // this item is now private
1176
                    $is_perso = 1;
1177
                } elseif ($originalRecord['perso'] === '1' && $dataDestination['personal_folder'] === '1') {
1178
                // previous is public folder and personal one
1179
                    // check if PSK is set
1180
                    if (!isset($_SESSION['user_settings']['session_psk']) || empty($_SESSION['user_settings']['session_psk'])) {
1181
                        $returnValues = '[{"error" : "no_psk"}, {"error_text" : "'.addslashes($LANG['alert_message_personal_sk_missing']).'"}]';
1182
                        echo $returnValues;
1183
                        break;
1184
                    }
1185
1186
                    // decrypt and re-encrypt password
1187
                    $decrypt = cryption(
1188
                        $originalRecord['pw'],
1189
                        mysqli_escape_string($link, stripslashes($_SESSION['user_settings']['session_psk'])),
1190
                        "decrypt"
1191
                    );
1192
                    $encrypt = cryption(
1193
                        $decrypt['string'],
1194
                        mysqli_escape_string($link, stripslashes($_SESSION['user_settings']['session_psk'])),
1195
                        "encrypt"
1196
                    );
1197
1198
                    // reaffect pw
1199
                    $originalRecord['pw'] = $encrypt['string'];
1200
1201
                    // this item is now private
1202
                    $is_perso = 1;
1203
                } elseif ($originalRecord['perso'] === '0' && $dataDestination['personal_folder'] === '0') {
1204
                    // decrypt and re-encrypt password
1205
                    $decrypt = cryption(
1206
                        $originalRecord['pw'],
1207
                        "",
1208
                        "decrypt"
1209
                    );
1210
                    $encrypt = cryption(
1211
                        $decrypt['string'],
1212
                        "",
1213
                        "encrypt"
1214
                    );
1215
1216
                    // reaffect pw
1217
                    $originalRecord['pw'] = $encrypt['string'];
1218
1219
                    // is public item
1220
                    $is_perso = 0;
1221
                } else {
1222
                    $returnValues = '[{"error" : "case_not_managed"}, {"error_text" : "ERROR - case is not managed"}]';
1223
                        echo $returnValues;
1224
                        break;
1225
                }
1226
1227
                // insert the new record and get the new auto_increment id
1228
                DB::insert(
1229
                    prefix_table("items"),
1230
                    array(
1231
                        'label' => "duplicate"
1232
                    )
1233
                );
1234
                $newID = DB::insertId();
1235
                // generate the query to update the new record with the previous values
1236
                $aSet = array();
1237
                foreach ($originalRecord as $key => $value) {
1238
                    if ($key === "id_tree") {
1239
                        array_push($aSet, array("id_tree" => $post_dest_id));
1240
                    } elseif ($key === "viewed_no") {
1241
                        array_push($aSet, array("viewed_no" => "0"));
1242
                    } elseif ($key === "pw" && empty($pw) === false) {
1243
                        array_push($aSet, array("pw" => $originalRecord['pw']));
1244
                        array_push($aSet, array("pw_iv" => ""));
1245
                    } elseif ($key === "perso") {
1246
                        array_push($aSet, array("perso" => $is_perso));
1247
                    } elseif ($key != "id" && $key != "key") {
1248
                        array_push($aSet, array($key => $value));
1249
                    }
1250
                }
1251
1252
                DB::update(
1253
                    prefix_table("items"),
1254
                    $aSet,
1255
                    "id = %i",
1256
                    $newID
1257
                );
1258
                // Add attached itms
1259
                $rows = DB::query("SELECT * FROM ".prefix_table("files")." WHERE id_item=%i", $post_item_id);
1260
                foreach ($rows as $record) {
1261
                    // Check if file still exists
1262
                    if (file_exists($SETTINGS['path_to_upload_folder'].DIRECTORY_SEPARATOR.$record['file'])) {
1263
                        // duplicate file
1264
                        $fileRandomId = md5($record['name'].time());
1265
                        copy(
1266
                            $SETTINGS['path_to_upload_folder'].DIRECTORY_SEPARATOR.$record['file'],
1267
                            $SETTINGS['path_to_upload_folder'].DIRECTORY_SEPARATOR.$fileRandomId
1268
                        );
1269
1270
                        // store in DB
1271
                        DB::insert(
1272
                            prefix_table('files'),
1273
                            array(
1274
                                'id_item' => $newID,
1275
                                'name' => $record['name'],
1276
                                'size' => $record['size'],
1277
                                'extension' => $record['extension'],
1278
                                'type' => $record['type'],
1279
                                'file' => $fileRandomId,
1280
                                'status' => $record['status']
1281
                            )
1282
                        );
1283
                    }
1284
                }
1285
1286
                // Add specific restrictions
1287
                $rows = DB::query("SELECT * FROM ".prefix_table("restriction_to_roles")." WHERE item_id = %i", $post_item_id);
1288
                foreach ($rows as $record) {
1289
                    DB::insert(
1290
                        prefix_table('restriction_to_roles'),
1291
                        array(
1292
                            'item_id' => $newID,
1293
                            'role_id' => $record['role_id']
1294
                            )
1295
                    );
1296
                }
1297
1298
                // Add Tags
1299
                $rows = DB::query("SELECT * FROM ".prefix_table("tags")." WHERE item_id = %i", $post_item_id);
1300
                foreach ($rows as $record) {
1301
                    DB::insert(
1302
                        prefix_table('tags'),
1303
                        array(
1304
                            'item_id' => $newID,
1305
                            'tag' => $record['tag']
1306
                            )
1307
                    );
1308
                }
1309
1310
                // Add custom fields
1311
1312
1313
                // Add this duplicate in logs
1314
                logItems($newID, $originalRecord['label'], $_SESSION['user_id'], 'at_creation', $_SESSION['login']);
1315
                // Add the fact that item has been copied in logs
1316
                logItems($newID, $originalRecord['label'], $_SESSION['user_id'], 'at_copy', $_SESSION['login']);
1317
                // reload cache table
1318
                require_once $SETTINGS['cpassman_dir'].'/sources/main.functions.php';
1319
                updateCacheTable("reload", "");
1320
1321
                $returnValues = '[{"status" : "ok"}, {"new_id" : "'.$newID.'"}]';
1322
            } else {
1323
                // no item
1324
                $returnValues = '[{"error" : "no_item"}, {"error_text" : "No item ID"}]';
1325
            }
1326
            // return data
1327
            echo $returnValues;
1328
            break;
1329
1330
        /*
1331
          * CASE
1332
          * Display informations of selected item
1333
        */
1334
        case "show_details_item":
1335
            // Check KEY and rights
1336
            $_SESSION['user_settings']['show_step2'] = false;
1337
            if ($post_key !== $_SESSION['key']) {
1338
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
1339
                echo prepareExchangedData($returnValues, "encode");
1340
                break;
1341
            }
1342
1343
            // Decrypt and retreive data in JSON format
1344
            $dataReceived = prepareExchangedData($post_data, "decode");
1345
            // Init post variables
1346
            $post_id = filter_var(htmlspecialchars_decode($dataReceived['id']), FILTER_SANITIZE_NUMBER_INT);
1347
            $post_folder_id = filter_var(htmlspecialchars_decode($dataReceived['folder_id']), FILTER_SANITIZE_NUMBER_INT);
1348
            $post_salt_key_required = filter_var(htmlspecialchars_decode($dataReceived['salt_key_required']), FILTER_SANITIZE_STRING);
1349
            $post_salt_key_set = filter_var(htmlspecialchars_decode($dataReceived['salt_key_set']), FILTER_SANITIZE_STRING);
1350
            $post_expired_item = filter_var(htmlspecialchars_decode($dataReceived['expired_item']), FILTER_SANITIZE_STRING);
1351
            $post_restricted = filter_var(htmlspecialchars_decode($dataReceived['restricted']), FILTER_SANITIZE_STRING);
1352
            $post_page = filter_var(htmlspecialchars_decode($dataReceived['page']), FILTER_SANITIZE_STRING);
1353
1354
            $arrData = array();
1355
            // return ID
1356
            $arrData['id'] = $post_id;
1357
            $arrData['id_user'] = API_USER_ID;
1358
            $arrData['author'] = "API";
1359
1360
            // Check if item is deleted
1361
            // taking into account that item can be restored.
1362
            // so if restoration timestamp is higher than the deletion one
1363
            // then we can show it
1364
            $item_deleted = DB::queryFirstRow(
1365
                "SELECT *
1366
                FROM ".prefix_table("log_items")."
1367
                WHERE id_item = %i AND action = %s
1368
                ORDER BY date DESC
1369
                LIMIT 0, 1",
1370
                $post_id,
1371
                "at_delete"
1372
            );
1373
            $dataDeleted = DB::count();
1374
1375
            $item_restored = DB::queryFirstRow(
1376
                "SELECT *
1377
                FROM ".prefix_table("log_items")."
1378
                WHERE id_item = %i AND action = %s
1379
                ORDER BY date DESC
1380
                LIMIT 0, 1",
1381
                $post_id,
1382
                "at_restored"
1383
            );
1384
1385
            if ($dataDeleted != 0 && intval($item_deleted['date']) > intval($item_restored['date'])) {
1386
                // This item is deleted => exit
1387
                echo prepareExchangedData(array('show_detail_option' => 2), "encode");
1388
                break;
1389
            }
1390
1391
            // Get all informations for this item
1392
            $dataItem = DB::queryfirstrow(
1393
                "SELECT *
1394
                FROM ".prefix_table("items")." as i
1395
                INNER JOIN ".prefix_table("log_items")." as l ON (l.id_item = i.id)
1396
                WHERE i.id = %i AND l.action = %s",
1397
                $post_id,
1398
                "at_creation"
1399
            );
1400
1401
            // LEFT JOIN ".$pre."categories_items as c ON (c.id_item = i.id)
1402
            // INNER JOIN ".$pre."automatic_del as d ON (d.item_id = i.id)
1403
            // Get all USERS infos
1404
            $listNotif = array_filter(explode(";", $dataItem['notification']));
1405
            $listRest = array_filter(explode(";", $dataItem['restricted_to']));
1406
            $listeRestriction = $listNotification = $_SESSION['listNotificationEmails'] = "";
1407
1408
            $user_in_restricted_list_of_item = false;
1409
            $rows = DB::query("SELECT id, login, email, admin FROM ".prefix_table("users"));
1410
            foreach ($rows as $record) {
1411
                // Get auhtor
1412
                if ($record['id'] === $dataItem['id_user']) {
1413
                    $arrData['author'] = $record['login'];
1414
                    $arrData['author_email'] = $record['email'];
1415
                    $arrData['id_user'] = $dataItem['id_user'];
1416
                    if (in_array($record['id'], $listNotif)) {
1417
                        $arrData['notification_status'] = true;
1418
                    } else {
1419
                        $arrData['notification_status'] = false;
1420
                    }
1421
                }
1422
1423
                // Get restriction list for users
1424
                if (in_array($record['id'], $listRest)) {
1425
                    $listeRestriction .= $record['login'].";";
1426
                    if ($_SESSION['user_id'] === $record['id']) {
1427
                        $user_in_restricted_list_of_item = true;
1428
                    }
1429
                }
1430
                // Get notification list for users
1431
                if (in_array($record['id'], $listNotif)) {
1432
                    $listNotification .= $record['login'].";";
1433
                    $_SESSION['listNotificationEmails'] .= $record['email'].",";
1434
                }
1435
1436
                // Add Admins to notification list if expected
1437
                if (isset($SETTINGS['enable_email_notification_on_item_shown']) === true && $SETTINGS['enable_email_notification_on_item_shown'] === "1"
1438
                    && $record['admin'] === "1"
1439
                ) {
1440
                    $listNotification .= $record['login'].";";
1441
                    $_SESSION['listNotificationEmails'] .= $record['email'].",";
1442
                }
1443
            }
1444
            // manage case of API user
1445
            if ($dataItem['id_user'] === API_USER_ID) {
1446
                $arrData['author'] = "API [".$dataItem['description']."]";
1447
                $arrData['id_user'] = API_USER_ID;
1448
                $arrData['author_email'] = "";
1449
                $arrData['notification_status'] = false;
1450
            }
1451
1452
            // Get all tags for this item
1453
            $tags = "";
1454
            $rows = DB::query("SELECT tag FROM ".prefix_table("tags")." WHERE item_id=%i", $post_id);
1455
            foreach ($rows as $record) {
1456
                if (empty($tags)) {
1457
                    $tags = "<span style='' class='round-grey pointer tip' title='".addslashes($LANG['list_items_with_tag'])."' onclick='searchItemsWithTags(\"".$record['tag']."\")'><i class='fa fa-tag fa-sm'></i>&nbsp;<span class=\"item_tag\">".$record['tag']."</span></span>";
1458
                } else {
1459
                    $tags .= "&nbsp;&nbsp;<span style='' class='round-grey pointer tip' title='".addslashes($LANG['list_items_with_tag'])."' onclick='searchItemsWithTags(\"".$record['tag']."\")'><i class='fa fa-tag fa-sm'></i>&nbsp;<span class=\"item_tag\">".$record['tag']."</span></span>";
1460
                }
1461
            }
1462
1463
            // TODO -> improve this check
1464
            // check that actual user can access this item
1465
            $restrictionActive = true;
1466
            $restrictedTo = array_filter(explode(';', $dataItem['restricted_to']));
1467
            if (in_array($_SESSION['user_id'], $restrictedTo)) {
1468
                $restrictionActive = false;
1469
            }
1470
            if (empty($dataItem['restricted_to'])) {
1471
                $restrictionActive = false;
1472
            }
1473
1474
1475
            // Check if user has a role that is accepted
1476
            $rows_tmp = DB::query(
1477
                "SELECT role_id
1478
                FROM ".prefix_table("restriction_to_roles")."
1479
                WHERE item_id=%i",
1480
                $post_id
1481
            );
1482
            foreach ($rows_tmp as $rec_tmp) {
1483
                if (in_array($rec_tmp['role_id'], explode(';', $_SESSION['fonction_id']))) {
1484
                    $restrictionActive = false;
1485
                }
1486
            }
1487
1488
            // Uncrypt PW
1489
            if (null !== $post_salt_key_required
1490
                && $post_salt_key_required === '1'
1491
                && null !== $post_salt_key_set
1492
                && $post_salt_key_set === '1'
1493
            ) {
1494
                $pw = cryption(
1495
                    $dataItem['pw'],
1496
                    $_SESSION['user_settings']['session_psk'],
1497
                    "decrypt"
1498
                );
1499
                $arrData['edit_item_salt_key'] = 1;
1500
            } else {
1501
                $pw = cryption(
1502
                    $dataItem['pw'],
1503
                    "",
1504
                    "decrypt"
1505
                );
1506
                $arrData['edit_item_salt_key'] = 0;
1507
            }
1508
1509
            $pw = @$pw['string'];
1510
            if (!isUTF8($pw)) {
1511
                $pw = '';
1512
            }
1513
1514
            // check if item is expired
1515
            if (null !== $post_expired_item
1516
                && $post_expired_item === '1'
1517
            ) {
1518
                $item_is_expired = true;
1519
            } else {
1520
                $item_is_expired = false;
1521
            }
1522
1523
            // check user is admin
1524
            if ($_SESSION['user_admin'] === '1' && $dataItem['perso'] != 1 && (isset($SETTINGS_EXT['admin_full_right']) && $SETTINGS_EXT['admin_full_right'] === true) || !isset($SETTINGS_EXT['admin_full_right'])) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: {currentAssign}, Probably Intended Meaning: {alternativeAssign}
Loading history...
1525
                $arrData['show_details'] = 0;
1526
            // Check if actual USER can see this ITEM
1527
            } elseif ((
1528
                (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1') && ($dataItem['perso'] === '0' || ($dataItem['perso'] === '1' && in_array($dataItem['id_tree'], $_SESSION['personal_folders']) === true)) && $restrictionActive === false)
1529
                ||
1530
                (isset($SETTINGS['anyone_can_modify']) && $SETTINGS['anyone_can_modify'] === '1' && $dataItem['anyone_can_modify'] === '1' && (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1') && $restrictionActive === false)
1531
                ||
1532
                (null !== $post_folder_id
1533
                    && isset($_SESSION['list_restricted_folders_for_items'][$post_folder_id])
1534
                    && in_array($post_id, $_SESSION['list_restricted_folders_for_items'][$post_folder_id])
1535
                    && $post_restricted === '1'
1536
                    && $user_in_restricted_list_of_item === true)
1537
                ||
1538
                (isset($SETTINGS['restricted_to_roles']) && $SETTINGS['restricted_to_roles'] === '1'
1539
                    && $restrictionActive === false
1540
                )
1541
            ) {
1542
                // Allow show details
1543
                $arrData['show_details'] = 1;
1544
                // Display menu icon for deleting if user is allowed
1545
                if ($dataItem['id_user'] == $_SESSION['user_id']
1546
                    || $_SESSION['is_admin'] === '1'
1547
                    || ($_SESSION['user_manager'] === '1' && $SETTINGS['manager_edit'] === '1')
1548
                    || $dataItem['anyone_can_modify'] === '1'
1549
                    || in_array($dataItem['id_tree'], $_SESSION['list_folders_editable_by_role'])
1550
                    || in_array($_SESSION['user_id'], $restrictedTo)
1551
                    || count($restrictedTo) === 0
1552
                ) {
1553
                    $arrData['user_can_modify'] = 1;
1554
                    $user_is_allowed_to_modify = true;
1555
                } else {
1556
                    $arrData['user_can_modify'] = 0;
1557
                    $user_is_allowed_to_modify = false;
1558
                }
1559
1560
                // Get restriction list for roles
1561
                $listRestrictionRoles = array();
1562
                if (isset($SETTINGS['restricted_to_roles']) && $SETTINGS['restricted_to_roles'] === '1') {
1563
                    // Add restriction if item is restricted to roles
1564
                    $rows = DB::query(
1565
                        "SELECT t.title
1566
                        FROM ".prefix_table("roles")."_title as t
1567
                        INNER JOIN ".prefix_table("restriction_to_roles")." as r ON (t.id=r.role_id)
1568
                        WHERE r.item_id = %i
1569
                        ORDER BY t.title ASC",
1570
                        $post_id
1571
                    );
1572
                    foreach ($rows as $record) {
1573
                        if (!in_array($record['title'], $listRestrictionRoles)) {
1574
                            array_push($listRestrictionRoles, $record['title']);
1575
                        }
1576
                    }
1577
                }
1578
                // Check if any KB is linked to this item
1579
                if (isset($SETTINGS['enable_kb']) && $SETTINGS['enable_kb'] === '1') {
1580
                    $tmp = "";
1581
                    $rows = DB::query(
1582
                        "SELECT k.label, k.id
1583
                        FROM ".prefix_table("kb_items")." as i
1584
                        INNER JOIN ".prefix_table("kb")." as k ON (i.kb_id=k.id)
1585
                        WHERE i.item_id = %i
1586
                        ORDER BY k.label ASC",
1587
                        $post_id
1588
                    );
1589
                    foreach ($rows as $record) {
1590
                        if (empty($tmp)) {
1591
                            $tmp = "<a class='round-grey' href='".$SETTINGS['cpassman_url']."/index.php?page=kb&id=".$record['id']."'><i class='fa fa-map-pin fa-sm'></i>&nbsp;".$record['label']."</a>";
1592
                        } else {
1593
                            $tmp .= "&nbsp;<a class='round-grey' href='".$SETTINGS['cpassman_url']."/index.php?page=kb&id=".$record['id']."'><i class='fa fa-map-pin fa-sm'></i>&nbsp;".$record['label']."</a>";
1594
                        }
1595
                    }
1596
                    $arrData['links_to_kbs'] = $tmp;
1597
                }
1598
                // Prepare DIalogBox data
1599
                if ($item_is_expired === false) {
1600
                    $arrData['show_detail_option'] = 0;
1601
                } elseif ($user_is_allowed_to_modify === true && $item_is_expired === true) {
1602
                    $arrData['show_detail_option'] = 1;
1603
                } else {
1604
                    $arrData['show_detail_option'] = 2;
1605
                }
1606
1607
                $arrData['label'] = htmlspecialchars_decode($dataItem['label'], ENT_QUOTES);
1608
                $arrData['pw'] = $pw;
1609
                $arrData['email'] = $dataItem['email'];
1610
                $arrData['url'] = htmlspecialchars_decode($dataItem['url']);
1611
                $arrData['folder'] = $dataItem['id_tree'];
1612
                if (empty($dataItem['url']) === false) {
1613
                    $arrData['link'] = "&nbsp;<a href='".$dataItem['url']."' target='_blank'>&nbsp;<i class='fa fa-link tip' title='".$LANG['open_url_link']."'></i></a>";
1614
                }
1615
1616
                $arrData['description'] = preg_replace('/(?<!\\r)\\n+(?!\\r)/', '', strip_tags($dataItem['description'], $SETTINGS_EXT['allowedTags']));
1617
                $arrData['login'] = htmlspecialchars_decode(str_replace(array('"'), array('&quot;'), $dataItem['login']), ENT_QUOTES);
1618
                $arrData['id_restricted_to'] = $listeRestriction;
1619
                $arrData['id_restricted_to_roles'] = count($listRestrictionRoles) > 0 ? implode(";", $listRestrictionRoles).";" : "";
1620
                $arrData['tags'] = $tags;
1621
                $arrData['folder'] = $dataItem['id_tree'];
1622
1623
                if (isset($SETTINGS['enable_server_password_change'])
1624
                    && $SETTINGS['enable_server_password_change'] === '1') {
1625
                    $arrData['auto_update_pwd_frequency'] = $dataItem['auto_update_pwd_frequency'];
1626
                } else {
1627
                    $arrData['auto_update_pwd_frequency'] = "0";
1628
                }
1629
1630
                if (isset($SETTINGS['anyone_can_modify_bydefault'])
1631
                    && $SETTINGS['anyone_can_modify_bydefault'] === '1') {
1632
                    $arrData['anyone_can_modify'] = 1;
1633
                } else {
1634
                    $arrData['anyone_can_modify'] = $dataItem['anyone_can_modify'];
1635
                }
1636
1637
                // statistics
1638
                DB::update(
1639
                    prefix_table("items"),
1640
                    array(
1641
                        'viewed_no' => $dataItem['viewed_no'] + 1,
1642
                    ),
1643
                    "id = %i",
1644
                    $post_id
1645
                );
1646
                $arrData['viewed_no'] = $dataItem['viewed_no'] + 1;
1647
1648
                // get fields
1649
                $fieldsTmp = $arrCatList = "";
1650
                if (isset($SETTINGS['item_extra_fields']) && $SETTINGS['item_extra_fields'] === '1'
1651
                    && null !== $post_page && $post_page === "items"
1652
                ) {
1653
                    // get list of associated Categories
1654
                    $arrCatList = array();
1655
                    $rows_tmp = DB::query(
1656
                        "SELECT id_category
1657
                        FROM ".prefix_table("categories_folders")."
1658
                        WHERE id_folder=%i",
1659
                        $post_folder_id
1660
                    );
1661
                    if (DB::count() > 0) {
1662
                        foreach ($rows_tmp as $row) {
1663
                            array_push($arrCatList, $row['id_category']);
1664
                        }
1665
1666
                        // get fields for this Item
1667
                        $rows_tmp = DB::query(
1668
                            "SELECT i.field_id AS field_id, i.data AS data, i.data_iv AS data_iv,
1669
                            i.encryption_type AS encryption_type, c.encrypted_data, c.parent_id AS parent_id,
1670
                            c.type as field_type
1671
                            FROM ".prefix_table("categories_items")." AS i
1672
                            INNER JOIN ".prefix_table("categories")." AS c ON (i.field_id=c.id)
1673
                            WHERE i.item_id=%i AND c.parent_id IN %ls",
1674
                            $post_id,
1675
                            $arrCatList
1676
                        );
1677
                        foreach ($rows_tmp as $row) {
1678
                            // Uncrypt data
1679
                            if ($row['encryption_type'] === "defuse") {
1680
                                $fieldText = cryption(
1681
                                    $row['data'],
1682
                                    "",
1683
                                    "decrypt"
1684
                                );
1685
                                $fieldText = $fieldText['string'];
1686
                            } else {
1687
                                $fieldText = $row['data'];
1688
                            }
1689
1690
                            // build returned list of Fields text
1691
                            if (empty($fieldsTmp)) {
1692
                                $fieldsTmp = $row['field_id'].
1693
                                    "~~".str_replace('"', '&quot;', $fieldText)."~~".$row['parent_id'].
1694
                                    "~~".$row['field_type'];
1695
                            } else {
1696
                                $fieldsTmp .= "_|_".$row['field_id'].
1697
                                "~~".str_replace('"', '&quot;', $fieldText)."~~".$row['parent_id'].
1698
                                "~~".$row['field_type'];
1699
                            }
1700
                        }
1701
                    }
1702
                }
1703
                $arrData['fields'] = $fieldsTmp;
1704
                $arrData['categories'] = $arrCatList;
1705
1706
                // Manage user restriction
1707
                if (null !== $post_restricted) {
1708
                    $arrData['restricted'] = $post_restricted;
1709
                } else {
1710
                    $arrData['restricted'] = "";
1711
                }
1712
                // Decrement the number before being deleted
1713
                if (isset($SETTINGS['enable_delete_after_consultation']) && $SETTINGS['enable_delete_after_consultation'] === '1') {
1714
                    // Is the Item to be deleted?
1715
                    $dataDelete = DB::queryfirstrow("SELECT * FROM ".prefix_table("automatic_del")." WHERE item_id=%i", $post_id);
1716
                    $arrData['to_be_deleted'] = $dataDelete['del_value'];
1717
                    $arrData['to_be_deleted_type'] = $dataDelete['del_type'];
1718
1719
                    // Now delete if required
1720
                    if ($dataDelete['del_enabled'] === '1' || intval($arrData['id_user']) !== intval($_SESSION['user_id'])) {
1721
                        if ($dataDelete['del_type'] === '1' && $dataDelete['del_value'] >= 1) {
1722
                            // decrease counter
1723
                            DB::update(
1724
                                $pre."automatic_del",
1725
                                array(
1726
                                    'del_value' => $dataDelete['del_value'] - 1
1727
                                    ),
1728
                                "item_id = %i",
1729
                                $post_id
1730
                            );
1731
                            // store value
1732
                            $arrData['to_be_deleted'] = $dataDelete['del_value'] - 1;
1733
                        } elseif ($dataDelete['del_type'] === '1' && $dataDelete['del_value'] <= 1 || $dataDelete['del_type'] === '2' && $dataDelete['del_value'] < time()
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: {currentAssign}, Probably Intended Meaning: {alternativeAssign}
Loading history...
1734
                        ) {
1735
                            $arrData['show_details'] = 0;
1736
                            // delete item
1737
                            DB::delete($pre."automatic_del", "item_id = %i", $post_id);
1738
                            // make inactive object
1739
                            DB::update(
1740
                                prefix_table("items"),
1741
                                array(
1742
                                    'inactif' => '1',
1743
                                    ),
1744
                                "id = %i",
1745
                                $post_id
1746
                            );
1747
                            // log
1748
                            logItems($post_id, $dataItem['label'], $_SESSION['user_id'], 'at_delete', $_SESSION['login'], 'at_automatically_deleted');
1749
                            $arrData['to_be_deleted'] = 0;
1750
                        } elseif ($dataDelete['del_type'] === '2') {
1751
                            $arrData['to_be_deleted'] = date($SETTINGS['date_format'], $dataDelete['del_value']);
1752
                        }
1753
                    } else {
1754
                        $arrData['to_be_deleted'] = "";
1755
                    }
1756
                } else {
1757
                    $arrData['to_be_deleted'] = "not_enabled";
1758
                }
1759
1760
                $arrData['notification_list'] = "";
1761
                $arrData['notification_status'] = "";
1762
            } else {
1763
                $arrData['show_details'] = 0;
1764
                // get readable list of restriction
1765
                $listOfRestricted = "";
1766
                if (empty($dataItem['restricted_to']) === false) {
1767
                    foreach (explode(';', $dataItem['restricted_to']) as $userRest) {
1768
                        if (empty($userRest) === false) {
1769
                            $dataTmp = DB::queryfirstrow("SELECT login FROM ".prefix_table("users")." WHERE id= ".$userRest);
1770
                            if (empty($listOfRestricted)) {
1771
                                $listOfRestricted = $dataTmp['login'];
1772
                            } else {
1773
                                $listOfRestricted .= ";".$dataTmp['login'];
1774
                            }
1775
                        }
1776
                    }
1777
                }
1778
                $arrData['restricted_to'] = $listOfRestricted;
1779
            }
1780
1781
            // Set a timestamp
1782
            $arrData['timestamp'] = time();
1783
1784
            // Set temporary session variable to allow step2
1785
            $_SESSION['user_settings']['show_step2'] = true;
1786
1787
            // Encrypt data to return
1788
            echo prepareExchangedData($arrData, "encode");
1789
            break;
1790
1791
        /*
1792
           * CASE
1793
           * Display History of the selected Item
1794
        */
1795
        case "showDetailsStep2":
1796
            // Is this query expected (must be run after a step1 and not standalone)
1797
            if ($_SESSION['user_settings']['show_step2'] !== true) {
1798
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
1799
                echo prepareExchangedData($returnValues, "encode");
1800
                break;
1801
            }
1802
1803
            // Load item data
1804
            $dataItem = DB::queryFirstRow(
1805
                "SELECT i.*, n.title AS folder_title
1806
                FROM ".prefix_table("items")." AS i
1807
                INNER JOIN ".prefix_table("nested_tree")." AS n ON (i.id_tree = n.id)
1808
                WHERE i.id = %i",
1809
                $post_id
1810
            );
1811
1812
            // check that actual user can access this item
1813
            $restrictionActive = true;
1814
            $restrictedTo = array_filter(explode(';', $dataItem['restricted_to']));
1815
            if (in_array($_SESSION['user_id'], $restrictedTo)) {
1816
                $restrictionActive = false;
1817
            }
1818
            if (empty($dataItem['restricted_to'])) {
1819
                $restrictionActive = false;
1820
            }
1821
1822
            // Check if user has a role that is accepted
1823
            $rows_tmp = DB::query(
1824
                "SELECT role_id
1825
                FROM ".prefix_table("restriction_to_roles")."
1826
                WHERE item_id=%i",
1827
                $post_id
1828
            );
1829
            foreach ($rows_tmp as $rec_tmp) {
1830
                if (in_array($rec_tmp['role_id'], explode(';', $_SESSION['fonction_id']))) {
1831
                    $restrictionActive = false;
1832
                }
1833
            }
1834
1835
            // check user is admin
1836
            if ($_SESSION['user_admin'] === '1' && $dataItem['perso'] != 1 && (isset($SETTINGS_EXT['admin_full_right']) && $SETTINGS_EXT['admin_full_right'] === true) || !isset($SETTINGS_EXT['admin_full_right'])) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: {currentAssign}, Probably Intended Meaning: {alternativeAssign}
Loading history...
1837
                $arrData['show_details'] = 0;
1838
            // Check if actual USER can see this ITEM
1839
            } elseif ((
1840
                (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1') && ($dataItem['perso'] === '0' || ($dataItem['perso'] === '1' && in_array($dataItem['id_tree'], $_SESSION['personal_folders']) === true)) && $restrictionActive === false)
1841
                ||
1842
                (isset($SETTINGS['anyone_can_modify']) && $SETTINGS['anyone_can_modify'] === '1' && $dataItem['anyone_can_modify'] === '1' && (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1') && $restrictionActive === false)
1843
                ||
1844
                (null !== $post_folder_id
1845
                    && isset($_SESSION['list_restricted_folders_for_items'][$post_folder_id])
1846
                    && in_array($post_id, $_SESSION['list_restricted_folders_for_items'][$post_folder_id])
1847
                    && $post_restricted === '1'
1848
                    && $user_in_restricted_list_of_item === true)
1849
                ||
1850
                (isset($SETTINGS['restricted_to_roles']) && $SETTINGS['restricted_to_roles'] === '1'
1851
                    && $restrictionActive === false
1852
                )
1853
            ) {
1854
                // GET Audit trail
1855
                $history = "";
1856
                $historyOfPws = "";
1857
                $rows = DB::query(
1858
                    "SELECT l.date as date, l.action as action, l.raison as raison, u.login as login, l.raison_iv AS raison_iv
1859
                    FROM ".prefix_table("log_items")." as l
1860
                    LEFT JOIN ".prefix_table("users")." as u ON (l.id_user=u.id)
1861
                    WHERE id_item=%i AND action <> %s
1862
                    ORDER BY date ASC",
1863
                    $post_id,
1864
                    "at_shown"
1865
                );
1866
                foreach ($rows as $record) {
1867
                    $reason = explode(':', $record['raison']);
1868
                    if ($record['action'] === "at_modification" && $reason[0] === "at_pw ") {
1869
                        // check if item is PF
1870
                        if ($dataItem['perso'] != 1) {
1871
                            $reason[1] = cryption(
1872
                                $reason[1],
1873
                                "",
1874
                                "decrypt"
1875
                            );
1876
                        } else {
1877
                            if (isset($_SESSION['user_settings']['session_psk']) === true) {
1878
                                $reason[1] = cryption(
1879
                                    $reason[1],
1880
                                    $_SESSION['user_settings']['session_psk'],
1881
                                    "decrypt"
1882
                                );
1883
                            } else {
1884
                                $reason[1] = '';
1885
                            }
1886
                        }
1887
                        $reason[1] = @$reason[1]['string'];
1888
                        // if not UTF8 then cleanup and inform that something is wrong with encrytion/decryption
1889
                        if (!isUTF8($reason[1]) || is_array($reason[1])) {
1890
                            $reason[1] = "";
1891
                        }
1892
                    }
1893
                    // imported via API
1894
                    if (empty($record['login'])) {
1895
                        $record['login'] = $LANG['imported_via_api'];
1896
                    }
1897
1898
                    if (empty($reason[1]) === false || $record['action'] === "at_copy" || $record['action'] === "at_creation" || $record['action'] === "at_manual" || $record['action'] === "at_modification" || $record['action'] === "at_delete" || $record['action'] === "at_restored") {
1899
                        if (trim($reason[0]) === "at_pw" && empty($reason[1]) === false) {
1900
                            if (empty($historyOfPws)) {
1901
                                $historyOfPws = $LANG['previous_pw']."\n".$reason[1];
1902
                            } else {
1903
                                $historyOfPws .= "\n".$reason[1];
1904
                            }
1905
                        }
1906
                    }
1907
                }
1908
1909
                // generate 2d key
1910
                $_SESSION['key_tmp'] = bin2hex(PHP_Crypt::createKey(PHP_Crypt::RAND, 16));
1911
1912
                // Prepare files listing
1913
                $files = $filesEdit = "";
1914
                // launch query
1915
                $rows = DB::query("SELECT id, name, file, extension FROM ".prefix_table("files")." WHERE id_item=%i", $post_id);
1916
                foreach ($rows as $record) {
1917
                    // get icon image depending on file format
1918
                    $iconImage = fileFormatImage($record['extension']);
1919
1920
                    // prepare text to display
1921
                    if (strlen($record['name']) > 60 && strrpos($record['name'], ".") >= 56) {
1922
                        $filename = substr($record['name'], 0, 50)."(...)".substr($record['name'], strrpos($record['name'], "."));
1923
                    } else {
1924
                        $filename = $record['name'];
1925
                    }
1926
1927
                    // If file is an image, then prepare lightbox. If not image, then prepare donwload
1928
                    if (in_array($record['extension'], $SETTINGS_EXT['image_file_ext'])) {
1929
                        $files .= '<div class=\'small_spacing\'><i class=\'fa fa-file-image-o\' /></i>&nbsp;<a class=\'image_dialog\' href=\'#'.$record['id'].'\' title=\''.$record['name'].'\'>'.$filename.'</a></div>';
1930
                    } else {
1931
                        $files .= '<div class=\'small_spacing\'><i class=\'fa fa-file-text-o\' /></i>&nbsp;<a href=\'sources/downloadFile.php?name='.urlencode($record['name']).'&key='.$_SESSION['key'].'&key_tmp='.$_SESSION['key_tmp'].'&fileid='.$record['id'].'\' class=\'small_spacing\'>'.$filename.'</a></div>';
1932
                    }
1933
                    // Prepare list of files for edit dialogbox
1934
                    $filesEdit .= '<span id=\'span_edit_file_'.$record['id'].'\'><span class=\'fa fa-'.$iconImage.'\'></span>&nbsp;<span id=\'delete-edit-file_'.$record['id'].'\' class=\'fa fa-eraser tip file-eraser_icon\' style=\'cursor:pointer;\' onclick=\'delete_attached_file("'.$record['id'].'", "0")\' title=\''.$LANG['at_delete'].'\'></span>&nbsp;'.$filename."</span><br />";
1935
                }
1936
                // display lists
1937
                $filesEdit = str_replace('"', '&quot;', $filesEdit);
1938
                $files_id = $files;
1939
1940
                // disable add bookmark if alread bookmarked
1941
                if (in_array($post_id, $_SESSION['favourites'])) {
1942
                    $favourite = 1;
1943
                } else {
1944
                    $favourite = 0;
1945
                }
1946
1947
                // Add the fact that item has been viewed in logs
1948
                if (isset($SETTINGS['log_accessed']) && $SETTINGS['log_accessed'] === '1') {
1949
                    logItems($post_id, $dataItem['label'], $_SESSION['user_id'], 'at_shown', $_SESSION['login']);
1950
                }
1951
1952
                // Add this item to the latests list
1953
                if (isset($_SESSION['latest_items']) && isset($SETTINGS['max_latest_items']) && !in_array($dataItem['id'], $_SESSION['latest_items'])) {
1954
                    if (count($_SESSION['latest_items']) >= $SETTINGS['max_latest_items']) {
1955
                        array_pop($_SESSION['latest_items']); //delete last items
1956
                    }
1957
                    array_unshift($_SESSION['latest_items'], $dataItem['id']);
1958
                    // update DB
1959
                    DB::update(
1960
                        prefix_table("users"),
1961
                        array(
1962
                            'latest_items' => implode(';', $_SESSION['latest_items'])
1963
                            ),
1964
                        "id=".$_SESSION['user_id']
1965
                    );
1966
                }
1967
1968
                // send notification if enabled
1969
                if (isset($SETTINGS['enable_email_notification_on_item_shown']) === true && $SETTINGS['enable_email_notification_on_item_shown'] === '1') {
1970
                    // Get path
1971
                    $arbo = $tree->getPath($dataItem['id_tree'], true);
1972
                    $path = '';
1973
                    foreach ($arbo as $elem) {
1974
                        if (empty($path) === true) {
1975
                            $path = htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES).' ';
1976
                        } else {
1977
                            $path .= '&#8594; ' . htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES);
1978
                        }
1979
                    }
1980
                    // Build text to show user
1981
                    if (empty($path) === true) {
1982
                        $path = addslashes($dataItem['label']);
1983
                    } else {
1984
                        $path = addslashes($dataItem['label']).' ('.$path.')';
1985
                    }
1986
1987
                    // send back infos
1988
                    DB::insert(
1989
                        prefix_table('emails'),
1990
                        array(
1991
                            'timestamp' => time(),
1992
                            'subject' => $LANG['email_on_open_notification_subject'],
1993
                            'body' => str_replace(
1994
                                array('#tp_user#', '#tp_item#', '#tp_link#'),
1995
                                array(
1996
                                    addslashes($_SESSION['login']),
1997
                                    $path,
1998
                                    $SETTINGS['cpassman_url']."/index.php?page=items&group=".$dataItem['id_tree']."&id=".$dataItem['id']
1999
                                ),
2000
                                $LANG['email_on_open_notification_mail']
2001
                            ),
2002
                            'receivers' => $_SESSION['listNotificationEmails'],
2003
                            'status' => ''
2004
                        )
2005
                    );
2006
                }
2007
2008
                // has this item a change proposal
2009
                DB::query("SELECT * FROM ".$pre."items_change WHERE item_id = %i", $post_id);
2010
2011
                $_SESSION['user_settings']['show_step2'] = false;
2012
2013
                echo prepareExchangedData(
2014
                    array(
2015
                        "history" => htmlspecialchars($history, ENT_QUOTES, 'UTF-8'),
2016
                        "history_of_pwds" => htmlspecialchars($historyOfPws, ENT_QUOTES, 'UTF-8'),
2017
                        "favourite" => $favourite,
2018
                        "files_edit" => $filesEdit,
2019
                        "files_id" => $files_id,
2020
                        "has_change_proposal" => DB::count(),
2021
                        "error" => ""
2022
                    ),
2023
                    "encode"
2024
                );
2025
            }
2026
            break;
2027
2028
        /*
2029
         * CASE
2030
         * Delete an item
2031
        */
2032
        case "del_item":
2033
            // Check KEY and rights
2034
            if ($post_key !== $_SESSION['key']) {
2035
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
2036
                echo $returnValues;
2037
                break;
2038
            }
2039
2040
            // perform a check in case of Read-Only user creating an item in his PF
2041
            if ($_SESSION['user_read_only'] === true && !in_array($dataReceived['categorie'], $_SESSION['personal_folders'])) {
2042
                echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
2043
                break;
2044
            }
2045
2046
            // Check that user can access this item
2047
            $granted = accessToItemIsGranted($post_id);
2048
            if ($granted !== true) {
2049
                echo prepareExchangedData(array("error" => $granted), "encode");
2050
                break;
2051
            }
2052
2053
            // Load item data
2054
            $data = DB::queryFirstRow(
2055
                "SELECT id_tree
2056
                FROM ".prefix_table("items")."
2057
                WHERE id = %i",
2058
                $post_id
2059
            );
2060
2061
            // delete item consists in disabling it
2062
            DB::update(
2063
                prefix_table("items"),
2064
                array(
2065
                    'inactif' => '1',
2066
                    ),
2067
                "id = %i",
2068
                $post_id
2069
            );
2070
            // log
2071
            logItems($post_id, $post_label, $_SESSION['user_id'], 'at_delete', $_SESSION['login']);
2072
            // Update CACHE table
2073
            updateCacheTable("delete_value", $post_id);
2074
            break;
2075
2076
        /*
2077
        * CASE
2078
        * Update a Group
2079
        */
2080
        case "update_folder":
2081
            // Check KEY and rights
2082
            if ($post_key !== $_SESSION['key'] || $_SESSION['user_read_only'] === true) {
2083
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
2084
                echo $returnValues;
2085
                break;
2086
            }
2087
            // decrypt and retreive data in JSON format
2088
            $dataReceived = prepareExchangedData($post_data, "decode");
2089
2090
            // Prepare variables
2091
            $title = filter_var(htmlspecialchars_decode($dataReceived['title'], ENT_QUOTES), FILTER_SANITIZE_STRING);
2092
            $post_folder_id = filter_var(htmlspecialchars_decode($dataReceived['folder']), FILTER_SANITIZE_NUMBER_INT);
2093
2094
            // Check if user is allowed to access this folder
2095
            if (!in_array($post_folder_id, $_SESSION['groupes_visibles'])) {
2096
                echo '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
2097
                break;
2098
            }
2099
2100
            // Check if title doesn't contains html codes
2101
            if (preg_match_all("|<[^>]+>(.*)</[^>]+>|U", $title, $out)) {
2102
                echo '[ { "error" : "'.addslashes($LANG['error_html_codes']).'" } ]';
2103
                break;
2104
            }
2105
            // check that title is not numeric
2106
            if (is_numeric($title) === true) {
2107
                echo '[{"error" : "ERR_TITLE_ONLY_WITH_NUMBERS"}]';
2108
                break;
2109
            }
2110
2111
            // Check if duplicate folders name are allowed
2112
            $createNewFolder = true;
2113
            if (isset($SETTINGS['duplicate_folder']) && $SETTINGS['duplicate_folder'] === '0') {
2114
                $data = DB::queryFirstRow("SELECT id, title FROM ".prefix_table("nested_tree")." WHERE title = %s", $title);
2115
                if (empty($data['id']) === false && $dataReceived['folder'] != $data['id']) {
2116
                    echo '[ { "error" : "'.addslashes($LANG['error_group_exist']).'" } ]';
2117
                    break;
2118
                }
2119
            }
2120
2121
            // query on folder
2122
            $data = DB::queryfirstrow(
2123
                "SELECT parent_id, personal_folder
2124
                FROM ".prefix_table("nested_tree")."
2125
                WHERE id = %i",
2126
                $post_folder_id
2127
            );
2128
2129
            // check if complexity level is good
2130
            // if manager or admin don't care
2131
            if ($_SESSION['is_admin'] != 1 && $_SESSION['user_manager'] != 1 && $data['personal_folder'] === '0') {
2132
                $data = DB::queryfirstrow(
2133
                    "SELECT valeur
2134
                    FROM ".prefix_table("misc")."
2135
                    WHERE intitule = %i AND type = %s",
2136
                    $data['parent_id'],
2137
                    "complex"
2138
                );
2139
                if (intval($dataReceived['complexity']) < intval($data['valeur'])) {
2140
                    echo '[ { "error" : "'.addslashes($LANG['error_folder_complexity_lower_than_top_folder']." [<b>".$SETTINGS_EXT['pwComplexity'][$data['valeur']][1]).'</b>]"} ]';
2141
                    break;
2142
                }
2143
            }
2144
2145
            // update Folders table
2146
            $tmp = DB::queryFirstRow(
2147
                "SELECT title, parent_id, personal_folder FROM ".prefix_table("nested_tree")." WHERE id = %i",
2148
                $dataReceived['folder']
2149
            );
2150
            if ($tmp['parent_id'] != 0 || $tmp['title'] != $_SESSION['user_id'] || $tmp['personal_folder'] != 1) {
2151
                DB::update(
2152
                    prefix_table("nested_tree"),
2153
                    array(
2154
                        'title' => $title
2155
                        ),
2156
                    'id=%s',
2157
                    $post_folder_id
2158
                );
2159
                // update complixity value
2160
                DB::update(
2161
                    prefix_table("misc"),
2162
                    array(
2163
                        'valeur' => $dataReceived['complexity']
2164
                        ),
2165
                    'intitule = %s AND type = %s',
2166
                    $post_folder_id,
2167
                    "complex"
2168
                );
2169
                // rebuild fuild tree folder
2170
                $tree->rebuild();
2171
            }
2172
            // send data
2173
            echo '[{"error" : ""}]';
2174
            break;
2175
2176
        /*
2177
        * CASE
2178
        * Move a Group including sub-folders
2179
        */
2180
        case "move_folder":
2181
            // Check KEY and rights
2182
            if ($post_key !== $_SESSION['key'] || $_SESSION['user_read_only'] === true) {
2183
                $returnValues = '[{"error" :  "'.addslashes($LANG['error_not_allowed_to']).'"}]';
2184
                echo $returnValues;
2185
                break;
2186
            }
2187
            // decrypt and retreive data in JSON format
2188
            $dataReceived = prepareExchangedData($post_data, "decode");
2189
            $post_source_folder_id = filter_var(htmlspecialchars_decode($dataReceived['source_folder_id']), FILTER_SANITIZE_NUMBER_INT);
2190
            $post_target_folder_id = filter_var(htmlspecialchars_decode($dataReceived['target_folder_id']), FILTER_SANITIZE_NUMBER_INT);
2191
2192
            // Check that user can access this folder
2193
            if ((
2194
                  in_array($post_source_folder_id, $_SESSION['groupes_visibles']) === false ||
2195
                  in_array($post_target_folder_id, $_SESSION['groupes_visibles']) === false) &&
2196
                  (
2197
                      $post_target_folder_id === '0' &&
2198
                      isset($SETTINGS['can_create_root_folder']) === true && $SETTINGS['can_create_root_folder'] === '1'
2199
                  )
2200
            ) {
2201
                $returnValues = '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
2202
                echo $returnValues;
2203
                break;
2204
            }
2205
2206
            $tmp_source = DB::queryFirstRow(
2207
                "SELECT title, parent_id, personal_folder
2208
                FROM ".prefix_table("nested_tree")."
2209
                WHERE id = %i",
2210
                $post_source_folder_id
2211
            );
2212
2213
            $tmp_target = DB::queryFirstRow(
2214
                "SELECT title, parent_id, personal_folder
2215
                FROM ".prefix_table("nested_tree")."
2216
                WHERE id = %i",
2217
                $post_target_folder_id
2218
            );
2219
2220
            // check if target is not a child of source
2221
            if ($tree->isChildOf($post_target_folder_id, $post_source_folder_id) === true) {
2222
                $returnValues = '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
2223
                echo $returnValues;
2224
                break;
2225
            }
2226
2227
            // check if source or target folder is PF. If Yes, then cancel operation
2228
            if ($tmp_source['personal_folder'] === '1' || $tmp_target['personal_folder'] === '1') {
2229
                $returnValues = '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
2230
                echo $returnValues;
2231
                break;
2232
            }
2233
2234
            // check if source or target folder is PF. If Yes, then cancel operation
2235
            if ($tmp_source['title'] === $_SESSION['user_id'] || $tmp_target['title'] === $_SESSION['user_id']) {
2236
                $returnValues = '[{"error" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
2237
                echo $returnValues;
2238
                break;
2239
            }
2240
2241
2242
            // moving SOURCE folder
2243
            DB::update(
2244
                prefix_table("nested_tree"),
2245
                array(
2246
                    'parent_id' => $post_target_folder_id
2247
                    ),
2248
                'id=%s',
2249
                $post_source_folder_id
2250
            );
2251
            $tree->rebuild();
2252
2253
2254
            // send data
2255
            echo '[{"error" : ""}]';
2256
            break;
2257
2258
        /*
2259
        * CASE
2260
        * Store hierarchic position of Group
2261
        */
2262
        case 'save_position':
2263
            DB::update(
2264
                prefix_table("nested_tree"),
2265
                array(
2266
                    'parent_id' => $post_destination
2267
                    ),
2268
                'id = %i',
2269
                $post_source
2270
            );
2271
            $tree = new Tree\NestedTree\NestedTree(prefix_table("nested_tree"), 'id', 'parent_id', 'title');
2272
            $tree->rebuild();
2273
            break;
2274
2275
        /*
2276
        * CASE
2277
        * List items of a group
2278
        */
2279
        case 'lister_items_groupe':
2280
            // Check KEY and rights
2281
            if ($post_key !== $_SESSION['key']) {
2282
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.str_replace('"', '\"', $LANG['error_not_allowed_to']).'"}]';
2283
                echo prepareExchangedData($returnValues, "encode");
2284
                break;
2285
            }
2286
2287
            // Prepare POST variables
2288
            $post_restricted = filter_input(INPUT_POST, 'restricted', FILTER_SANITIZE_NUMBER_INT);
2289
            $post_start = filter_input(INPUT_POST, 'start', FILTER_SANITIZE_NUMBER_INT);
2290
            $post_nb_items_to_display_once = filter_input(INPUT_POST, 'nb_items_to_display_once', FILTER_SANITIZE_NUMBER_INT);
2291
2292
            $arboHtml = $html = "";
2293
            $arr_arbo = [];
2294
            $folderIsPf = false;
2295
            $showError = 0;
2296
            $itemsIDList = $rights = $returnedData = $uniqueLoadData = $html_json = array();
2297
            // Build query limits
2298
            if (empty($post_start) === true) {
2299
                $start = 0;
2300
            } else {
2301
                $start = $post_start;
2302
            }
2303
2304
            // to do only on 1st iteration
2305
            if (intval($start) === 0) {
2306
                // Prepare tree
2307
                $arbo = $tree->getPath($post_id, true);
2308
                foreach ($arbo as $elem) {
2309
                    if ($elem->title == $_SESSION['user_id'] && $elem->nlevel === '1') {
2310
                        $elem->title = $_SESSION['login'];
2311
                        $folderIsPf = true;
2312
                    }
2313
                    // Store path elements
2314
                    array_push(
2315
                        $arr_arbo,
2316
                        array(
2317
                            "id" => $elem->id,
2318
                            "title" => htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES),
2319
                            "visible" => in_array($elem->id, $_SESSION['groupes_visibles']) ? 1 : 0
2320
                        )
2321
                    );
2322
                }
2323
2324
                // store last folder accessed in cookie
2325
                setcookie(
2326
                    "jstree_select",
2327
                    $post_id,
2328
                    time() + $SETTINGS_EXT['one_day_seconds'] * $SETTINGS['personal_saltkey_cookie_duration'],
2329
                    '/'
2330
                );
2331
2332
                // check role access on this folder (get the most restrictive) (2.1.23)
2333
                $accessLevel = 2;
2334
                $arrTmp = [];
2335
                foreach (explode(';', $_SESSION['fonction_id']) as $role) {
2336
                    $access = DB::queryFirstRow(
2337
                        "SELECT type FROM ".prefix_table("roles_values")." WHERE role_id = %i AND folder_id = %i",
2338
                        $role,
2339
                        $post_id
2340
                    );
2341
                    if ($access['type'] === "R") {
2342
                        array_push($arrTmp, 1);
2343
                    } elseif ($access['type'] === "W") {
2344
                        array_push($arrTmp, 0);
2345
                    } elseif ($access['type'] === "ND") {
2346
                        array_push($arrTmp, 2);
2347
                    } else {
2348
                        array_push($arrTmp, 3);
2349
                    }
2350
                }
2351
                $accessLevel = min($arrTmp);
2352
                $uniqueLoadData['accessLevel'] = $accessLevel;
2353
2354
                // check if this folder is a PF. If yes check if saltket is set
2355
                if ((!isset($_SESSION['user_settings']['encrypted_psk']) || empty($_SESSION['user_settings']['encrypted_psk'])) && $folderIsPf === true) {
2356
                    $showError = "is_pf_but_no_saltkey";
2357
                }
2358
                $uniqueLoadData['showError'] = $showError;
2359
2360
                // check if items exist
2361
                $where = new WhereClause('and');
2362
                if (null !== $post_restricted && $post_restricted === 1 && empty($_SESSION['list_folders_limited'][$post_id]) === false) {
2363
                    $counter = count($_SESSION['list_folders_limited'][$post_id]);
2364
                    $uniqueLoadData['counter'] = $counter;
2365
                // check if this folder is visible
2366
                } elseif (!in_array(
2367
                    $post_id,
2368
                    array_merge(
2369
                        $_SESSION['groupes_visibles'],
2370
                        @array_keys($_SESSION['list_restricted_folders_for_items']),
2371
                        @array_keys($_SESSION['list_folders_limited'])
2372
                    )
2373
                )) {
2374
                    echo prepareExchangedData(
2375
                        array(
2376
                            "error" => "not_authorized",
2377
                            "arborescence" => $arr_arbo
2378
                        ),
2379
                        "encode"
2380
                    );
2381
                    break;
2382
                } else {
2383
                    DB::query("SELECT * FROM ".prefix_table("items")." WHERE inactif = %i", 0);
2384
                    $counter = DB::count();
2385
                    $uniqueLoadData['counter'] = $counter;
2386
                }
2387
2388
                // Identify if it is a personal folder
2389
                if (in_array($post_id, $_SESSION['personal_visible_groups'])) {
2390
                    $findPfGroup = 1;
2391
                } else {
2392
                    $findPfGroup = "";
2393
                }
2394
                $uniqueLoadData['findPfGroup'] = $findPfGroup;
2395
2396
2397
                // Get folder complexity
2398
                $folderComplexity = DB::queryFirstRow(
2399
                    "SELECT valeur FROM ".prefix_table("misc")." WHERE type = %s AND intitule = %i",
2400
                    "complex",
2401
                    $post_id
2402
                );
2403
                $folderComplexity = $folderComplexity['valeur'];
2404
                $uniqueLoadData['folderComplexity'] = $folderComplexity;
2405
2406
                // Has this folder some categories to be displayed?
2407
                $displayCategories = "";
2408
                if (isset($SETTINGS['item_extra_fields']) && $SETTINGS['item_extra_fields'] === '1') {
2409
                    $catRow = DB::query(
2410
                        "SELECT id_category FROM ".prefix_table("categories_folders")." WHERE id_folder = %i",
2411
                        $post_id
2412
                    );
2413
                    if (count($catRow) > 0) {
2414
                        foreach ($catRow as $cat) {
2415
                            if (empty($displayCategories)) {
2416
                                $displayCategories = $cat['id_category'];
2417
                            } else {
2418
                                $displayCategories .= ";".$cat['id_category'];
2419
                            }
2420
                        }
2421
                    }
2422
                }
2423
                $uniqueLoadData['displayCategories'] = $displayCategories;
2424
2425
                // is this folder a personal one
2426
                $folder_is_personal = in_array($post_id, $_SESSION['personal_folders']);
2427
                $uniqueLoadData['folder_is_personal'] = $folder_is_personal;
2428
2429
                //
2430
                $folder_is_in_personal = in_array($post_id, array_merge($_SESSION['personal_visible_groups'], $_SESSION['personal_folders']));
2431
                $uniqueLoadData['folder_is_in_personal'] = $folder_is_in_personal;
2432
2433
                //
2434
                if (isset($_SESSION['list_folders_editable_by_role'])) {
2435
                    $list_folders_editable_by_role = in_array($post_id, $_SESSION['list_folders_editable_by_role']);
2436
                } else {
2437
                    $list_folders_editable_by_role = "";
2438
                }
2439
                $uniqueLoadData['list_folders_editable_by_role'] = $list_folders_editable_by_role;
2440
            } else {
2441
                // get preloaded data
2442
                $uniqueLoadData = json_decode(
2443
                    filter_input(INPUT_POST, 'uniqueLoadData', FILTER_UNSAFE_RAW),
2444
                    true
2445
                );
2446
2447
                // initialize main variables
2448
                $showError = $uniqueLoadData['showError'];
2449
                $accessLevel = $uniqueLoadData['accessLevel'];
2450
                $counter = $uniqueLoadData['counter'];
2451
                $findPfGroup = $uniqueLoadData['findPfGroup'];
2452
                $counter_full = $uniqueLoadData['counter_full'];
2453
                $displayCategories = $uniqueLoadData['displayCategories'];
2454
                $folderComplexity = $uniqueLoadData['folderComplexity'];
2455
                //$arboHtml = $uniqueLoadData['arboHtml'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2456
                $folder_is_personal = $uniqueLoadData['folder_is_personal'];
2457
                $folder_is_in_personal = $uniqueLoadData['folder_is_in_personal'];
2458
                $list_folders_editable_by_role = $uniqueLoadData['list_folders_editable_by_role'];
2459
            }
2460
2461
            // prepare query WHere conditions
2462
            $where = new WhereClause('and');
2463
            if (null !== $post_restricted && $post_restricted === 1 && empty($_SESSION['list_folders_limited'][$post_id]) === false) {
2464
                $where->add('i.id IN %ls', $_SESSION['list_folders_limited'][$post_id]);
2465
            } else {
2466
                $where->add('i.id_tree=%i', $post_id);
2467
            }
2468
2469
            // build the HTML for this set of Items
2470
            if ($counter > 0 && empty($showError)) {
2471
                // init variables
2472
                $init_personal_folder = false;
2473
                $expired_item = false;
2474
                $limited_to_items = "";
2475
2476
                // List all ITEMS
2477
                if ($folderIsPf === false) {
2478
                    $where->add('i.inactif=%i', 0);
2479
                    $where->add('l.date=%l', "(SELECT date FROM ".prefix_table("log_items")." WHERE action IN ('at_creation', 'at_modification') AND id_item=i.id ORDER BY date DESC LIMIT 1)");
2480
                    if (empty($limited_to_items) === false) {
2481
                        $where->add('i.id IN %ls', explode(",", $limited_to_items));
2482
                    }
2483
2484
                    $query_limit = " LIMIT ".
2485
                        $start.",".
2486
                        $post_nb_items_to_display_once;
2487
2488
                    $rows = DB::query(
2489
                        "SELECT i.id AS id, MIN(i.restricted_to) AS restricted_to, MIN(i.perso) AS perso,
2490
                        MIN(i.label) AS label, MIN(i.description) AS description, MIN(i.pw) AS pw, MIN(i.login) AS login,
2491
                        MIN(i.anyone_can_modify) AS anyone_can_modify, l.date AS date, i.id_tree AS tree_id,
2492
                        MIN(n.renewal_period) AS renewal_period,
2493
                        MIN(l.action) AS log_action, l.id_user AS log_user
2494
                        FROM ".prefix_table("items")." AS i
2495
                        INNER JOIN ".prefix_table("nested_tree")." AS n ON (i.id_tree = n.id)
2496
                        INNER JOIN ".prefix_table("log_items")." AS l ON (i.id = l.id_item)
2497
                        WHERE %l
2498
                        GROUP BY i.id, l.date, l.id_user, l.action
2499
                        ORDER BY i.label ASC, l.date DESC".$query_limit, //
2500
                        $where
2501
                    );
2502
                } else {
2503
                    $post_nb_items_to_display_once = "max";
2504
                    $where->add('i.inactif=%i', 0);
2505
2506
                    $rows = DB::query(
2507
                        "SELECT i.id AS id, MIN(i.restricted_to) AS restricted_to, MIN(i.perso) AS perso,
2508
                        MIN(i.label) AS label, MIN(i.description) AS description, MIN(i.pw) AS pw, MIN(i.login) AS login,
2509
                        MIN(i.anyone_can_modify) AS anyone_can_modify,l.date AS date, i.id_tree AS tree_id,
2510
                        MIN(n.renewal_period) AS renewal_period,
2511
                        MIN(l.action) AS log_action, l.id_user AS log_user
2512
                        FROM ".prefix_table("items")." AS i
2513
                        INNER JOIN ".prefix_table("nested_tree")." AS n ON (i.id_tree = n.id)
2514
                        INNER JOIN ".prefix_table("log_items")." AS l ON (i.id = l.id_item)
2515
                        WHERE %l
2516
                        GROUP BY i.id, l.date, l.id_user, l.action
2517
                        ORDER BY i.label ASC, l.date DESC",
2518
                        $where
2519
                    );
2520
                }
2521
2522
                $idManaged = '';
2523
                $i = 0;
2524
                $arr_items_html = array();
2525
2526
                foreach ($rows as $record) {
2527
                    // exclude all results except the first one returned by query
2528
                    if (empty($idManaged) === true || $idManaged !== $record['id']) {
2529
                        // Get Expiration date
2530
                        $expired_item = 0;
2531
                        if ($SETTINGS['activate_expiration'] === '1') {
2532
                            if ($record['renewal_period'] > 0 &&
2533
                                ($record['date'] + ($record['renewal_period'] * $SETTINGS_EXT['one_month_seconds'])) < time()
2534
                            ) {
2535
                                $html_json[$record['id']]['expiration_flag'] = "mi-red";
2536
                                $expired_item = 1;
2537
                            } else {
2538
                                if ($record['perso'] !== '1') {
2539
                                    $html_json[$record['id']]['expiration_flag'] = "mi-green";
2540
                                } else {
2541
                                    $html_json[$record['id']]['expiration_flag'] = "";
2542
                                }
2543
                            }
2544
                        }
2545
                        // Init
2546
                        $html_json[$record['id']]['expired'] = $expired_item;
2547
                        $html_json[$record['id']]['item_id'] = $record['id'];
2548
                        $html_json[$record['id']]['tree_id'] = $record['tree_id'];
2549
                        $html_json[$record['id']]['label'] = strip_tags(cleanString($record['label']));
2550
                        if (isset($SETTINGS['show_description']) === true && $SETTINGS['show_description'] === '1') {
2551
                            $html_json[$record['id']]['desc'] = strip_tags(cleanString(explode("<br>", $record['description'])[0]));
2552
                        } else {
2553
                            $html_json[$record['id']]['desc'] = "";
2554
                        }
2555
2556
                        // list of restricted users
2557
                        $is_user_in_restricted_list = in_array($_SESSION['user_id'], explode(';', $record['restricted_to']));
2558
2559
                        $itemPw = $itemLogin = "";
2560
                        $displayItem = false;
2561
                        $need_sk = false;
2562
                        $canMove = false;
2563
                        $item_is_restricted_to_role = false;
2564
2565
                        // TODO: Element is restricted to a group. Check if element can be seen by user
2566
                        // => récupérer un tableau contenant les roles associés à cet ID (a partir table restriction_to_roles)
2567
                        $user_is_included_in_role = false;
2568
                        $roles = DB::query(
2569
                            "SELECT role_id FROM ".prefix_table("restriction_to_roles")." WHERE item_id=%i",
2570
                            $record['id']
2571
                        );
2572
                        if (DB::count() > 0) {
2573
                            $item_is_restricted_to_role = true;
2574
                            foreach ($roles as $val) {
2575
                                if (in_array($val['role_id'], $_SESSION['user_roles'])) {
2576
                                    $user_is_included_in_role = true;
2577
                                    break;
2578
                                }
2579
                            }
2580
                        }
2581
2582
                        // Manage the restricted_to variable
2583
                        if (null !== $post_restricted) {
2584
                            $restrictedTo = $post_restricted;
2585
                        } else {
2586
                            $restrictedTo = "";
2587
                        }
2588
2589
                        if ($list_folders_editable_by_role === true) {
2590
                            if (empty($restrictedTo)) {
2591
                                $restrictedTo = $_SESSION['user_id'];
2592
                            } else {
2593
                                $restrictedTo .= ','.$_SESSION['user_id'];
2594
                            }
2595
                        }
2596
                        $html_json[$record['id']]['restricted'] = $restrictedTo;
2597
2598
                        // Can user modify it?
2599
                        if (($record['anyone_can_modify'] === '1' && $_SESSION['user_read_only'] !== '1')
2600
                            || $_SESSION['user_id'] === $record['log_user']
2601
                            || ($_SESSION['user_read_only'] === '1' && $folderIsPf === false)
2602
                            || (isset($SETTINGS['manager_edit']) && $SETTINGS['manager_edit'] === '1') // force draggable if user is manager
2603
                        ) {
2604
                            $canMove = true;
2605
                        }
2606
2607
                        // Fix a bug on Personal Item creation - field `perso` must be set to `1`
2608
                        if ($record['perso'] !== '1' && (int) $folder_is_personal === 1) {
2609
                            DB::update(
2610
                                prefix_table("items"),
2611
                                array(
2612
                                    'perso' => 1
2613
                                ),
2614
                                "id=%i",
2615
                                $record['id']
2616
                            );
2617
                            $record['perso'] = '1';
2618
                        }
2619
2620
                        // Now check 'list_restricted_folders_for_items'
2621
                        $item_limited_access = false;
2622
                        if (in_array($post_id, array_keys($_SESSION['list_restricted_folders_for_items'])) === true
2623
                            && in_array($post_id, array_keys($_SESSION['list_folders_limited'])) === false
2624
                        ) {
2625
                            if (in_array($record['id'], $_SESSION['list_restricted_folders_for_items'][$post_id]) === false) {
2626
                                $item_limited_access = true;
2627
                            }
2628
                        }
2629
2630
                        // CASE where item is restricted to a role to which the user is not associated
2631
                        if (isset($user_is_included_in_role) === true
2632
                            && $user_is_included_in_role === false
2633
                            && isset($item_is_restricted_to_role) === true
2634
                            && $item_is_restricted_to_role === true
2635
                            && $is_user_in_restricted_list === false
2636
                            && (int) $folder_is_personal !== 1
2637
                        ) {
2638
                            $html_json[$record['id']]['perso'] = "fa-tag mi-red";
2639
                            $html_json[$record['id']]['sk'] = 0;
2640
                            $html_json[$record['id']]['display'] = "no_display";
2641
                            $html_json[$record['id']]['open_edit'] = 0;
2642
                            $html_json[$record['id']]['reload'] = "";
2643
                            $html_json[$record['id']]['accessLevel'] = 3;
2644
                            $html_json[$record['id']]['canMove'] = 0;
2645
                            $findPfGroup = 0;
2646
                            $displayItem = false;
2647
                            $need_sk = false;
2648
                            $canMove = false;
2649
                        // Case where item is in own personal folder
2650
                        } elseif ((int) $folder_is_in_personal === 1
2651
                            && (int) $record['perso'] === 1
2652
                        ) {
2653
                            $html_json[$record['id']]['perso'] = "fa-user-secret mi-grey-1";
2654
                            $findPfGroup = 1;
2655
                            $displayItem = true;
2656
                            $need_sk = true;
2657
                            $canMove = true;
2658
2659
                            $html_json[$record['id']]['sk'] = 1;
2660
                            $html_json[$record['id']]['display'] = "";
2661
                            $html_json[$record['id']]['open_edit'] = 1;
2662
                            $html_json[$record['id']]['reload'] = "";
2663
                            $html_json[$record['id']]['accessLevel'] = 0;
2664
                            $html_json[$record['id']]['canMove'] = 1;
2665
                        // CAse where item is restricted to a group of users included user
2666
                        } elseif ((empty($record['restricted_to']) === false
2667
                            || $list_folders_editable_by_role === true)
2668
                            && $is_user_in_restricted_list === true
2669
                        ) {
2670
                            $html_json[$record['id']]['perso'] = "fa-tag mi-yellow";
2671
                            $findPfGroup = 0;
2672
                            $displayItem = true;
2673
                            $canMove = true;
2674
                            $html_json[$record['id']]['sk'] = 0;
2675
                            $html_json[$record['id']]['display'] = "";
2676
                            $html_json[$record['id']]['open_edit'] = 1;
2677
                            $html_json[$record['id']]['reload'] = "";
2678
                            $html_json[$record['id']]['accessLevel'] = 0;
2679
                            $html_json[$record['id']]['canMove'] = ($_SESSION['user_read_only'] === '1' && $folderIsPf === false) ? 0 : 1;
2680
                        // CAse where item is restricted to a group of users not including user
2681
                        } elseif ((int) $record['perso'] === 1
2682
                            ||
2683
                            (
2684
                                empty($record['restricted_to']) === false
2685
                                && $is_user_in_restricted_list === false
2686
                            )
2687
                            ||
2688
                            (
2689
                                isset($user_is_included_in_role) === true
2690
                                && isset($item_is_restricted_to_role) === true
2691
                                && $user_is_included_in_role === false
2692
                                && $item_is_restricted_to_role === true
2693
                            )
2694
                        ) {
2695
                            if (isset($user_is_included_in_role) === true
2696
                                && isset($item_is_restricted_to_role) === true
2697
                                && $user_is_included_in_role === false
2698
                                && $item_is_restricted_to_role === true
2699
                            ) {
2700
                                $html_json[$record['id']]['perso'] = "fa-tag mi-red";
2701
                                $displayItem = false;
2702
                                $need_sk = true;
2703
                                $canMove = false;
2704
2705
                                $html_json[$record['id']]['sk'] = 0;
2706
                                $html_json[$record['id']]['display'] = "no_display";
2707
                                $html_json[$record['id']]['open_edit'] = 0;
2708
                                $html_json[$record['id']]['reload'] = "";
2709
                                $html_json[$record['id']]['accessLevel'] = 3;
2710
                                $html_json[$record['id']]['canMove'] = 0;
2711
                            } else {
2712
                                $html_json[$record['id']]['perso'] = "fa-tag mi-yellow";
2713
                                // reinit in case of not personal group
2714
                                if ($init_personal_folder === false) {
2715
                                    $findPfGroup = "";
2716
                                    $init_personal_folder = true;
2717
                                }
2718
2719
                                if (empty($record['restricted_to']) === false && $is_user_in_restricted_list === true) {
2720
                                    $displayItem = true;
2721
                                }
2722
2723
                                $html_json[$record['id']]['sk'] = 0;
2724
                                $html_json[$record['id']]['display'] = "";
2725
                                $html_json[$record['id']]['open_edit'] = 0;
2726
                                $html_json[$record['id']]['reload'] = "";
2727
                                $html_json[$record['id']]['accessLevel'] = 0;
2728
                                $html_json[$record['id']]['canMove'] = 0;
2729
                            }
2730
                        } else {
2731
                            $html_json[$record['id']]['perso'] = "fa-tag mi-green";
2732
                            $displayItem = true;
2733
                            // reinit in case of not personal group
2734
                            if ($init_personal_folder === false) {
2735
                                $findPfGroup = "";
2736
                                $init_personal_folder = true;
2737
                            }
2738
2739
                            $html_json[$record['id']]['sk'] = 0;
2740
                            $html_json[$record['id']]['display'] = $item_limited_access === true ? "no_display" : "";
2741
                            $html_json[$record['id']]['open_edit'] = 1;
2742
                            $html_json[$record['id']]['reload'] = "";
2743
                            $html_json[$record['id']]['accessLevel'] = $item_limited_access === true ? 0 : $accessLevel;
2744
                            $html_json[$record['id']]['canMove'] = $accessLevel === 0 ? (($_SESSION['user_read_only'] === '1' && $folderIsPf === false) ? 0 : 1) : $canMove;
2745
                        }
2746
2747
                        $html_json[$record['id']]['pw_status'] = "";
2748
2749
                        // increment array for icons shortcuts (don't do if option is not enabled)
2750
                        if (isset($SETTINGS['copy_to_clipboard_small_icons']) && $SETTINGS['copy_to_clipboard_small_icons'] === '1') {
2751
                            if ($need_sk === true && isset($_SESSION['user_settings']['session_psk'])) {
2752
                                $pw = cryption(
2753
                                    $record['pw'],
2754
                                    $_SESSION['user_settings']['session_psk'],
2755
                                    "decrypt"
2756
                                );
2757
                            } else {
2758
                                $pw = cryption(
2759
                                    $record['pw'],
2760
                                    "",
2761
                                    "decrypt"
2762
                                );
2763
                            }
2764
2765
                            // test charset => may cause a json error if is not utf8
2766
                            $pw = $pw['string'];
2767
                            if (isUTF8($pw) === false) {
2768
                                $pw = "";
2769
                                $html_json[$record['id']]['pw_status'] = "encryption_error";
2770
                            }
2771
                        } else {
2772
                            $pw = "";
2773
                        }
2774
                        $html_json[$record['id']]['pw'] = $pw;
2775
                        $html_json[$record['id']]['login'] = $record['login'];
2776
                        $html_json[$record['id']]['anyone_can_modify'] = isset($SETTINGS['anyone_can_modify']) ? $SETTINGS['anyone_can_modify'] : '0';
2777
                        $html_json[$record['id']]['copy_to_clipboard_small_icons'] = isset($SETTINGS['copy_to_clipboard_small_icons']) ? $SETTINGS['copy_to_clipboard_small_icons'] : '0';
2778
                        $html_json[$record['id']]['display_item'] = $displayItem === true ? 1 : 0;
2779
                        $html_json[$record['id']]['enable_favourites'] = isset($SETTINGS['enable_favourites']) ? $SETTINGS['enable_favourites'] : '0';
2780
2781
                        // Prepare make Favorite small icon
2782
                        if (in_array($record['id'], $_SESSION['favourites'])) {
2783
                            $html_json[$record['id']]['in_favorite'] = 1;
2784
                        } else {
2785
                            $html_json[$record['id']]['in_favorite'] = 0;
2786
                        }
2787
2788
                        // Build array with items
2789
                        array_push($itemsIDList, array($record['id'], $pw, $record['login'], $displayItem));
2790
2791
                        $i++;
2792
                    }
2793
                    $idManaged = $record['id'];
2794
                }
2795
2796
                $rights = recupDroitCreationSansComplexite($post_id);
2797
            }
2798
2799
            // DELETE - 2.1.19 - AND (l.action = 'at_creation' OR (l.action = 'at_modification' AND l.raison LIKE 'at_pw :%'))
2800
            // count
2801
            if (intval($start) === 0) {
2802
                DB::query(
2803
                    "SELECT i.id
2804
                    FROM ".prefix_table("items")." as i
2805
                    INNER JOIN ".prefix_table("nested_tree")." as n ON (i.id_tree = n.id)
2806
                    INNER JOIN ".prefix_table("log_items")." as l ON (i.id = l.id_item)
2807
                    WHERE %l
2808
                    ORDER BY i.label ASC, l.date DESC",
2809
                    $where
2810
                );
2811
                $counter_full = DB::count();
2812
                $uniqueLoadData['counter_full'] = $counter_full;
2813
            }
2814
2815
            // Check list to be continued status
2816
            if ($post_nb_items_to_display_once !== 'max' && ($post_nb_items_to_display_once + $start) < $counter_full) {
2817
                $listToBeContinued = "yes";
2818
            } else {
2819
                $listToBeContinued = "end";
2820
            }
2821
2822
            // Prepare returned values
2823
            $returnValues = array(
2824
                "html_json" => $html_json,
2825
                "recherche_group_pf" => $findPfGroup,
2826
                "arborescence" => $arr_arbo,
2827
                "array_items" => $itemsIDList,
2828
                "error" => $showError,
2829
                "saltkey_is_required" => $folderIsPf === true ? 1 : 0,
2830
                "show_clipboard_small_icons" => isset($SETTINGS['copy_to_clipboard_small_icons']) && $SETTINGS['copy_to_clipboard_small_icons'] === '1' ? 1 : 0,
2831
                "next_start" => intval($post_nb_items_to_display_once) + intval($start),
2832
                "list_to_be_continued" => $listToBeContinued,
2833
                "items_count" => $counter,
2834
                "counter_full" => $counter_full,
2835
                'folder_complexity' => $folderComplexity,
2836
                'displayCategories' => $displayCategories,
2837
                'access_level' => $accessLevel,
2838
                'IsPersonalFolder' => $folderIsPf === true ? 1 : 0,
2839
                'uniqueLoadData' => json_encode($uniqueLoadData)
2840
            );
2841
            // Check if $rights is not null
2842
            if (count($rights) > 0) {
2843
                $returnValues = array_merge($returnValues, $rights);
2844
            }
2845
            // Encrypt data to return
2846
            echo prepareExchangedData($returnValues, "encode");
2847
2848
            break;
2849
2850
        /*
2851
        * CASE
2852
        * Get complexity level of a group
2853
        */
2854
        case "get_complixity_level":
2855
            // Prepare POST variables
2856
            $post_groupe = filter_input(INPUT_POST, 'groupe', FILTER_SANITIZE_STRING);
2857
            $post_context = filter_input(INPUT_POST, 'context', FILTER_SANITIZE_STRING);
2858
2859
            // get some info about ITEM
2860
            $dataItem = DB::queryfirstrow(
2861
                "SELECT perso, anyone_can_modify
2862
                FROM ".prefix_table("items")."
2863
                WHERE id=%i",
2864
                $post_item_id
2865
            );
2866
            // is user allowed to access this folder - readonly
2867
            if (null !== $post_groupe && empty($post_groupe) === false) {
2868
                if (in_array($post_groupe, $_SESSION['read_only_folders']) || !in_array($post_groupe, $_SESSION['groupes_visibles'])) {
2869
                    // check if this item can be modified by anyone
2870
                    if (isset($SETTINGS['anyone_can_modify']) && $SETTINGS['anyone_can_modify'] === '1') {
2871
                        if ($dataItem['anyone_can_modify'] != 1) {
2872
                            // else return not authorized
2873
                            $returnValues = array(
2874
                                "error" => "user_is_readonly",
2875
                                "message" => $LANG['error_not_allowed_to']
2876
                            );
2877
                            echo prepareExchangedData($returnValues, "encode");
2878
                            break;
2879
                        }
2880
                    } else {
2881
                        // else return not authorized
2882
                        $returnValues = array(
2883
                            "error" => "user_is_readonly",
2884
                            "message" => $LANG['error_not_allowed_to']
2885
                        );
2886
                        echo prepareExchangedData($returnValues, "encode");
2887
                        break;
2888
                    }
2889
                }
2890
            }
2891
2892
            if (null !== $post_item_id && empty($post_item_id) === false) {
2893
                // Lock Item (if already locked), go back and warn
2894
                $dataTmp = DB::queryFirstRow("SELECT timestamp, user_id FROM ".prefix_table("items_edition")." WHERE item_id = %i", $post_item_id);
2895
2896
                // If token is taken for this Item and delay is passed then delete it.
2897
                if (isset($SETTINGS['delay_item_edition']) &&
2898
                    $SETTINGS['delay_item_edition'] > 0 && empty($dataTmp['timestamp']) === false &&
2899
                    round(abs(time() - $dataTmp['timestamp']) / 60, 2) > $SETTINGS['delay_item_edition']
2900
                ) {
2901
                    DB::delete(prefix_table("items_edition"), "item_id = %i", $post_item_id);
2902
                    //reload the previous data
2903
                    $dataTmp = DB::queryFirstRow(
2904
                        "SELECT timestamp, user_id FROM ".prefix_table("items_edition")." WHERE item_id = %i",
2905
                        $post_item_id
2906
                    );
2907
                }
2908
2909
                // If edition by same user (and token not freed before for any reason, then update timestamp)
2910
                if (empty($dataTmp['timestamp']) === false && $dataTmp['user_id'] == $_SESSION['user_id']) {
2911
                    DB::update(
2912
                        prefix_table("items_edition"),
2913
                        array(
2914
                            "timestamp" => time()
2915
                        ),
2916
                        "user_id = %i AND item_id = %i",
2917
                        $_SESSION['user_id'],
2918
                        $post_item_id
2919
                    );
2920
                    // If no token for this Item, then initialize one
2921
                } elseif (empty($dataTmp[0])) {
2922
                    DB::insert(
2923
                        prefix_table("items_edition"),
2924
                        array(
2925
                            'timestamp' => time(),
2926
                            'item_id' => $post_item_id,
2927
                            'user_id' => $_SESSION['user_id']
2928
                        )
2929
                    );
2930
                    // Edition not possible
2931
                } else {
2932
                    $returnValues = array(
2933
                        "error" => "no_edition_possible",
2934
                        "error_msg" => addslashes($LANG['error_no_edition_possible_locked'])
2935
                    );
2936
                    echo prepareExchangedData($returnValues, "encode");
2937
                    break;
2938
                }
2939
            }
2940
2941
            // do query on this folder
2942
            $data_this_folder = DB::queryFirstRow(
2943
                "SELECT id, personal_folder, title
2944
                FROM ".prefix_table("nested_tree")."
2945
                WHERE id = %s",
2946
                $post_groupe
2947
            );
2948
2949
            // check if user can perform this action
2950
            if (null !== $post_context && empty($post_context) === false) {
2951
                if ($post_context === "create_folder" || $post_context === "edit_folder"
2952
                    || $post_context === "delete_folder" || $post_context === "copy_folder"
2953
                ) {
2954
                    if ($_SESSION['is_admin'] !== '1'
2955
                        && ($_SESSION['user_manager'] !== '1')
2956
                        && (
2957
                            isset($SETTINGS['enable_user_can_create_folders'])
2958
                           && $SETTINGS['enable_user_can_create_folders'] !== '1'
2959
                        )
2960
                        && (
2961
                            $data_this_folder['personal_folder'] !== '1' && $data_this_folder['title'] !== $_SESSION['user_id']
2962
                        )   // take into consideration if this is a personal folder
2963
                    ) {
2964
                        $returnValues = array(
2965
                            "error" => "no_folder_creation_possible",
2966
                            "error_msg" => addslashes($LANG['error_not_allowed_to'])
2967
                        );
2968
                        echo prepareExchangedData($returnValues, "encode");
2969
                        break;
2970
                    }
2971
                }
2972
            }
2973
2974
            // Get required Complexity for this Folder
2975
            $data = DB::queryFirstRow(
2976
                "SELECT m.valeur, n.personal_folder
2977
                FROM ".prefix_table("misc")." AS m
2978
                INNER JOIN ".prefix_table("nested_tree")." AS n ON (m.intitule = n.id)
2979
                WHERE type=%s AND intitule = %s",
2980
                "complex",
2981
                $post_groupe
2982
            );
2983
2984
            if (isset($data['valeur']) === true && (empty($data['valeur']) === false || $data['valeur'] === '0')) {
2985
                $complexity = $SETTINGS_EXT['pwComplexity'][$data['valeur']][1];
2986
                $folder_is_personal = $data['personal_folder'];
2987
            } else {
2988
                $complexity = $LANG['not_defined'];
2989
2990
                // if not defined, then previous query failed and personal_folder is null
2991
                // do new query to know if current folder is pf
2992
                $data_pf = DB::queryFirstRow(
2993
                    "SELECT personal_folder
2994
                    FROM ".prefix_table("nested_tree")."
2995
                    WHERE id = %s",
2996
                    $post_groupe
2997
                );
2998
                $folder_is_personal = $data_pf['personal_folder'];
2999
            }
3000
            // Prepare Item actual visibility (what Users/Roles can see it)
3001
            $visibilite = "";
3002
            if (empty($dataPf[0]) === false) {
3003
                $visibilite = $_SESSION['login'];
3004
            } else {
3005
                $rows = DB::query(
3006
                    "SELECT t.title
3007
                    FROM ".prefix_table("roles_values")." as v
3008
                    INNER JOIN ".prefix_table("roles_title")." as t ON (v.role_id = t.id)
3009
                    WHERE v.folder_id = %i
3010
                    GROUP BY title",
3011
                    $post_groupe
3012
                );
3013
                foreach ($rows as $record) {
3014
                    if (empty($visibilite)) {
3015
                        $visibilite = $record['title'];
3016
                    } else {
3017
                        $visibilite .= " - ".$record['title'];
3018
                    }
3019
                }
3020
            }
3021
3022
            recupDroitCreationSansComplexite($post_groupe);
3023
3024
            $returnValues = array(
3025
                "error" => "",
3026
                "val" => $data['valeur'],
3027
                "visibility" => $visibilite,
3028
                "complexity" => $complexity,
3029
                "personal" => $folder_is_personal
3030
            );
3031
            echo prepareExchangedData($returnValues, "encode");
3032
            break;
3033
3034
        /*
3035
        * CASE
3036
        * DELETE attached file from an item
3037
        */
3038
        case "delete_attached_file":
3039
            // Get some info before deleting
3040
            $data = DB::queryFirstRow(
3041
                "SELECT name, id_item, file
3042
                FROM ".prefix_table("files")."
3043
                WHERE id = %i",
3044
                filter_input(INPUT_POST, 'file_id', FILTER_SANITIZE_NUMBER_INT)
3045
            );
3046
3047
            // Load item data
3048
            $data_item = DB::queryFirstRow(
3049
                "SELECT id_tree
3050
                FROM ".prefix_table("items")."
3051
                WHERE id = %i",
3052
                $data['id_item']
3053
            );
3054
3055
            // Check that user can access this folder
3056
            if (!in_array($data_item['id_tree'], $_SESSION['groupes_visibles'])) {
3057
                echo prepareExchangedData(array("error" => "ERR_FOLDER_NOT_ALLOWED"), "encode");
3058
                break;
3059
            }
3060
3061
            if (empty($data['id_item']) === false) {
3062
                // Delete from FILES table
3063
                DB::delete(
3064
                    prefix_table("files"),
3065
                    "id = %i",
3066
                    filter_input(INPUT_POST, 'file_id', FILTER_SANITIZE_NUMBER_INT)
3067
                );
3068
                // Update the log
3069
                logItems($data['id_item'], $data['name'], $_SESSION['user_id'], 'at_modification', $_SESSION['login'], 'at_del_file : '.$data['name']);
3070
                // Delete file from server
3071
                fileDelete($SETTINGS['path_to_upload_folder']."/".$data['file']);
3072
            }
3073
            break;
3074
3075
        /*
3076
        * CASE
3077
        * REBUILD the description editor
3078
        */
3079
        case "rebuild_description_textarea":
3080
            $post_id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);
3081
3082
            $returnValues = array();
3083
            if (isset($SETTINGS['richtext']) && $SETTINGS['richtext'] === '1') {
3084
                if ($post_id === "desc") {
3085
                    $returnValues['desc'] = '$("#desc").ckeditor({toolbar :[["Bold", "Italic", "Strike", "-", "NumberedList", "BulletedList", "-", "Link","Unlink","-","RemoveFormat"]], height: 100,language: "'.$SETTINGS_EXT['langs'][$_SESSION['user_language']].'"});';
3086
                } elseif ($post_id === "edit_desc") {
3087
                    $returnValues['desc'] = 'CKEDITOR.replace("edit_desc",{toolbar :[["Bold", "Italic", "Strike", "-", "NumberedList", "BulletedList", "-", "Link","Unlink","-","RemoveFormat"]], height: 100,language: "'.$SETTINGS_EXT['langs'][$_SESSION['user_language']].'"});';
3088
                }
3089
            }
3090
            // Multselect
3091
            $returnValues['multi_select'] = '$("#edit_restricted_to_list").multiselect({selectedList: 7, minWidth: 430, height: 145, checkAllText: "'.$LANG['check_all_text'].'", uncheckAllText: "'.$LANG['uncheck_all_text'].'",noneSelectedText: "'.$LANG['none_selected_text'].'"});';
3092
            // Display popup
3093
            if ($post_id === "edit_desc") {
3094
                $returnValues['dialog'] = '$("#div_formulaire_edition_item").dialog("open");';
3095
            } else {
3096
                $returnValues['dialog'] = '$("#div_formulaire_saisi").dialog("open");';
3097
            }
3098
            echo $returnValues;
0 ignored issues
show
Bug introduced by
Are you sure $returnValues of type array|string[] can be used in echo? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3098
            echo /** @scrutinizer ignore-type */ $returnValues;
Loading history...
3099
            break;
3100
3101
        /*
3102
        * CASE
3103
        * Clear HTML tags
3104
        */
3105
        case "clear_html_tags":
3106
            // Get information for this item
3107
            $dataItem = DB::queryfirstrow(
3108
                "SELECT description FROM ".prefix_table("items")." WHERE id=%i",
3109
                filter_input(INPUT_POST, 'id_item', FILTER_SANITIZE_NUMBER_INT)
3110
            );
3111
            // Clean up the string
3112
            echo json_encode(array("description" => strip_tags($dataItem['description'])), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
3113
            break;
3114
3115
        /*
3116
        * FUNCTION
3117
        * Launch an action when clicking on a quick icon
3118
        * $action = 0 => Make not favorite
3119
        * $action = 1 => Make favorite
3120
        */
3121
        case "action_on_quick_icon":
3122
            if (filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING) === '1') {
3123
                // Add new favourite
3124
                array_push($_SESSION['favourites'], $post_id);
3125
                DB::update(
3126
                    prefix_table("users"),
3127
                    array(
3128
                        'favourites' => implode(';', $_SESSION['favourites'])
3129
                        ),
3130
                    'id = %i',
3131
                    $_SESSION['user_id']
3132
                );
3133
                // Update SESSION with this new favourite
3134
                $data = DB::queryfirstrow(
3135
                    "SELECT label,id_tree
3136
                    FROM ".prefix_table("items")."
3137
                    WHERE id = ".mysqli_real_escape_string($link, $post_id)
3138
                );
3139
                $_SESSION['favourites_tab'][$post_id] = array(
3140
                    'label' => $data['label'],
3141
                    'url' => 'index.php?page=items&amp;group='.$data['id_tree'].'&amp;id='.$post_id
3142
                    );
3143
            } elseif (filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING) === '0') {
3144
                // delete from session
3145
                foreach ($_SESSION['favourites'] as $key => $value) {
3146
                    if ($_SESSION['favourites'][$key] === $post_id) {
3147
                        unset($_SESSION['favourites'][$key]);
3148
                        break;
3149
                    }
3150
                }
3151
                // delete from DB
3152
                DB::update(
3153
                    prefix_table("users"),
3154
                    array(
3155
                        "favourites" =>implode(';', $_SESSION['favourites'])
3156
                    ),
3157
                    "id = %i",
3158
                    $_SESSION['user_id']
3159
                );
3160
                // refresh session fav list
3161
                if (isset($_SESSION['favourites_tab'])) {
3162
                    foreach ($_SESSION['favourites_tab'] as $key => $value) {
3163
                        if ($key == $post_id) {
3164
                            unset($_SESSION['favourites_tab'][$key]);
3165
                            break;
3166
                        }
3167
                    }
3168
                }
3169
            }
3170
            break;
3171
3172
        /*
3173
        * CASE
3174
        * Move an ITEM
3175
        */
3176
        case "move_item":
3177
            // Check KEY and rights
3178
            if ($post_key !== $_SESSION['key']
3179
                || $_SESSION['user_read_only'] === true || !isset($SETTINGS['pwd_maximum_length'])
3180
            ) {
3181
                // error
3182
                exit();
3183
            }
3184
3185
            // get data about item
3186
            $dataSource = DB::queryfirstrow(
3187
                "SELECT i.pw, f.personal_folder,i.id_tree, f.title,i.label
3188
                FROM ".prefix_table("items")." as i
3189
                INNER JOIN ".prefix_table("nested_tree")." as f ON (i.id_tree=f.id)
3190
                WHERE i.id=%i",
3191
                $post_item_id
3192
            );
3193
3194
            // get data about new folder
3195
            $dataDestination = DB::queryfirstrow(
3196
                "SELECT personal_folder, title FROM ".prefix_table("nested_tree")." WHERE id = %i",
3197
                $post_folder_id
3198
            );
3199
3200
            // Do quick check if psh is required
3201
            if ((isset($_SESSION['user_settings']['session_psk']) === false || empty($_SESSION['user_settings']['session_psk']) === true)
3202
                && ($dataSource['personal_folder'] === '1' || $dataDestination['personal_folder'] === '1')
3203
            ) {
3204
                 echo '[{"error" : "ERR_PSK_REQUIRED"}]';
3205
                break;
3206
            }
3207
3208
            // Check that user can access this folder
3209
            if (!in_array($dataSource['id_tree'], $_SESSION['groupes_visibles'])
3210
                || !in_array($post_folder_id, $_SESSION['groupes_visibles'])
3211
            ) {
3212
                echo '[{"error" : "ERR_FOLDER_NOT_ALLOWED"}]';
3213
                break;
3214
            }
3215
3216
            // previous is non personal folder and new too
3217
            if ($dataSource['personal_folder'] === '0' && $dataDestination['personal_folder'] === '0') {
3218
                // just update is needed. Item key is the same
3219
                DB::update(
3220
                    prefix_table("items"),
3221
                    array(
3222
                        'id_tree' => $post_folder_id
3223
                        ),
3224
                    "id=%i",
3225
                    $post_item_id
3226
                );
3227
            } elseif ($dataSource['personal_folder'] === '0' && $dataDestination['personal_folder'] === '1') {
3228
                $decrypt = cryption(
3229
                    $dataSource['pw'],
3230
                    "",
3231
                    "decrypt"
3232
                );
3233
                $encrypt = cryption(
3234
                    $decrypt['string'],
3235
                    mysqli_escape_string($link, stripslashes($_SESSION['user_settings']['session_psk'])),
3236
                    "encrypt"
3237
                );
3238
                // update pw
3239
                DB::update(
3240
                    prefix_table("items"),
3241
                    array(
3242
                        'id_tree' => $post_folder_id,
3243
                        'pw' => $encrypt['string'],
3244
                        'pw_iv' => "",
3245
                        'perso' => 1
3246
                    ),
3247
                    "id=%i",
3248
                    $post_item_id
3249
                );
3250
            // If previous is personal folder and new is personal folder too => no key exist on item
3251
            } elseif ($dataSource['personal_folder'] === '1' && $dataDestination['personal_folder'] === '1') {
3252
                // just update is needed. Item key is the same
3253
                DB::update(
3254
                    prefix_table("items"),
3255
                    array(
3256
                        'id_tree' => $post_folder_id
3257
                    ),
3258
                    "id=%i",
3259
                    $post_item_id
3260
                );
3261
            // If previous is personal folder and new is not personal folder => no key exist on item => add new
3262
            } elseif ($dataSource['personal_folder'] === '1' && $dataDestination['personal_folder'] === '0') {
3263
                $decrypt = cryption(
3264
                    $dataSource['pw'],
3265
                    mysqli_escape_string($link, stripslashes($_SESSION['user_settings']['session_psk'])),
3266
                    "decrypt"
3267
                );
3268
                $encrypt = cryption(
3269
                    $decrypt['string'],
3270
                    "",
3271
                    "encrypt"
3272
                );
3273
3274
                // update item
3275
                DB::update(
3276
                    prefix_table("items"),
3277
                    array(
3278
                        'id_tree' => $post_folder_id,
3279
                        'pw' => $encrypt['string'],
3280
                        'pw_iv' => "",
3281
                        'perso' => 0
3282
                    ),
3283
                    "id=%i",
3284
                    $post_item_id
3285
                );
3286
            }
3287
            // Log item moved
3288
            logItems(
3289
                $post_item_id,
3290
                $dataSource['label'],
3291
                $_SESSION['user_id'],
3292
                'at_modification',
3293
                $_SESSION['login'],
3294
                'at_moved : '.$dataSource['title'].' -> '.$dataDestination['title']
3295
            );
3296
3297
            echo '[{"from_folder":"'.$dataSource['id_tree'].'" , "to_folder":"'.$post_folder_id.'" , "error" : ""}]';
3298
            break;
3299
3300
        /*
3301
        * CASE
3302
        * MASSIVE Move an ITEM
3303
        */
3304
        case "mass_move_items":
3305
            // Check KEY and rights
3306
            if ($post_key !== $_SESSION['key'] || $_SESSION['user_read_only'] === true || !isset($SETTINGS['pwd_maximum_length'])) {
3307
                // error
3308
                exit();
3309
            }
3310
3311
            // loop on items to move
3312
            foreach (explode(";", filter_input(INPUT_POST, 'item_ids', FILTER_SANITIZE_STRING)) as $item_id) {
3313
                if (empty($item_id) === false) {
3314
                    // get data about item
3315
                    $dataSource = DB::queryfirstrow(
3316
                        "SELECT i.pw, f.personal_folder,i.id_tree, f.title,i.label
3317
                        FROM ".prefix_table("items")." as i
3318
                        INNER JOIN ".prefix_table("nested_tree")." as f ON (i.id_tree=f.id)
3319
                        WHERE i.id=%i",
3320
                        $item_id
3321
                    );
3322
3323
                    // Check that user can access this folder
3324
                    if (in_array($dataSource['id_tree'], $_SESSION['groupes_visibles']) === false
3325
                        || in_array($post_folder_id, $_SESSION['groupes_visibles']) === false
3326
                    ) {
3327
                        echo '[{"error":"not_allowed" , "status":"ok"}]';
3328
                        exit();
3329
                    }
3330
3331
                    // get data about new folder
3332
                    $dataDestination = DB::queryfirstrow(
3333
                        "SELECT personal_folder, title FROM ".prefix_table("nested_tree")." WHERE id = %i",
3334
                        $post_folder_id
3335
                    );
3336
3337
                    // previous is non personal folder and new too
3338
                    if ($dataSource['personal_folder'] === '0' && $dataDestination['personal_folder'] === '0') {
3339
                        // just update is needed. Item key is the same
3340
                        DB::update(
3341
                            prefix_table("items"),
3342
                            array(
3343
                                'id_tree' => $post_folder_id
3344
                                ),
3345
                            "id=%i",
3346
                            $item_id
3347
                        );
3348
                    } elseif ($dataSource['personal_folder'] === '0' && $dataDestination['personal_folder'] === '1') {
3349
                        $decrypt = cryption(
3350
                            $dataSource['pw'],
3351
                            "",
3352
                            "decrypt"
3353
                        );
3354
                        $encrypt = cryption(
3355
                            $decrypt['string'],
3356
                            mysqli_escape_string($link, stripslashes($_SESSION['user_settings']['session_psk'])),
3357
                            "encrypt"
3358
                        );
3359
                        // update pw
3360
                        DB::update(
3361
                            prefix_table("items"),
3362
                            array(
3363
                                'id_tree' => $post_folder_id,
3364
                                'pw' => $encrypt['string'],
3365
                                'pw_iv' => "",
3366
                                'perso' => 1
3367
                            ),
3368
                            "id=%i",
3369
                            $item_id
3370
                        );
3371
                    // If previous is personal folder and new is personal folder too => no key exist on item
3372
                    } elseif ($dataSource['personal_folder'] === '1' && $dataDestination['personal_folder'] === '1') {
3373
                        // just update is needed. Item key is the same
3374
                        DB::update(
3375
                            prefix_table("items"),
3376
                            array(
3377
                                'id_tree' => $post_folder_id
3378
                            ),
3379
                            "id=%i",
3380
                            $item_id
3381
                        );
3382
                    // If previous is personal folder and new is not personal folder => no key exist on item => add new
3383
                    } elseif ($dataSource['personal_folder'] === '1' && $dataDestination['personal_folder'] === '0') {
3384
                        $decrypt = cryption(
3385
                            $dataSource['pw'],
3386
                            mysqli_escape_string($link, stripslashes($_SESSION['user_settings']['session_psk'])),
3387
                            "decrypt"
3388
                        );
3389
                        $encrypt = cryption(
3390
                            $decrypt['string'],
3391
                            "",
3392
                            "encrypt"
3393
                        );
3394
3395
                        // update item
3396
                        DB::update(
3397
                            prefix_table("items"),
3398
                            array(
3399
                                'id_tree' => $post_folder_id,
3400
                                'pw' => $encrypt['string'],
3401
                                'pw_iv' => "",
3402
                                'perso' => 0
3403
                            ),
3404
                            "id=%i",
3405
                            $item_id
3406
                        );
3407
                    }
3408
                    // Log item moved
3409
                    logItems(
3410
                        $item_id,
0 ignored issues
show
Bug introduced by
$item_id of type string is incompatible with the type integer expected by parameter $ident of logItems(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3410
                        /** @scrutinizer ignore-type */ $item_id,
Loading history...
3411
                        $dataSource['label'],
3412
                        $_SESSION['user_id'],
3413
                        'at_modification',
3414
                        $_SESSION['login'],
3415
                        'at_moved : '.$dataSource['title'].' -> '.$dataDestination['title']
3416
                    );
3417
                }
3418
            }
3419
3420
            // reload cache table
3421
            require_once $SETTINGS['cpassman_dir'].'/sources/main.functions.php';
3422
            updateCacheTable("reload", "");
3423
3424
            echo '[{"error":"" , "status":"ok"}]';
3425
            break;
3426
3427
        /*
3428
         * CASE
3429
         * MASSIVE Delete an item
3430
        */
3431
        case "mass_delete_items":
3432
            // Check KEY and rights
3433
            if ($post_key !== $_SESSION['key']) {
3434
                $returnValues = '[{"error" : "not_allowed"}, {"error_text" : "'.addslashes($LANG['error_not_allowed_to']).'"}]';
3435
                echo $returnValues;
3436
                break;
3437
            }
3438
3439
            // loop on items to move
3440
            foreach (explode(";", filter_input(INPUT_POST, 'item_ids', FILTER_SANITIZE_STRING)) as $item_id) {
3441
                if (empty($item_id) === false) {
3442
                    // get info
3443
                    $dataSource = DB::queryfirstrow(
3444
                        "SELECT label, id_tree
3445
                        FROM ".prefix_table("items")."
3446
                        WHERE id=%i",
3447
                        $item_id
3448
                    );
3449
3450
                    // Check that user can access this folder
3451
                    if (in_array($dataSource['id_tree'], $_SESSION['groupes_visibles']) === false
3452
                    ) {
3453
                        echo '[{"error":"'.addslashes($LANG['error_not_allowed_to']).'" , "status":"nok"}]';
3454
                        exit();
3455
                    }
3456
3457
                    // perform a check in case of Read-Only user creating an item in his PF
3458
                    if ($_SESSION['user_read_only'] === true) {
3459
                        echo '[{"error":"'.addslashes($LANG['error_not_allowed_to']).'" , "status":"nok"}]';
3460
                        exit();
3461
                    }
3462
3463
                    // delete item consists in disabling it
3464
                    DB::update(
3465
                        prefix_table("items"),
3466
                        array(
3467
                            'inactif' => '1',
3468
                            ),
3469
                        "id = %i",
3470
                        $item_id
3471
                    );
3472
3473
                    // log
3474
                    logItems($item_id, $dataSource['label'], $_SESSION['user_id'], 'at_delete', $_SESSION['login']);
3475
3476
                    // Update CACHE table
3477
                    updateCacheTable("delete_value", $item_id);
3478
                }
3479
            }
3480
3481
            echo '[{"error":"" , "status":"ok"}]';
3482
3483
            break;
3484
3485
            /*
3486
           * CASE
3487
           * Send email
3488
        */
3489
        case "send_email":
3490
            if ($post_key !== $_SESSION['key']) {
3491
                echo '[{"error" : "something_wrong"}]';
3492
                break;
3493
            } else {
3494
                if (empty(filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING)) === false) {
3495
                    $content = explode(',', filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING));
3496
                }
3497
                // get links url
3498
                if (empty($SETTINGS['email_server_url'])) {
3499
                    $SETTINGS['email_server_url'] = $SETTINGS['cpassman_url'];
3500
                }
3501
                if ($post_cat === "request_access_to_author") {
3502
                    $dataAuthor = DB::queryfirstrow("SELECT email,login FROM ".prefix_table("users")." WHERE id= ".$content[1]);
3503
                    $dataItem = DB::queryfirstrow("SELECT label, id_tree FROM ".prefix_table("items")." WHERE id= ".$content[0]);
3504
3505
                    // Get path
3506
                    $path = prepareEmaiItemPath(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $path is correct as prepareEmaiItemPath($dat...em['label'], $SETTINGS) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
3507
                        $dataItem['id_tree'],
3508
                        $dataItem['label'],
3509
                        $SETTINGS
3510
                    );
3511
                    
3512
                    $ret = sendEmail(
3513
                        $LANG['email_request_access_subject'],
3514
                        str_replace(
3515
                            array('#tp_item_author#', '#tp_user#', '#tp_item#'),
3516
                            array(" ".addslashes($dataAuthor['login']), addslashes($_SESSION['login']), $path),
3517
                            $LANG['email_request_access_mail']
3518
                        ),
3519
                        $dataAuthor['email'],
3520
                        $LANG,
3521
                        $SETTINGS
3522
                    );
3523
                } elseif ($post_cat === "share_this_item") {
3524
                    $dataItem = DB::queryfirstrow(
3525
                        "SELECT label,id_tree
3526
                        FROM ".prefix_table("items")."
3527
                        WHERE id= %i",
3528
                        $post_id
3529
                    );
3530
3531
                    // Get path
3532
                    $path = prepareEmaiItemPath(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $path is correct as prepareEmaiItemPath($dat...em['label'], $SETTINGS) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
3533
                        $dataItem['id_tree'],
3534
                        $dataItem['label'],
3535
                        $SETTINGS
3536
                    );
3537
                    
3538
                    // send email
3539
                    $ret = sendEmail(
3540
                        $LANG['email_share_item_subject'],
3541
                        str_replace(
3542
                            array('#tp_link#', '#tp_user#', '#tp_item#'),
3543
                            array($SETTINGS['email_server_url'].'/index.php?page=items&group='.$dataItem['id_tree'].'&id='.$post_id, addslashes($_SESSION['login']), addslashes($path)),
0 ignored issues
show
Bug introduced by
$path of type void is incompatible with the type string expected by parameter $str of addslashes(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3543
                            array($SETTINGS['email_server_url'].'/index.php?page=items&group='.$dataItem['id_tree'].'&id='.$post_id, addslashes($_SESSION['login']), addslashes(/** @scrutinizer ignore-type */ $path)),
Loading history...
3544
                            $LANG['email_share_item_mail']
3545
                        ),
3546
                        $post_receipt,
3547
                        $LANG,
3548
                        $SETTINGS
3549
                    );
3550
                }
3551
                echo '[{'.$ret.'}]';
3552
            }
3553
            break;
3554
3555
        /*
3556
           * CASE
3557
           * manage notification of an Item
3558
        */
3559
        case "notify_a_user":
3560
            if ($post_key !== $_SESSION['key']) {
3561
                echo '[{"error" : "something_wrong"}]';
3562
                break;
3563
            } else {
3564
                if (filter_input(INPUT_POST, 'notify_type', FILTER_SANITIZE_STRING) === "on_show") {
3565
                    // Check if values already exist
3566
                    $data = DB::queryfirstrow(
3567
                        "SELECT notification FROM ".prefix_table("items")." WHERE id = %i",
3568
                        $post_item_id
3569
                    );
3570
                    $notifiedUsers = explode(';', $data['notification']);
3571
                    // User is not in actual notification list
3572
                    if ($post_status === "true" && !in_array($post_user_id, $notifiedUsers)) {
3573
                        // User is not in actual notification list and wants to be notified
3574
                        DB::update(
3575
                            prefix_table("items"),
3576
                            array(
3577
                                'notification' => empty($data['notification']) ?
3578
                                    filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_NUMBER_INT).";"
3579
                                    : $data['notification'].filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_NUMBER_INT)
3580
                                ),
3581
                            "id=%i",
3582
                            $post_item_id
3583
                        );
3584
                        echo '[{"error" : "", "new_status":"true"}]';
3585
                        break;
3586
                    } elseif ($post_status === false && in_array($post_user_id, $notifiedUsers)) {
3587
                        // TODO : delete user from array and store in DB
3588
                        // User is in actual notification list and doesn't want to be notified
3589
                        DB::update(
3590
                            prefix_table("items"),
3591
                            array(
3592
                                'notification' => empty($data['notification']) ?
3593
                                    filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_NUMBER_INT)
3594
                                    : $data['notification'].";".filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_NUMBER_INT)
3595
                                ),
3596
                            "id=%i",
3597
                            $post_item_id
3598
                        );
3599
                    }
3600
                }
3601
            }
3602
            break;
3603
3604
        /*
3605
        * CASE
3606
        * Item History Log - add new entry
3607
        */
3608
        case "history_entry_add":
3609
            if ($post_key !== $_SESSION['key']) {
3610
                $data = array("error" => "key_is_wrong");
3611
                echo prepareExchangedData($data, "encode");
3612
                break;
3613
            } else {
3614
                // decrypt and retreive data in JSON format
3615
                $dataReceived = prepareExchangedData($post_data, "decode");
3616
                // Get all informations for this item
3617
                $dataItem = DB::queryfirstrow(
3618
                    "SELECT *
3619
                    FROM ".prefix_table("items")." as i
3620
                    INNER JOIN ".prefix_table("log_items")." as l ON (l.id_item = i.id)
3621
                    WHERE i.id=%i AND l.action = %s",
3622
                    $dataReceived['item_id'],
3623
                    "at_creation"
3624
                );
3625
                // check that actual user can access this item
3626
                $restrictionActive = true;
3627
                $restrictedTo = array_filter(explode(';', $dataItem['restricted_to']));
3628
                if (in_array($_SESSION['user_id'], $restrictedTo)) {
3629
                    $restrictionActive = false;
3630
                }
3631
                if (empty($dataItem['restricted_to'])) {
3632
                    $restrictionActive = false;
3633
                }
3634
3635
                if ((
3636
                        (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles'])) && ($dataItem['perso'] === '0' || ($dataItem['perso'] === '1' && $dataItem['id_user'] == $_SESSION['user_id'])) && $restrictionActive === false
3637
                    )
3638
                    ||
3639
                    (
3640
                        isset($SETTINGS['anyone_can_modify']) && $SETTINGS['anyone_can_modify'] === '1' && $dataItem['anyone_can_modify'] === '1' && (in_array($dataItem['id_tree'], $_SESSION['groupes_visibles']) || $_SESSION['is_admin'] === '1') && $restrictionActive === false
3641
                    )
3642
                    ||
3643
                    (@in_array(
3644
                        $post_id,
3645
                        $_SESSION['list_folders_limited'][$post_folder_id]
3646
                    ))
3647
                ) {
3648
                    $error = "";
3649
                    // Query
3650
                    logItems($dataReceived['item_id'], $dataItem['label'], $_SESSION['user_id'], 'at_manual', $_SESSION['login'], htmlspecialchars_decode($dataReceived['label']), ENT_QUOTES);
3651
                    // Prepare new line
3652
                    $data = DB::queryfirstrow(
3653
                        "SELECT * FROM ".prefix_table("log_items")." WHERE id_item = %i ORDER BY date DESC",
3654
                        $dataReceived['item_id']
3655
                    );
3656
                    $historic = date($SETTINGS['date_format']." ".$SETTINGS['time_format'], $data['date'])." - ".$_SESSION['login']." - ".$LANG[$data['action']]." - ".$data['raison'];
3657
                    // send back
3658
                    $data = array(
3659
                        "error" => "",
3660
                        "new_line" => "<br>".addslashes($historic)
3661
                    );
3662
                    echo prepareExchangedData($data, "encode");
3663
                } else {
3664
                    $data = array("error" => "something_wrong");
3665
                    echo prepareExchangedData($data, "encode");
3666
                    break;
3667
                }
3668
            }
3669
            break;
3670
3671
        /*
3672
        * CASE
3673
        * Free Item for Edition
3674
        */
3675
        case "free_item_for_edition":
3676
            // Check KEY
3677
            if ($post_key !== $_SESSION['key']) {
3678
                echo '[ { "error" : "key_not_conform" } ]';
3679
                break;
3680
            }
3681
            // Do
3682
            DB::delete(
3683
                prefix_table("items_edition"),
3684
                "item_id = %i",
3685
                $post_id
3686
            );
3687
            break;
3688
3689
        /*
3690
        * CASE
3691
        * Check if Item has been changed since loaded
3692
        */
3693
        case "is_item_changed":
3694
            $data = DB::queryFirstRow(
3695
                "SELECT date FROM ".prefix_table("log_items")." WHERE action = %s AND id_item = %i ORDER BY date DESC",
3696
                "at_modification",
3697
                $post_item_id
3698
            );
3699
            // Check if it's in a personal folder. If yes, then force complexity overhead.
3700
            if ($data['date'] > filter_input(INPUT_POST, 'timestamp', FILTER_SANITIZE_STRING)) {
3701
                echo '{ "modified" : "1" }';
3702
            } else {
3703
                echo '{ "modified" : "0" }';
3704
            }
3705
            break;
3706
3707
        /*
3708
        * CASE
3709
        * Check if Item has been changed since loaded
3710
        */
3711
        case "generate_OTV_url":
3712
            // Check KEY
3713
            if ($post_key !== $_SESSION['key']) {
3714
                echo '[ { "error" : "key_not_conform" } ]';
3715
                break;
3716
            }
3717
3718
            // delete all existing old otv codes
3719
            $rows = DB::query("SELECT id FROM ".prefix_table("otv")." WHERE timestamp < ".(time() - $SETTINGS['otv_expiration_period'] * 86400));
3720
            foreach ($rows as $record) {
3721
                DB::delete(prefix_table('otv'), "id=%i", $record['id']);
3722
            }
3723
3724
            // generate session
3725
            $otv_code = GenerateCryptKey(32, false, true, true, false);
3726
3727
            DB::insert(
3728
                prefix_table("otv"),
3729
                array(
3730
                    'id' => null,
3731
                    'item_id' => $post_id,
3732
                    'timestamp' => time(),
3733
                    'originator' => intval($_SESSION['user_id']),
3734
                    'code' => $otv_code
3735
                    )
3736
            );
3737
            $newID = DB::insertId();
3738
3739
            $otv_session = array(
3740
                "code"      => $otv_code,
3741
                "stamp" => time()
3742
            );
3743
3744
            if (!isset($SETTINGS['otv_expiration_period'])) {
3745
                $SETTINGS['otv_expiration_period'] = 7;
3746
            }
3747
            $url = $SETTINGS['cpassman_url']."/index.php?otv=true&".http_build_query($otv_session);
3748
            $exp_date = date($SETTINGS['date_format']." ".$SETTINGS['time_format'], time() + (intval($SETTINGS['otv_expiration_period']) * 86400));
3749
3750
            echo json_encode(
3751
                array(
3752
                    "error" => "",
3753
                    "url" => str_replace(
3754
                        array("#URL#", "#DAY#"),
3755
                        array('<span id=\'otv_link\'>'.$url.'</span>&nbsp;<span class=\'fa-stack tip" title=\''.addslashes($LANG['copy']).'\' style=\'cursor:pointer;\' id=\'button_copy_otv_link\'><span class=\'fa fa-square fa-stack-2x\'></span><span class=\'fa fa-clipboard fa-stack-1x fa-inverse\'></span></span>', $exp_date),
3756
                        $LANG['one_time_view_item_url_box']
3757
                    )
3758
                )
3759
            );
3760
            break;
3761
3762
        /*
3763
        * CASE
3764
        * Free Item for Edition
3765
        */
3766
        case "image_preview_preparation":
3767
            // Check KEY
3768
            if ($post_key !== $_SESSION['key']) {
3769
                echo '[ { "error" : "key_not_conform" } ]';
3770
                break;
3771
            }
3772
3773
            // get file info
3774
            $file_info = DB::queryfirstrow(
3775
                "SELECT file, status FROM ".prefix_table("files")." WHERE id=%i",
3776
                intval(substr(filter_input(INPUT_POST, 'uri', FILTER_SANITIZE_STRING), 1))
3777
            );
3778
3779
            // prepare image info
3780
            $post_title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
3781
            $image_code = $file_info['file'];
3782
            $extension = substr($post_title, strrpos($post_title, '.') + 1);
3783
            $file_to_display = $SETTINGS['url_to_upload_folder'].'/'.$image_code;
3784
            $file_suffix = "";
3785
3786
            // should we encrypt/decrypt the file
3787
            encrypt_or_decrypt_file($file_info['file'], $file_info['status']);
3788
3789
            // should we decrypt the attachment?
3790
            if (isset($file_info['status']) && $file_info['status'] === "encrypted") {
3791
                // Delete the file as viewed
3792
                fileDelete($SETTINGS['path_to_upload_folder'].'/'.$image_code."_delete.".$extension);
3793
3794
                // Open the file
3795
                if (file_exists($SETTINGS['path_to_upload_folder'].'/'.$image_code)) {
3796
                    // Should we encrypt or decrypt?
3797
                    prepareFileWithDefuse(
3798
                        'decrypt',
3799
                        $SETTINGS['path_to_upload_folder'].'/'.$image_code,
3800
                        $SETTINGS['path_to_upload_folder'].'/'.$image_code."_delete.".$extension
3801
                    );
3802
3803
                    // prepare variable
3804
                    $file_to_display = $file_to_display."_delete.".$extension;
3805
                    $file_suffix = "_delete.".$extension;
3806
                }
3807
            }
3808
3809
            // Encrypt data to return
3810
            echo prepareExchangedData(
3811
                array(
3812
                    "error" => "",
3813
                    "new_file" => $file_to_display,
3814
                    "file_suffix" => $file_suffix,
3815
                    "file_path" => $SETTINGS['path_to_upload_folder'].'/'.$image_code."_delete.".$extension
3816
                ),
3817
                "encode"
3818
            );
3819
            break;
3820
3821
        /*
3822
        * CASE
3823
        * Free Item for Edition
3824
        */
3825
        case "delete_file":
3826
            // Check KEY
3827
            if ($post_key !== $_SESSION['key']) {
3828
                echo '[ { "error" : "key_not_conform" } ]';
3829
                break;
3830
            }
3831
3832
            // get file info
3833
            $result = DB::queryfirstrow(
3834
                "SELECT file FROM ".prefix_table("files")." WHERE id=%i",
3835
                intval(substr(filter_input(INPUT_POST, 'uri', FILTER_SANITIZE_STRING), 1))
3836
            );
3837
3838
            fileDelete($SETTINGS['path_to_upload_folder'].'/'.$result['file'].filter_input(INPUT_POST, 'file_suffix', FILTER_SANITIZE_STRING));
3839
3840
            break;
3841
3842
        /*
3843
        * CASE
3844
        * Get list of users that have access to the folder
3845
        */
3846
        case "get_refined_list_of_users":
3847
            // Check KEY
3848
            if ($post_key !== $_SESSION['key']) {
3849
                echo '[ { "error" : "key_not_conform" } ]';
3850
                break;
3851
            }
3852
            $error = "";
3853
3854
            // get list of users
3855
            $aList = array();
3856
            $selOptionsUsers = "";
3857
            $selOptionsRoles = "";
3858
            $selEOptionsUsers = "";
3859
            $selEOptionsRoles = "";
3860
            $rows = DB::query(
3861
                "SELECT r.role_id AS role_id, t.title AS title
3862
                FROM ".prefix_table("roles_values")." AS r
3863
                INNER JOIN ".prefix_table("roles_title")." AS t ON (r.role_id = t.id)
3864
                WHERE r.folder_id = %i",
3865
                $post_iFolderId
3866
            );
3867
            foreach ($rows as $record) {
3868
                $selOptionsRoles .= '<option value="role_'.$record['role_id'].'" class="folder_rights_role">'.$record['title'].'</option>';
3869
                $selEOptionsRoles .= '<option value="role_'.$record['role_id'].'" class="folder_rights_role_edit">'.$record['title'].'</option>';
3870
                $rows2 = DB::query("SELECT id, login, fonction_id FROM ".prefix_table("users")." WHERE fonction_id LIKE '%".$record['role_id']."%'");
3871
                foreach ($rows2 as $record2) {
3872
                    foreach (explode(";", $record2['fonction_id']) as $role) {
3873
                        if (!in_array($record2['id'], $aList) && $role == $record['role_id']) {
3874
                            array_push($aList, $record2['id']);
3875
                            $selOptionsUsers .= '<option value="'.$record2['id'].'" class="folder_rights_user">'.$record2['login'].'</option>';
3876
                            $selEOptionsUsers .= '<option value="'.$record2['id'].'" class="folder_rights_user_edit">'.$record2['login'].'</option>';
3877
                        }
3878
                    }
3879
                }
3880
            }
3881
3882
            // export data
3883
            $data = array(
3884
                'error' => $error,
3885
                'selOptionsUsers' => $selOptionsUsers,
3886
                'selOptionsRoles' => $selOptionsRoles,
3887
                'selEOptionsUsers' => $selEOptionsUsers,
3888
                'selEOptionsRoles' => $selEOptionsRoles
3889
            );
3890
            echo prepareExchangedData($data, "encode");
3891
3892
            break;
3893
3894
        /*
3895
        * CASE
3896
        * Get list of users that have access to the folder
3897
        */
3898
        case "check_for_title_duplicate":
3899
            // Check KEY
3900
            if ($post_key !== $_SESSION['key']) {
3901
                echo '[ { "error" : "key_not_conform" } ]';
3902
                break;
3903
            }
3904
            $error = "";
3905
            $duplicate = 0;
3906
3907
            // decrypt and retreive data in JSON format
3908
            $dataReceived = prepareExchangedData($post_data, "decode");
3909
            // Prepare variables
3910
            $label = htmlspecialchars_decode($dataReceived['label']);
3911
            $idFolder = $dataReceived['idFolder'];
3912
3913
            // don't check if Personal Folder
3914
            $data = DB::queryFirstRow("SELECT title FROM ".prefix_table("nested_tree")." WHERE id = %i", $idFolder);
3915
            if ($data['title'] == $_SESSION['user_id']) {
3916
                // send data
3917
                echo '[{"duplicate" : "'.$duplicate.'" , error" : ""}]';
3918
            } else {
3919
                if (filter_input(INPUT_POST, 'option', FILTER_SANITIZE_STRING) === "same_folder") {
3920
                // case unique folder
3921
                    DB::query(
3922
                        "SELECT label
3923
                        FROM ".prefix_table("items")."
3924
                        WHERE id_tree = %i AND label = %s",
3925
                        $idFolder,
3926
                        $label
3927
                    );
3928
                } else {
3929
                // case complete database
3930
3931
                    //get list of personal folders
3932
                    $arrayPf = array();
3933
                    $listPf = "";
3934
                    if (empty($row['id']) === false) {
3935
                        $rows = DB::query(
3936
                            "SELECT id FROM ".prefix_table("nested_tree")." WHERE personal_folder = %i",
3937
                            "1"
3938
                        );
3939
                        foreach ($rows as $record) {
3940
                            if (!in_array($record['id'], $arrayPf)) {
3941
                                array_push($arrayPf, $record['id']);
3942
                            }
3943
                        }
3944
                    }
3945
3946
                    // build WHERE condition
3947
                    $where = new WhereClause('and');
3948
                    $where->add('id_tree = %i', $idFolder);
3949
                    $where->add('label = %s', $label);
3950
                    if (empty($arrayPf) === false) {
3951
                        $where->add("id_tree NOT IN (".implode(',', $arrayPf).")");
3952
                    }
3953
3954
                    DB::query(
3955
                        "SELECT label
3956
                        FROM ".prefix_table("items")."
3957
                        WHERE %l",
3958
                        $where
3959
                    );
3960
                }
3961
3962
                // count results
3963
                if (DB::count() > 0) {
3964
                    $duplicate = 1;
3965
                }
3966
3967
                // send data
3968
                echo '[{"duplicate" : "'.$duplicate.'" , "error" : ""}]';
3969
            }
3970
            break;
3971
3972
        /*
3973
        * CASE
3974
        * Get list of users that have access to the folder
3975
        */
3976
        case "refresh_visible_folders":
3977
            // Check KEY
3978
            if ($post_key !== $_SESSION['key']) {
3979
                echo '[ { "error" : "key_not_conform" } ]';
3980
                break;
3981
            }
3982
3983
            // Init
3984
3985
            // Will we show the root folder?
3986
            $arr_data['can_create_root_folder'] = isset($SETTINGS['can_create_root_folder']) && $SETTINGS['can_create_root_folder'] === '1' ? 1 : 0;
3987
3988
            // Build list of visible folders
3989
            $selectVisibleFoldersOptions = $selectVisibleNonPersonalFoldersOptions = $selectVisibleActiveFoldersOptions = "";
3990
            if (isset($SETTINGS['can_create_root_folder']) && $SETTINGS['can_create_root_folder'] === '1') {
3991
                $selectVisibleFoldersOptions = '<option value="0">'.$LANG['root'].'</option>';
3992
            }
3993
3994
            if ($_SESSION['user_admin'] === '1' && (isset($SETTINGS_EXT['admin_full_right'])
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: {currentAssign}, Probably Intended Meaning: {alternativeAssign}
Loading history...
3995
                && $SETTINGS_EXT['admin_full_right'] === true) || !isset($SETTINGS_EXT['admin_full_right'])) {
3996
                $_SESSION['groupes_visibles'] = $_SESSION['personal_visible_groups'];
3997
                $_SESSION['groupes_visibles_list'] = implode(',', $_SESSION['groupes_visibles']);
3998
            }
3999
4000
            if (isset($_SESSION['list_folders_limited']) && count($_SESSION['list_folders_limited']) > 0) {
4001
                $listFoldersLimitedKeys = @array_keys($_SESSION['list_folders_limited']);
4002
            } else {
4003
                $listFoldersLimitedKeys = array();
4004
            }
4005
            // list of items accessible but not in an allowed folder
4006
            if (isset($_SESSION['list_restricted_folders_for_items'])
4007
                && count($_SESSION['list_restricted_folders_for_items']) > 0) {
4008
                $listRestrictedFoldersForItemsKeys = @array_keys($_SESSION['list_restricted_folders_for_items']);
4009
            } else {
4010
                $listRestrictedFoldersForItemsKeys = array();
4011
            }
4012
4013
4014
            //Build tree
4015
            $tree = new SplClassLoader('Tree\NestedTree', $SETTINGS['cpassman_dir'].'/includes/libraries');
4016
            $tree->register();
4017
            $tree = new Tree\NestedTree\NestedTree($pre.'nested_tree', 'id', 'parent_id', 'title');
4018
            $tree->rebuild();
4019
            $folders = $tree->getDescendants();
4020
            $inc = 0;
4021
4022
            foreach ($folders as $folder) {
4023
                // Be sure that user can only see folders he/she is allowed to
4024
                if (in_array($folder->id, $_SESSION['forbiden_pfs']) === false
4025
                    || in_array($folder->id, $_SESSION['groupes_visibles']) === true
4026
                    || in_array($folder->id, $listFoldersLimitedKeys) === true
4027
                    || in_array($folder->id, $listRestrictedFoldersForItemsKeys) === true
4028
                ) {
4029
                    // Init
4030
                    $displayThisNode = false;
4031
                    $hide_node = false;
4032
                    $nbChildrenItems = 0;
4033
4034
                    // Check if any allowed folder is part of the descendants of this node
4035
                    $nodeDescendants = $tree->getDescendants($folder->id, true, false, true);
4036
                    foreach ($nodeDescendants as $node) {
4037
                        // manage tree counters
4038
                        /*if (isset($SETTINGS['tree_counters']) && $SETTINGS['tree_counters'] === '1') {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
4039
                            DB::query(
4040
                                "SELECT * FROM ".prefix_table("items")."
4041
                                WHERE inactif=%i AND id_tree = %i",
4042
                                0,
4043
                                $node
4044
                            );
4045
                            $nbChildrenItems += DB::count();
4046
                        }*/
4047
                        if (in_array($node, array_merge($_SESSION['groupes_visibles'], $_SESSION['list_restricted_folders_for_items'])) === true
4048
                            || @in_array($node, $listFoldersLimitedKeys)
4049
                            || @in_array($node, $listRestrictedFoldersForItemsKeys)
4050
                        ) {
4051
                            $displayThisNode = true;
4052
                            //break;
4053
                        }
4054
                    }
4055
4056
                    if ($displayThisNode === true) {
4057
                        // resize title if necessary
4058
                        $fldTitle = str_replace("&", "&amp;", $folder->title);
4059
4060
                        // rename personal folder with user login
4061
                        if ($folder->title == $_SESSION['user_id'] && $folder->nlevel === '1') {
4062
                            $fldTitle = $_SESSION['login'];
4063
                        }
4064
4065
                        // ALL FOLDERS
4066
                        // Is this folder disabled?
4067
                        $disabled = 0;
4068
                        if (in_array($folder->id, $_SESSION['groupes_visibles']) === false
4069
                            || in_array($folder->id, $_SESSION['read_only_folders']) === true
4070
                            || ($_SESSION['user_read_only'] === '1' && in_array($folder->id, $_SESSION['personal_visible_groups']) === false)
4071
                        ) {
4072
                            $disabled = 1;
4073
                        }
4074
                        // Build array
4075
                        $arr_data['folders'][$inc]['id'] = $folder->id;
4076
                        $arr_data['folders'][$inc]['level'] = $folder->nlevel;
4077
                        $arr_data['folders'][$inc]['title'] = htmlspecialchars_decode($fldTitle, ENT_QUOTES);
4078
                        $arr_data['folders'][$inc]['disabled'] = $disabled;
4079
4080
4081
                        // Is this folder an active folders? (where user can do something)
4082
                        $is_visible_active = 0;
4083
                        if (isset($_SESSION['read_only_folders']) === true
4084
                            && in_array($folder->id, $_SESSION['read_only_folders']) === true) {
4085
                            $is_visible_active = 1;
4086
                        }
4087
                        $arr_data['folders'][$inc]['is_visible_active'] = $is_visible_active;
4088
4089
                        $inc++;
4090
                    }
4091
                }
4092
            }
4093
4094
            $data = array(
4095
                'error' => "",
4096
                'html_json' => $arr_data
4097
            );
4098
            // send data
4099
            echo prepareExchangedData($data, "encode");
4100
4101
            break;
4102
4103
        /*
4104
        * CASE
4105
        * Load item history
4106
        */
4107
        case "load_item_history":
4108
            // Check KEY
4109
            if ($post_key !== $_SESSION['key']) {
4110
                echo prepareExchangedData(array("error" => "ERR_KEY_NOT_CORRECT"), "encode");
4111
                break;
4112
            }
4113
4114
            // decrypt and retreive data in JSON format
4115
            $dataReceived = prepareExchangedData($post_data, "decode");
4116
4117
            // Prepare variables
4118
            $id = noHTML(htmlspecialchars_decode($dataReceived['id']));
4119
4120
            // get item info
4121
            $dataItem = DB::queryFirstRow(
4122
                "SELECT *
4123
                FROM ".prefix_table("items")."
4124
                WHERE id=%i",
4125
                $id
4126
            );
4127
4128
            // get item history
4129
            $history = '<table style="margin:0px; width:100%; border-collapse: collapse; background-color:#D4D5D5;" cellspacing="0" cellpadding="1">';
4130
            $rows = DB::query(
4131
                "SELECT l.date as date, l.action as action, l.raison as raison, l.raison_iv AS raison_iv,
4132
                u.login as login, u.avatar_thumb as avatar_thumb
4133
                FROM ".prefix_table("log_items")." as l
4134
                LEFT JOIN ".prefix_table("users")." as u ON (l.id_user=u.id)
4135
                WHERE id_item=%i AND action <> %s
4136
                ORDER BY date ASC",
4137
                $id,
4138
                "at_shown"
4139
            );
4140
            foreach ($rows as $record) {
4141
                $reason = explode(':', $record['raison']);
4142
                if ($record['action'] === "at_modification" && $reason[0] === "at_pw ") {
4143
                    // check if item is PF
4144
                    if ($dataItem['perso'] != 1) {
4145
                        $reason[1] = cryption(
4146
                            $reason[1],
4147
                            "",
4148
                            "decrypt"
4149
                        );
4150
                    } else {
4151
                        if (isset($_SESSION['user_settings']['session_psk']) === true) {
4152
                            $reason[1] = cryption(
4153
                                $reason[1],
4154
                                $_SESSION['user_settings']['session_psk'],
4155
                                "decrypt"
4156
                            );
4157
                        } else {
4158
                            $reason[1] = '';
4159
                        }
4160
                    }
4161
                    $reason[1] = @$reason[1]['string'];
4162
                    // if not UTF8 then cleanup and inform that something is wrong with encrytion/decryption
4163
                    if (!isUTF8($reason[1]) || is_array($reason[1])) {
4164
                        $reason[1] = "";
4165
                    }
4166
                }
4167
                // imported via API
4168
                if (empty($record['login'])) {
4169
                    $record['login'] = $LANG['imported_via_api']." [".$record['raison']."]";
4170
                }
4171
4172
                if (empty($reason[1]) === false
4173
                    || $record['action'] === "at_copy"
4174
                    || $record['action'] === "at_creation"
4175
                    || $record['action'] === "at_manual"
4176
                    || $record['action'] === "at_modification"
4177
                    || $record['action'] === "at_delete"
4178
                    || $record['action'] === "at_restored") {
4179
                    // Prepare avatar
4180
                    if (isset($record['avatar_thumb']) && empty($record['avatar_thumb']) === false) {
4181
                        if (file_exists($SETTINGS['cpassman_dir'].'/includes/avatars/'.$record['avatar_thumb'])) {
4182
                            $avatar = $SETTINGS['cpassman_url'].'/includes/avatars/'.$record['avatar_thumb'];
4183
                        } else {
4184
                            $avatar = $SETTINGS['cpassman_url'].'/includes/images/photo.jpg';
4185
                        }
4186
                    } else {
4187
                        $avatar = $SETTINGS['cpassman_url'].'/includes/images/photo.jpg';
4188
                    }
4189
4190
                    $history .= '<tr style="">'.
4191
                        '<td rowspan="2" style="width:40px;"><img src="'.$avatar.'" style="border-radius:20px; height:35px;"></td>'.
4192
                        '<td colspan="2" style="font-size:11px;"><i>'.$LANG['by'].' '.$record['login'].' '.$LANG['at'].' '.date($SETTINGS['date_format'].' '.$SETTINGS['time_format'], $record['date']).'</i></td></tr>'.
4193
                        '<tr style="border-bottom:3px solid #C9C9C9;"><td style="width:100px;"><b>'.$LANG[$record['action']].'</b></td>'.
4194
                        '<td style="">'.(empty($record['raison']) === false && $record['action'] !== "at_creation" ? (count($reason) > 1 ? $LANG[trim($reason[0])].' : '.handleBackslash($reason[1]) : ($record['action'] === "at_manual" ? $reason[0] : $LANG[trim($reason[0])])) : '').'</td>'.
4195
                        '</tr>'.
4196
                        '<tr></tr>';
4197
                }
4198
            }
4199
            $history .= "</table>";
4200
4201
            $data = array(
4202
                'error' => "",
4203
                'new_html' => $history
4204
            );
4205
4206
            // send data
4207
            echo prepareExchangedData($data, "encode");
4208
4209
            break;
4210
4211
        case "suggest_item_change":
4212
            // Check KEY
4213
            if ($post_key !== $_SESSION['key']) {
4214
                echo '[ { "error" : "key_not_conform" } ]';
4215
                break;
4216
            }
4217
            // decrypt and retrieve data in JSON format
4218
            $data_received = prepareExchangedData($post_data, "decode");
4219
4220
            // prepare variables
4221
            $label = htmlspecialchars_decode($data_received['label'], ENT_QUOTES);
4222
            $pwd = htmlspecialchars_decode($data_received['pwd']);
4223
            $login = htmlspecialchars_decode($data_received['login'], ENT_QUOTES);
4224
            $email = htmlspecialchars_decode($data_received['email']);
4225
            $url = htmlspecialchars_decode($data_received['url']);
4226
            $folder = htmlspecialchars_decode($data_received['folder']);
4227
            $comment = htmlspecialchars_decode($data_received['comment']);
4228
            $item_id = htmlspecialchars_decode($data_received['item_id']);
4229
4230
            if (empty($pwd)) {
4231
                $encrypt['string'] = "";
4232
            } else {
4233
                $encrypt = cryption($pwd, "", "encrypt");
4234
            }
4235
4236
            // query
4237
            DB::insert(
4238
                prefix_table("items_change"),
4239
                array(
4240
                    'item_id' => $item_id,
4241
                    'label' => $label,
4242
                    'pw' => $encrypt['string'],
4243
                    'login' => $login,
4244
                    'email' => $email,
4245
                    'url' => $url,
4246
                    'description' => "",
4247
                    'comment' => $comment,
4248
                    'folder_id' => $folder,
4249
                    'user_id' => $_SESSION['user_id'],
4250
                    'timestamp' => time()
4251
                )
4252
            );
4253
            $newID = DB::insertId();
4254
4255
            // get some info to add to the notification email
4256
            $resp_user = DB::queryfirstrow(
4257
                "SELECT login FROM ".prefix_table("users")." WHERE id = %i",
4258
                $_SESSION['user_id']
4259
            );
4260
            $resp_folder = DB::queryfirstrow(
4261
                "SELECT title FROM ".prefix_table("nested_tree")." WHERE id = %i",
4262
                $folder
4263
            );
4264
4265
            // notify Managers
4266
            $rows = DB::query(
4267
                "SELECT email
4268
                FROM ".prefix_table("users")."
4269
                WHERE `gestionnaire` = %i AND `email` IS NOT NULL",
4270
                1
4271
            );
4272
            foreach ($rows as $record) {
4273
                sendEmail(
4274
                    $LANG['suggestion_notify_subject'],
4275
                    str_replace(array('#tp_label#', '#tp_user#', '#tp_folder#'), array(addslashes($label), addslashes($resp_user['login']), addslashes($resp_folder['title'])), $LANG['suggestion_notify_body']),
4276
                    $record['email'],
4277
                    $LANG,
4278
                    $SETTINGS
4279
                );
4280
            }
4281
4282
            echo '[ { "error" : "" } ]';
4283
            break;
4284
4285
        case "build_list_of_users":
4286
            // Check KEY
4287
            if ($post_key !== $_SESSION['key']) {
4288
                echo '[ { "error" : "key_not_conform" } ]';
4289
                break;
4290
            }
4291
4292
            // Get list of users
4293
            $usersList = array();
4294
            $usersString = "";
4295
            $rows = DB::query("SELECT id,login,email FROM ".$pre."users ORDER BY login ASC");
4296
            foreach ($rows as $record) {
4297
                $usersList[$record['login']] = array(
4298
                    "id" => $record['id'],
4299
                    "login" => $record['login'],
4300
                    "email" => $record['email'],
4301
                    );
4302
                $usersString .= $record['id']."#".$record['login'].";";
4303
            }
4304
4305
            $data = array(
4306
                'error' => "",
4307
                'list' => $usersString
4308
            );
4309
4310
            // send data
4311
            echo prepareExchangedData($data, "encode");
4312
            break;
4313
4314
        case "send_request_access":
4315
            // Check KEY
4316
            if ($post_key !== $_SESSION['key']) {
4317
                echo '[ { "error" : "key_not_conform" } ]';
4318
                break;
4319
            }
4320
4321
            // decrypt and retrieve data in JSON format
4322
            $data_received = prepareExchangedData($post_data, "decode");
4323
4324
            // prepare variables
4325
            $emailText = htmlspecialchars_decode($data_received['text'], ENT_QUOTES);
4326
            $item_id = htmlspecialchars_decode($data_received['item_id']);
4327
            $user_id = htmlspecialchars_decode($data_received['user_id']);
4328
4329
            // Send email
4330
            $dataAuthor = DB::queryfirstrow("SELECT email,login FROM ".prefix_table("users")." WHERE id= ".$user_id);
4331
            $dataItem = DB::queryfirstrow("SELECT label, id_tree FROM ".prefix_table("items")." WHERE id= ".$item_id);
4332
4333
            // Get path
4334
            $path = prepareEmaiItemPath(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $path is correct as prepareEmaiItemPath($dat...em['label'], $SETTINGS) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
4335
                $dataItem['id_tree'],
4336
                $dataItem['label'],
4337
                $SETTINGS
4338
            );
4339
4340
            $ret = sendEmail(
4341
                $LANG['email_request_access_subject'],
4342
                str_replace(
4343
                  array(
4344
                      '#tp_item_author#',
4345
                      '#tp_user#',
4346
                      '#tp_item#',
4347
                      '#tp_reason#'
4348
                  ),
4349
                  array(
4350
                      " ".addslashes($dataAuthor['login']),
4351
                      addslashes($_SESSION['login']),
4352
                      $path,
4353
                      nl2br(addslashes($emailText))
4354
                  ),
4355
                  $LANG['email_request_access_mail']
4356
                ),
4357
                $dataAuthor['email'],
4358
                $LANG,
4359
                $SETTINGS
4360
            );
4361
4362
            // Do log
4363
            logItems(
4364
              $item_id,
4365
              $dataItem['label'],
4366
              $_SESSION['user_id'],
4367
              'at_access',
4368
              $_SESSION['login']
4369
            );
4370
4371
            // Return
4372
            echo '[ { "error" : "" } ]';
4373
4374
            break;
4375
    }
4376
}
4377
// Build the QUERY in case of GET
4378
if (isset($_GET['type'])) {
4379
    switch ($_GET['type']) {
4380
        /*
4381
        * CASE
4382
        * Autocomplet for TAGS
4383
        */
4384
        case "autocomplete_tags":
4385
            // Get a list off all existing TAGS
4386
            $listOfTags = "";
4387
            $rows = DB::query("SELECT tag FROM ".prefix_table("tags")." WHERE tag LIKE %ss GROUP BY tag", $_GET['term']);
4388
            foreach ($rows as $record) {
4389
                if (empty($listOfTags)) {
4390
                    $listOfTags = '"'.$record['tag'].'"';
4391
                } else {
4392
                    $listOfTags .= ', "'.$record['tag'].'"';
4393
                }
4394
            }
4395
            echo "[".$listOfTags."]";
4396
            break;
4397
    }
4398
}
4399
4400
/*
4401
* FUNCTION
4402
* Identify if this group authorize creation of item without the complexit level reached
4403
*/
4404
function recupDroitCreationSansComplexite($groupe)
4405
{
4406
    $data = DB::queryFirstRow(
4407
        "SELECT bloquer_creation, bloquer_modification, personal_folder FROM ".prefix_table("nested_tree")." WHERE id = %i",
4408
        $groupe
4409
    );
4410
    // Check if it's in a personal folder. If yes, then force complexity overhead.
4411
    if ($data['personal_folder'] === '1') {
4412
        return array("bloquer_modification_complexite" => 1, "bloquer_creation_complexite" => 1);
4413
    }
4414
4415
    return array("bloquer_modification_complexite" => $data['bloquer_modification'], "bloquer_creation_complexite" => $data['bloquer_creation']);
4416
}
4417
4418
/*
4419
* FUNCTION
4420
* permits to identify what icon to display depending on file extension
4421
*/
4422
function fileFormatImage($ext)
4423
{
4424
    global $SETTINGS_EXT;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
4425
    if (in_array($ext, $SETTINGS_EXT['office_file_ext'])) {
4426
        $image = "file-word-o";
4427
    } elseif ($ext === "pdf") {
4428
        $image = "file-pdf-o";
4429
    } elseif (in_array($ext, $SETTINGS_EXT['image_file_ext'])) {
4430
        $image = "file-image-o";
4431
    } elseif ($ext === "txt") {
4432
        $image = "file-text-o";
4433
    } else {
4434
        $image = "file-o";
4435
    }
4436
4437
    return $image;
4438
}
4439
4440
/**
4441
 * Returns a cleaned up password
4442
 *
4443
 * @param string $pwd
4444
 * @return void
4445
 */
4446
function passwordReplacement($pwd)
4447
{
4448
    $pwPatterns = array('/ETCOMMERCIAL/', '/SIGNEPLUS/');
4449
    $pwRemplacements = array('&', '+');
4450
4451
    return preg_replace($pwPatterns, $pwRemplacements, $pwd);
0 ignored issues
show
Bug Best Practice introduced by
The expression return preg_replace($pwP...$pwRemplacements, $pwd) returns the type string which is incompatible with the documented return type void.
Loading history...
4452
}
4453
4454
/**
4455
 * Returns the Item + path 
4456
 *
4457
 * @param integer $id_tree
4458
 * @param string $label
4459
 * @param array $SETTINGS
4460
 * @return void
4461
 */
4462
function prepareEmaiItemPath($id_tree, $label, $SETTINGS) {
4463
    // Class loader
4464
    require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';
4465
4466
    //Load Tree
4467
    $tree = new SplClassLoader('Tree\NestedTree', '../includes/libraries');
4468
    $tree->register();
4469
    $tree = new Tree\NestedTree\NestedTree(prefix_table("nested_tree"), 'id', 'parent_id', 'title');
4470
4471
    $arbo = $tree->getPath($id_tree, true);
4472
    $path = '';
4473
    foreach ($arbo as $elem) {
4474
        if (empty($path) === true) {
4475
            $path = htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES).' ';
4476
        } else {
4477
            $path .= '&#8594; ' . htmlspecialchars(stripslashes(htmlspecialchars_decode($elem->title, ENT_QUOTES)), ENT_QUOTES);
4478
        }
4479
    }
4480
    // Build text to show user
4481
    if (empty($path) === true) {
4482
        $path = addslashes($label);
4483
    } else {
4484
        $path = addslashes($label).' ('.$path.')';
4485
    }
4486
4487
    return $path;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $path returns the type string which is incompatible with the documented return type void.
Loading history...
4488
}
4489