dolibarr 24.0.2
security.lib.php
Go to the documentation of this file.
1<?php
2
3/* Copyright (C) 2008-2021 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2008-2021 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2020 Ferran Marcet <fmarcet@2byte.es>
6 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2026 William Mead <william@m34d.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 * or see https://www.gnu.org/
23 */
24
33include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/securitycore.lib.php';
34
35
44function dol_encode($chain, $key = '1')
45{
46 if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char
47 $output_tab = array();
48 $strlength = dol_strlen($chain);
49 for ($i = 0; $i < $strlength; $i++) {
50 $output_tab[$i] = chr(ord(substr($chain, $i, 1)) + 17);
51 }
52 $chain = implode("", $output_tab);
53 } elseif ($key) {
54 $result = '';
55 $strlength = dol_strlen($chain);
56 for ($i = 0; $i < $strlength; $i++) {
57 $keychar = substr($key, ($i % strlen($key)) - 1, 1);
58 $result .= chr(ord(substr($chain, $i, 1)) + (ord($keychar) - 65));
59 }
60 $chain = $result;
61 }
62
63 return base64_encode($chain);
64}
65
75function dol_decode($chain, $key = '1')
76{
77 $chain = base64_decode($chain);
78
79 if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char
80 $output_tab = array();
81 $strlength = dol_strlen($chain);
82 for ($i = 0; $i < $strlength; $i++) {
83 $output_tab[$i] = chr(ord(substr($chain, $i, 1)) - 17);
84 }
85
86 $chain = implode("", $output_tab);
87 } elseif ($key) {
88 $result = '';
89 $strlength = dol_strlen($chain);
90 for ($i = 0; $i < $strlength; $i++) {
91 $keychar = substr($key, ($i % strlen($key)) - 1, 1);
92 $result .= chr(ord(substr($chain, $i, 1)) - (ord($keychar) - 65));
93 }
94 $chain = $result;
95 }
96
97 return $chain;
98}
99
106function dolGetRandomBytes($length)
107{
108 if (function_exists('random_bytes')) { // Available with PHP 7+ only.
109 return bin2hex(random_bytes((int) floor($length / 2))); // the bin2hex will double the number of bytes so we take length / 2
110 }
111
112 return bin2hex(openssl_random_pseudo_bytes((int) floor($length / 2))); // the bin2hex will double the number of bytes so we take length / 2. May be very slow on Windows.
113}
114
122function dolGetLdapPasswordHash($password, $type = 'md5')
123{
124 if (empty($type)) {
125 $type = 'md5';
126 }
127
128 $salt = substr(sha1((string) time()), 0, 8);
129
130 if ($type === 'md5') {
131 return '{MD5}' . base64_encode(hash("md5", $password, true)); //For OpenLdap with md5 (based on an unencrypted password in base)
132 } elseif ($type === 'md5frommd5') {
133 return '{MD5}' . base64_encode(hex2bin($password)); // Create OpenLDAP MD5 password from Dolibarr MD5 password
134 } elseif ($type === 'smd5') {
135 return "{SMD5}" . base64_encode(hash("md5", $password . $salt, true) . $salt);
136 } elseif ($type === 'sha') {
137 return '{SHA}' . base64_encode(hash("sha1", $password, true));
138 } elseif ($type === 'ssha') {
139 return "{SSHA}" . base64_encode(hash("sha1", $password . $salt, true) . $salt);
140 } elseif ($type === 'sha256') {
141 return "{SHA256}" . base64_encode(hash("sha256", $password, true));
142 } elseif ($type === 'ssha256') {
143 return "{SSHA256}" . base64_encode(hash("sha256", $password . $salt, true) . $salt);
144 } elseif ($type === 'sha384') {
145 return "{SHA384}" . base64_encode(hash("sha384", $password, true));
146 } elseif ($type === 'ssha384') {
147 return "{SSHA384}" . base64_encode(hash("sha384", $password . $salt, true) . $salt);
148 } elseif ($type === 'sha512') {
149 return "{SHA512}" . base64_encode(hash("sha512", $password, true));
150 } elseif ($type === 'ssha512') {
151 return "{SSHA512}" . base64_encode(hash("sha512", $password . $salt, true) . $salt);
152 } elseif ($type === 'crypt') {
153 return '{CRYPT}' . crypt($password, $salt);
154 } elseif ($type === 'clear') {
155 return '{CLEAR}' . $password; // Just for test, plain text password is not secured !
156 }
157 return "";
158}
159
180function restrictedArea(User $user, $features, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0, $nodie = 0, $mode = '')
181{
182 global $hookmanager;
183
184 // Define $objectid
185 if (is_object($object)) {
186 $objectid = $object->id;
187 } else {
188 $objectid = $object; // $objectid can be X or 'X,Y,Z'
189 }
190 if ($objectid == "-1") {
191 $objectid = 0;
192 }
193 if ($objectid) {
194 $objectid = preg_replace('/[^0-9\.\,]/', '', (string) $objectid); // For the case value is coming from a non sanitized user input
195 }
196
197 //dol_syslog("functions.lib:restrictedArea $feature, $object, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
198 /*print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", object=".$object;
199 print ", dbtablename=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
200 print ", perm: user->hasRight(".$features.($feature2 ? ",".$feature2 : "").", lire) = ".($feature2 ? $user->hasRight($features, $feature2, 'lire') : $user->hasRight($features, 'lire'))."<br>";
201 */
202
203 $parentfortableentity = '';
204
205 $originalfeatures = $features;
206
207 // Fix syntax of $features param to support non standard module names.
208 if ($features == 'agenda') {
209 $tableandshare = 'actioncomm&societe';
210 $feature2 = 'myactions|allactions';
211 $dbt_select = 'id';
212 } elseif ($features == 'bank') {
213 $features = 'banque';
214 } elseif ($features == 'remisecheque') {
215 $features = 'banque';
216 } elseif ($features == 'facturerec') {
217 $features = 'facture';
218 } elseif ($features == 'supplier_invoicerec') {
219 $features = 'fournisseur';
220 $feature2 = 'facture';
221 } elseif ($features == 'company') {
222 $features = 'societe';
223 } elseif ($features == 'mo') {
224 $features = 'mrp';
225 } elseif ($features == 'member') {
226 $features = 'adherent';
227 } elseif ($features == 'subscription') {
228 $features = 'adherent';
229 $feature2 = 'cotisation';
230 $tableandshare = 'subscription&adherent';
231 $parentfortableentity = 'fk_adherent@adherent'; // A subscription has no entity, the entity is the one of its member
232 } elseif ($features == 'website' && is_object($object) && $object->element == 'websitepage') {
233 $parentfortableentity = 'fk_website@website';
234 } elseif ($features == 'project') {
235 $features = 'projet';
236 } elseif ($features == 'project_task') {
237 $features = 'projet';
238 $objectid = (int) $object->fk_project;
239 $object = $objectid;
240 } elseif (is_object($object) && ($features == 'conferenceorbooth@eventorganization' || ($features == 'eventorganization' && $object->element == 'conferenceorbooth'))) {
241 // The module of an event organization declares no permission of its own, on purpose.
242 // Permission are done on project table.
243 if (!empty($user->socid) || empty($object->fk_project)) {
244 if ($nodie) {
245 return 0;
246 } else {
248 }
249 }
250 $features = 'projet';
251 $tableandshare = 'projet&project';
252 $objectid = (int) $object->fk_project;
253 $object = $objectid;
254 } elseif ($features == 'product') {
255 $features = 'produit';
256 } elseif ($features == 'productbatch') {
257 $features = 'produit';
258 } elseif ($features == 'tax') {
259 $feature2 = 'charges';
260 } elseif ($features == 'workstation') {
261 $feature2 = 'workstation';
262 } elseif ($features == 'hrm' && is_object($object) && in_array($object->element, array('job', 'position', 'skill'))) {
263 $feature2 = 'all'; // These 3 objects have no permission of their own, they share the level "all"
264 } elseif ($features == 'recruitment' && is_object($object) && in_array($object->element, array('recruitmentjobposition', 'recruitmentcandidature'))) {
265 // The recruitment module declares no permission at its first level, all its objects share the
266 // second level "recruitmentjobposition". When the caller provides the module name only
267 // (like document.php with its modulepart), we complete the missing parameters from the object.
268 if (empty($feature2)) {
269 $feature2 = 'recruitmentjobposition';
270 }
271 if (empty($tableandshare)) {
272 $tableandshare = $object->table_element;
273 }
274 } elseif ($features == 'stocktransfer' && is_object($object) && $object->element == 'stocktransfer') {
275 $feature2 = 'stocktransfer'; // This module declares no permission at its first level, only this one
276 } elseif (in_array($features, array('fournisseur', 'commande_fournisseur', 'facture_fournisseur', 'order_supplier', 'invoice_supplier'))) { // When vendor invoice and purchase order are into module 'fournisseur'
277 $features = 'fournisseur';
278 if (is_object($object) && $object->element == 'invoice_supplier') {
279 $feature2 = 'facture';
280 } elseif (is_object($object) && $object->element == 'order_supplier') {
281 $feature2 = 'commande';
282 }
283 } elseif ($features == 'payment_sc') {
284 $tableandshare = 'paiementcharge';
285 $parentfortableentity = 'fk_charge@chargesociales';
286 } elseif ($features == 'payment_vat') {
287 $tableandshare = 'payment_vat';
288 $parentfortableentity = 'fk_tva@tva';
289 } elseif ($features == 'payment_donation') {
290 $tableandshare = 'payment_donation';
291 $parentfortableentity = 'fk_donation@don'; // A donation payment has no entity, the entity is the one of its donation
292 }
293
294 // if commonObjectLine : Using many2one related commonObject
295 // @see commonObjectLine::parentElement
296 if (in_array($features, ['commandedet', 'propaldet', 'facturedet', 'supplier_proposaldet', 'evaluationdet', 'skilldet', 'deliverydet', 'contratdet'])) {
297 $features = substr($features, 0, -3); // @phan-suppress-current-line DolibarrForbiddenFunctionPlugin
298 } elseif (in_array($features, ['stocktransferline', 'inventoryline', 'bomline', 'expensereport_det', 'facture_fourn_det'])) {
299 $features = substr($features, 0, -4); // @phan-suppress-current-line DolibarrForbiddenFunctionPlugin
300 } elseif ($features == 'commandefournisseurdispatch') {
301 $features = 'commandefournisseur';
302 } elseif ($features == 'invoice_supplier_det_rec') {
303 $features = 'invoice_supplier_rec';
304 }
305 if ($features == 'evaluation') {
306 $features = 'hrm';
307 $feature2 = 'evaluation';
308 }
309
310 // When the object is a task (element='project_task') and $feature2 is empty,
311 // $checkUserAccessToObject() falls into the $checkproject path and uses the task ID
312 // as project ID, which always fails. Setting $feature2='project_task' triggers the
313 // normalization at line 974 that redirects to the $checktask path, which correctly
314 // resolves $task->fk_project before calling getProjectsAuthorizedForUser().
315 if (is_object($object) && in_array($object->element, array('project_task', 'task'))
316 && (empty($features) || in_array($features, array('projet', 'project')))
317 && empty($feature2)) {
318 $features = 'projet';
319 $feature2 = 'project_task';
320 if (empty($tableandshare)) {
321 $tableandshare = 'projet_task';
322 }
323 }
324
325 // If the $features parameter is empty, there is no permission we can check, so the access must
326 // be refused. Without this test, all the checks of permission below would be silently skipped and
327 // the access would be granted to any user without any test (see also selectobject.php that forces
328 // its features parameter to 'unknownobject' instead of '' for the same reason).
329 if (empty($features) || trim((string) $features) === '') {
330 dol_syslog('restrictedArea() called with an empty features parameter, we refuse the access', LOG_WARNING);
331 if ($nodie) {
332 return 0;
333 } else {
334 accessforbidden('Bad value for parameter features');
335 }
336 }
337
338 // print $features.' - '.$tableandshare.' - '.$feature2.' - '.$dbt_select."\n";
339
340 // Get more permissions checks from hooks
341 $parameters = array(
342 'features' => $features,
343 'feature2' => $feature2,
344 'originalfeatures' => $originalfeatures,
345 'tableandshare' => $tableandshare,
346 'object' => $object,
347 'objectid' => $objectid,
348 'dbt_keyfield' => $dbt_keyfield,
349 'dbt_select' => $dbt_select,
350 'idtype' => $dbt_select,
351 'isdraft' => $isdraft,
352 'nodie' => $nodie,
353 'mode' => $mode
354 );
355 if (!empty($hookmanager)) {
356 $reshook = $hookmanager->executeHooks('restrictedArea', $parameters);
357
358 if (isset($hookmanager->resArray['result'])) {
359 if ($hookmanager->resArray['result'] == 0) {
360 if ($nodie) {
361 return 0;
362 } else {
363 accessforbidden(); // Module returns 0, so access forbidden
364 }
365 }
366 }
367 if ($reshook > 0) { // No other test done.
368 return 1;
369 }
370 }
371
372 // Features/modules to check (to support the & and | operator)
373 $featuresarray = array($features);
374 if (preg_match('/&/', $features)) {
375 $featuresarray = explode("&", $features);
376 } elseif (preg_match('/\|/', $features)) {
377 $featuresarray = explode("|", $features);
378 }
379
380 // More subfeatures to check
381 if (!empty($feature2)) {
382 $feature2 = explode("|", $feature2);
383 }
384
385 $listofmodules = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL'));
386
387 //var_dump($featuresarray, $object->id);
388
389 // Check read permission from module
390 $readok = 1;
391 $nbko = 0;
392 foreach ($featuresarray as $feature) { // first we check nb of test ko
393 $featureforlistofmodule = $feature;
394 if ($featureforlistofmodule == 'produit') {
395 $featureforlistofmodule = 'product';
396 }
397 if ($featureforlistofmodule == 'supplier_proposal') {
398 $featureforlistofmodule = 'supplierproposal';
399 }
400 if (!empty($user->socid) && getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL') && !in_array($featureforlistofmodule, $listofmodules)) { // If limits on modules for external users, module must be into list of modules for external users
401 $readok = 0;
402 $nbko++;
403 continue;
404 }
405
406 if (in_array($feature, array('societe', 'company')) && (empty($feature2) || !in_array('contact', $feature2))) {
407 if (!$user->hasRight('societe', 'lire') && !$user->hasRight('fournisseur', 'lire')) {
408 $readok = 0;
409 $nbko++;
410 }
411 } elseif ((in_array($feature, array('societe', 'company')) && (!empty($feature2) && in_array('contact', $feature2))) || $feature == 'contact') {
412 if (!$user->hasRight('societe', 'contact', 'lire')) {
413 $readok = 0;
414 $nbko++;
415 }
416 } elseif ($feature == 'produit|service') {
417 if (!$user->hasRight('produit', 'lire') && !$user->hasRight('service', 'lire')) {
418 $readok = 0;
419 $nbko++;
420 }
421 } elseif ($feature == 'produit') {
422 // $object is only a real Product/Service when the check is scoped to one specific
423 // record (e.g. a product card); a generic area check (e.g. the product/service
424 // dashboard) never sets it, so it keeps its default int value and has no ->type to
425 // tell products and services apart - fall back to requiring either right.
426 if (!is_object($object)) {
427 if (!$user->hasRight('produit', 'lire') && !$user->hasRight('service', 'lire')) {
428 $readok = 0;
429 $nbko++;
430 }
431 } elseif ($object->type == 0 && !$user->hasRight('produit', 'lire')) {
432 $readok = 0;
433 $nbko++;
434 } elseif ($object->type == 1 && !$user->hasRight('service', 'lire')) {
435 $readok = 0;
436 $nbko++;
437 }
438 } elseif ($feature == 'prelevement') {
439 if (!$user->hasRight('prelevement', 'bons', 'lire')) {
440 $readok = 0;
441 $nbko++;
442 }
443 } elseif ($feature == 'cheque') {
444 if (!$user->hasRight('banque', 'cheque')) {
445 $readok = 0;
446 $nbko++;
447 }
448 } elseif ($feature == 'projet') {
449 if (!$user->hasRight('projet', 'lire') && !$user->hasRight('projet', 'all', 'lire')) {
450 $readok = 0;
451 $nbko++;
452 }
453 } elseif ($feature == 'payment') {
454 if (!$user->hasRight('facture', 'lire')) {
455 $readok = 0;
456 $nbko++;
457 }
458 } elseif ($feature == 'payment_supplier') {
459 if (!$user->hasRight('fournisseur', 'facture', 'lire')) {
460 $readok = 0;
461 $nbko++;
462 }
463 } elseif ($feature == 'payment_sc') {
464 if (!$user->hasRight('tax', 'charges', 'lire')) {
465 $readok = 0;
466 $nbko++;
467 }
468 } elseif ($feature == 'payment_vat') {
469 if (!$user->hasRight('tax', 'charges', 'lire')) {
470 $readok = 0;
471 $nbko++;
472 }
473 } elseif ($feature == 'payment_donation') {
474 if (!$user->hasRight('don', 'lire')) {
475 $readok = 0;
476 $nbko++;
477 }
478 } elseif ($feature == 'webhook') {
479 if (empty($user->admin)) {
480 $readok = 0;
481 $nbko++;
482 }
483 } elseif (!empty($feature2)) { // This is for permissions on 2 levels (module->object->read)
484 $tmpreadok = 1;
485 foreach ($feature2 as $subfeature) {
486 if ($subfeature == 'user' && $user->id == $objectid) {
487 continue; // A user can always read its own card
488 }
489 if ($subfeature == 'fiscalyear' && $user->hasRight('accounting', 'fiscalyear', 'write')) {
490 // only one right for fiscalyear
491 $tmpreadok = 1;
492 continue;
493 }
494 if (!empty($subfeature) && !$user->hasRight($feature, $subfeature, 'lire') && !$user->hasRight($feature, $subfeature, 'read')) {
495 $tmpreadok = 0;
496 } elseif (empty($subfeature) && !$user->hasRight($feature, 'lire') && !$user->hasRight($feature, 'read')) {
497 $tmpreadok = 0;
498 } else {
499 $tmpreadok = 1;
500 break;
501 } // Break is to bypass second test if the first is ok
502 }
503 if (!$tmpreadok) { // We found a test on feature that is ko
504 $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko).
505 $nbko++;
506 }
507 } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level (module->read)
508 if (!$user->hasRight($feature, 'lire')
509 && !$user->hasRight($feature, 'read')
510 && !$user->hasRight($feature, 'run')) {
511 $readok = 0;
512 $nbko++;
513 }
514 }
515 }
516
517 // If a or and at least one ok
518 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
519 $readok = 1;
520 }
521
522 if (!$readok) {
523 if ($nodie) {
524 return 0;
525 } else {
527 }
528 }
529 //print "Read access is ok";
530
531 // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files)
532 $createok = 1;
533 $nbko = 0;
534 if ($mode == 'read') {
535 $wemustcheckpermissionforcreate = 0;
536 $wemustcheckpermissionfordeletedraft = 0;
537 $wemustcheckpermissionfordelete = 0;
538 } elseif ($mode == 'write') {
539 $wemustcheckpermissionforcreate = 1;
540 $wemustcheckpermissionfordeletedraft = 1;
541 $wemustcheckpermissionfordelete = 0;
542 } elseif ($mode == 'delete') {
543 $wemustcheckpermissionforcreate = 0;
544 $wemustcheckpermissionfordeletedraft = 0;
545 $wemustcheckpermissionfordelete = 1;
546 } else {
547 // This is possible in a GUI context only
548 $wemustcheckpermissionforcreate = (GETPOST('sendit', 'alpha') || GETPOST('linkit', 'alpha') || in_array(GETPOST('action', 'aZ09'), array('create', 'update', 'set', 'upload', 'add_element_resource', 'confirm_deletebank', 'confirm_delete_linked_resource')) || GETPOST('roworder', 'alpha', 2));
549 $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
550 $wemustcheckpermissionfordelete = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
551 }
552
553 //var_dump($wemustcheckpermissionforcreate, $wemustcheckpermissionfordeletedraft, $wemustcheckpermissionfordelete);
554
555 if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) {
556 foreach ($featuresarray as $feature) {
557 if ($feature == 'contact') {
558 if (!$user->hasRight('societe', 'contact', 'creer')) {
559 $createok = 0;
560 $nbko++;
561 }
562 } elseif ($feature == 'produit|service') {
563 if (!$user->hasRight('produit', 'creer') && !$user->hasRight('service', 'creer')) {
564 $createok = 0;
565 $nbko++;
566 }
567 } elseif ($feature == 'prelevement') {
568 if (!$user->hasRight('prelevement', 'bons', 'creer')) {
569 $createok = 0;
570 $nbko++;
571 }
572 } elseif ($feature == 'commande_fournisseur') {
573 if (!$user->hasRight('fournisseur', 'commande', 'creer') || !$user->hasRight('supplier_order', 'creer')) {
574 $createok = 0;
575 $nbko++;
576 }
577 } elseif ($feature == 'banque') {
578 if (!$user->hasRight('banque', 'modifier')) {
579 $createok = 0;
580 $nbko++;
581 }
582 } elseif ($feature == 'cheque') {
583 if (!$user->hasRight('banque', 'cheque')) {
584 $createok = 0;
585 $nbko++;
586 }
587 } elseif ($feature == 'import') {
588 if (!$user->hasRight('import', 'run')) {
589 $createok = 0;
590 $nbko++;
591 }
592 } elseif ($feature == 'ecm') {
593 if (!$user->hasRight('ecm', 'upload')) {
594 $createok = 0;
595 $nbko++;
596 }
597 } elseif ($feature == 'modulebuilder') {
598 if (!$user->hasRight('modulebuilder', 'run')) {
599 $createok = 0;
600 $nbko++;
601 }
602 } elseif ($feature == 'payment') {
603 if (!$user->hasRight('facture', 'paiement')) {
604 $createok = 0;
605 $nbko++;
606 }
607 } elseif ($feature == 'payment_supplier') { // Permission to write on a payment of an invoice is permission to edit an invoice.
608 if (!$user->hasRight('fournisseur', 'facture', 'creer')) {
609 $createok = 0;
610 $nbko++;
611 }
612 } elseif ($feature == 'webhook') {
613 if (empty($user->admin)) {
614 $createok = 0;
615 $nbko++;
616 }
617 } elseif (!empty($feature2)) { // This is for permissions on 2 levels (module->object->write)
618 foreach ($feature2 as $subfeature) {
619 if ($subfeature == 'user' && $user->id == $objectid && $user->hasRight('user', 'self', 'creer')) {
620 continue; // User can edit its own card
621 }
622 if ($subfeature == 'user' && $user->id == $objectid && $user->hasRight('user', 'self', 'password')) {
623 continue; // User can edit its own password
624 }
625 if ($subfeature == 'user' && $user->id != $objectid && $user->hasRight('user', 'user', 'password')) {
626 continue; // User can edit another user's password
627 }
628
629 if (!$user->hasRight($feature, $subfeature, 'creer')
630 && !$user->hasRight($feature, $subfeature, 'write')
631 && !$user->hasRight($feature, $subfeature, 'create')) {
632 $createok = 0;
633 $nbko++;
634 } else {
635 $createok = 1;
636 // Break to bypass second test if the first is ok
637 break;
638 }
639 }
640 } elseif (!empty($feature)) { // This is for permissions on 1 levels (module->write)
641 //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; exit;
642 if (!$user->hasRight($feature, 'creer')
643 && !$user->hasRight($feature, 'write')
644 && !$user->hasRight($feature, 'create')) {
645 $createok = 0;
646 $nbko++;
647 }
648 }
649 }
650
651 // If a or and at least one ok
652 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
653 $createok = 1;
654 }
655
656 if ($wemustcheckpermissionforcreate && !$createok) {
657 if ($nodie) {
658 return 0;
659 } else {
661 }
662 }
663 //print "Write access is ok";
664 }
665
666 // Check create user permission (special case)
667 $createuserok = 1;
668 if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') {
669 if (!$user->hasRight('user', 'user', 'creer')) {
670 $createuserok = 0;
671 }
672
673 if (!$createuserok) {
674 if ($nodie) {
675 return 0;
676 } else {
678 }
679 }
680 //print "Create user access is ok";
681 }
682
683 // Check delete permission from module
684 $deleteok = 1;
685 $nbko = 0;
686 if ($wemustcheckpermissionfordelete) {
687 foreach ($featuresarray as $feature) {
688 if ($feature == 'bookmark') {
689 if (!$user->hasRight('bookmark', 'supprimer')) {
690 if ($user->id != $object->fk_user || !$user->hasRight('bookmark', 'creer')) {
691 $deleteok = 0;
692 }
693 }
694 } elseif ($feature == 'contact') {
695 if (!$user->hasRight('societe', 'contact', 'supprimer')) {
696 $deleteok = 0;
697 }
698 } elseif ($feature == 'produit|service') {
699 if (!$user->hasRight('produit', 'supprimer') && !$user->hasRight('service', 'supprimer')) {
700 $deleteok = 0;
701 }
702 } elseif ($feature == 'commande_fournisseur') {
703 if (!$user->hasRight('fournisseur', 'commande', 'supprimer')) {
704 $deleteok = 0;
705 }
706 } elseif ($feature == 'payment_supplier') { // Permission to delete a payment of an invoice is permission to edit an invoice.
707 if (!$user->hasRight('fournisseur', 'facture', 'creer')) {
708 $deleteok = 0;
709 }
710 } elseif ($feature == 'payment') {
711 if (!$user->hasRight('facture', 'paiement')) {
712 $deleteok = 0;
713 }
714 } elseif ($feature == 'payment_sc') {
715 if (!$user->hasRight('tax', 'charges', 'creer')) {
716 $deleteok = 0;
717 }
718 } elseif ($feature == 'banque') {
719 if (!$user->hasRight('banque', 'modifier')) {
720 $deleteok = 0;
721 }
722 } elseif ($feature == 'cheque') {
723 if (!$user->hasRight('banque', 'cheque')) {
724 $deleteok = 0;
725 }
726 } elseif ($feature == 'ecm') {
727 if (!$user->hasRight('ecm', 'upload')) {
728 $deleteok = 0;
729 }
730 } elseif ($feature == 'ftp') {
731 if (!$user->hasRight('ftp', 'write')) {
732 $deleteok = 0;
733 }
734 } elseif ($feature == 'salaries') {
735 if (!$user->hasRight('salaries', 'delete')) {
736 $deleteok = 0;
737 }
738 } elseif ($feature == 'adherent') {
739 if (!$user->hasRight('adherent', 'supprimer')) {
740 $deleteok = 0;
741 }
742 } elseif ($feature == 'paymentbybanktransfer') {
743 if (!$user->hasRight('paymentbybanktransfer', 'create')) { // There is no delete permission
744 $deleteok = 0;
745 }
746 } elseif ($feature == 'prelevement') {
747 if (!$user->hasRight('prelevement', 'bons', 'creer')) { // There is no delete permission
748 $deleteok = 0;
749 }
750 } elseif (!empty($feature2)) { // This is for permissions on 2 levels
751 foreach ($feature2 as $subfeature) {
752 if (!$user->hasRight($feature, $subfeature, 'supprimer') && !$user->hasRight($feature, $subfeature, 'delete')) {
753 $deleteok = 0;
754 } else {
755 $deleteok = 1;
756 break;
757 } // For bypass the second test if the first is ok
758 }
759 } elseif (!empty($feature)) { // This is used for permissions on 1 level
760 //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
761 if (!$user->hasRight($feature, 'supprimer')
762 && !$user->hasRight($feature, 'delete')
763 && !$user->hasRight($feature, 'run')) {
764 $deleteok = 0;
765 }
766 }
767 }
768
769 // If a or and at least one ok
770 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
771 $deleteok = 1;
772 }
773
774 if (!$deleteok && !($isdraft && $createok)) {
775 if ($nodie) {
776 return 0;
777 } else {
779 }
780 }
781 //print "Delete access is ok";
782 }
783
784 // If we have a particular object to check permissions on, we check if $user has permission
785 // for this given object (link to company, is contact for project, ...)
786 if (!empty($objectid) && $objectid > 0) {
787 $ok = checkUserAccessToObject($user, $featuresarray, $object, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity);
788 $params = array('objectid' => $objectid, 'features' => implode(',', $featuresarray), 'features2' => $feature2);
789 //print 'checkUserAccessToObject ok='.$ok;
790 if ($nodie) {
791 return $ok ? 1 : 0;
792 } else {
793 if ($ok) {
794 return 1;
795 } else {
796 accessforbidden('', 1, 1, 0, $params);
797 }
798 }
799 }
800
801 return 1;
802}
803
819function checkUserAccessToObject($user, array $featuresarray, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid', $parenttableforentity = '')
820{
821 global $db, $conf;
822
823 if (is_object($object)) {
824 $objectid = $object->id;
825 } else {
826 $objectid = $object; // $objectid can be X or 'X,Y,Z'
827 }
828 $objectid = preg_replace('/[^0-9\.\,]/', '', (string) $objectid); // For the case value is coming from a non sanitized user input
829
830 //dol_syslog("functions.lib:restrictedArea $feature, $object, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
831 //print "user_id=".$user->id.", features=".join(',', $featuresarray).", object=".$object;
832 //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."<br>";
833
834 // More parameters
835 $params = explode('&', $tableandshare);
836 $dbtablename = (!empty($params[0]) ? $params[0] : '');
837 $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
838
839 foreach ($featuresarray as $feature) {
840 $sql = '';
841
842 //var_dump($feature);exit;
843
844 // For backward compatibility
845 if ($feature == 'societe' && !empty($feature2) && is_array($feature2) && in_array('contact', $feature2)) {
846 $feature = 'contact';
847 $feature2 = '';
848 }
849 if ($feature == 'member') {
850 $feature = 'adherent';
851 }
852 if ($feature == 'category') {
853 $feature = 'categorie';
854 }
855 if ($feature == 'project') {
856 $feature = 'projet';
857 }
858 if ($feature == 'projet' && !empty($feature2) && is_array($feature2) && !empty(array_intersect(array('project_task', 'projet_task'), $feature2))) {
859 $feature = 'project_task';
860 }
861 if ($feature == 'task' || $feature == 'projet_task') {
862 $feature = 'project_task';
863 $dbtablename = 'projet_task';
864 }
865 if ($feature == 'eventorganization') {
866 $feature = 'agenda';
867 $dbtablename = 'actioncomm';
868 }
869 if ($feature == 'payment_sc' && empty($parenttableforentity)) {
870 // If we check perm on payment page but $parenttableforentity not defined, we force value on parent table
871 $parenttableforentity = '';
872 $dbtablename = "chargesociales";
873 $feature = "chargesociales";
874 $objectid = (string) $object->fk_charge;
875 }
876
877 $checkonentityready = 0;
878
879 // Array to define rules of checks to do
880 $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'payment', 'payment_supplier', 'payment_sc', 'payment_vat', 'payment_donation', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource', 'expensereport', 'holiday', 'salaries', 'website', 'recruitment', 'chargesociales', 'knowledgemanagement', 'stock', 'stockmovement'); // Test on entity only (Objects with no link to company)
881 $checksoc = array('societe'); // Test for object Societe
882 $checkparentsoc = array('agenda', 'contact', 'contrat', 'ticket', 'stocktransfer'); // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...).
883 $checkproject = array('projet', 'project'); // Test for project object
884 $checktask = array('projet_task', 'project_task'); // Test for task object
885 $checkhierarchy = array('expensereport', 'holiday', 'hrm'); // check permission among the hierarchy of user
886 $checkuser = array('bookmark'); // check permission among the fk_user (must be myself or null)
887 $nocheck = array('barcode', 'webhook'); // No test
888
889 //$checkdefault = 'all other not already defined'; // Test on entity + link to third party on field $dbt_keyfield. Not allowed if link is empty (Ex: invoice, orders...).
890
891 // If dbtablename not defined, we use same name for table than module name
892 if (empty($dbtablename)) {
893 $dbtablename = $feature;
894 $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
895 }
896
897 // $objectid was already sanitized at begin of this method (can be an int or a list of int separated by comma).
898 // To avoid an access forbidden with a numeric ref
899 if ($dbt_select != 'rowid' && $dbt_select != 'id') {
900 $objectid = "'".$objectid."'";
901 }
902
903 // Check permission for objectid on entity only
904 if (in_array($feature, $check) && !empty($objectid)) { // For $objectid = 0, no check
905 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
906 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
907 if (($feature == 'user' || $feature == 'usergroup') && isModEnabled('multicompany')) { // Special for multicompany
908 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
909 if ($conf->entity == 1 && $user->admin && !$user->entity) {
910 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
911 $sql .= " AND dbt.entity IS NOT NULL";
912 } else {
913 $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
914 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
915 $sql .= " AND ((ug.fk_user = dbt.rowid";
916 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
917 $sql .= " OR dbt.entity = 0)"; // Show always superadmin
918 }
919 } else {
920 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
921 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
922 }
923 } else {
924 $reg = array();
925 if ($parenttableforentity && preg_match('/(.*)@(.*)/', $parenttableforentity, $reg)) {
926 $sql .= ", ".MAIN_DB_PREFIX.$db->sanitize($reg[2])." as dbtp";
927 $sql .= " WHERE dbt.".$db->sanitize($reg[1])." = dbtp.rowid AND dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
928 $sql .= " AND dbtp.entity IN (".getEntity($sharedelement, 1).")";
929 } else {
930 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
931 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
932 }
933 }
934 $checkonentityready = 1;
935 }
936
937 if (in_array($feature, $checksoc) && !empty($objectid)) { // We check feature = checksoc. For $objectid = 0, no check
938 // If external user: Check permission for external users
939 if ($user->socid > 0) {
940 if ((string) $user->socid != $objectid) {
941 return false;
942 }
943 } elseif (isModEnabled('societe') && !$user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir')) {
944 dol_syslog("security.lib.php::checkUserAccessToObject Deny access due: (isModEnabled('societe') && !user->hasRight('societe', 'lire') && !user->hasRight('societe', 'client', 'voir'))", LOG_DEBUG);
945 return false;
946 } elseif (isModEnabled("societe") && ($user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir'))) {
947 // If internal user: Check permission for internal users that are restricted on their objects
948 $sql = "SELECT COUNT(sc.fk_soc) as nb";
949 $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
950 $sql .= ", ".MAIN_DB_PREFIX."societe as s)";
951 $sql .= " WHERE sc.fk_soc IN (".$db->sanitize($objectid, 1).")";
952 $sql .= " AND (sc.fk_user = ".((int) $user->id);
953 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
954 $userschilds = $user->getAllChildIds();
955 if (!empty($userschilds)) $sql .= " OR sc.fk_user IN (".$db->sanitize(implode(',', $userschilds)).")";
956 }
957 $sql .= ")";
958 $sql .= " AND sc.fk_soc = s.rowid";
959 $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
960 } elseif (isModEnabled('multicompany')) {
961 // If multicompany and internal users with all permissions, check user is in correct entity
962 $sql = "SELECT COUNT(s.rowid) as nb";
963 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
964 $sql .= " WHERE s.rowid IN (".$db->sanitize($objectid, 1).")";
965 $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
966 }
967
968 $checkonentityready = 1;
969 }
970 if (in_array($feature, $checkparentsoc) && !empty($objectid)) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...).
971 if ($user->socid > 0) {
972 // If external user: Check permission for external users (limtited to their company, even object with company link that is null must remain not visible)
973 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
974 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
975 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")"; // Link to third party
976 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
977 $sql .= " AND dbt.fk_soc = ".((int) $user->socid); // Third party must be user company
978 } elseif (isModEnabled("societe") && ($user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir'))) {
979 // If internal user: Check permission for internal users that are restricted on their objects
980 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
981 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
982 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
983 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
984 $sql .= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)"; // Contact not linked to a company or to a company of user
985 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
986 } elseif (isModEnabled('multicompany')) {
987 // If multicompany and internal users with all permissions, check user is in correct entity
988 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
989 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
990 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
991 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
992 }
993
994 $checkonentityready = 1;
995 }
996 if (in_array($feature, $checkproject) && !empty($objectid)) {
997 if (isModEnabled('project') && !$user->hasRight('projet', 'all', 'lire')) {
998 $projectid = $objectid; // Note that if $objectid is a string list of id; the test later will return false
999
1000 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1001 $projectstatic = new Project($db);
1002 $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
1003
1004 $tmparray = explode(',', $tmps);
1005 if (!in_array($projectid, $tmparray)) {
1006 return false;
1007 }
1008 } else {
1009 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1010 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1011 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1012 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1013 }
1014 $checkonentityready = 1;
1015 }
1016 if (in_array($feature, $checktask) && !empty($objectid)) {
1017 if (isModEnabled('project') && !$user->hasRight('projet', 'all', 'lire')) {
1018 if (preg_match('/,/', $objectid)) { // if this is a list of id
1019 return false;
1020 }
1021 $task = new Task($db);
1022 $task->fetch((int) $objectid);
1023 $projectid = $task->fk_project;
1024
1025 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1026 $projectstatic = new Project($db);
1027 $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
1028
1029 $tmparray = explode(',', $tmps);
1030 if (!in_array($projectid, $tmparray)) {
1031 return false;
1032 }
1033 } else {
1034 $sharedelement = 'project'; // for multicompany compatibility
1035 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1036 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1037 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1038 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1039 }
1040
1041 $checkonentityready = 1;
1042 }
1043 //var_dump($sql);
1044
1045 if (!$checkonentityready && !in_array($feature, $nocheck) && !empty($objectid)) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
1046 // If external user: Check permission for external users
1047 if ($user->socid > 0) {
1048 if (empty($dbt_keyfield)) {
1049 dol_print_error(null, 'Param dbt_keyfield is required but not defined');
1050 }
1051 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_keyfield).") as nb";
1052 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1053 $sql .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
1054 $sql .= " AND dbt.".$db->sanitize($dbt_keyfield)." = ".((int) $user->socid);
1055 } elseif (isModEnabled("societe") && !$user->hasRight('societe', 'client', 'voir')) {
1056 // If internal user without permission to see all thirdparties: Check permission for internal users that are restricted on their objects
1057 if (empty($dbt_keyfield)) {
1058 dol_print_error(null, 'Param dbt_keyfield is required but not defined');
1059 }
1060 if ($feature != 'ticket') {
1061 $sql = "SELECT COUNT(sc.fk_soc) as nb";
1062 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
1063 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1064 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1065 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1066 $sql .= " AND sc.fk_soc = dbt.".$db->sanitize($dbt_keyfield);
1067 $sql .= " AND (sc.fk_user = ".((int) $user->id);
1068 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
1069 $userschilds = $user->getAllChildIds();
1070 if (!empty($userschilds)) $sql .= " OR sc.fk_user IN (".$db->sanitize(implode(',', $userschilds)).")";
1071 }
1072 $sql .= ')';
1073 } else {
1074 // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties.
1075 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1076 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1077 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = dbt.".$db->sanitize($dbt_keyfield)." AND sc.fk_user = ".((int) $user->id);
1078 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1079 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1080 $sql .= " AND (sc.fk_user = ".((int) $user->id)." OR dbt.".$dbt_keyfield." IS NULL OR dbt.".$dbt_keyfield." = 0)";
1081 }
1082 } elseif (isModEnabled('multicompany') && (!empty($object->ismultientitymanaged) || !isset($object->ismultientitymanaged))) {
1083 // If multicompany, and user is an internal user with all permissions, check that object is in correct entity
1084 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1085 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
1086 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1087 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1088 }
1089 }
1090
1091 // For events, check on users assigned to event
1092 if ($feature === 'agenda' && !empty($objectid)) {
1093 // Also check owner or attendee for users without allactions->read
1094 if (!$user->hasRight('agenda', 'allactions', 'read')) {
1095 if (preg_match('/,/', $objectid)) { // if this is a list of id
1096 return false;
1097 }
1098
1099 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1100 $action = new ActionComm($db);
1101 $action->fetch((int) $objectid);
1102 if ($action->authorid != $user->id && $action->userownerid != $user->id && !(array_key_exists($user->id, $action->userassigned))) {
1103 return false;
1104 }
1105 }
1106 }
1107
1108 // For some object, we also have to check it is in the user hierarchy
1109 // Param $object must be the full object and not a simple id to have this test possible.
1110 if (in_array($feature, $checkhierarchy) && is_object($object) && !empty($objectid)) {
1111 $childids = $user->getAllChildIds(1);
1112 $useridtocheck = 0;
1113 if ($feature == 'holiday') {
1114 $useridtocheck = $object->fk_user;
1115 if (!$user->hasRight('holiday', 'readall') && !in_array($useridtocheck, $childids) && !in_array($object->fk_validator, $childids)) {
1116 return false;
1117 }
1118 }
1119 if ($feature == 'expensereport') {
1120 $useridtocheck = $object->fk_user_author;
1121 if (!$user->hasRight('expensereport', 'readall')) {
1122 if (!in_array($useridtocheck, $childids)) {
1123 return false;
1124 }
1125 }
1126 }
1127 if ($feature == 'hrm' && in_array('evaluation', $feature2)) {
1128 $useridtocheck = $object->fk_user;
1129
1130 if ($user->hasRight('hrm', 'evaluation', 'readall')) {
1131 // the user can view evaluations for anyone
1132 return true;
1133 }
1134 if (!$user->hasRight('hrm', 'evaluation', 'read')) {
1135 // the user can't view any evaluations
1136 return false;
1137 }
1138 // the user can only see their own evaluations or their subordinates'
1139 return in_array($useridtocheck, $childids);
1140 }
1141 }
1142
1143 // For some object, we also have to check it is public or owned by user
1144 // Param $object must be the full object and not a simple id to have this test possible.
1145 if (in_array($feature, $checkuser) && is_object($object) && !empty($objectid)) {
1146 $useridtocheck = $object->fk_user;
1147 if (!empty($useridtocheck) && $useridtocheck > 0 && $useridtocheck != $user->id && empty($user->admin)) {
1148 return false;
1149 }
1150 }
1151
1152 // A private contact (field priv) can only be accessed by the user that created it
1153 if ($feature == 'contact' && in_array($dbtablename, array('socpeople', 'contact')) && !empty($objectid)) {
1154 $sqlpriv = "SELECT COUNT(dbt.rowid) as nb";
1155 $sqlpriv .= " FROM ".MAIN_DB_PREFIX."socpeople as dbt";
1156 $sqlpriv .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
1157 $sqlpriv .= " AND dbt.priv = 1 AND (dbt.fk_user_creat IS NULL OR dbt.fk_user_creat <> ".((int) $user->id).")";
1158 $resqlpriv = $db->query($sqlpriv);
1159 if (!$resqlpriv) {
1160 return false;
1161 }
1162 $objpriv = $db->fetch_object($resqlpriv);
1163 if ($objpriv && $objpriv->nb > 0) {
1164 return false;
1165 }
1166 }
1167
1168 if ($sql) {
1169 $resql = $db->query($sql);
1170 if ($resql) {
1171 $obj = $db->fetch_object($resql);
1172 if (!$obj || $obj->nb < count(explode(',', $objectid))) { // error if we found 0 or less record than the nb of ids provided
1173 return false;
1174 }
1175 } else {
1176 dol_syslog("Bad forged sql in security.lib.php::checkUserAccessToObject", LOG_WARNING);
1177 return false;
1178 }
1179 }
1180 }
1181
1182 dol_syslog("security.lib.php::checkUserAccessToObject::return True", LOG_DEBUG);
1183 return true;
1184}
1185
1186
1198function httponly_accessforbidden($message = '1', $http_response_code = 403, $stringalreadysanitized = 0)
1199{
1200 top_httphead();
1201 http_response_code($http_response_code);
1202
1203 if ($stringalreadysanitized) {
1204 print $message;
1205 } else {
1206 print htmlentities($message);
1207 }
1208
1209 exit(1);
1210}
1211
1225function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
1226{
1227 global $conf, $db, $user, $langs, $hookmanager;
1228 global $action, $object;
1229
1230 if (!is_object($langs)) {
1231 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
1232 $langs = new Translate('', $conf);
1233 $langs->setDefaultLang();
1234 }
1235
1236 $langs->loadLangs(array("main", "errors"));
1237
1238 if ($printheader && !defined('NOHEADERNOFOOTER')) {
1239 if (function_exists("llxHeader")) {
1240 llxHeader('');
1241 } elseif (function_exists("llxHeaderVierge")) {
1242 llxHeaderVierge('');
1243 }
1244 print '<div style="padding: 20px">';
1245 }
1246 print '<div class="error">';
1247 if (empty($message)) {
1248 print $langs->trans("ErrorForbidden");
1249 } else {
1250 print $langs->trans($message);
1251 }
1252 print '</div>';
1253 print '<br>';
1254 if (empty($showonlymessage)) {
1255 if (empty($hookmanager)) {
1256 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1257 $hookmanager = new HookManager($db);
1258 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
1259 $hookmanager->initHooks(array('main'));
1260 }
1261
1262 $parameters = array('message' => $message, 'params' => $params);
1263 $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1264 print $hookmanager->resPrint;
1265 if (empty($reshook)) {
1266 $langs->loadLangs(array("errors"));
1267 if ($user->login) {
1268 print $langs->trans("CurrentLogin").': <span class="error">'.$user->login.'</span><br>';
1269 print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users"));
1270 print $langs->trans("ErrorForbidden4");
1271 } else {
1272 print $langs->trans("ErrorForbidden3");
1273 }
1274 }
1275 }
1276 if ($printfooter && !defined('NOHEADERNOFOOTER') && function_exists("llxFooter")) {
1277 print '</div>';
1278 llxFooter();
1279 }
1280
1281 // End PHP
1282 exit(0);
1283}
1284
1285
1293{
1294 $max = getDolGlobalString('MAIN_UPLOAD_DOC'); // In Kb
1295
1296 $maxphp = @ini_get('upload_max_filesize'); // In unknown
1297 if (preg_match('/k$/i', $maxphp)) {
1298 $maxphp = preg_replace('/k$/i', '', $maxphp);
1299 $maxphp = (int) ((float) $maxphp * 1);
1300 }
1301 if (preg_match('/m$/i', $maxphp)) {
1302 $maxphp = preg_replace('/m$/i', '', $maxphp);
1303 $maxphp = (int) ((float) $maxphp * 1024);
1304 }
1305 if (preg_match('/g$/i', $maxphp)) {
1306 $maxphp = preg_replace('/g$/i', '', $maxphp);
1307 $maxphp = (int) ((float) $maxphp * 1024 * 1024);
1308 }
1309 if (preg_match('/t$/i', $maxphp)) {
1310 $maxphp = preg_replace('/t$/i', '', $maxphp);
1311 $maxphp = (int) ((float) $maxphp * 1024 * 1024 * 1024);
1312 }
1313 $maxphp2 = @ini_get('post_max_size'); // In unknown
1314 if (preg_match('/k$/i', $maxphp2)) {
1315 $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
1316 $maxphp2 = (int) ((float) $maxphp2) * 1;
1317 }
1318 if (preg_match('/m$/i', $maxphp2)) {
1319 $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
1320 $maxphp2 = (int) ((float) $maxphp2 * 1024);
1321 }
1322 if (preg_match('/g$/i', $maxphp2)) {
1323 $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
1324 $maxphp2 = (int) ((float) $maxphp2 * 1024 * 1024);
1325 }
1326 if (preg_match('/t$/i', $maxphp2)) {
1327 $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
1328 $maxphp2 = (int) ((float) $maxphp2 * 1024 * 1024 * 1024);
1329 }
1330 // Now $max and $maxphp and $maxphp2 are in Kb
1331 $maxmin = $max;
1332 $maxphptoshow = $maxphptoshowparam = '';
1333 if ($maxphp > 0) {
1334 $maxmin = min($maxmin, $maxphp);
1335 $maxphptoshow = $maxphp;
1336 $maxphptoshowparam = 'upload_max_filesize';
1337 }
1338 if ($maxphp2 > 0) {
1339 $maxmin = min($maxmin, $maxphp2);
1340 if ($maxphp2 < $maxphp) {
1341 $maxphptoshow = $maxphp2;
1342 $maxphptoshowparam = 'post_max_size';
1343 }
1344 }
1345 //var_dump($maxphp.'-'.$maxphp2);
1346 //var_dump($maxmin);
1347
1348 return array('max' => $max, 'maxmin' => $maxmin, 'maxphptoshow' => $maxphptoshow, 'maxphptoshowparam' => $maxphptoshowparam);
1349}
1350
1358function checkIPInCidr($ip, $cidr)
1359{
1360 list($network, $prefix) = explode('/', $cidr, 2);
1361
1362 // Convert IPs to binary format
1363 $ip_bin = @inet_pton($ip);
1364 $net_bin = @inet_pton($network);
1365 if ($ip_bin === false || $net_bin === false) {
1366 return -1;
1367 }
1368
1369 // Require same address IPvX family
1370 if (strlen($ip_bin) !== strlen($net_bin)) {
1371 return -1;
1372 }
1373
1374 // Comparison boundaries
1375 $total_bits = strlen($ip_bin) * 8;
1376 $prefix = max(0, min((int) $prefix, $total_bits));
1377 $full_bytes = intdiv($prefix, 8);
1378 $rem_bits = $prefix % 8;
1379
1380 // Compare full bytes and partial bytes
1381 if ($full_bytes > 0) {
1382 if (substr($ip_bin, 0, $full_bytes) !== substr($net_bin, 0, $full_bytes)) {
1383 return 0;
1384 }
1385 }
1386 if ($rem_bits > 0) {
1387 $mask = (0xFF << (8 - $rem_bits)) & 0xFF;
1388 $ip_byte = ord($ip_bin[$full_bytes]);
1389 $net_byte = ord($net_bin[$full_bytes]);
1390 if (($ip_byte & $mask) !== ($net_byte & $mask)) {
1391 return 0;
1392 }
1393 }
1394 return 1;
1395}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!defined( 'NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined( 'NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) if(!defined( 'NOLOGIN')) if(!defined('NOCSRFCHECK')) if(!defined( 'NOIPCHECK')) llxHeaderVierge($title, $head="", $disablejs=0, $disablehead=0, $arrayofjs=[], $arrayofcss=[], $ws='')
Header function.
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage agenda events (actions)
Class to manage hooks.
Class to manage projects.
Class to manage tasks.
Class to manage translations.
Class to manage Dolibarr users.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
dolGetRandomBytes($length)
Return a string of random bytes (hexa string) with length = $length for cryptographic purposes.
httponly_accessforbidden($message='1', $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.
dol_encode($chain, $key='1')
Encode a string with base 64 algorithm + specific delta change.
checkUserAccessToObject($user, array $featuresarray, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid', $parenttableforentity='')
Check that access by a given user to an object is ok.
checkIPInCidr($ip, $cidr)
Check if IP address is in CIDR range.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
getMaxFileSizeArray()
Return the max allowed for file upload.
dol_decode($chain, $key='1')
Decode a base 64 encoded + specific delta change.
dolGetLdapPasswordHash($password, $type='md5')
Returns a specific ldap hash of a password.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.