dolibarr  16.0.1
security.lib.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2008-2021 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2008-2021 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2020 Ferran Marcet <fmarcet@2byte.es>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <https://www.gnu.org/licenses/>.
18  * or see https://www.gnu.org/
19  */
20 
38 function dol_encode($chain, $key = '1')
39 {
40  if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char
41  $output_tab = array();
42  $strlength = dol_strlen($chain);
43  for ($i = 0; $i < $strlength; $i++) {
44  $output_tab[$i] = chr(ord(substr($chain, $i, 1)) + 17);
45  }
46  $chain = implode("", $output_tab);
47  } elseif ($key) {
48  $result = '';
49  $strlength = dol_strlen($chain);
50  for ($i = 0; $i < $strlength; $i++) {
51  $keychar = substr($key, ($i % strlen($key)) - 1, 1);
52  $result .= chr(ord(substr($chain, $i, 1)) + (ord($keychar) - 65));
53  }
54  $chain = $result;
55  }
56 
57  return base64_encode($chain);
58 }
59 
69 function dol_decode($chain, $key = '1')
70 {
71  $chain = base64_decode($chain);
72 
73  if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char
74  $output_tab = array();
75  $strlength = dol_strlen($chain);
76  for ($i = 0; $i < $strlength; $i++) {
77  $output_tab[$i] = chr(ord(substr($chain, $i, 1)) - 17);
78  }
79 
80  $chain = implode("", $output_tab);
81  } elseif ($key) {
82  $result = '';
83  $strlength = dol_strlen($chain);
84  for ($i = 0; $i < $strlength; $i++) {
85  $keychar = substr($key, ($i % strlen($key)) - 1, 1);
86  $result .= chr(ord(substr($chain, $i, 1)) - (ord($keychar) - 65));
87  }
88  $chain = $result;
89  }
90 
91  return $chain;
92 }
93 
104 function dol_hash($chain, $type = '0')
105 {
106  global $conf;
107 
108  // No need to add salt for password_hash
109  if (($type == '0' || $type == 'auto') && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) {
110  return password_hash($chain, PASSWORD_DEFAULT);
111  }
112 
113  // Salt value
114  if (!empty($conf->global->MAIN_SECURITY_SALT) && $type != '4' && $type !== 'openldap') {
115  $chain = $conf->global->MAIN_SECURITY_SALT.$chain;
116  }
117 
118  if ($type == '1' || $type == 'sha1') {
119  return sha1($chain);
120  } elseif ($type == '2' || $type == 'sha1md5') {
121  return sha1(md5($chain));
122  } elseif ($type == '3' || $type == 'md5') {
123  return md5($chain);
124  } elseif ($type == '4' || $type == 'openldap') {
125  return dolGetLdapPasswordHash($chain, getDolGlobalString('LDAP_PASSWORD_HASH_TYPE', 'md5'));
126  } elseif ($type == '5' || $type == 'sha256') {
127  return hash('sha256', $chain);
128  } elseif ($type == '6' || $type == 'password_hash') {
129  return password_hash($chain, PASSWORD_DEFAULT);
130  } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') {
131  return sha1($chain);
132  } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') {
133  return sha1(md5($chain));
134  }
135 
136  // No particular encoding defined, use default
137  return md5($chain);
138 }
139 
151 function dol_verifyHash($chain, $hash, $type = '0')
152 {
153  global $conf;
154 
155  if ($type == '0' && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) {
156  if ($hash[0] == '$') {
157  return password_verify($chain, $hash);
158  } elseif (strlen($hash) == 32) {
159  return dol_verifyHash($chain, $hash, '3'); // md5
160  } elseif (strlen($hash) == 40) {
161  return dol_verifyHash($chain, $hash, '2'); // sha1md5
162  }
163 
164  return false;
165  }
166 
167  return dol_hash($chain, $type) == $hash;
168 }
169 
177 function dolGetLdapPasswordHash($password, $type = 'md5')
178 {
179  if (empty($type)) {
180  $type = 'md5';
181  }
182 
183  $salt = substr(sha1(time()), 0, 8);
184 
185  if ($type === 'md5') {
186  return '{MD5}' . base64_encode(hash("md5", $password, true)); //For OpenLdap with md5 (based on an unencrypted password in base)
187  } elseif ($type === 'md5frommd5') {
188  return '{MD5}' . base64_encode(hex2bin($password)); // Create OpenLDAP MD5 password from Dolibarr MD5 password
189  } elseif ($type === 'smd5') {
190  return "{SMD5}" . base64_encode(hash("md5", $password . $salt, true) . $salt);
191  } elseif ($type === 'sha') {
192  return '{SHA}' . base64_encode(hash("sha1", $password, true));
193  } elseif ($type === 'ssha') {
194  return "{SSHA}" . base64_encode(hash("sha1", $password . $salt, true) . $salt);
195  } elseif ($type === 'sha256') {
196  return "{SHA256}" . base64_encode(hash("sha256", $password, true));
197  } elseif ($type === 'ssha256') {
198  return "{SSHA256}" . base64_encode(hash("sha256", $password . $salt, true) . $salt);
199  } elseif ($type === 'sha384') {
200  return "{SHA384}" . base64_encode(hash("sha384", $password, true));
201  } elseif ($type === 'ssha384') {
202  return "{SSHA384}" . base64_encode(hash("sha384", $password . $salt, true) . $salt);
203  } elseif ($type === 'sha512') {
204  return "{SHA512}" . base64_encode(hash("sha512", $password, true));
205  } elseif ($type === 'ssha512') {
206  return "{SSHA512}" . base64_encode(hash("sha512", $password . $salt, true) . $salt);
207  } elseif ($type === 'crypt') {
208  return '{CRYPT}' . crypt($password, $salt);
209  } elseif ($type === 'clear') {
210  return '{CLEAR}' . $password; // Just for test, plain text password is not secured !
211  }
212 }
213 
234 function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0, $mode = 0)
235 {
236  global $db, $conf;
237  global $hookmanager;
238 
239  $objectid = ((int) $objectid); // For the case value is coming from a non sanitized user input
240 
241  //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
242  //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid;
243  //print ", dbtablename=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
244  //print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."<br>";
245 
246  $parentfortableentity = '';
247 
248  // Fix syntax of $features param
249  $originalfeatures = $features;
250  if ($features == 'facturerec') {
251  $features = 'facture';
252  }
253  if ($features == 'mo') {
254  $features = 'mrp';
255  }
256  if ($features == 'member') {
257  $features = 'adherent';
258  }
259  if ($features == 'subscription') {
260  $features = 'adherent';
261  $feature2 = 'cotisation';
262  };
263  if ($features == 'websitepage') {
264  $features = 'website';
265  $tableandshare = 'website_page';
266  $parentfortableentity = 'fk_website@website';
267  }
268  if ($features == 'project') {
269  $features = 'projet';
270  }
271  if ($features == 'product') {
272  $features = 'produit';
273  }
274 
275  // Get more permissions checks from hooks
276  $parameters = array('features'=>$features, 'originalfeatures'=>$originalfeatures, 'objectid'=>$objectid, 'dbt_select'=>$dbt_select, 'idtype'=>$dbt_select, 'isdraft'=>$isdraft);
277  $reshook = $hookmanager->executeHooks('restrictedArea', $parameters);
278 
279  if (isset($hookmanager->resArray['result'])) {
280  if ($hookmanager->resArray['result'] == 0) {
281  if ($mode) {
282  return 0;
283  } else {
284  accessforbidden(); // Module returns 0, so access forbidden
285  }
286  }
287  }
288  if ($reshook > 0) { // No other test done.
289  return 1;
290  }
291 
292  // Features/modules to check
293  $featuresarray = array($features);
294  if (preg_match('/&/', $features)) {
295  $featuresarray = explode("&", $features);
296  } elseif (preg_match('/\|/', $features)) {
297  $featuresarray = explode("|", $features);
298  }
299 
300  // More subfeatures to check
301  if (!empty($feature2)) {
302  $feature2 = explode("|", $feature2);
303  }
304 
305  $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL);
306 
307  // Check read permission from module
308  $readok = 1;
309  $nbko = 0;
310  foreach ($featuresarray as $feature) { // first we check nb of test ko
311  $featureforlistofmodule = $feature;
312  if ($featureforlistofmodule == 'produit') {
313  $featureforlistofmodule = 'product';
314  }
315  if (!empty($user->socid) && !empty($conf->global->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
316  $readok = 0;
317  $nbko++;
318  continue;
319  }
320 
321  if ($feature == 'societe') {
322  if (empty($user->rights->societe->lire) && empty($user->rights->fournisseur->lire)) {
323  $readok = 0;
324  $nbko++;
325  }
326  } elseif ($feature == 'contact') {
327  if (empty($user->rights->societe->contact->lire)) {
328  $readok = 0;
329  $nbko++;
330  }
331  } elseif ($feature == 'produit|service') {
332  if (!$user->rights->produit->lire && !$user->rights->service->lire) {
333  $readok = 0;
334  $nbko++;
335  }
336  } elseif ($feature == 'prelevement') {
337  if (!$user->rights->prelevement->bons->lire) {
338  $readok = 0;
339  $nbko++;
340  }
341  } elseif ($feature == 'cheque') {
342  if (empty($user->rights->banque->cheque)) {
343  $readok = 0;
344  $nbko++;
345  }
346  } elseif ($feature == 'projet') {
347  if (!$user->rights->projet->lire && empty($user->rights->projet->all->lire)) {
348  $readok = 0;
349  $nbko++;
350  }
351  } elseif ($feature == 'payment') {
352  if (!$user->rights->facture->lire) {
353  $readok = 0;
354  $nbko++;
355  }
356  } elseif ($feature == 'payment_supplier') {
357  if (empty($user->rights->fournisseur->facture->lire)) {
358  $readok = 0;
359  $nbko++;
360  }
361  } elseif (!empty($feature2)) { // This is for permissions on 2 levels
362  $tmpreadok = 1;
363  foreach ($feature2 as $subfeature) {
364  if ($subfeature == 'user' && $user->id == $objectid) {
365  continue; // A user can always read its own card
366  }
367  if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) {
368  $tmpreadok = 0;
369  } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) {
370  $tmpreadok = 0;
371  } else {
372  $tmpreadok = 1;
373  break;
374  } // Break is to bypass second test if the first is ok
375  }
376  if (!$tmpreadok) { // We found a test on feature that is ko
377  $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko).
378  $nbko++;
379  }
380  } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level
381  if (empty($user->rights->$feature->lire)
382  && empty($user->rights->$feature->read)
383  && empty($user->rights->$feature->run)) {
384  $readok = 0;
385  $nbko++;
386  }
387  }
388  }
389 
390  // If a or and at least one ok
391  if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
392  $readok = 1;
393  }
394 
395  if (!$readok) {
396  if ($mode) {
397  return 0;
398  } else {
399  accessforbidden();
400  }
401  }
402  //print "Read access is ok";
403 
404  // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files)
405  $createok = 1;
406  $nbko = 0;
407  $wemustcheckpermissionforcreate = (GETPOST('sendit', 'alpha') || GETPOST('linkit', 'alpha') || in_array(GETPOST('action', 'aZ09'), array('create', 'update', 'add_element_resource', 'confirm_delete_linked_resource')) || GETPOST('roworder', 'alpha', 2));
408  $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
409 
410  if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) {
411  foreach ($featuresarray as $feature) {
412  if ($feature == 'contact') {
413  if (empty($user->rights->societe->contact->creer)) {
414  $createok = 0;
415  $nbko++;
416  }
417  } elseif ($feature == 'produit|service') {
418  if (empty($user->rights->produit->creer) && empty($user->rights->service->creer)) {
419  $createok = 0;
420  $nbko++;
421  }
422  } elseif ($feature == 'prelevement') {
423  if (!$user->rights->prelevement->bons->creer) {
424  $createok = 0;
425  $nbko++;
426  }
427  } elseif ($feature == 'commande_fournisseur') {
428  if (empty($user->rights->fournisseur->commande->creer) || empty($user->rights->supplier_order->creer)) {
429  $createok = 0;
430  $nbko++;
431  }
432  } elseif ($feature == 'banque') {
433  if (empty($user->rights->banque->modifier)) {
434  $createok = 0;
435  $nbko++;
436  }
437  } elseif ($feature == 'cheque') {
438  if (empty($user->rights->banque->cheque)) {
439  $createok = 0;
440  $nbko++;
441  }
442  } elseif ($feature == 'import') {
443  if (empty($user->rights->import->run)) {
444  $createok = 0;
445  $nbko++;
446  }
447  } elseif ($feature == 'ecm') {
448  if (!$user->rights->ecm->upload) {
449  $createok = 0;
450  $nbko++;
451  }
452  } elseif (!empty($feature2)) { // This is for permissions on one level
453  foreach ($feature2 as $subfeature) {
454  if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) {
455  continue; // User can edit its own card
456  }
457  if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) {
458  continue; // User can edit its own password
459  }
460  if ($subfeature == 'user' && $user->id != $objectid && $user->rights->user->user->password) {
461  continue; // User can edit another user's password
462  }
463 
464  if (empty($user->rights->$feature->$subfeature->creer)
465  && empty($user->rights->$feature->$subfeature->write)
466  && empty($user->rights->$feature->$subfeature->create)) {
467  $createok = 0;
468  $nbko++;
469  } else {
470  $createok = 1;
471  // Break to bypass second test if the first is ok
472  break;
473  }
474  }
475  } elseif (!empty($feature)) { // This is for permissions on 2 levels ('creer' or 'write')
476  //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; exit;
477  if (empty($user->rights->$feature->creer)
478  && empty($user->rights->$feature->write)
479  && empty($user->rights->$feature->create)) {
480  $createok = 0;
481  $nbko++;
482  }
483  }
484  }
485 
486  // If a or and at least one ok
487  if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
488  $createok = 1;
489  }
490 
491  if ($wemustcheckpermissionforcreate && !$createok) {
492  if ($mode) {
493  return 0;
494  } else {
495  accessforbidden();
496  }
497  }
498  //print "Write access is ok";
499  }
500 
501  // Check create user permission
502  $createuserok = 1;
503  if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') {
504  if (!$user->rights->user->user->creer) {
505  $createuserok = 0;
506  }
507 
508  if (!$createuserok) {
509  if ($mode) {
510  return 0;
511  } else {
512  accessforbidden();
513  }
514  }
515  //print "Create user access is ok";
516  }
517 
518  // Check delete permission from module
519  $deleteok = 1;
520  $nbko = 0;
521  if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') {
522  foreach ($featuresarray as $feature) {
523  if ($feature == 'contact') {
524  if (!$user->rights->societe->contact->supprimer) {
525  $deleteok = 0;
526  }
527  } elseif ($feature == 'produit|service') {
528  if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) {
529  $deleteok = 0;
530  }
531  } elseif ($feature == 'commande_fournisseur') {
532  if (!$user->rights->fournisseur->commande->supprimer) {
533  $deleteok = 0;
534  }
535  } elseif ($feature == 'payment_supplier') { // Permission to delete a payment of an invoice is permission to edit an invoice.
536  if (!$user->rights->fournisseur->facture->creer) {
537  $deleteok = 0;
538  }
539  } elseif ($feature == 'payment') {
540  if (!$user->rights->facture->paiement) {
541  $deleteok = 0;
542  }
543  } elseif ($feature == 'banque') {
544  if (empty($user->rights->banque->modifier)) {
545  $deleteok = 0;
546  }
547  } elseif ($feature == 'cheque') {
548  if (empty($user->rights->banque->cheque)) {
549  $deleteok = 0;
550  }
551  } elseif ($feature == 'ecm') {
552  if (!$user->rights->ecm->upload) {
553  $deleteok = 0;
554  }
555  } elseif ($feature == 'ftp') {
556  if (!$user->rights->ftp->write) {
557  $deleteok = 0;
558  }
559  } elseif ($feature == 'salaries') {
560  if (!$user->rights->salaries->delete) {
561  $deleteok = 0;
562  }
563  } elseif ($feature == 'adherent') {
564  if (empty($user->rights->adherent->supprimer)) {
565  $deleteok = 0;
566  }
567  } elseif ($feature == 'paymentbybanktransfer') {
568  if (empty($user->rights->paymentbybanktransfer->create)) { // There is no delete permission
569  $deleteok = 0;
570  }
571  } elseif ($feature == 'prelevement') {
572  if (empty($user->rights->prelevement->bons->creer)) { // There is no delete permission
573  $deleteok = 0;
574  }
575  } elseif (!empty($feature2)) { // This is for permissions on 2 levels
576  foreach ($feature2 as $subfeature) {
577  if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) {
578  $deleteok = 0;
579  } else {
580  $deleteok = 1;
581  break;
582  } // For bypass the second test if the first is ok
583  }
584  } elseif (!empty($feature)) { // This is used for permissions on 1 level
585  //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
586  if (empty($user->rights->$feature->supprimer)
587  && empty($user->rights->$feature->delete)
588  && empty($user->rights->$feature->run)) {
589  $deleteok = 0;
590  }
591  }
592  }
593 
594  // If a or and at least one ok
595  if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
596  $deleteok = 1;
597  }
598 
599  if (!$deleteok && !($isdraft && $createok)) {
600  if ($mode) {
601  return 0;
602  } else {
603  accessforbidden();
604  }
605  }
606  //print "Delete access is ok";
607  }
608 
609  // If we have a particular object to check permissions on, we check if $user has permission
610  // for this given object (link to company, is contact for project, ...)
611  if (!empty($objectid) && $objectid > 0) {
612  $ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity);
613  $params = array('objectid' => $objectid, 'features' => join(',', $featuresarray), 'features2' => $feature2);
614  //print 'checkUserAccessToObject ok='.$ok;
615  if ($mode) {
616  return $ok ? 1 : 0;
617  } else {
618  return $ok ? 1 : accessforbidden('', 1, 1, 0, $params);
619  }
620  }
621 
622  return 1;
623 }
624 
640 function checkUserAccessToObject($user, array $featuresarray, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid', $parenttableforentity = '')
641 {
642  global $db, $conf;
643 
644  if (is_object($object)) {
645  $objectid = $object->id;
646  } else {
647  $objectid = $object; // $objectid can be X or 'X,Y,Z'
648  }
649 
650  //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
651  //print "user_id=".$user->id.", features=".join(',', $featuresarray).", feature2=".$feature2.", objectid=".$objectid;
652  //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."<br>";
653 
654  // More parameters
655  $params = explode('&', $tableandshare);
656  $dbtablename = (!empty($params[0]) ? $params[0] : '');
657  $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
658 
659  foreach ($featuresarray as $feature) {
660  $sql = '';
661 
662  //var_dump($feature);exit;
663 
664  // For backward compatibility
665  if ($feature == 'member') {
666  $feature = 'adherent';
667  }
668  if ($feature == 'project') {
669  $feature = 'projet';
670  }
671  if ($feature == 'task') {
672  $feature = 'projet_task';
673  }
674 
675  $checkonentitydone = 0;
676 
677  // Array to define rules of checks to do
678  $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'payment', 'payment_supplier', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource', 'expensereport', 'holiday', 'salaries', 'website', 'recruitment'); // Test on entity only (Objects with no link to company)
679  $checksoc = array('societe'); // Test for societe object
680  $checkother = array('contact', 'agenda'); // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...).
681  $checkproject = array('projet', 'project'); // Test for project object
682  $checktask = array('projet_task'); // Test for task object
683  $checkhierarchy = array('expensereport', 'holiday');
684  $nocheck = array('barcode', 'stock'); // No test
685  //$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...).
686 
687  // If dbtablename not defined, we use same name for table than module name
688  if (empty($dbtablename)) {
689  $dbtablename = $feature;
690  $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
691  }
692 
693  // Check permission for object on entity only
694  if (in_array($feature, $check)) {
695  $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
696  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
697  if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled)) { // Special for multicompany
698  if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
699  if ($conf->entity == 1 && $user->admin && !$user->entity) {
700  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
701  $sql .= " AND dbt.entity IS NOT NULL";
702  } else {
703  $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
704  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
705  $sql .= " AND ((ug.fk_user = dbt.rowid";
706  $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
707  $sql .= " OR dbt.entity = 0)"; // Show always superadmin
708  }
709  } else {
710  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
711  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
712  }
713  } else {
714  $reg = array();
715  if ($parenttableforentity && preg_match('/(.*)@(.*)/', $parenttableforentity, $reg)) {
716  $sql .= ", ".MAIN_DB_PREFIX.$reg[2]." as dbtp";
717  $sql .= " WHERE dbt.".$reg[1]." = dbtp.rowid AND dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
718  $sql .= " AND dbtp.entity IN (".getEntity($sharedelement, 1).")";
719  } else {
720  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
721  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
722  }
723  }
724  $checkonentitydone = 1;
725  }
726  if (in_array($feature, $checksoc)) { // We check feature = checksoc
727  // If external user: Check permission for external users
728  if ($user->socid > 0) {
729  if ($user->socid != $objectid) {
730  return false;
731  }
732  } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && empty($user->rights->societe->client->voir))) {
733  // If internal user: Check permission for internal users that are restricted on their objects
734  $sql = "SELECT COUNT(sc.fk_soc) as nb";
735  $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
736  $sql .= ", ".MAIN_DB_PREFIX."societe as s)";
737  $sql .= " WHERE sc.fk_soc IN (".$db->sanitize($objectid, 1).")";
738  $sql .= " AND sc.fk_user = ".((int) $user->id);
739  $sql .= " AND sc.fk_soc = s.rowid";
740  $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
741  } elseif (!empty($conf->multicompany->enabled)) {
742  // If multicompany and internal users with all permissions, check user is in correct entity
743  $sql = "SELECT COUNT(s.rowid) as nb";
744  $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
745  $sql .= " WHERE s.rowid IN (".$db->sanitize($objectid, 1).")";
746  $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
747  }
748 
749  $checkonentitydone = 1;
750  }
751  if (in_array($feature, $checkother)) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...).
752  // If external user: Check permission for external users
753  if ($user->socid > 0) {
754  $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
755  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
756  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
757  $sql .= " AND dbt.fk_soc = ".((int) $user->socid);
758  } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && empty($user->rights->societe->client->voir))) {
759  // If internal user: Check permission for internal users that are restricted on their objects
760  $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
761  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
762  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
763  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
764  $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
765  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
766  } elseif (!empty($conf->multicompany->enabled)) {
767  // If multicompany and internal users with all permissions, check user is in correct entity
768  $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
769  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
770  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
771  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
772  }
773 
774  $checkonentitydone = 1;
775  }
776  if (in_array($feature, $checkproject)) {
777  if (!empty($conf->project->enabled) && empty($user->rights->projet->all->lire)) {
778  $projectid = $objectid;
779 
780  include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
781  $projectstatic = new Project($db);
782  $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
783 
784  $tmparray = explode(',', $tmps);
785  if (!in_array($projectid, $tmparray)) {
786  return false;
787  }
788  } else {
789  $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
790  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
791  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
792  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
793  }
794 
795  $checkonentitydone = 1;
796  }
797  if (in_array($feature, $checktask)) {
798  if (!empty($conf->project->enabled) && empty($user->rights->projet->all->lire)) {
799  $task = new Task($db);
800  $task->fetch($objectid);
801  $projectid = $task->fk_project;
802 
803  include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
804  $projectstatic = new Project($db);
805  $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
806 
807  $tmparray = explode(',', $tmps);
808  if (!in_array($projectid, $tmparray)) {
809  return false;
810  }
811  } else {
812  $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
813  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
814  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
815  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
816  }
817 
818  $checkonentitydone = 1;
819  }
820  if (!$checkonentitydone && !in_array($feature, $nocheck)) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
821  // If external user: Check permission for external users
822  if ($user->socid > 0) {
823  if (empty($dbt_keyfield)) {
824  dol_print_error('', 'Param dbt_keyfield is required but not defined');
825  }
826  $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
827  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
828  $sql .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
829  $sql .= " AND dbt.".$dbt_keyfield." = ".((int) $user->socid);
830  } elseif (!empty($conf->societe->enabled) && empty($user->rights->societe->client->voir)) {
831  // If internal user: Check permission for internal users that are restricted on their objects
832  if ($feature != 'ticket') {
833  if (empty($dbt_keyfield)) {
834  dol_print_error('', 'Param dbt_keyfield is required but not defined');
835  }
836  $sql = "SELECT COUNT(sc.fk_soc) as nb";
837  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
838  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
839  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
840  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
841  $sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield;
842  $sql .= " AND sc.fk_user = ".((int) $user->id);
843  } else {
844  // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties.
845  $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
846  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
847  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = dbt.".$dbt_keyfield." AND sc.fk_user = ".((int) $user->id);
848  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
849  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
850  $sql .= " AND (sc.fk_user = ".((int) $user->id)." OR sc.fk_user IS NULL)";
851  }
852  } elseif (!empty($conf->multicompany->enabled)) {
853  // If multicompany and internal users with all permissions, check user is in correct entity
854  $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
855  $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
856  $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
857  $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
858  }
859  }
860  //print $sql;
861 
862  // For events, check on users assigned to event
863  if ($feature === 'agenda') {
864  // Also check owner or attendee for users without allactions->read
865  if ($objectid > 0 && empty($user->rights->agenda->allactions->read)) {
866  require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
867  $action = new ActionComm($db);
868  $action->fetch($objectid);
869  if ($action->authorid != $user->id && $action->userownerid != $user->id && !(array_key_exists($user->id, $action->userassigned))) {
870  return false;
871  }
872  }
873  }
874 
875  // For some object, we also have to check it is in the user hierarchy
876  // Param $object must be the full object and not a simple id to have this test possible.
877  if (in_array($feature, $checkhierarchy) && is_object($object)) {
878  $childids = $user->getAllChildIds(1);
879  $useridtocheck = 0;
880  if ($feature == 'holiday') {
881  $useridtocheck = $object->fk_user;
882  if (!in_array($useridtocheck, $childids)) {
883  return false;
884  }
885  $useridtocheck = $object->fk_validator;
886  if (!in_array($useridtocheck, $childids)) {
887  return false;
888  }
889  }
890  if ($feature == 'expensereport') {
891  $useridtocheck = $object->fk_user_author;
892  if (!$user->rights->expensereport->readall) {
893  if (!in_array($useridtocheck, $childids)) {
894  return false;
895  }
896  }
897  }
898  }
899 
900  if ($sql) {
901  $resql = $db->query($sql);
902  if ($resql) {
903  $obj = $db->fetch_object($resql);
904  if (!$obj || $obj->nb < count(explode(',', $objectid))) { // error if we found 0 or less record than nb of id provided
905  return false;
906  }
907  } else {
908  dol_syslog("Bad forged sql in checkUserAccessToObject", LOG_WARNING);
909  return false;
910  }
911  }
912  }
913 
914  return true;
915 }
916 
928 function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
929 {
930  global $conf, $db, $user, $langs, $hookmanager;
931  if (!is_object($langs)) {
932  include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
933  $langs = new Translate('', $conf);
934  $langs->setDefaultLang();
935  }
936 
937  $langs->load("errors");
938 
939  if ($printheader) {
940  if (function_exists("llxHeader")) {
941  llxHeader('');
942  } elseif (function_exists("llxHeaderVierge")) {
943  llxHeaderVierge('');
944  }
945  }
946  print '<div class="error">';
947  if (!$message) {
948  print $langs->trans("ErrorForbidden");
949  } else {
950  print $message;
951  }
952  print '</div>';
953  print '<br>';
954  if (empty($showonlymessage)) {
955  global $action, $object;
956  if (empty($hookmanager)) {
957  $hookmanager = new HookManager($db);
958  // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
959  $hookmanager->initHooks(array('main'));
960  }
961  $parameters = array('message'=>$message, 'params'=>$params);
962  $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
963  print $hookmanager->resPrint;
964  if (empty($reshook)) {
965  $langs->loadLangs(array("errors"));
966  if ($user->login) {
967  print $langs->trans("CurrentLogin").': <span class="error">'.$user->login.'</span><br>';
968  print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users"));
969  print $langs->trans("ErrorForbidden4");
970  } else {
971  print $langs->trans("ErrorForbidden3");
972  }
973  }
974  }
975  if ($printfooter && function_exists("llxFooter")) {
976  llxFooter();
977  }
978  exit(0);
979 }
980 
981 
989 {
990  global $conf;
991 
992  $max = $conf->global->MAIN_UPLOAD_DOC; // In Kb
993  $maxphp = @ini_get('upload_max_filesize'); // In unknown
994  if (preg_match('/k$/i', $maxphp)) {
995  $maxphp = preg_replace('/k$/i', '', $maxphp);
996  $maxphp = $maxphp * 1;
997  }
998  if (preg_match('/m$/i', $maxphp)) {
999  $maxphp = preg_replace('/m$/i', '', $maxphp);
1000  $maxphp = $maxphp * 1024;
1001  }
1002  if (preg_match('/g$/i', $maxphp)) {
1003  $maxphp = preg_replace('/g$/i', '', $maxphp);
1004  $maxphp = $maxphp * 1024 * 1024;
1005  }
1006  if (preg_match('/t$/i', $maxphp)) {
1007  $maxphp = preg_replace('/t$/i', '', $maxphp);
1008  $maxphp = $maxphp * 1024 * 1024 * 1024;
1009  }
1010  $maxphp2 = @ini_get('post_max_size'); // In unknown
1011  if (preg_match('/k$/i', $maxphp2)) {
1012  $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
1013  $maxphp2 = $maxphp2 * 1;
1014  }
1015  if (preg_match('/m$/i', $maxphp2)) {
1016  $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
1017  $maxphp2 = $maxphp2 * 1024;
1018  }
1019  if (preg_match('/g$/i', $maxphp2)) {
1020  $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
1021  $maxphp2 = $maxphp2 * 1024 * 1024;
1022  }
1023  if (preg_match('/t$/i', $maxphp2)) {
1024  $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
1025  $maxphp2 = $maxphp2 * 1024 * 1024 * 1024;
1026  }
1027  // Now $max and $maxphp and $maxphp2 are in Kb
1028  $maxmin = $max;
1029  $maxphptoshow = $maxphptoshowparam = '';
1030  if ($maxphp > 0) {
1031  $maxmin = min($maxmin, $maxphp);
1032  $maxphptoshow = $maxphp;
1033  $maxphptoshowparam = 'upload_max_filesize';
1034  }
1035  if ($maxphp2 > 0) {
1036  $maxmin = min($maxmin, $maxphp2);
1037  if ($maxphp2 < $maxphp) {
1038  $maxphptoshow = $maxphp2;
1039  $maxphptoshowparam = 'post_max_size';
1040  }
1041  }
1042  //var_dump($maxphp.'-'.$maxphp2);
1043  //var_dump($maxmin);
1044 
1045  return array('max'=>$max, 'maxmin'=>$maxmin, 'maxphptoshow'=>$maxphptoshow, 'maxphptoshowparam'=>$maxphptoshowparam);
1046 }
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
getMaxFileSizeArray()
Return the max allowed for file upload.
dol_hash($chain, $type= '0')
Returns a hash of a string.
dol_decode($chain, $key= '1')
Decode a base 64 encoded + specific delta change.
Class to manage agenda events (actions)
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default= '')
Return dolibarr global constant string value.
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOCSRFCHECK')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:59
dol_verifyHash($chain, $hash, $type= '0')
Compute a hash and compare it to the given one For backward compatibility reasons, if the hash is not in the password_hash format, we will try to match against md5 and sha1md5 If constant MAIN_SECURITY_HASH_ALGO is defined, we use this function as hashing function.
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.
Class to manage hooks.
Class to manage projects.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
dol_encode($chain, $key= '1')
Encode a string with base 64 algorithm + specific delta change.
accessforbidden($message= '', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Class to manage translations.
if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) if(!defined('NOLOGIN')) if(!defined('NOCSRFCHECK')) if(!defined('NOIPCHECK')) llxHeaderVierge()
Header function.
restrictedArea($user, $features, $objectid=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.
if(isModEnabled('facture')&&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur')&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)&&$user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice')&&$user->rights->supplier_invoice->lire)) if(isModEnabled('don')&&!empty($user->rights->don->lire)) if(isModEnabled('tax')&&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture')&&isModEnabled('commande')&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
Class to manage tasks.
Definition: task.class.php:37
dolGetLdapPasswordHash($password, $type= 'md5')
Returns a specific ldap hash of a password.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
llxFooter()
Empty footer.
Definition: wrapper.php:73