dolibarr 25.0.0-alpha
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, $mode = 0)
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 // Fix syntax of $features param to support non standard module names.
206 // @todo : use elseif ?
207 $originalfeatures = $features;
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 == 'facturerec') {
215 $features = 'facture';
216 } elseif ($features == 'supplier_invoicerec') {
217 $features = 'fournisseur';
218 $feature2 = 'facture';
219 } elseif ($features == 'mo') {
220 $features = 'mrp';
221 } elseif ($features == 'member') {
222 $features = 'adherent';
223 } elseif ($features == 'subscription') {
224 $features = 'adherent';
225 $feature2 = 'cotisation';
226 } elseif ($features == 'website' && is_object($object) && $object->element == 'websitepage') {
227 $parentfortableentity = 'fk_website@website';
228 } elseif ($features == 'project') {
229 $features = 'projet';
230 } elseif ($features == 'eventorganization' && is_object($object) && $object->element == 'conferenceorbooth') {
231 // The module of an event organization declares no permission of its own, on purpose, so a check on
232 // 'eventorganization' is refused to everyone, an administrator included. Check the parent project
233 // instead, which is what the card of the object does itself.
234 // The card refuses an external user before that check, and fk_project is nullable, so we must refuse
235 // both cases here too: with no parent project there is nothing left to check the access on, and
236 // granting it would be an access with no check at all.
237 if (!empty($user->socid) || empty($object->fk_project)) {
238 if ($mode) {
239 return 0;
240 } else {
242 }
243 }
244 $features = 'projet';
245 $tableandshare = 'projet&project';
246 $objectid = (int) $object->fk_project;
247 $object = $objectid;
248 } elseif ($features == 'product') {
249 $features = 'produit';
250 } elseif ($features == 'productbatch') {
251 $features = 'produit';
252 } elseif ($features == 'tax') {
253 $feature2 = 'charges';
254 } elseif ($features == 'workstation') {
255 $feature2 = 'workstation';
256 } elseif ($features == 'hrm' && is_object($object) && in_array($object->element, array('job', 'position', 'skill'))) {
257 $feature2 = 'all'; // These 3 objects have no permission of their own, they share the level "all"
258 } elseif ($features == 'stocktransfer' && is_object($object) && $object->element == 'stocktransfer') {
259 $feature2 = 'stocktransfer'; // This module declares no permission at its first level, only this one
260 } elseif ($features == 'fournisseur') { // When vendor invoice and purchase order are into module 'fournisseur'
261 if (is_object($object) && $object->element == 'invoice_supplier') {
262 $feature2 = 'facture';
263 } elseif (is_object($object) && $object->element == 'order_supplier') {
264 $feature2 = 'commande';
265 }
266 } elseif ($features == 'payment_sc') {
267 $tableandshare = 'paiementcharge';
268 $parentfortableentity = 'fk_charge@chargesociales';
269 }
270
271 // if commonObjectLine : Using many2one related commonObject
272 // @see commonObjectLine::parentElement
273 if (in_array($features, ['commandedet', 'propaldet', 'facturedet', 'supplier_proposaldet', 'evaluationdet', 'skilldet', 'deliverydet', 'contratdet'])) {
274 $features = substr($features, 0, -3);
275 } elseif (in_array($features, ['stocktransferline', 'inventoryline', 'bomline', 'expensereport_det', 'facture_fourn_det'])) {
276 $features = substr($features, 0, -4);
277 } elseif ($features == 'commandefournisseurdispatch') {
278 $features = 'commandefournisseur';
279 } elseif ($features == 'invoice_supplier_det_rec') {
280 $features = 'invoice_supplier_rec';
281 }
282 if ($features == 'evaluation') {
283 $features = 'hrm';
284 $feature2 = 'evaluation';
285 }
286
287 // When the object is a task (element='project_task') and $feature2 is empty,
288 // $checkUserAccessToObject() falls into the $checkproject path and uses the task ID
289 // as project ID, which always fails. Setting $feature2='project_task' triggers the
290 // normalization at line 974 that redirects to the $checktask path, which correctly
291 // resolves $task->fk_project before calling getProjectsAuthorizedForUser().
292 if (is_object($object) && in_array($object->element, array('project_task', 'task'))
293 && (empty($features) || in_array($features, array('projet', 'project')))
294 && empty($feature2)) {
295 $features = 'projet';
296 $feature2 = 'project_task';
297 if (empty($tableandshare)) {
298 $tableandshare = 'projet_task';
299 }
300 }
301
302 // print $features.' - '.$tableandshare.' - '.$feature2.' - '.$dbt_select."\n";
303
304 // Get more permissions checks from hooks
305 $parameters = array(
306 'features' => $features,
307 'feature2' => $feature2,
308 'originalfeatures' => $originalfeatures,
309 'tableandshare' => $tableandshare,
310 'object' => $object,
311 'objectid' => $objectid,
312 'dbt_keyfield' => $dbt_keyfield,
313 'dbt_select' => $dbt_select,
314 'idtype' => $dbt_select,
315 'isdraft' => $isdraft,
316 'mode' => $mode,
317 );
318 if (!empty($hookmanager)) {
319 $reshook = $hookmanager->executeHooks('restrictedArea', $parameters);
320
321 if (isset($hookmanager->resArray['result'])) {
322 if ($hookmanager->resArray['result'] == 0) {
323 if ($mode) {
324 return 0;
325 } else {
326 accessforbidden(); // Module returns 0, so access forbidden
327 }
328 }
329 }
330 if ($reshook > 0) { // No other test done.
331 return 1;
332 }
333 }
334
335 // Features/modules to check (to support the & and | operator)
336 $featuresarray = array($features);
337 if (preg_match('/&/', $features)) {
338 $featuresarray = explode("&", $features);
339 } elseif (preg_match('/\|/', $features)) {
340 $featuresarray = explode("|", $features);
341 }
342
343 // More subfeatures to check
344 if (!empty($feature2)) {
345 $feature2 = explode("|", $feature2);
346 }
347
348 $listofmodules = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL'));
349
350 // Check read permission from module
351 $readok = 1;
352 $nbko = 0;
353 foreach ($featuresarray as $feature) { // first we check nb of test ko
354 $featureforlistofmodule = $feature;
355 if ($featureforlistofmodule == 'produit') {
356 $featureforlistofmodule = 'product';
357 }
358 if ($featureforlistofmodule == 'supplier_proposal') {
359 $featureforlistofmodule = 'supplierproposal';
360 }
361 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
362 $readok = 0;
363 $nbko++;
364 continue;
365 }
366
367 if ($feature == 'societe' && (empty($feature2) || !in_array('contact', $feature2))) {
368 if (!$user->hasRight('societe', 'lire') && !$user->hasRight('fournisseur', 'lire')) {
369 $readok = 0;
370 $nbko++;
371 }
372 } elseif (($feature == 'societe' && (!empty($feature2) && in_array('contact', $feature2))) || $feature == 'contact') {
373 if (!$user->hasRight('societe', 'contact', 'lire')) {
374 $readok = 0;
375 $nbko++;
376 }
377 } elseif ($feature == 'produit|service') {
378 if (!$user->hasRight('produit', 'lire') && !$user->hasRight('service', 'lire')) {
379 $readok = 0;
380 $nbko++;
381 }
382 } elseif ($feature == 'prelevement') {
383 if (!$user->hasRight('prelevement', 'bons', 'lire')) {
384 $readok = 0;
385 $nbko++;
386 }
387 } elseif ($feature == 'cheque') {
388 if (!$user->hasRight('banque', 'cheque')) {
389 $readok = 0;
390 $nbko++;
391 }
392 } elseif ($feature == 'projet') {
393 if (!$user->hasRight('projet', 'lire') && !$user->hasRight('projet', 'all', 'lire')) {
394 $readok = 0;
395 $nbko++;
396 }
397 } elseif ($feature == 'payment') {
398 if (!$user->hasRight('facture', 'lire')) {
399 $readok = 0;
400 $nbko++;
401 }
402 } elseif ($feature == 'payment_supplier') {
403 if (!$user->hasRight('fournisseur', 'facture', 'lire')) {
404 $readok = 0;
405 $nbko++;
406 }
407 } elseif ($feature == 'payment_sc') {
408 if (!$user->hasRight('tax', 'charges', 'lire')) {
409 $readok = 0;
410 $nbko++;
411 }
412 } elseif ($feature == 'webhook') {
413 if (empty($user->admin)) {
414 $readok = 0;
415 $nbko++;
416 }
417 } elseif (!empty($feature2)) { // This is for permissions on 2 levels (module->object->read)
418 $tmpreadok = 1;
419 foreach ($feature2 as $subfeature) {
420 if ($subfeature == 'user' && $user->id == $objectid) {
421 continue; // A user can always read its own card
422 }
423 if ($subfeature == 'fiscalyear' && $user->hasRight('accounting', 'fiscalyear', 'write')) {
424 // only one right for fiscalyear
425 $tmpreadok = 1;
426 continue;
427 }
428 if (!empty($subfeature) && !$user->hasRight($feature, $subfeature, 'lire') && !$user->hasRight($feature, $subfeature, 'read')) {
429 $tmpreadok = 0;
430 } elseif (empty($subfeature) && !$user->hasRight($feature, 'lire') && !$user->hasRight($feature, 'read')) {
431 $tmpreadok = 0;
432 } else {
433 $tmpreadok = 1;
434 break;
435 } // Break is to bypass second test if the first is ok
436 }
437 if (!$tmpreadok) { // We found a test on feature that is ko
438 $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko).
439 $nbko++;
440 }
441 } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level (module->read)
442 if (!$user->hasRight($feature, 'lire')
443 && !$user->hasRight($feature, 'read')
444 && !$user->hasRight($feature, 'run')) {
445 $readok = 0;
446 $nbko++;
447 }
448 }
449 }
450
451 // If a or and at least one ok
452 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
453 $readok = 1;
454 }
455
456 if (!$readok) {
457 if ($mode) {
458 return 0;
459 } else {
461 }
462 }
463 //print "Read access is ok";
464
465 // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files)
466 $createok = 1;
467 $nbko = 0;
468 $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));
469 $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
470
471 if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) {
472 foreach ($featuresarray as $feature) {
473 if ($feature == 'contact') {
474 if (!$user->hasRight('societe', 'contact', 'creer')) {
475 $createok = 0;
476 $nbko++;
477 }
478 } elseif ($feature == 'produit|service') {
479 if (!$user->hasRight('produit', 'creer') && !$user->hasRight('service', 'creer')) {
480 $createok = 0;
481 $nbko++;
482 }
483 } elseif ($feature == 'prelevement') {
484 if (!$user->hasRight('prelevement', 'bons', 'creer')) {
485 $createok = 0;
486 $nbko++;
487 }
488 } elseif ($feature == 'commande_fournisseur') {
489 if (!$user->hasRight('fournisseur', 'commande', 'creer') || !$user->hasRight('supplier_order', 'creer')) {
490 $createok = 0;
491 $nbko++;
492 }
493 } elseif ($feature == 'banque') {
494 if (!$user->hasRight('banque', 'modifier')) {
495 $createok = 0;
496 $nbko++;
497 }
498 } elseif ($feature == 'cheque') {
499 if (!$user->hasRight('banque', 'cheque')) {
500 $createok = 0;
501 $nbko++;
502 }
503 } elseif ($feature == 'import') {
504 if (!$user->hasRight('import', 'run')) {
505 $createok = 0;
506 $nbko++;
507 }
508 } elseif ($feature == 'ecm') {
509 if (!$user->hasRight('ecm', 'upload')) {
510 $createok = 0;
511 $nbko++;
512 }
513 } elseif ($feature == 'modulebuilder') {
514 if (!$user->hasRight('modulebuilder', 'run')) {
515 $createok = 0;
516 $nbko++;
517 }
518 } elseif ($feature == 'payment') {
519 if (!$user->hasRight('facture', 'paiement')) {
520 $createok = 0;
521 $nbko++;
522 }
523 } elseif ($feature == 'payment_supplier') { // Permission to write on a payment of an invoice is permission to edit an invoice.
524 if (!$user->hasRight('fournisseur', 'facture', 'creer')) {
525 $createok = 0;
526 $nbko++;
527 }
528 } elseif ($feature == 'webhook') {
529 if (empty($user->admin)) {
530 $createok = 0;
531 $nbko++;
532 }
533 } elseif (!empty($feature2)) { // This is for permissions on 2 levels (module->object->write)
534 foreach ($feature2 as $subfeature) {
535 if ($subfeature == 'user' && $user->id == $objectid && $user->hasRight('user', 'self', 'creer')) {
536 continue; // User can edit its own card
537 }
538 if ($subfeature == 'user' && $user->id == $objectid && $user->hasRight('user', 'self', 'password')) {
539 continue; // User can edit its own password
540 }
541 if ($subfeature == 'user' && $user->id != $objectid && $user->hasRight('user', 'user', 'password')) {
542 continue; // User can edit another user's password
543 }
544
545 if (!$user->hasRight($feature, $subfeature, 'creer')
546 && !$user->hasRight($feature, $subfeature, 'write')
547 && !$user->hasRight($feature, $subfeature, 'create')) {
548 $createok = 0;
549 $nbko++;
550 } else {
551 $createok = 1;
552 // Break to bypass second test if the first is ok
553 break;
554 }
555 }
556 } elseif (!empty($feature)) { // This is for permissions on 1 levels (module->write)
557 //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; exit;
558 if (!$user->hasRight($feature, 'creer')
559 && !$user->hasRight($feature, 'write')
560 && !$user->hasRight($feature, 'create')) {
561 $createok = 0;
562 $nbko++;
563 }
564 }
565 }
566
567 // If a or and at least one ok
568 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
569 $createok = 1;
570 }
571
572 if ($wemustcheckpermissionforcreate && !$createok) {
573 if ($mode) {
574 return 0;
575 } else {
577 }
578 }
579 //print "Write access is ok";
580 }
581
582 // Check create user permission
583 $createuserok = 1;
584 if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') {
585 if (!$user->hasRight('user', 'user', 'creer')) {
586 $createuserok = 0;
587 }
588
589 if (!$createuserok) {
590 if ($mode) {
591 return 0;
592 } else {
594 }
595 }
596 //print "Create user access is ok";
597 }
598
599 // Check delete permission from module
600 $deleteok = 1;
601 $nbko = 0;
602 if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') {
603 foreach ($featuresarray as $feature) {
604 if ($feature == 'bookmark') {
605 if (!$user->hasRight('bookmark', 'supprimer')) {
606 if ($user->id != $object->fk_user || !$user->hasRight('bookmark', 'creer')) {
607 $deleteok = 0;
608 }
609 }
610 } elseif ($feature == 'contact') {
611 if (!$user->hasRight('societe', 'contact', 'supprimer')) {
612 $deleteok = 0;
613 }
614 } elseif ($feature == 'produit|service') {
615 if (!$user->hasRight('produit', 'supprimer') && !$user->hasRight('service', 'supprimer')) {
616 $deleteok = 0;
617 }
618 } elseif ($feature == 'commande_fournisseur') {
619 if (!$user->hasRight('fournisseur', 'commande', 'supprimer')) {
620 $deleteok = 0;
621 }
622 } elseif ($feature == 'payment_supplier') { // Permission to delete a payment of an invoice is permission to edit an invoice.
623 if (!$user->hasRight('fournisseur', 'facture', 'creer')) {
624 $deleteok = 0;
625 }
626 } elseif ($feature == 'payment') {
627 if (!$user->hasRight('facture', 'paiement')) {
628 $deleteok = 0;
629 }
630 } elseif ($feature == 'payment_sc') {
631 if (!$user->hasRight('tax', 'charges', 'creer')) {
632 $deleteok = 0;
633 }
634 } elseif ($feature == 'banque') {
635 if (!$user->hasRight('banque', 'modifier')) {
636 $deleteok = 0;
637 }
638 } elseif ($feature == 'cheque') {
639 if (!$user->hasRight('banque', 'cheque')) {
640 $deleteok = 0;
641 }
642 } elseif ($feature == 'ecm') {
643 if (!$user->hasRight('ecm', 'upload')) {
644 $deleteok = 0;
645 }
646 } elseif ($feature == 'ftp') {
647 if (!$user->hasRight('ftp', 'write')) {
648 $deleteok = 0;
649 }
650 } elseif ($feature == 'salaries') {
651 if (!$user->hasRight('salaries', 'delete')) {
652 $deleteok = 0;
653 }
654 } elseif ($feature == 'adherent') {
655 if (!$user->hasRight('adherent', 'supprimer')) {
656 $deleteok = 0;
657 }
658 } elseif ($feature == 'paymentbybanktransfer') {
659 if (!$user->hasRight('paymentbybanktransfer', 'create')) { // There is no delete permission
660 $deleteok = 0;
661 }
662 } elseif ($feature == 'prelevement') {
663 if (!$user->hasRight('prelevement', 'bons', 'creer')) { // There is no delete permission
664 $deleteok = 0;
665 }
666 } elseif (!empty($feature2)) { // This is for permissions on 2 levels
667 foreach ($feature2 as $subfeature) {
668 if (!$user->hasRight($feature, $subfeature, 'supprimer') && !$user->hasRight($feature, $subfeature, 'delete')) {
669 $deleteok = 0;
670 } else {
671 $deleteok = 1;
672 break;
673 } // For bypass the second test if the first is ok
674 }
675 } elseif (!empty($feature)) { // This is used for permissions on 1 level
676 //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
677 if (!$user->hasRight($feature, 'supprimer')
678 && !$user->hasRight($feature, 'delete')
679 && !$user->hasRight($feature, 'run')) {
680 $deleteok = 0;
681 }
682 }
683 }
684
685 // If a or and at least one ok
686 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
687 $deleteok = 1;
688 }
689
690 if (!$deleteok && !($isdraft && $createok)) {
691 if ($mode) {
692 return 0;
693 } else {
695 }
696 }
697 //print "Delete access is ok";
698 }
699
700 // If we have a particular object to check permissions on, we check if $user has permission
701 // for this given object (link to company, is contact for project, ...)
702 if (!empty($objectid) && $objectid > 0) {
703 $ok = checkUserAccessToObject($user, $featuresarray, $object, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity);
704 $params = array('objectid' => $objectid, 'features' => implode(',', $featuresarray), 'features2' => $feature2);
705 //print 'checkUserAccessToObject ok='.$ok;
706 if ($mode) {
707 return $ok ? 1 : 0;
708 } else {
709 if ($ok) {
710 return 1;
711 } else {
712 accessforbidden('', 1, 1, 0, $params);
713 }
714 }
715 }
716
717 return 1;
718}
719
735function checkUserAccessToObject($user, array $featuresarray, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid', $parenttableforentity = '')
736{
737 global $db, $conf;
738
739 if (is_object($object)) {
740 $objectid = $object->id;
741 } else {
742 $objectid = $object; // $objectid can be X or 'X,Y,Z'
743 }
744 $objectid = preg_replace('/[^0-9\.\,]/', '', (string) $objectid); // For the case value is coming from a non sanitized user input
745
746 //dol_syslog("functions.lib:restrictedArea $feature, $object, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
747 //print "user_id=".$user->id.", features=".join(',', $featuresarray).", object=".$object;
748 //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."<br>";
749
750 // More parameters
751 $params = explode('&', $tableandshare);
752 $dbtablename = (!empty($params[0]) ? $params[0] : '');
753 $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
754
755 foreach ($featuresarray as $feature) {
756 $sql = '';
757
758 //var_dump($feature);exit;
759
760 // For backward compatibility
761 if ($feature == 'societe' && !empty($feature2) && is_array($feature2) && in_array('contact', $feature2)) {
762 $feature = 'contact';
763 $feature2 = '';
764 }
765 if ($feature == 'member') {
766 $feature = 'adherent';
767 }
768 if ($feature == 'category') {
769 $feature = 'categorie';
770 }
771 if ($feature == 'project') {
772 $feature = 'projet';
773 }
774 if ($feature == 'projet' && !empty($feature2) && is_array($feature2) && !empty(array_intersect(array('project_task', 'projet_task'), $feature2))) {
775 $feature = 'project_task';
776 }
777 if ($feature == 'task' || $feature == 'projet_task') {
778 $feature = 'project_task';
779 $dbtablename = 'projet_task';
780 }
781 if ($feature == 'eventorganization') {
782 $feature = 'agenda';
783 $dbtablename = 'actioncomm';
784 }
785 if ($feature == 'payment_sc' && empty($parenttableforentity)) {
786 // If we check perm on payment page but $parenttableforentity not defined, we force value on parent table
787 $parenttableforentity = '';
788 $dbtablename = "chargesociales";
789 $feature = "chargesociales";
790 $objectid = (string) $object->fk_charge;
791 }
792
793 $checkonentitydone = 0;
794
795 // Array to define rules of checks to do
796 $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'payment', 'payment_supplier', 'payment_sc', '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)
797 $checksoc = array('societe'); // Test for object Societe
798 $checkparentsoc = array('agenda', 'contact', 'contrat'); // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...).
799 $checkproject = array('projet', 'project'); // Test for project object
800 $checktask = array('projet_task', 'project_task'); // Test for task object
801 $checkhierarchy = array('expensereport', 'holiday', 'hrm'); // check permission among the hierarchy of user
802 $checkuser = array('bookmark'); // check permission among the fk_user (must be myself or null)
803 $nocheck = array('barcode', 'webhook'); // No test
804
805 //$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...).
806
807 // If dbtablename not defined, we use same name for table than module name
808 if (empty($dbtablename)) {
809 $dbtablename = $feature;
810 $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
811 }
812
813 // The default rule reads the columns entity and $dbt_keyfield of the table, but some tables own neither of
814 // them. The sql was then built on columns that do not exist, so it always failed and the access was refused
815 // to the users that this rule applies to.
816 // The rule is selected on the table and not on the element of the object, because $object is an id and not
817 // an object for most of the callers, the card of an asset and the card of a workstation included.
818 if (!empty($objectid) && in_array($dbtablename, array('asset', 'paiement', 'paiementfourn', 'workstation_workstation', 'hrm_job', 'hrm_job_user', 'hrm_skill'))) {
819 // None of these objects is linked to a third party, so an external user can own none of them. The
820 // default rule refused him through a link that does not exist, we must refuse him explicitly instead,
821 // otherwise the rules below, which do not look at the third party of the user at all, would grant it.
822 if (!empty($user->socid)) {
823 return false;
824 }
825 if (in_array($dbtablename, array('hrm_job', 'hrm_job_user', 'hrm_skill'))) {
826 // These 3 tables have no entity column either, so no rule that reads the table can be run on them.
827 // The permission is still checked by restrictedArea(), and the $checkhierarchy rule below still runs.
828 // Note that these 3 objects are therefore not partitioned between entities at all, in the database
829 // itself: their cards already answer to a user of another entity, and their lists already show the
830 // records of all of them. This rule does not widen that, it aligns with it.
831 $nocheck[] = $feature;
832 } else {
833 $check[] = $feature; // Test on the entity only, there is no third party to restrict on
834 }
835 }
836
837 // $objectid was already sanitized at begin of this method (can be an int or a list of int separated by comma).
838 // To avoid an access forbidden with a numeric ref
839 if ($dbt_select != 'rowid' && $dbt_select != 'id') {
840 $objectid = "'".$objectid."'";
841 }
842
843 // Check permission for objectid on entity only
844 if (in_array($feature, $check) && !empty($objectid)) { // For $objectid = 0, no check
845 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
846 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
847 if (($feature == 'user' || $feature == 'usergroup') && isModEnabled('multicompany')) { // Special for multicompany
848 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
849 if ($conf->entity == 1 && $user->admin && !$user->entity) {
850 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
851 $sql .= " AND dbt.entity IS NOT NULL";
852 } else {
853 $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
854 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
855 $sql .= " AND ((ug.fk_user = dbt.rowid";
856 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
857 $sql .= " OR dbt.entity = 0)"; // Show always superadmin
858 }
859 } else {
860 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
861 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
862 }
863 } else {
864 $reg = array();
865 if ($parenttableforentity && preg_match('/(.*)@(.*)/', $parenttableforentity, $reg)) {
866 $sql .= ", ".MAIN_DB_PREFIX.$db->sanitize($reg[2])." as dbtp";
867 $sql .= " WHERE dbt.".$db->sanitize($reg[1])." = dbtp.rowid AND dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
868 $sql .= " AND dbtp.entity IN (".getEntity($sharedelement, 1).")";
869 } else {
870 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
871 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
872 }
873 }
874 $checkonentitydone = 1;
875 }
876
877 if (in_array($feature, $checksoc) && !empty($objectid)) { // We check feature = checksoc. For $objectid = 0, no check
878 // If external user: Check permission for external users
879 if ($user->socid > 0) {
880 if ((string) $user->socid != $objectid) {
881 return false;
882 }
883 } elseif (isModEnabled('societe') && !$user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir')) {
884 dol_syslog("security.lib.php::checkUserAccessToObject Deny access due: (isModEnabled('societe') && !user->hasRight('societe', 'lire') && !user->hasRight('societe', 'client', 'voir'))", LOG_DEBUG);
885 return false;
886 } elseif (isModEnabled("societe") && ($user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir'))) {
887 // If internal user: Check permission for internal users that are restricted on their objects
888 $sql = "SELECT COUNT(sc.fk_soc) as nb";
889 $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
890 $sql .= ", ".MAIN_DB_PREFIX."societe as s)";
891 $sql .= " WHERE sc.fk_soc IN (".$db->sanitize($objectid, 1).")";
892 $sql .= " AND (sc.fk_user = ".((int) $user->id);
893 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
894 $userschilds = $user->getAllChildIds();
895 if (!empty($userschilds)) $sql .= " OR sc.fk_user IN (".$db->sanitize(implode(',', $userschilds)).")";
896 }
897 $sql .= ")";
898 $sql .= " AND sc.fk_soc = s.rowid";
899 $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
900 } elseif (isModEnabled('multicompany')) {
901 // If multicompany and internal users with all permissions, check user is in correct entity
902 $sql = "SELECT COUNT(s.rowid) as nb";
903 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
904 $sql .= " WHERE s.rowid IN (".$db->sanitize($objectid, 1).")";
905 $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
906 }
907
908 $checkonentitydone = 1;
909 }
910 if (in_array($feature, $checkparentsoc) && !empty($objectid)) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...).
911 // If external user: Check permission for external users
912 if ($user->socid > 0) {
913 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
914 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
915 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
916 $sql .= " AND dbt.fk_soc = ".((int) $user->socid);
917 } elseif (isModEnabled("societe") && ($user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir'))) {
918 // If internal user: Check permission for internal users that are restricted on their objects
919 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
920 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
921 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
922 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
923 $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
924 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
925 } elseif (isModEnabled('multicompany')) {
926 // If multicompany and internal users with all permissions, check user is in correct entity
927 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
928 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
929 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
930 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
931 }
932
933 $checkonentitydone = 1;
934 }
935 if (in_array($feature, $checkproject) && !empty($objectid)) {
936 if (isModEnabled('project') && !$user->hasRight('projet', 'all', 'lire')) {
937 $projectid = $objectid; // Note that if $objectid is a string list of id; the test later will return false
938
939 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
940 $projectstatic = new Project($db);
941 $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
942
943 $tmparray = explode(',', $tmps);
944 if (!in_array($projectid, $tmparray)) {
945 return false;
946 }
947 } else {
948 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
949 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
950 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
951 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
952 }
953 $checkonentitydone = 1;
954 }
955 if (in_array($feature, $checktask) && !empty($objectid)) {
956 if (isModEnabled('project') && !$user->hasRight('projet', 'all', 'lire')) {
957 if (preg_match('/,/', $objectid)) { // if this is a list of id
958 return false;
959 }
960 $task = new Task($db);
961 $task->fetch((int) $objectid);
962 $projectid = $task->fk_project;
963
964 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
965 $projectstatic = new Project($db);
966 $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
967
968 $tmparray = explode(',', $tmps);
969 if (!in_array($projectid, $tmparray)) {
970 return false;
971 }
972 } else {
973 $sharedelement = 'project'; // for multicompany compatibility
974 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
975 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
976 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
977 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
978 }
979
980 $checkonentitydone = 1;
981 }
982 //var_dump($sql);
983
984 if (!$checkonentitydone && !in_array($feature, $nocheck) && !empty($objectid)) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
985 // If external user: Check permission for external users
986 if ($user->socid > 0) {
987 if (empty($dbt_keyfield)) {
988 dol_print_error(null, 'Param dbt_keyfield is required but not defined');
989 }
990 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_keyfield).") as nb";
991 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
992 $sql .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
993 $sql .= " AND dbt.".$db->sanitize($dbt_keyfield)." = ".((int) $user->socid);
994 } elseif (isModEnabled("societe") && !$user->hasRight('societe', 'client', 'voir')) {
995 // If internal user without permission to see all thirdparties: Check permission for internal users that are restricted on their objects
996 if (empty($dbt_keyfield)) {
997 dol_print_error(null, 'Param dbt_keyfield is required but not defined');
998 }
999 if ($feature != 'ticket') {
1000 $sql = "SELECT COUNT(sc.fk_soc) as nb";
1001 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
1002 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1003 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1004 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1005 $sql .= " AND sc.fk_soc = dbt.".$db->sanitize($dbt_keyfield);
1006 $sql .= " AND (sc.fk_user = ".((int) $user->id);
1007 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
1008 $userschilds = $user->getAllChildIds();
1009 if (!empty($userschilds)) $sql .= " OR sc.fk_user IN (".$db->sanitize(implode(',', $userschilds)).")";
1010 }
1011 $sql .= ')';
1012 } else {
1013 // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties.
1014 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1015 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1016 $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);
1017 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1018 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1019 $sql .= " AND (sc.fk_user = ".((int) $user->id)." OR dbt.".$dbt_keyfield." IS NULL OR dbt.".$dbt_keyfield." = 0)";
1020 }
1021 } elseif (isModEnabled('multicompany') && (!empty($object->ismultientitymanaged) || !isset($object->ismultientitymanaged))) {
1022 // If multicompany, and user is an internal user with all permissions, check that object is in correct entity
1023 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1024 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
1025 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1026 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1027 }
1028 }
1029
1030 // For events, check on users assigned to event
1031 if ($feature === 'agenda' && !empty($objectid)) {
1032 // Also check owner or attendee for users without allactions->read
1033 if (!$user->hasRight('agenda', 'allactions', 'read')) {
1034 if (preg_match('/,/', $objectid)) { // if this is a list of id
1035 return false;
1036 }
1037
1038 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1039 $action = new ActionComm($db);
1040 $action->fetch((int) $objectid);
1041 if ($action->authorid != $user->id && $action->userownerid != $user->id && !(array_key_exists($user->id, $action->userassigned))) {
1042 return false;
1043 }
1044 }
1045 }
1046
1047 // For some object, we also have to check it is in the user hierarchy
1048 // Param $object must be the full object and not a simple id to have this test possible.
1049 if (in_array($feature, $checkhierarchy) && is_object($object) && !empty($objectid)) {
1050 $childids = $user->getAllChildIds(1);
1051 $useridtocheck = 0;
1052 if ($feature == 'holiday') {
1053 $useridtocheck = $object->fk_user;
1054 if (!$user->hasRight('holiday', 'readall') && !in_array($useridtocheck, $childids) && !in_array($object->fk_validator, $childids)) {
1055 return false;
1056 }
1057 }
1058 if ($feature == 'expensereport') {
1059 $useridtocheck = $object->fk_user_author;
1060 if (!$user->hasRight('expensereport', 'readall')) {
1061 if (!in_array($useridtocheck, $childids)) {
1062 return false;
1063 }
1064 }
1065 }
1066 if ($feature == 'hrm' && in_array('evaluation', $feature2)) {
1067 $useridtocheck = $object->fk_user;
1068
1069 if ($user->hasRight('hrm', 'evaluation', 'readall')) {
1070 // the user can view evaluations for anyone
1071 return true;
1072 }
1073 if (!$user->hasRight('hrm', 'evaluation', 'read')) {
1074 // the user can't view any evaluations
1075 return false;
1076 }
1077 // the user can only see their own evaluations or their subordinates'
1078 return in_array($useridtocheck, $childids);
1079 }
1080 }
1081
1082 // For some object, we also have to check it is public or owned by user
1083 // Param $object must be the full object and not a simple id to have this test possible.
1084 if (in_array($feature, $checkuser) && is_object($object) && !empty($objectid)) {
1085 $useridtocheck = $object->fk_user;
1086 if (!empty($useridtocheck) && $useridtocheck > 0 && $useridtocheck != $user->id && empty($user->admin)) {
1087 return false;
1088 }
1089 }
1090
1091 if ($sql) {
1092 $resql = $db->query($sql);
1093 if ($resql) {
1094 $obj = $db->fetch_object($resql);
1095 if (!$obj || $obj->nb < count(explode(',', $objectid))) { // error if we found 0 or less record than the nb of ids provided
1096 return false;
1097 }
1098 } else {
1099 dol_syslog("Bad forged sql in security.lib.php::checkUserAccessToObject", LOG_WARNING);
1100 return false;
1101 }
1102 }
1103 }
1104
1105 dol_syslog("security.lib.php::checkUserAccessToObject::return True", LOG_DEBUG);
1106 return true;
1107}
1108
1109
1121function httponly_accessforbidden($message = '1', $http_response_code = 403, $stringalreadysanitized = 0)
1122{
1123 top_httphead();
1124 http_response_code($http_response_code);
1125
1126 if ($stringalreadysanitized) {
1127 print $message;
1128 } else {
1129 print htmlentities($message);
1130 }
1131
1132 exit(1);
1133}
1134
1148function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
1149{
1150 global $conf, $db, $user, $langs, $hookmanager;
1151 global $action, $object;
1152
1153 if (!is_object($langs)) {
1154 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
1155 $langs = new Translate('', $conf);
1156 $langs->setDefaultLang();
1157 }
1158
1159 $langs->loadLangs(array("main", "errors"));
1160
1161 if ($printheader && !defined('NOHEADERNOFOOTER')) {
1162 if (function_exists("llxHeader")) {
1163 llxHeader('');
1164 } elseif (function_exists("llxHeaderVierge")) {
1165 llxHeaderVierge('');
1166 }
1167 print '<div style="padding: 20px">';
1168 }
1169 print '<div class="error">';
1170 if (empty($message)) {
1171 print $langs->trans("ErrorForbidden");
1172 } else {
1173 print $langs->trans($message);
1174 }
1175 print '</div>';
1176 print '<br>';
1177 if (empty($showonlymessage)) {
1178 if (empty($hookmanager)) {
1179 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1180 $hookmanager = new HookManager($db);
1181 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
1182 $hookmanager->initHooks(array('main'));
1183 }
1184
1185 $parameters = array('message' => $message, 'params' => $params);
1186 $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1187 print $hookmanager->resPrint;
1188 if (empty($reshook)) {
1189 $langs->loadLangs(array("errors"));
1190 if ($user->login) {
1191 print $langs->trans("CurrentLogin").': <span class="error">'.$user->login.'</span><br>';
1192 print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users"));
1193 print $langs->trans("ErrorForbidden4");
1194 } else {
1195 print $langs->trans("ErrorForbidden3");
1196 }
1197 }
1198 }
1199 if ($printfooter && !defined('NOHEADERNOFOOTER') && function_exists("llxFooter")) {
1200 print '</div>';
1201 llxFooter();
1202 }
1203
1204 // End PHP
1205 exit(0);
1206}
1207
1208
1216{
1217 $max = getDolGlobalString('MAIN_UPLOAD_DOC'); // In Kb
1218
1219 $maxphp = @ini_get('upload_max_filesize'); // In unknown
1220 if (preg_match('/k$/i', $maxphp)) {
1221 $maxphp = preg_replace('/k$/i', '', $maxphp);
1222 $maxphp = (int) ((float) $maxphp * 1);
1223 }
1224 if (preg_match('/m$/i', $maxphp)) {
1225 $maxphp = preg_replace('/m$/i', '', $maxphp);
1226 $maxphp = (int) ((float) $maxphp * 1024);
1227 }
1228 if (preg_match('/g$/i', $maxphp)) {
1229 $maxphp = preg_replace('/g$/i', '', $maxphp);
1230 $maxphp = (int) ((float) $maxphp * 1024 * 1024);
1231 }
1232 if (preg_match('/t$/i', $maxphp)) {
1233 $maxphp = preg_replace('/t$/i', '', $maxphp);
1234 $maxphp = (int) ((float) $maxphp * 1024 * 1024 * 1024);
1235 }
1236 $maxphp2 = @ini_get('post_max_size'); // In unknown
1237 if (preg_match('/k$/i', $maxphp2)) {
1238 $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
1239 $maxphp2 = (int) ((float) $maxphp2) * 1;
1240 }
1241 if (preg_match('/m$/i', $maxphp2)) {
1242 $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
1243 $maxphp2 = (int) ((float) $maxphp2 * 1024);
1244 }
1245 if (preg_match('/g$/i', $maxphp2)) {
1246 $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
1247 $maxphp2 = (int) ((float) $maxphp2 * 1024 * 1024);
1248 }
1249 if (preg_match('/t$/i', $maxphp2)) {
1250 $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
1251 $maxphp2 = (int) ((float) $maxphp2 * 1024 * 1024 * 1024);
1252 }
1253 // Now $max and $maxphp and $maxphp2 are in Kb
1254 $maxmin = $max;
1255 $maxphptoshow = $maxphptoshowparam = '';
1256 if ($maxphp > 0) {
1257 $maxmin = min($maxmin, $maxphp);
1258 $maxphptoshow = $maxphp;
1259 $maxphptoshowparam = 'upload_max_filesize';
1260 }
1261 if ($maxphp2 > 0) {
1262 $maxmin = min($maxmin, $maxphp2);
1263 if ($maxphp2 < $maxphp) {
1264 $maxphptoshow = $maxphp2;
1265 $maxphptoshowparam = 'post_max_size';
1266 }
1267 }
1268 //var_dump($maxphp.'-'.$maxphp2);
1269 //var_dump($maxmin);
1270
1271 return array('max' => $max, 'maxmin' => $maxmin, 'maxphptoshow' => $maxphptoshow, 'maxphptoshowparam' => $maxphptoshowparam);
1272}
1273
1281function checkIPInCidr($ip, $cidr)
1282{
1283 list($network, $prefix) = explode('/', $cidr, 2);
1284
1285 // Convert IPs to binary format
1286 $ip_bin = @inet_pton($ip);
1287 $net_bin = @inet_pton($network);
1288 if ($ip_bin === false || $net_bin === false) {
1289 return -1;
1290 }
1291
1292 // Require same address IPvX family
1293 if (strlen($ip_bin) !== strlen($net_bin)) {
1294 return -1;
1295 }
1296
1297 // Comparison boundaries
1298 $total_bits = strlen($ip_bin) * 8;
1299 $prefix = max(0, min((int) $prefix, $total_bits));
1300 $full_bytes = intdiv($prefix, 8);
1301 $rem_bits = $prefix % 8;
1302
1303 // Compare full bytes and partial bytes
1304 if ($full_bytes > 0) {
1305 if (substr($ip_bin, 0, $full_bytes) !== substr($net_bin, 0, $full_bytes)) {
1306 return 0;
1307 }
1308 }
1309 if ($rem_bits > 0) {
1310 $mask = (0xFF << (8 - $rem_bits)) & 0xFF;
1311 $ip_byte = ord($ip_bin[$full_bytes]);
1312 $net_byte = ord($net_bin[$full_bytes]);
1313 if (($ip_byte & $mask) !== ($net_byte & $mask)) {
1314 return 0;
1315 }
1316 }
1317 return 1;
1318}
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.
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.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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
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.
getMaxFileSizeArray()
Return the max allowed for file upload.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.
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.