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-2026 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2025-2026 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
45function dol_encode($chain, $key = '1')
46{
47 if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char
48 $output_tab = array();
49 $strlength = strlen($chain);
50 for ($i = 0; $i < $strlength; $i++) {
51 $output_tab[$i] = chr(ord(substr($chain, $i, 1)) + 17);
52 }
53 $chain = implode("", $output_tab);
54 } elseif ($key) {
55 $result = '';
56 $strlength = strlen($chain);
57 for ($i = 0; $i < $strlength; $i++) {
58 $keychar = substr($key, ($i % strlen($key)) - 1, 1);
59 $result .= chr(ord(substr($chain, $i, 1)) + (ord($keychar) - 65));
60 }
61 $chain = $result;
62 }
63
64 return base64_encode($chain);
65}
66
77function dol_decode($chain, $key = '1')
78{
79 $chain = base64_decode($chain);
80
81 if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char
82 $output_tab = array();
83 $strlength = strlen($chain);
84 for ($i = 0; $i < $strlength; $i++) {
85 $output_tab[$i] = chr(ord(substr($chain, $i, 1)) - 17);
86 }
87
88 $chain = implode("", $output_tab);
89 } elseif ($key) {
90 $result = '';
91 $strlength = strlen($chain);
92 for ($i = 0; $i < $strlength; $i++) {
93 $keychar = substr($key, ($i % strlen($key)) - 1, 1);
94 $result .= chr(ord(substr($chain, $i, 1)) - (ord($keychar) - 65));
95 }
96 $chain = $result;
97 }
98
99 return $chain;
100}
101
108function dolGetRandomBytes($length)
109{
110 if (function_exists('random_bytes')) { // Available with PHP 7+ only.
111 return bin2hex(random_bytes((int) floor($length / 2))); // the bin2hex will double the number of bytes so we take length / 2
112 }
113
114 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.
115}
116
125function dolGetLdapPasswordHash($password, $type = 'md5')
126{
127 if (empty($type)) {
128 $type = 'md5';
129 }
130
131 $salt = substr(sha1((string) time()), 0, 8);
132
133 if ($type === 'md5') {
134 return '{MD5}' . base64_encode(hash("md5", $password, true)); //For OpenLdap with md5 (based on an unencrypted password in base)
135 } elseif ($type === 'md5frommd5') {
136 return '{MD5}' . base64_encode(hex2bin($password)); // Create OpenLDAP MD5 password from Dolibarr MD5 password
137 } elseif ($type === 'smd5') {
138 return "{SMD5}" . base64_encode(hash("md5", $password . $salt, true) . $salt);
139 } elseif ($type === 'sha') {
140 return '{SHA}' . base64_encode(hash("sha1", $password, true));
141 } elseif ($type === 'ssha') {
142 return "{SSHA}" . base64_encode(hash("sha1", $password . $salt, true) . $salt);
143 } elseif ($type === 'sha256') {
144 return "{SHA256}" . base64_encode(hash("sha256", $password, true));
145 } elseif ($type === 'ssha256') {
146 return "{SSHA256}" . base64_encode(hash("sha256", $password . $salt, true) . $salt);
147 } elseif ($type === 'sha384') {
148 return "{SHA384}" . base64_encode(hash("sha384", $password, true));
149 } elseif ($type === 'ssha384') {
150 return "{SSHA384}" . base64_encode(hash("sha384", $password . $salt, true) . $salt);
151 } elseif ($type === 'sha512') {
152 return "{SHA512}" . base64_encode(hash("sha512", $password, true));
153 } elseif ($type === 'ssha512') {
154 return "{SSHA512}" . base64_encode(hash("sha512", $password . $salt, true) . $salt);
155 } elseif ($type === 'crypt') {
156 return '{CRYPT}' . crypt($password, $salt);
157 } elseif ($type === 'clear') {
158 return '{CLEAR}' . $password; // Just for test, plain text password is not secured !
159 }
160 return "";
161}
162
183function restrictedArea(User $user, $features, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0, $nodie = 0, $mode = '')
184{
185 global $hookmanager;
186
187 // Define $objectid
188 if (is_object($object)) {
189 $objectid = $object->id;
190 } else {
191 $objectid = $object; // $objectid can be X or 'X,Y,Z'
192 }
193 if ($objectid == "-1") {
194 $objectid = 0;
195 }
196 if ($objectid) {
197 $objectid = preg_replace('/[^0-9\.\,]/', '', (string) $objectid); // For the case value is coming from a non sanitized user input
198 }
199
200 //dol_syslog("functions.lib:restrictedArea $feature, $object, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
201 /*print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", object=".$object;
202 print ", dbtablename=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
203 print ", perm: user->hasRight(".$features.($feature2 ? ",".$feature2 : "").", lire) = ".($feature2 ? $user->hasRight($features, $feature2, 'lire') : $user->hasRight($features, 'lire'))."<br>";
204 */
205
206 $parentfortableentity = '';
207
208 $originalfeatures = $features;
209
210 // Fix syntax of $features param to support non standard module names.
211 if ($features == 'agenda') {
212 $tableandshare = 'actioncomm&societe';
213 $feature2 = 'myactions|allactions';
214 $dbt_select = 'id';
215 } elseif ($features == 'bank') {
216 $features = 'banque';
217 } elseif ($features == 'remisecheque') {
218 $features = 'banque';
219 } elseif ($features == 'facturerec') {
220 $features = 'facture';
221 } elseif ($features == 'supplier_invoicerec') {
222 $features = 'fournisseur';
223 $feature2 = 'facture';
224 } elseif ($features == 'company') {
225 $features = 'societe';
226 } elseif ($features == 'mo') {
227 $features = 'mrp';
228 } elseif ($features == 'member') {
229 $features = 'adherent';
230 } elseif ($features == 'subscription') {
231 $features = 'adherent';
232 $feature2 = 'cotisation';
233 $tableandshare = 'subscription&adherent';
234 $parentfortableentity = 'fk_adherent@adherent'; // A subscription has no entity, the entity is the one of its member
235 } elseif ($features == 'website' && is_object($object) && $object->element == 'websitepage') {
236 $parentfortableentity = 'fk_website@website';
237 } elseif ($features == 'project') {
238 $features = 'projet';
239 } elseif ($features == 'project_task') {
240 $features = 'projet';
241 $objectid = (int) $object->fk_project;
242 $object = $objectid;
243 } elseif (is_object($object) && ($features == 'conferenceorbooth@eventorganization' || ($features == 'eventorganization' && $object->element == 'conferenceorbooth'))) {
244 // The module of an event organization declares no permission of its own, on purpose.
245 // Permission are done on project table.
246 if (!empty($user->socid) || empty($object->fk_project)) {
247 if ($nodie) {
248 return 0;
249 } else {
251 }
252 }
253 $features = 'projet';
254 $tableandshare = 'projet&project';
255 $objectid = (int) $object->fk_project;
256 $object = $objectid;
257 } elseif ($features == 'product') {
258 $features = 'produit';
259 } elseif ($features == 'productbatch') {
260 $features = 'produit';
261 } elseif ($features == 'tax') {
262 $feature2 = 'charges';
263 } elseif ($features == 'workstation') {
264 $feature2 = 'workstation';
265 } elseif ($features == 'hrm' && is_object($object) && in_array($object->element, array('job', 'position', 'skill'))) {
266 $feature2 = 'all'; // These 3 objects have no permission of their own, they share the level "all"
267 } elseif ($features == 'recruitment' && is_object($object) && in_array($object->element, array('recruitmentjobposition', 'recruitmentcandidature'))) {
268 // The recruitment module declares no permission at its first level, all its objects share the
269 // second level "recruitmentjobposition". When the caller provides the module name only
270 // (like document.php with its modulepart), we complete the missing parameters from the object.
271 if (empty($feature2)) {
272 $feature2 = 'recruitmentjobposition';
273 }
274 if (empty($tableandshare)) {
275 $tableandshare = $object->table_element;
276 }
277 } elseif ($features == 'stocktransfer' && is_object($object) && $object->element == 'stocktransfer') {
278 $feature2 = 'stocktransfer'; // This module declares no permission at its first level, only this one
279 } elseif (in_array($features, array('fournisseur', 'commande_fournisseur', 'facture_fournisseur', 'order_supplier', 'invoice_supplier'))) { // When vendor invoice and purchase order are into module 'fournisseur'
280 $features = 'fournisseur';
281 if (is_object($object) && $object->element == 'invoice_supplier') {
282 $feature2 = 'facture';
283 } elseif (is_object($object) && $object->element == 'order_supplier') {
284 $feature2 = 'commande';
285 }
286 } elseif ($features == 'payment_sc') {
287 $tableandshare = 'paiementcharge';
288 $parentfortableentity = 'fk_charge@chargesociales';
289 } elseif ($features == 'payment_vat') {
290 $tableandshare = 'payment_vat';
291 $parentfortableentity = 'fk_tva@tva';
292 } elseif ($features == 'payment_donation') {
293 $tableandshare = 'payment_donation';
294 $parentfortableentity = 'fk_donation@don'; // A donation payment has no entity, the entity is the one of its donation
295 }
296
297 // if commonObjectLine : Using many2one related commonObject
298 // @see commonObjectLine::parentElement
299 if (in_array($features, ['commandedet', 'propaldet', 'facturedet', 'supplier_proposaldet', 'evaluationdet', 'skilldet', 'deliverydet', 'contratdet'])) {
300 $features = substr($features, 0, -3); // @phan-suppress-current-line DolibarrForbiddenFunctionPlugin
301 } elseif (in_array($features, ['stocktransferline', 'inventoryline', 'bomline', 'expensereport_det', 'facture_fourn_det'])) {
302 $features = substr($features, 0, -4); // @phan-suppress-current-line DolibarrForbiddenFunctionPlugin
303 } elseif ($features == 'commandefournisseurdispatch') {
304 $features = 'commandefournisseur';
305 } elseif ($features == 'invoice_supplier_det_rec') {
306 $features = 'invoice_supplier_rec';
307 }
308 if ($features == 'evaluation') {
309 $features = 'hrm';
310 $feature2 = 'evaluation';
311 }
312
313 // When the object is a task (element='project_task') and $feature2 is empty,
314 // $checkUserAccessToObject() falls into the $checkproject path and uses the task ID
315 // as project ID, which always fails. Setting $feature2='project_task' triggers the
316 // normalization at line 974 that redirects to the $checktask path, which correctly
317 // resolves $task->fk_project before calling getProjectsAuthorizedForUser().
318 if (is_object($object) && in_array($object->element, array('project_task', 'task'))
319 && (empty($features) || in_array($features, array('projet', 'project')))
320 && empty($feature2)) {
321 $features = 'projet';
322 $feature2 = 'project_task';
323 if (empty($tableandshare)) {
324 $tableandshare = 'projet_task';
325 }
326 }
327
328 // If the $features parameter is empty, there is no permission we can check, so the access must
329 // be refused. Without this test, all the checks of permission below would be silently skipped and
330 // the access would be granted to any user without any test (see also selectobject.php that forces
331 // its features parameter to 'unknownobject' instead of '' for the same reason).
332 if (empty($features) || trim((string) $features) === '') {
333 dol_syslog('restrictedArea() called with an empty features parameter, we refuse the access', LOG_WARNING);
334 if ($nodie) {
335 return 0;
336 } else {
337 accessforbidden('Bad value for parameter features');
338 }
339 }
340
341 // print $features.' - '.$tableandshare.' - '.$feature2.' - '.$dbt_select."\n";
342
343 // Get more permissions checks from hooks
344 $parameters = array(
345 'features' => $features,
346 'feature2' => $feature2,
347 'originalfeatures' => $originalfeatures,
348 'tableandshare' => $tableandshare,
349 'object' => $object,
350 'objectid' => $objectid,
351 'dbt_keyfield' => $dbt_keyfield,
352 'dbt_select' => $dbt_select,
353 'idtype' => $dbt_select,
354 'isdraft' => $isdraft,
355 'nodie' => $nodie,
356 'mode' => $mode
357 );
358 if (!empty($hookmanager)) {
359 $reshook = $hookmanager->executeHooks('restrictedArea', $parameters);
360
361 if (isset($hookmanager->resArray['result'])) {
362 if ($hookmanager->resArray['result'] == 0) {
363 if ($nodie) {
364 return 0;
365 } else {
366 accessforbidden(); // Module returns 0, so access forbidden
367 }
368 }
369 }
370 if ($reshook > 0) { // No other test done.
371 return 1;
372 }
373 }
374
375 // Features/modules to check (to support the & and | operator)
376 $featuresarray = array($features);
377 if (preg_match('/&/', $features)) {
378 $featuresarray = explode("&", $features);
379 } elseif (preg_match('/\|/', $features)) {
380 $featuresarray = explode("|", $features);
381 }
382
383 // More subfeatures to check
384 if (!empty($feature2)) {
385 $feature2 = explode("|", $feature2);
386 }
387
388 $listofmodules = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL'));
389
390 //var_dump($featuresarray, $object->id);
391
392 // Check read permission from module
393 $readok = 1;
394 $nbko = 0;
395 foreach ($featuresarray as $feature) { // first we check nb of test ko
396 $featureforlistofmodule = $feature;
397 if ($featureforlistofmodule == 'produit') {
398 $featureforlistofmodule = 'product';
399 }
400 if ($featureforlistofmodule == 'supplier_proposal') {
401 $featureforlistofmodule = 'supplierproposal';
402 }
403 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
404 $readok = 0;
405 $nbko++;
406 continue;
407 }
408
409 if (in_array($feature, array('societe', 'company')) && (empty($feature2) || !in_array('contact', $feature2))) {
410 if (!$user->hasRight('societe', 'lire') && !$user->hasRight('fournisseur', 'lire')) {
411 $readok = 0;
412 $nbko++;
413 }
414 } elseif ((in_array($feature, array('societe', 'company')) && (!empty($feature2) && in_array('contact', $feature2))) || $feature == 'contact') {
415 if (!$user->hasRight('societe', 'contact', 'lire')) {
416 $readok = 0;
417 $nbko++;
418 }
419 } elseif ($feature == 'produit|service') {
420 if (!$user->hasRight('produit', 'lire') && !$user->hasRight('service', 'lire')) {
421 $readok = 0;
422 $nbko++;
423 }
424 } elseif ($feature == 'produit') {
425 // $object is only a real Product/Service when the check is scoped to one specific
426 // record (e.g. a product card); a generic area check (e.g. the product/service
427 // dashboard) never sets it, so it keeps its default int value and has no ->type to
428 // tell products and services apart - fall back to requiring either right.
429 if (!is_object($object)) {
430 if (!$user->hasRight('produit', 'lire') && !$user->hasRight('service', 'lire')) {
431 $readok = 0;
432 $nbko++;
433 }
434 } elseif ($object->type == 0 && !$user->hasRight('produit', 'lire')) {
435 $readok = 0;
436 $nbko++;
437 } elseif ($object->type == 1 && !$user->hasRight('service', 'lire')) {
438 $readok = 0;
439 $nbko++;
440 }
441 } elseif ($feature == 'prelevement') {
442 if (!$user->hasRight('prelevement', 'bons', 'lire')) {
443 $readok = 0;
444 $nbko++;
445 }
446 } elseif ($feature == 'cheque') {
447 if (!$user->hasRight('banque', 'cheque')) {
448 $readok = 0;
449 $nbko++;
450 }
451 } elseif ($feature == 'projet') {
452 if (!$user->hasRight('projet', 'lire') && !$user->hasRight('projet', 'all', 'lire')) {
453 $readok = 0;
454 $nbko++;
455 }
456 } elseif ($feature == 'payment') {
457 if (!$user->hasRight('facture', 'lire')) {
458 $readok = 0;
459 $nbko++;
460 }
461 } elseif ($feature == 'payment_supplier') {
462 if (!$user->hasRight('fournisseur', 'facture', 'lire')) {
463 $readok = 0;
464 $nbko++;
465 }
466 } elseif ($feature == 'payment_sc') {
467 if (!$user->hasRight('tax', 'charges', 'lire')) {
468 $readok = 0;
469 $nbko++;
470 }
471 } elseif ($feature == 'payment_vat') {
472 if (!$user->hasRight('tax', 'charges', 'lire')) {
473 $readok = 0;
474 $nbko++;
475 }
476 } elseif ($feature == 'payment_donation') {
477 if (!$user->hasRight('don', 'lire')) {
478 $readok = 0;
479 $nbko++;
480 }
481 } elseif ($feature == 'webhook') {
482 if (empty($user->admin)) {
483 $readok = 0;
484 $nbko++;
485 }
486 } elseif (!empty($feature2)) { // This is for permissions on 2 levels (module->object->read)
487 $tmpreadok = 1;
488 foreach ($feature2 as $subfeature) {
489 if ($subfeature == 'user' && $user->id == $objectid) {
490 continue; // A user can always read its own card
491 }
492 if ($subfeature == 'fiscalyear' && $user->hasRight('accounting', 'fiscalyear', 'write')) {
493 // only one right for fiscalyear
494 $tmpreadok = 1;
495 continue;
496 }
497 if (!empty($subfeature) && !$user->hasRight($feature, $subfeature, 'lire') && !$user->hasRight($feature, $subfeature, 'read')) {
498 $tmpreadok = 0;
499 } elseif (empty($subfeature) && !$user->hasRight($feature, 'lire') && !$user->hasRight($feature, 'read')) {
500 $tmpreadok = 0;
501 } else {
502 $tmpreadok = 1;
503 break;
504 } // Break is to bypass second test if the first is ok
505 }
506 if (!$tmpreadok) { // We found a test on feature that is ko
507 $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko).
508 $nbko++;
509 }
510 } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level (module->read)
511 if (!$user->hasRight($feature, 'lire')
512 && !$user->hasRight($feature, 'read')
513 && !$user->hasRight($feature, 'run')) {
514 $readok = 0;
515 $nbko++;
516 }
517 }
518 }
519
520 // If a or and at least one ok
521 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
522 $readok = 1;
523 }
524
525 if (!$readok) {
526 if ($nodie) {
527 return 0;
528 } else {
530 }
531 }
532 //print "Read access is ok";
533
534 // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files)
535 $createok = 1;
536 $nbko = 0;
537 if ($mode == 'read') {
538 $wemustcheckpermissionforcreate = 0;
539 $wemustcheckpermissionfordeletedraft = 0;
540 $wemustcheckpermissionfordelete = 0;
541 } elseif ($mode == 'write') {
542 $wemustcheckpermissionforcreate = 1;
543 $wemustcheckpermissionfordeletedraft = 1;
544 $wemustcheckpermissionfordelete = 0;
545 } elseif ($mode == 'delete') {
546 $wemustcheckpermissionforcreate = 0;
547 $wemustcheckpermissionfordeletedraft = 0;
548 $wemustcheckpermissionfordelete = 1;
549 } else {
550 // This is possible in a GUI context only
551 $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));
552 $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
553 $wemustcheckpermissionfordelete = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
554 }
555
556 //var_dump($wemustcheckpermissionforcreate, $wemustcheckpermissionfordeletedraft, $wemustcheckpermissionfordelete);
557
558 if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) {
559 foreach ($featuresarray as $feature) {
560 if ($feature == 'contact') {
561 if (!$user->hasRight('societe', 'contact', 'creer')) {
562 $createok = 0;
563 $nbko++;
564 }
565 } elseif ($feature == 'produit|service') {
566 if (!$user->hasRight('produit', 'creer') && !$user->hasRight('service', 'creer')) {
567 $createok = 0;
568 $nbko++;
569 }
570 } elseif ($feature == 'prelevement') {
571 if (!$user->hasRight('prelevement', 'bons', 'creer')) {
572 $createok = 0;
573 $nbko++;
574 }
575 } elseif ($feature == 'commande_fournisseur') {
576 if (!$user->hasRight('fournisseur', 'commande', 'creer') || !$user->hasRight('supplier_order', 'creer')) {
577 $createok = 0;
578 $nbko++;
579 }
580 } elseif ($feature == 'banque') {
581 if (!$user->hasRight('banque', 'modifier')) {
582 $createok = 0;
583 $nbko++;
584 }
585 } elseif ($feature == 'cheque') {
586 if (!$user->hasRight('banque', 'cheque')) {
587 $createok = 0;
588 $nbko++;
589 }
590 } elseif ($feature == 'import') {
591 if (!$user->hasRight('import', 'run')) {
592 $createok = 0;
593 $nbko++;
594 }
595 } elseif ($feature == 'ecm') {
596 if (!$user->hasRight('ecm', 'upload')) {
597 $createok = 0;
598 $nbko++;
599 }
600 } elseif ($feature == 'modulebuilder') {
601 if (!$user->hasRight('modulebuilder', 'run')) {
602 $createok = 0;
603 $nbko++;
604 }
605 } elseif ($feature == 'payment') {
606 if (!$user->hasRight('facture', 'paiement')) {
607 $createok = 0;
608 $nbko++;
609 }
610 } elseif ($feature == 'payment_supplier') { // Permission to write on a payment of an invoice is permission to edit an invoice.
611 if (!$user->hasRight('fournisseur', 'facture', 'creer')) {
612 $createok = 0;
613 $nbko++;
614 }
615 } elseif ($feature == 'webhook') {
616 if (empty($user->admin)) {
617 $createok = 0;
618 $nbko++;
619 }
620 } elseif (!empty($feature2)) { // This is for permissions on 2 levels (module->object->write)
621 foreach ($feature2 as $subfeature) {
622 if ($subfeature == 'user' && $user->id == $objectid && $user->hasRight('user', 'self', 'creer')) {
623 continue; // User can edit its own card
624 }
625 if ($subfeature == 'user' && $user->id == $objectid && $user->hasRight('user', 'self', 'password')) {
626 continue; // User can edit its own password
627 }
628 if ($subfeature == 'user' && $user->id != $objectid && $user->hasRight('user', 'user', 'password')) {
629 continue; // User can edit another user's password
630 }
631
632 if (!$user->hasRight($feature, $subfeature, 'creer')
633 && !$user->hasRight($feature, $subfeature, 'write')
634 && !$user->hasRight($feature, $subfeature, 'create')) {
635 $createok = 0;
636 $nbko++;
637 } else {
638 $createok = 1;
639 // Break to bypass second test if the first is ok
640 break;
641 }
642 }
643 } elseif (!empty($feature)) { // This is for permissions on 1 levels (module->write)
644 //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; exit;
645 if (!$user->hasRight($feature, 'creer')
646 && !$user->hasRight($feature, 'write')
647 && !$user->hasRight($feature, 'create')) {
648 $createok = 0;
649 $nbko++;
650 }
651 }
652 }
653
654 // If a or and at least one ok
655 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
656 $createok = 1;
657 }
658
659 if ($wemustcheckpermissionforcreate && !$createok) {
660 if ($nodie) {
661 return 0;
662 } else {
664 }
665 }
666 //print "Write access is ok";
667 }
668
669 // Check create user permission (special case)
670 $createuserok = 1;
671 if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') {
672 if (!$user->hasRight('user', 'user', 'creer')) {
673 $createuserok = 0;
674 }
675
676 if (!$createuserok) {
677 if ($nodie) {
678 return 0;
679 } else {
681 }
682 }
683 //print "Create user access is ok";
684 }
685
686 // Check delete permission from module
687 $deleteok = 1;
688 $nbko = 0;
689 if ($wemustcheckpermissionfordelete) {
690 foreach ($featuresarray as $feature) {
691 if ($feature == 'bookmark') {
692 if (!$user->hasRight('bookmark', 'supprimer')) {
693 if ($user->id != $object->fk_user || !$user->hasRight('bookmark', 'creer')) {
694 $deleteok = 0;
695 }
696 }
697 } elseif ($feature == 'contact') {
698 if (!$user->hasRight('societe', 'contact', 'supprimer')) {
699 $deleteok = 0;
700 }
701 } elseif ($feature == 'produit|service') {
702 if (!$user->hasRight('produit', 'supprimer') && !$user->hasRight('service', 'supprimer')) {
703 $deleteok = 0;
704 }
705 } elseif ($feature == 'commande_fournisseur') {
706 if (!$user->hasRight('fournisseur', 'commande', 'supprimer')) {
707 $deleteok = 0;
708 }
709 } elseif ($feature == 'payment_supplier') { // Permission to delete a payment of an invoice is permission to edit an invoice.
710 if (!$user->hasRight('fournisseur', 'facture', 'creer')) {
711 $deleteok = 0;
712 }
713 } elseif ($feature == 'payment') {
714 if (!$user->hasRight('facture', 'paiement')) {
715 $deleteok = 0;
716 }
717 } elseif ($feature == 'payment_sc') {
718 if (!$user->hasRight('tax', 'charges', 'creer')) {
719 $deleteok = 0;
720 }
721 } elseif ($feature == 'banque') {
722 if (!$user->hasRight('banque', 'modifier')) {
723 $deleteok = 0;
724 }
725 } elseif ($feature == 'cheque') {
726 if (!$user->hasRight('banque', 'cheque')) {
727 $deleteok = 0;
728 }
729 } elseif ($feature == 'ecm') {
730 if (!$user->hasRight('ecm', 'upload')) {
731 $deleteok = 0;
732 }
733 } elseif ($feature == 'ftp') {
734 if (!$user->hasRight('ftp', 'write')) {
735 $deleteok = 0;
736 }
737 } elseif ($feature == 'salaries') {
738 if (!$user->hasRight('salaries', 'delete')) {
739 $deleteok = 0;
740 }
741 } elseif ($feature == 'adherent') {
742 if (!$user->hasRight('adherent', 'supprimer')) {
743 $deleteok = 0;
744 }
745 } elseif ($feature == 'paymentbybanktransfer') {
746 if (!$user->hasRight('paymentbybanktransfer', 'create')) { // There is no delete permission
747 $deleteok = 0;
748 }
749 } elseif ($feature == 'prelevement') {
750 if (!$user->hasRight('prelevement', 'bons', 'creer')) { // There is no delete permission
751 $deleteok = 0;
752 }
753 } elseif (!empty($feature2)) { // This is for permissions on 2 levels
754 foreach ($feature2 as $subfeature) {
755 if (!$user->hasRight($feature, $subfeature, 'supprimer') && !$user->hasRight($feature, $subfeature, 'delete')) {
756 $deleteok = 0;
757 } else {
758 $deleteok = 1;
759 break;
760 } // For bypass the second test if the first is ok
761 }
762 } elseif (!empty($feature)) { // This is used for permissions on 1 level
763 //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
764 if (!$user->hasRight($feature, 'supprimer')
765 && !$user->hasRight($feature, 'delete')
766 && !$user->hasRight($feature, 'run')) {
767 $deleteok = 0;
768 }
769 }
770 }
771
772 // If a or and at least one ok
773 if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
774 $deleteok = 1;
775 }
776
777 if (!$deleteok && !($isdraft && $createok)) {
778 if ($nodie) {
779 return 0;
780 } else {
782 }
783 }
784 //print "Delete access is ok";
785 }
786
787 // If we have a particular object to check permissions on, we check if $user has permission
788 // for this given object (link to company, is contact for project, ...)
789 if (!empty($objectid) && $objectid > 0) {
790 $ok = checkUserAccessToObject($user, $featuresarray, $object, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity);
791 $params = array('objectid' => $objectid, 'features' => implode(',', $featuresarray), 'features2' => $feature2);
792 //print 'checkUserAccessToObject ok='.$ok;
793 if ($nodie) {
794 return $ok ? 1 : 0;
795 } else {
796 if ($ok) {
797 return 1;
798 } else {
799 accessforbidden('', 1, 1, 0, $params);
800 }
801 }
802 }
803
804 return 1;
805}
806
819function checkUserAccessToDocumentObject(User $user, $modulepart, $original_file, $mode = 'read')
820{
821 // Moduleparts of documents linked to a thirdparty: modulepart => array(element used to fetch the object, feature for restrictedArea())
822 $modulepartlinkedtothirdparty = array(
823 'societe' => array('societe', 'societe'),
824 'company' => array('societe', 'societe'),
825 'thirdparty' => array('societe', 'societe'),
826 'contact' => array('contact', 'contact'),
827 'socpeople' => array('contact', 'contact'),
828 'facture' => array('facture', 'facture'),
829 'invoice' => array('facture', 'facture'),
830 'propal' => array('propal', 'propal'),
831 'propale' => array('propal', 'propal'),
832 'proposal' => array('propal', 'propal'),
833 'commande' => array('commande', 'commande'),
834 'order' => array('commande', 'commande'),
835 'commande_fournisseur' => array('order_supplier', 'order_supplier'),
836 'order_supplier' => array('order_supplier', 'order_supplier'),
837 'supplier_order' => array('order_supplier', 'order_supplier'),
838 'facture_fournisseur' => array('invoice_supplier', 'invoice_supplier'),
839 'invoice_supplier' => array('invoice_supplier', 'invoice_supplier'),
840 'supplier_invoice' => array('invoice_supplier', 'invoice_supplier'),
841 'contract' => array('contrat', 'contrat'),
842 'contrat' => array('contrat', 'contrat'),
843 'fichinter' => array('fichinter', 'ficheinter'),
844 'ficheinter' => array('fichinter', 'ficheinter'),
845 'intervention' => array('fichinter', 'ficheinter'),
846 'ticket' => array('ticket', 'ticket'),
847 'expedition' => array('expedition', 'expedition'),
848 'shipment' => array('expedition', 'expedition'),
849 'shipping' => array('expedition', 'expedition'),
850 'reception' => array('reception', 'reception'),
851 'supplier_proposal' => array('supplier_proposal', 'supplier_proposal'),
852 'project' => array('project', 'project'),
853 'projet' => array('project', 'project'),
854 'project_task' => array('project', 'project'),
855 );
856 // For these moduleparts, the first subdirectory is the id of the object instead of its ref
857 $modulepartwithid = array('societe', 'company', 'thirdparty', 'contact', 'socpeople');
858 // For these moduleparts, the first subdirectory is the ref of the object (files of tasks are into the directory of their project)
859 $modulepartwithfirstdirasref = array('project', 'projet', 'project_task');
860
861 // Same fix than into dol_check_secure_access_document(): files of 'expedition' into 'receipt/' are delivery notes
862 if ($modulepart == 'expedition' && strpos($original_file, 'receipt/') === 0) {
863 $modulepart = 'delivery';
864 }
865 // Previews (apercu*) are files into the same directories than the documents of the object, so we check the same object
866 if (strpos($modulepart, 'apercu') === 0) {
867 $modulepart = dol_substr($modulepart, 6);
868 }
869
870 // Find the subdirectory name as the reference
871 $refname = basename(dirname($original_file)."/");
872 if ($refname == 'thumbs' || $refname == 'temp') {
873 $refname = basename(dirname(dirname($original_file))."/");
874 }
875
876 if (empty($modulepartlinkedtothirdparty[$modulepart])) {
877 $object = fetchObjectByElement(0, $modulepart, $refname);
878 if (is_object($object)) {
879 // Same than generic case of dol_check_secure_access_document(): file 'myobject/REF/file' may be protected by permission modulepart->myobject->read
880 $feature2 = '';
881 $tmparray = explode('/', ltrim($original_file, '/'));
882 if (count($tmparray) > 2 && ($user->hasRight($modulepart, $tmparray[0], $mode))) {
883 $feature2 = $tmparray[0];
884 }
885 // Call checkUserAccessToObject() directly (module permission already checked by dol_check_secure_access_document())
886 return checkUserAccessToObject($user, array($modulepart), $object, '', $feature2, 'fk_soc', 'rowid') ? 1 : 0;
887 }
888 // If $modulepart is not an object type (userphoto, companylogo, memberphoto, apercuxxx, systemtools...), there is no object to check
889 return 1;
890 }
891
892 if (in_array($modulepart, $modulepartwithid)) {
893 $tmparray = explode('/', ltrim($original_file, '/'));
894 $object = fetchObjectByElement((int) $tmparray[0], $modulepartlinkedtothirdparty[$modulepart][0]);
895 } elseif (in_array($modulepart, $modulepartwithfirstdirasref)) {
896 $tmparray = explode('/', ltrim($original_file, '/'));
897 $object = fetchObjectByElement(0, $modulepartlinkedtothirdparty[$modulepart][0], (count($tmparray) > 1 ? $tmparray[0] : ''));
898 } else {
899 $object = fetchObjectByElement(0, $modulepartlinkedtothirdparty[$modulepart][0], $refname);
900 }
901
902 if (is_object($object) && $object->id > 0) {
903 // Call checkUserAccessToObject() directly (module permission already checked by dol_check_secure_access_document())
904 return checkUserAccessToObject($user, array($modulepartlinkedtothirdparty[$modulepart][1]), $object, '', '', 'fk_soc', 'rowid') ? 1 : 0;
905 }
906
907 // Object not found (file outside the directory of an object or faked path like 'REF/./file'): refused to users restricted to some thirdparties
908 if (($user->socid > 0 || !$user->hasRight('societe', 'client', 'voir')) && !preg_match('/^specimen/i', basename($original_file))) {
909 dol_syslog("checkUserAccessToDocumentObject no object found for modulepart=".$modulepart." original_file=".$original_file.", access refused to user restricted to some thirdparties", LOG_WARNING);
910 return 0;
911 }
912
913 return 1;
914}
915
931function checkUserAccessToObject($user, array $featuresarray, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid', $parenttableforentity = '')
932{
933 global $db, $conf;
934
935 if (is_object($object)) {
936 $objectid = $object->id;
937 } else {
938 $objectid = $object; // $objectid can be X or 'X,Y,Z'
939 }
940 $objectid = preg_replace('/[^0-9\.\,]/', '', (string) $objectid); // For the case value is coming from a non sanitized user input
941
942 //dol_syslog("functions.lib:restrictedArea $feature, $object, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
943 //print "user_id=".$user->id.", features=".join(',', $featuresarray).", object=".$object;
944 //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."<br>";
945
946 // More parameters
947 $params = explode('&', $tableandshare);
948 $dbtablename = (!empty($params[0]) ? $params[0] : '');
949 $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
950 $tablegivenbycaller = !empty($params[0]); // The table of the object given by the caller must not be replaced by the default table of the feature
951
952 foreach ($featuresarray as $feature) {
953 $sql = '';
954
955 //var_dump($feature);exit;
956
957 // Normalize table and feature name for compatibility
958 if ($feature == 'bom') {
959 $feature = 'bom_bom';
960 }
961 if ($feature == 'societe' && !empty($feature2) && is_array($feature2) && in_array('contact', $feature2)) {
962 $feature = 'contact';
963 $feature2 = '';
964 }
965 if ($feature == 'member') {
966 $feature = 'adherent';
967 }
968 if ($feature == 'category') {
969 $feature = 'categorie';
970 }
971 if ($feature == 'bank') {
972 $feature = 'banque';
973 }
974 if (!$tablegivenbycaller && $feature == 'contract') {
975 $dbtablename = 'contrat';
976 }
977 if (!$tablegivenbycaller && $feature == 'mrp') {
978 $dbtablename = 'mrp_mo';
979 }
980 if (!$tablegivenbycaller && ($feature == 'order_supplier' || ($feature == 'fournisseur' && is_object($object) && $object->element == 'order_supplier'))) {
981 $dbtablename = 'commande_fournisseur';
982 }
983 if (!$tablegivenbycaller && ($feature == 'invoice_supplier' || ($feature == 'fournisseur' && is_object($object) && $object->element == 'invoice_supplier'))) {
984 $dbtablename = 'facture_fourn';
985 }
986 if (!$tablegivenbycaller && $feature == 'produit') {
987 $dbtablename = 'product';
988 }
989 if (!$tablegivenbycaller && $feature == 'ficheinter') {
990 $dbtablename = 'fichinter';
991 }
992 if (!$tablegivenbycaller && $feature == 'banque') {
993 // The module name (and permission name) is 'banque', but the table of the bank account object is 'bank_account'
994 $dbtablename = 'bank_account';
995 }
996 if ($feature == 'project') {
997 $feature = 'projet';
998 }
999 if ($feature == 'projet' && !empty($feature2) && is_array($feature2) && !empty(array_intersect(array('project_task', 'projet_task'), $feature2))) {
1000 $feature = 'project_task';
1001 }
1002 if (!$tablegivenbycaller && $feature == 'stock') {
1003 $dbtablename = 'entrepot';
1004 }
1005 if ($feature == 'task' || $feature == 'projet_task') {
1006 $feature = 'project_task';
1007 $dbtablename = 'projet_task';
1008 }
1009 if ($feature == 'eventorganization') {
1010 $feature = 'agenda';
1011 $dbtablename = 'actioncomm';
1012 }
1013 if ($feature == 'payment_sc' && empty($parenttableforentity)) {
1014 // If we check perm on payment page but $parenttableforentity not defined, we force value on parent table
1015 $parenttableforentity = '';
1016 $dbtablename = "chargesociales";
1017 $feature = "chargesociales";
1018 $objectid = (string) $object->fk_charge;
1019 }
1020 if (!$tablegivenbycaller && $feature == 'workstation') {
1021 $dbtablename = 'workstation_workstation';
1022 }
1023
1024 $checkonentityready = 0;
1025
1026 // Array to define rules of checks to do
1027
1028 // Test on entity only (Objects with no link to company)
1029 $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', 'workstation');
1030 // Test for object Societe
1031 $checksoc = array('societe');
1032 // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...).
1033 $checkparentsoc = array('agenda', 'contact', 'contrat', 'ticket', 'stocktransfer');
1034 // Test for project object
1035 $checkproject = array('projet', 'project');
1036 // Test for task object
1037 $checktask = array('projet_task', 'project_task');
1038 // Check permission among the hierarchy of user
1039 $checkhierarchy = array('expensereport', 'holiday', 'hrm');
1040 // Check permission among the fk_user (must be myself or null)
1041 $checkuser = array('bookmark');
1042 // No test
1043 $nocheck = array('barcode', 'webhook');
1044
1045 //$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...).
1046
1047 // If dbtablename not defined, we use same name for table than module name
1048 if (empty($dbtablename)) {
1049 $dbtablename = $feature;
1050 $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
1051 }
1052
1053 // The default rule reads the columns entity and $dbt_keyfield of the table, but some tables own neither of
1054 // them. The sql was then built on columns that do not exist, so it always failed and the access was refused
1055 // to the users that this rule applies to.
1056 // The rule is selected on the table and not on the element of the object, because $object is an id and not
1057 // an object for most of the callers, the card of an asset and the card of a workstation included.
1058 if (!empty($objectid) && in_array($dbtablename, array('asset', 'loan', 'localtax', 'paiement', 'paiementfourn', 'pos_cash_fence', 'tva', 'workstation_workstation', 'hrm_job', 'hrm_job_user', 'hrm_skill'))) {
1059 // None of these objects is linked to a third party, so an external user can own none of them. The
1060 // default rule refused him through a link that does not exist, we must refuse him explicitly instead,
1061 // otherwise the rules below, which do not look at the third party of the user at all, would grant it.
1062 if (!empty($user->socid)) {
1063 return false;
1064 }
1065 if (in_array($dbtablename, array('hrm_job', 'hrm_job_user', 'hrm_skill'))) {
1066 // These 3 tables have no entity column either, so no rule that reads the table can be run on them.
1067 // The permission is still checked by restrictedArea(), and the $checkhierarchy rule below still runs.
1068 // Note that these 3 objects are therefore not partitioned between entities at all, in the database
1069 // itself: their cards already answer to a user of another entity, and their lists already show the
1070 // records of all of them. This rule does not widen that, it aligns with it.
1071 $nocheck[] = $feature;
1072 } else {
1073 $check[] = $feature; // Test on the entity only, there is no third party to restrict on
1074 }
1075 }
1076
1077 // $objectid was already sanitized at begin of this method (can be an int or a list of int separated by comma).
1078 // To avoid an access forbidden with a numeric ref
1079 if ($dbt_select != 'rowid' && $dbt_select != 'id') {
1080 $objectid = "'".$objectid."'";
1081 }
1082
1083 //var_dump($feature, $dbtablename, $parenttableforentity);
1084
1085 // Check permission for objectid on entity only
1086 if (in_array($feature, $check) && !empty($objectid)) { // For $objectid = 0, no check
1087 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1088 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
1089 if (($feature == 'user' || $feature == 'usergroup') && isModEnabled('multicompany')) { // Special for multicompany
1090 if (getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1091 if ($conf->entity == 1 && $user->admin && !$user->entity) {
1092 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1093 $sql .= " AND dbt.entity IS NOT NULL";
1094 } else {
1095 $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1096 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1097 $sql .= " AND ((ug.fk_user = dbt.rowid";
1098 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
1099 $sql .= " OR dbt.entity = 0)"; // Show always superadmin
1100 }
1101 } else {
1102 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1103 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1104 }
1105 } else {
1106 $reg = array();
1107 if ($parenttableforentity && preg_match('/(.*)@(.*)/', $parenttableforentity, $reg)) {
1108 $sql .= ", ".MAIN_DB_PREFIX.$db->sanitize($reg[2])." as dbtp";
1109 $sql .= " WHERE dbt.".$db->sanitize($reg[1])." = dbtp.rowid AND dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1110 $sql .= " AND dbtp.entity IN (".getEntity($sharedelement, 1).")";
1111 } else {
1112 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1113 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1114 }
1115 }
1116 $checkonentityready = 1;
1117 //var_dump($checkonentityready, $sql);
1118 }
1119
1120 if (in_array($feature, $checksoc) && !empty($objectid)) { // We check feature = checksoc. For $objectid = 0, no check
1121 // If external user: Check permission for external users
1122 if ($user->socid > 0) {
1123 if ((string) $user->socid != $objectid) {
1124 return false;
1125 }
1126 } elseif (isModEnabled('societe') && !$user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir')) {
1127 dol_syslog("security.lib.php::checkUserAccessToObject Deny access due: (isModEnabled('societe') && !user->hasRight('societe', 'lire') && !user->hasRight('societe', 'client', 'voir'))", LOG_DEBUG);
1128 return false;
1129 } elseif (isModEnabled("societe") && ($user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir'))) {
1130 // If internal user: Check permission for internal users that are restricted on their objects
1131 $sql = "SELECT COUNT(sc.fk_soc) as nb";
1132 $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
1133 $sql .= ", ".MAIN_DB_PREFIX."societe as s)";
1134 $sql .= " WHERE sc.fk_soc IN (".$db->sanitize($objectid, 1).")";
1135 $sql .= " AND (sc.fk_user = ".((int) $user->id);
1136 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
1137 $userschilds = $user->getAllChildIds();
1138 if (!empty($userschilds)) {
1139 $sql .= " OR sc.fk_user IN (".$db->sanitize(implode(',', $userschilds)).")";
1140 }
1141 }
1142 $sql .= ")";
1143 $sql .= " AND sc.fk_soc = s.rowid";
1144 $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
1145 } elseif (isModEnabled('multicompany')) {
1146 // If multicompany and internal users with all permissions, check user is in correct entity
1147 $sql = "SELECT COUNT(s.rowid) as nb";
1148 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
1149 $sql .= " WHERE s.rowid IN (".$db->sanitize($objectid, 1).")";
1150 $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
1151 }
1152
1153 $checkonentityready = 1;
1154 }
1155
1156 if (in_array($feature, $checkparentsoc) && !empty($objectid)) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...).
1157 if ($user->socid > 0) {
1158 // If external user: Check permission for external users (limtited to their company, even object with company link that is null must remain not visible)
1159 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1160 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1161 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")"; // Link to third party
1162 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1163 $sql .= " AND dbt.fk_soc = ".((int) $user->socid); // Third party must be user company
1164 } elseif (isModEnabled("societe") && ($user->hasRight('societe', 'lire') && !$user->hasRight('societe', 'client', 'voir'))) {
1165 // If internal user: Check permission for internal users that are restricted on their objects
1166 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1167 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1168 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
1169 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1170 $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
1171 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1172 } elseif (isModEnabled('multicompany')) {
1173 // If multicompany and internal users with all permissions, check user is in correct entity
1174 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1175 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1176 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1177 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1178 }
1179
1180 $checkonentityready = 1;
1181 }
1182
1183 if (in_array($feature, $checkproject) && !empty($objectid)) {
1184 if (isModEnabled('project') && !$user->hasRight('projet', 'all', 'lire')) {
1185 $projectid = $objectid; // Note that if $objectid is a string list of id; the test later will return false
1186
1187 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1188 $projectstatic = new Project($db);
1189 $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
1190
1191 $tmparray = explode(',', $tmps);
1192 if (!in_array($projectid, $tmparray)) {
1193 return false;
1194 }
1195 } else {
1196 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1197 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1198 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1199 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1200 }
1201 $checkonentityready = 1;
1202 }
1203
1204 if (in_array($feature, $checktask) && !empty($objectid)) {
1205 if (isModEnabled('project') && !$user->hasRight('projet', 'all', 'lire')) {
1206 if (preg_match('/,/', $objectid)) { // if this is a list of id
1207 return false;
1208 }
1209 $task = new Task($db);
1210 $task->fetch((int) $objectid);
1211 $projectid = $task->fk_project;
1212
1213 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1214 $projectstatic = new Project($db);
1215 $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
1216
1217 $tmparray = explode(',', $tmps);
1218 if (!in_array($projectid, $tmparray)) {
1219 return false;
1220 }
1221 } else {
1222 $sharedelement = 'project'; // for multicompany compatibility
1223 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1224 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1225 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1226 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1227 }
1228
1229 $checkonentityready = 1;
1230 }
1231 //var_dump($checkonentityready, $sql);
1232
1233 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
1234 // If external user: Check permission for external users
1235 if ($user->socid > 0) {
1236 if (empty($dbt_keyfield)) {
1237 dol_print_error(null, 'Param dbt_keyfield is required but not defined');
1238 }
1239 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_keyfield).") as nb";
1240 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1241 $sql .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
1242 $sql .= " AND dbt.".$db->sanitize($dbt_keyfield)." = ".((int) $user->socid);
1243 } elseif (isModEnabled("societe") && !$user->hasRight('societe', 'client', 'voir')) {
1244 // If internal user without permission to see all thirdparties: Check permission for internal users that are restricted on their objects
1245 if (empty($dbt_keyfield)) {
1246 dol_print_error(null, 'Param dbt_keyfield is required but not defined');
1247 }
1248 if ($feature != 'ticket') {
1249 $sql = "SELECT COUNT(sc.fk_soc) as nb";
1250 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
1251 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1252 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1253 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1254 $sql .= " AND sc.fk_soc = dbt.".$db->sanitize($dbt_keyfield);
1255 $sql .= " AND (sc.fk_user = ".((int) $user->id);
1256 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
1257 $userschilds = $user->getAllChildIds();
1258 if (!empty($userschilds)) {
1259 $sql .= " OR sc.fk_user IN (".$db->sanitize(implode(',', $userschilds)).")";
1260 }
1261 }
1262 $sql .= ')';
1263 } else {
1264 // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties.
1265 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1266 $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
1267 $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);
1268 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1269 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1270 $sql .= " AND (sc.fk_user = ".((int) $user->id)." OR dbt.".$dbt_keyfield." IS NULL OR dbt.".$dbt_keyfield." = 0)";
1271 }
1272 } elseif (isModEnabled('multicompany') && (!empty($object->ismultientitymanaged) || !isset($object->ismultientitymanaged))) {
1273 // If multicompany, and user is an internal user with all permissions, check that object is in correct entity
1274 $sql = "SELECT COUNT(dbt.".$db->sanitize($dbt_select).") as nb";
1275 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($dbtablename)." as dbt";
1276 $sql .= " WHERE dbt.".$db->sanitize($dbt_select)." IN (".$db->sanitize($objectid, 1).")";
1277 $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
1278 }
1279 }
1280
1281 // For events, check on users assigned to event
1282 if ($feature === 'agenda' && !empty($objectid)) {
1283 // Also check owner or attendee for users without allactions->read
1284 if (!$user->hasRight('agenda', 'allactions', 'read')) {
1285 if (preg_match('/,/', $objectid)) { // if this is a list of id
1286 return false;
1287 }
1288
1289 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1290 $action = new ActionComm($db);
1291 $action->fetch((int) $objectid);
1292 if ($action->authorid != $user->id && $action->userownerid != $user->id && !(array_key_exists($user->id, $action->userassigned))) {
1293 return false;
1294 }
1295 }
1296 }
1297
1298 // For some object, we also have to check it is in the user hierarchy
1299 // Param $object must be the full object and not a simple id to have this test possible.
1300 if (in_array($feature, $checkhierarchy) && is_object($object) && !empty($objectid)) {
1301 $childids = $user->getAllChildIds(1);
1302 $useridtocheck = 0;
1303 if ($feature == 'holiday') {
1304 $useridtocheck = $object->fk_user;
1305 if (!$user->hasRight('holiday', 'readall') && !in_array($useridtocheck, $childids) && !in_array($object->fk_validator, $childids)) {
1306 return false;
1307 }
1308 }
1309 if ($feature == 'expensereport') {
1310 $useridtocheck = $object->fk_user_author;
1311 if (!$user->hasRight('expensereport', 'readall')) {
1312 if (!in_array($useridtocheck, $childids) && !($user->hasRight('expensereport', 'approve') && $object->fk_user_validator == $user->id)) {
1313 return false;
1314 }
1315 }
1316 }
1317 if ($feature == 'hrm' && in_array('evaluation', $feature2)) {
1318 $useridtocheck = $object->fk_user;
1319
1320 if ($user->hasRight('hrm', 'evaluation', 'readall')) {
1321 // the user can view evaluations for anyone
1322 return true;
1323 }
1324 if (!$user->hasRight('hrm', 'evaluation', 'read')) {
1325 // the user can't view any evaluations
1326 return false;
1327 }
1328 // the user can only see their own evaluations or their subordinates'
1329 return in_array($useridtocheck, $childids);
1330 }
1331 }
1332
1333 // For some object, we also have to check it is public or owned by user
1334 // Param $object must be the full object and not a simple id to have this test possible.
1335 if (in_array($feature, $checkuser) && is_object($object) && !empty($objectid)) {
1336 $useridtocheck = $object->fk_user;
1337 if (!empty($useridtocheck) && $useridtocheck > 0 && $useridtocheck != $user->id && empty($user->admin)) {
1338 return false;
1339 }
1340 }
1341
1342 // A private contact (field priv) can only be accessed by the user that created it
1343 if ($feature == 'contact' && in_array($dbtablename, array('socpeople', 'contact')) && !empty($objectid)) {
1344 $sqlpriv = "SELECT COUNT(dbt.rowid) as nb";
1345 $sqlpriv .= " FROM ".MAIN_DB_PREFIX."socpeople as dbt";
1346 $sqlpriv .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
1347 $sqlpriv .= " AND dbt.priv = 1 AND (dbt.fk_user_creat IS NULL OR dbt.fk_user_creat <> ".((int) $user->id).")";
1348 $resqlpriv = $db->query($sqlpriv);
1349 if (!$resqlpriv) {
1350 return false;
1351 }
1352 $objpriv = $db->fetch_object($resqlpriv);
1353 if ($objpriv && $objpriv->nb > 0) {
1354 return false;
1355 }
1356 }
1357
1358 if ($sql) {
1359 $resql = $db->query($sql);
1360 if ($resql) {
1361 $obj = $db->fetch_object($resql);
1362 if (!$obj || $obj->nb < count(explode(',', $objectid))) { // error if we found 0 or less record than the nb of ids provided
1363 return false;
1364 }
1365 } else {
1366 dol_syslog("Bad forged sql in security.lib.php::checkUserAccessToObject", LOG_WARNING);
1367 return false;
1368 }
1369 }
1370 }
1371
1372 dol_syslog("security.lib.php::checkUserAccessToObject::return True", LOG_DEBUG);
1373 return true;
1374}
1375
1390function getObjectIdsRefusedToUser(User $user, $object, array $ids)
1391{
1392 $feature = '';
1393 $sharedelement = $object->element; // Key used by getEntity() to check the entity, when it differs from the element
1394 switch ($object->element) {
1395 case 'societe':
1396 case 'contact':
1397 case 'contrat':
1398 case 'ticket':
1399 case 'facture':
1400 case 'commande':
1401 case 'propal':
1402 case 'supplier_proposal':
1403 case 'fichinter':
1404 case 'shipping':
1405 case 'reception':
1406 case 'order_supplier':
1407 case 'invoice_supplier':
1408 case 'product':
1409 case 'don':
1410 case 'stock':
1411 case 'user':
1412 case 'usergroup':
1413 case 'website':
1414 case 'payment':
1415 $feature = $object->element;
1416 break;
1417 case 'action':
1418 $feature = 'agenda';
1419 break;
1420 case 'project':
1421 $feature = 'projet';
1422 break;
1423 case 'project_task':
1424 include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
1425 $feature = 'project_task';
1426 break;
1427 case 'member':
1428 $feature = 'adherent';
1429 break;
1430 case 'mo':
1431 $feature = 'mrp';
1432 break;
1433 case 'chargesociales':
1434 $feature = 'chargesociales';
1435 $sharedelement = 'tax';
1436 break;
1437 case 'bank_account':
1438 $feature = 'banque';
1439 break;
1440 case 'category':
1441 $feature = 'categorie';
1442 break;
1443 case 'dolresource':
1444 $feature = 'resource';
1445 break;
1446 case 'knowledgerecord':
1447 $feature = 'knowledgemanagement';
1448 break;
1449 case 'expensereport':
1450 // Not linked to a third party but to its author, who must be in the hierarchy of the user unless he can read
1451 // all expense reports (same rule as checkUserAccessToObject() with the object, and expensereport/card.php).
1452 // checkUserAccessToObject() can't check it with an id only, so all ids are checked with one request.
1453 global $db;
1454 $sanitizedids = [];
1455 foreach ($ids as $id) {
1456 if ((int) $id > 0) {
1457 $sanitizedids[] = (int) $id;
1458 }
1459 }
1460 if (empty($sanitizedids)) {
1461 return [];
1462 }
1463 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."expensereport as t";
1464 $sql .= " WHERE t.rowid IN (".$db->sanitize(implode(',', $sanitizedids)).")";
1465 $sql .= " AND (t.entity NOT IN (".getEntity('expensereport', 1).")";
1466 if (!$user->hasRight('expensereport', 'readall')) {
1467 $sql .= " OR t.fk_user_author NOT IN (".$db->sanitize(implode(',', $user->getAllChildIds(1))).")";
1468 }
1469 $sql .= ")";
1470 $resql = $db->query($sql);
1471 if (!$resql) {
1472 dol_syslog(__FUNCTION__." ".$db->lasterror(), LOG_ERR);
1473 return $sanitizedids;
1474 }
1475 $refusedids = [];
1476 while ($obj = $db->fetch_object($resql)) {
1477 $refusedids[] = (int) $obj->rowid;
1478 }
1479 $db->free($resql);
1480 return $refusedids;
1481 case 'holiday':
1482 // Not linked to a third party but to its employee, who must be in the hierarchy of the user unless he can read all
1483 // leave requests or is the approver of the request (same rule as holiday/card.php). All ids are checked with one request.
1484 global $db;
1485 $sanitizedids = [];
1486 foreach ($ids as $id) {
1487 if ((int) $id > 0) {
1488 $sanitizedids[] = (int) $id;
1489 }
1490 }
1491 if (empty($sanitizedids)) {
1492 return [];
1493 }
1494 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."holiday as t";
1495 $sql .= " WHERE t.rowid IN (".$db->sanitize(implode(',', $sanitizedids)).")";
1496 $sql .= " AND (t.entity NOT IN (".getEntity('holiday', 1).")";
1497 if (!$user->hasRight('holiday', 'readall')) {
1498 $sql .= " OR (t.fk_user NOT IN (".$db->sanitize(implode(',', $user->getAllChildIds(1))).")";
1499 if ($user->hasRight('holiday', 'approve') && !getDolGlobalString('HOLIDAY_CAN_APPROVE_ONLY_THE_SUBORDINATES')) {
1500 $sql .= " AND t.fk_validator <> ".((int) $user->id);
1501 }
1502 $sql .= ")";
1503 }
1504 $sql .= ")";
1505 $resql = $db->query($sql);
1506 if (!$resql) {
1507 dol_syslog(__FUNCTION__." ".$db->lasterror(), LOG_ERR);
1508 return $sanitizedids;
1509 }
1510 $refusedids = [];
1511 while ($obj = $db->fetch_object($resql)) {
1512 $refusedids[] = (int) $obj->rowid;
1513 }
1514 $db->free($resql);
1515 return $refusedids;
1516 case 'salary':
1517 // Not linked to a third party but to its employee, who must be the user, or in his hierarchy if he can read the salaries of
1518 // his subordinates, unless he can read all salaries (same rule as salaries/list.php). All ids are checked with one request.
1519 global $db;
1520 $sanitizedids = [];
1521 foreach ($ids as $id) {
1522 if ((int) $id > 0) {
1523 $sanitizedids[] = (int) $id;
1524 }
1525 }
1526 if (empty($sanitizedids)) {
1527 return [];
1528 }
1529 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."salary as t";
1530 $sql .= " WHERE t.rowid IN (".$db->sanitize(implode(',', $sanitizedids)).")";
1531 $sql .= " AND (t.entity NOT IN (".getEntity('salary', 1).")";
1532 if (!$user->hasRight('salaries', 'readall')) {
1533 if ($user->hasRight('salaries', 'read') && $user->hasRight('salaries', 'readchild')) {
1534 $sql .= " OR t.fk_user IS NULL OR t.fk_user NOT IN (".$db->sanitize(implode(',', $user->getAllChildIds(1))).")";
1535 } elseif ($user->hasRight('salaries', 'read')) {
1536 $sql .= " OR t.fk_user IS NULL OR t.fk_user <> ".((int) $user->id);
1537 } else {
1538 $sql .= " OR 1 = 1";
1539 }
1540 }
1541 $sql .= ")";
1542 $resql = $db->query($sql);
1543 if (!$resql) {
1544 dol_syslog(__FUNCTION__." ".$db->lasterror(), LOG_ERR);
1545 return $sanitizedids;
1546 }
1547 $refusedids = [];
1548 while ($obj = $db->fetch_object($resql)) {
1549 $refusedids[] = (int) $obj->rowid;
1550 }
1551 $db->free($resql);
1552 return $refusedids;
1553 }
1554 if (empty($feature)) {
1555 // No rule known by checkUserAccessToObject() for this type of object (other modules, external modules...): we check
1556 // only the entity, with the same rule as the fetch of the object (field entity of the table or of its parent table).
1557 if (empty($object->table_element) || empty($object->ismultientitymanaged)) {
1558 return [];
1559 }
1560 global $db;
1561 $sanitizedids = [];
1562 foreach ($ids as $id) {
1563 if ((int) $id > 0) {
1564 $sanitizedids[] = (int) $id;
1565 }
1566 }
1567 if (empty($sanitizedids)) {
1568 return [];
1569 }
1570 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX.$db->sanitize($object->table_element)." as t";
1571 if (is_numeric($object->ismultientitymanaged)) {
1572 $sql .= " WHERE t.entity NOT IN (".getEntity($object->element, 1).")";
1573 } else {
1574 // Entity is on a parent table, for example 'fk_soc@societe'
1575 $tmparray = explode('@', $object->ismultientitymanaged);
1576 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$db->sanitize($tmparray[1])." as tp ON t.".$db->sanitize($tmparray[0])." = tp.rowid";
1577 $sql .= " WHERE (tp.rowid IS NULL OR tp.entity NOT IN (".getEntity($object->element, 1)."))";
1578 }
1579 $sql .= " AND t.rowid IN (".$db->sanitize(implode(',', $sanitizedids)).")";
1580 $resql = $db->query($sql);
1581 if (!$resql) {
1582 dol_syslog(__FUNCTION__." ".$db->lasterror(), LOG_ERR);
1583 return $sanitizedids;
1584 }
1585 $refusedids = [];
1586 while ($obj = $db->fetch_object($resql)) {
1587 $refusedids[] = (int) $obj->rowid;
1588 }
1589 $db->free($resql);
1590 return $refusedids;
1591 }
1592
1593 $refusedids = [];
1594 foreach ($ids as $id) {
1595 $id = (int) $id;
1596 if ($id <= 0) {
1597 continue;
1598 }
1599 if (!checkUserAccessToObject($user, [$feature], $id, $object->table_element.'&'.$sharedelement, '', 'fk_soc', 'rowid')) {
1600 $refusedids[] = $id;
1601 }
1602 }
1603
1604 return $refusedids;
1605}
1606
1607
1619function httponly_accessforbidden($message = '1', $http_response_code = 403, $stringalreadysanitized = 0)
1620{
1621 top_httphead();
1622 http_response_code($http_response_code);
1623
1624 if ($stringalreadysanitized) {
1625 print $message;
1626 } else {
1627 print htmlentities($message);
1628 }
1629
1630 exit(1);
1631}
1632
1646function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
1647{
1648 global $conf, $db, $user, $langs, $hookmanager;
1649 global $action, $object;
1650
1651 if (!is_object($langs)) {
1652 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
1653 $langs = new Translate('', $conf);
1654 $langs->setDefaultLang();
1655 }
1656
1657 $langs->loadLangs(array("main", "errors"));
1658
1659 if ($printheader && !defined('NOHEADERNOFOOTER')) {
1660 if (function_exists("llxHeader")) {
1661 llxHeader('');
1662 } elseif (function_exists("llxHeaderVierge")) {
1663 llxHeaderVierge('');
1664 }
1665 print '<div style="padding: 20px">';
1666 }
1667 print '<div class="error">';
1668 if (empty($message)) {
1669 print $langs->trans("ErrorForbidden");
1670 } else {
1671 print $langs->trans($message);
1672 }
1673 print '</div>';
1674 print '<br>';
1675 if (empty($showonlymessage)) {
1676 if (empty($hookmanager)) {
1677 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1678 $hookmanager = new HookManager($db);
1679 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
1680 $hookmanager->initHooks(array('main'));
1681 }
1682
1683 $parameters = array('message' => $message, 'params' => $params);
1684 $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1685 print $hookmanager->resPrint;
1686 if (empty($reshook)) {
1687 $langs->loadLangs(array("errors"));
1688 if ($user->login) {
1689 print $langs->trans("CurrentLogin").': <span class="error">'.$user->login.'</span><br>';
1690 print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users"));
1691 print $langs->trans("ErrorForbidden4");
1692 } else {
1693 print $langs->trans("ErrorForbidden3");
1694 }
1695 }
1696 }
1697 if ($printfooter && !defined('NOHEADERNOFOOTER') && function_exists("llxFooter")) {
1698 print '</div>';
1699 llxFooter();
1700 }
1701
1702 // End PHP
1703 exit(0);
1704}
1705
1706
1714{
1715 $max = getDolGlobalString('MAIN_UPLOAD_DOC'); // In Kb
1716
1717 $maxphp = @ini_get('upload_max_filesize'); // In unknown
1718 if (preg_match('/k$/i', $maxphp)) {
1719 $maxphp = preg_replace('/k$/i', '', $maxphp);
1720 $maxphp = (int) ((float) $maxphp * 1);
1721 }
1722 if (preg_match('/m$/i', $maxphp)) {
1723 $maxphp = preg_replace('/m$/i', '', $maxphp);
1724 $maxphp = (int) ((float) $maxphp * 1024);
1725 }
1726 if (preg_match('/g$/i', $maxphp)) {
1727 $maxphp = preg_replace('/g$/i', '', $maxphp);
1728 $maxphp = (int) ((float) $maxphp * 1024 * 1024);
1729 }
1730 if (preg_match('/t$/i', $maxphp)) {
1731 $maxphp = preg_replace('/t$/i', '', $maxphp);
1732 $maxphp = (int) ((float) $maxphp * 1024 * 1024 * 1024);
1733 }
1734 $maxphp2 = @ini_get('post_max_size'); // In unknown
1735 if (preg_match('/k$/i', $maxphp2)) {
1736 $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
1737 $maxphp2 = (int) ((float) $maxphp2) * 1;
1738 }
1739 if (preg_match('/m$/i', $maxphp2)) {
1740 $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
1741 $maxphp2 = (int) ((float) $maxphp2 * 1024);
1742 }
1743 if (preg_match('/g$/i', $maxphp2)) {
1744 $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
1745 $maxphp2 = (int) ((float) $maxphp2 * 1024 * 1024);
1746 }
1747 if (preg_match('/t$/i', $maxphp2)) {
1748 $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
1749 $maxphp2 = (int) ((float) $maxphp2 * 1024 * 1024 * 1024);
1750 }
1751 // Now $max and $maxphp and $maxphp2 are in Kb
1752 $maxmin = $max;
1753 $maxphptoshow = $maxphptoshowparam = '';
1754 if ($maxphp > 0) {
1755 $maxmin = min($maxmin, $maxphp);
1756 $maxphptoshow = $maxphp;
1757 $maxphptoshowparam = 'upload_max_filesize';
1758 }
1759 if ($maxphp2 > 0) {
1760 $maxmin = min($maxmin, $maxphp2);
1761 if ($maxphp2 < $maxphp) {
1762 $maxphptoshow = $maxphp2;
1763 $maxphptoshowparam = 'post_max_size';
1764 }
1765 }
1766 //var_dump($maxphp.'-'.$maxphp2);
1767 //var_dump($maxmin);
1768
1769 return array('max' => $max, 'maxmin' => $maxmin, 'maxphptoshow' => $maxphptoshow, 'maxphptoshowparam' => $maxphptoshowparam);
1770}
1771
1780function checkIPInCidr($ip, $cidr)
1781{
1782 list($network, $prefix) = explode('/', $cidr, 2);
1783
1784 // Convert IPs to binary format
1785 $ip_bin = @inet_pton($ip);
1786 $net_bin = @inet_pton($network);
1787 if ($ip_bin === false || $net_bin === false) {
1788 return -1;
1789 }
1790
1791 // Require same address IPvX family
1792 if (strlen($ip_bin) !== strlen($net_bin)) { // @phan-suppress-current-line DolibarrForbiddenFunctionPlugin
1793 return -1;
1794 }
1795
1796 // Comparison boundaries
1797 $total_bits = strlen($ip_bin) * 8;
1798 $prefix = max(0, min((int) $prefix, $total_bits));
1799 $full_bytes = intdiv($prefix, 8);
1800 $rem_bits = $prefix % 8;
1801
1802 // Compare full bytes and partial bytes
1803 if ($full_bytes > 0) {
1804 if (substr($ip_bin, 0, $full_bytes) !== substr($net_bin, 0, $full_bytes)) { // @phan-suppress-current-line DolibarrForbiddenFunctionPlugin
1805 return 0;
1806 }
1807 }
1808 if ($rem_bits > 0) {
1809 $mask = (0xFF << (8 - $rem_bits)) & 0xFF;
1810 $ip_byte = ord($ip_bin[$full_bytes]);
1811 $net_byte = ord($net_bin[$full_bytes]);
1812 if (($ip_byte & $mask) !== ($net_byte & $mask)) {
1813 return 0;
1814 }
1815 }
1816 return 1;
1817}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
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
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
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_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
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.
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.
getObjectIdsRefusedToUser(User $user, $object, array $ids)
Return, among a list of ids of objects of the same type, the ids of the objects the user is not allow...
checkUserAccessToDocumentObject(User $user, $modulepart, $original_file, $mode='read')
Check that a user can access the object a document is attached to.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.