PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/core/lib/security.lib.php

http://github.com/Dolibarr/dolibarr
PHP | 872 lines | 654 code | 59 blank | 159 comment | 314 complexity | 98b90091f989bb2408b145532808c581 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-3.0, LGPL-2.0, CC-BY-SA-4.0, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, MIT
  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. /**
  21. * \file htdocs/core/lib/security.lib.php
  22. * \ingroup core
  23. * \brief Set of function used for dolibarr security (common function included into filefunc.inc.php)
  24. * Warning, this file must not depends on other library files, except function.lib.php
  25. * because it is used at low code level.
  26. */
  27. /**
  28. * Encode a string with base 64 algorithm + specific delta change.
  29. *
  30. * @param string $chain string to encode
  31. * @param string $key rule to use for delta ('0', '1' or 'myownkey')
  32. * @return string encoded string
  33. * @see dol_decode()
  34. */
  35. function dol_encode($chain, $key = '1')
  36. {
  37. if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char
  38. $output_tab = array();
  39. $strlength = dol_strlen($chain);
  40. for ($i = 0; $i < $strlength; $i++) {
  41. $output_tab[$i] = chr(ord(substr($chain, $i, 1)) + 17);
  42. }
  43. $chain = implode("", $output_tab);
  44. } elseif ($key) {
  45. $result = '';
  46. $strlength = dol_strlen($chain);
  47. for ($i = 0; $i < $strlength; $i++) {
  48. $keychar = substr($key, ($i % strlen($key)) - 1, 1);
  49. $result .= chr(ord(substr($chain, $i, 1)) + (ord($keychar) - 65));
  50. }
  51. $chain = $result;
  52. }
  53. return base64_encode($chain);
  54. }
  55. /**
  56. * Decode a base 64 encoded + specific delta change.
  57. * This function is called by filefunc.inc.php at each page call.
  58. *
  59. * @param string $chain string to decode
  60. * @param string $key rule to use for delta ('0', '1' or 'myownkey')
  61. * @return string decoded string
  62. * @see dol_encode()
  63. */
  64. function dol_decode($chain, $key = '1')
  65. {
  66. $chain = base64_decode($chain);
  67. if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char
  68. $output_tab = array();
  69. $strlength = dol_strlen($chain);
  70. for ($i = 0; $i < $strlength; $i++) {
  71. $output_tab[$i] = chr(ord(substr($chain, $i, 1)) - 17);
  72. }
  73. $chain = implode("", $output_tab);
  74. } elseif ($key) {
  75. $result = '';
  76. $strlength = dol_strlen($chain);
  77. for ($i = 0; $i < $strlength; $i++) {
  78. $keychar = substr($key, ($i % strlen($key)) - 1, 1);
  79. $result .= chr(ord(substr($chain, $i, 1)) - (ord($keychar) - 65));
  80. }
  81. $chain = $result;
  82. }
  83. return $chain;
  84. }
  85. /**
  86. * Returns a hash of a string.
  87. * If constant MAIN_SECURITY_HASH_ALGO is defined, we use this function as hashing function (recommanded value is 'password_hash')
  88. * If constant MAIN_SECURITY_SALT is defined, we use it as a salt (used only if hashing algorightm is something else than 'password_hash').
  89. *
  90. * @param string $chain String to hash
  91. * @param string $type Type of hash ('0':auto will use MAIN_SECURITY_HASH_ALGO else md5, '1':sha1, '2':sha1+md5, '3':md5, '4':md5 for OpenLdap with no salt, '5':sha256, '6':password_hash). Use '3' here, if hash is not needed for security purpose, for security need, prefer '0'.
  92. * @return string Hash of string
  93. * @see getRandomPassword()
  94. */
  95. function dol_hash($chain, $type = '0')
  96. {
  97. global $conf;
  98. // No need to add salt for password_hash
  99. if (($type == '0' || $type == 'auto') && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) {
  100. return password_hash($chain, PASSWORD_DEFAULT);
  101. }
  102. // Salt value
  103. if (!empty($conf->global->MAIN_SECURITY_SALT) && $type != '4' && $type !== 'md5openldap') {
  104. $chain = $conf->global->MAIN_SECURITY_SALT.$chain;
  105. }
  106. if ($type == '1' || $type == 'sha1') {
  107. return sha1($chain);
  108. } elseif ($type == '2' || $type == 'sha1md5') {
  109. return sha1(md5($chain));
  110. } elseif ($type == '3' || $type == 'md5') {
  111. return md5($chain);
  112. } elseif ($type == '4' || $type == 'md5openldap') {
  113. return '{md5}'.base64_encode(pack("H*", md5($chain))); // For OpenLdap with md5 (based on an unencrypted password in base)
  114. } elseif ($type == '5' || $type == 'sha256') {
  115. return hash('sha256', $chain);
  116. } elseif ($type == '6' || $type == 'password_hash') {
  117. return password_hash($chain, PASSWORD_DEFAULT);
  118. } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') {
  119. return sha1($chain);
  120. } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') {
  121. return sha1(md5($chain));
  122. }
  123. // No particular encoding defined, use default
  124. return md5($chain);
  125. }
  126. /**
  127. * Compute a hash and compare it to the given one
  128. * For backward compatibility reasons, if the hash is not in the password_hash format, we will try to match against md5 and sha1md5
  129. * If constant MAIN_SECURITY_HASH_ALGO is defined, we use this function as hashing function.
  130. * If constant MAIN_SECURITY_SALT is defined, we use it as a salt.
  131. *
  132. * @param string $chain String to hash (not hashed string)
  133. * @param string $hash hash to compare
  134. * @param string $type Type of hash ('0':auto, '1':sha1, '2':sha1+md5, '3':md5, '4':md5 for OpenLdap, '5':sha256). Use '3' here, if hash is not needed for security purpose, for security need, prefer '0'.
  135. * @return bool True if the computed hash is the same as the given one
  136. */
  137. function dol_verifyHash($chain, $hash, $type = '0')
  138. {
  139. global $conf;
  140. if ($type == '0' && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) {
  141. if ($hash[0] == '$') {
  142. return password_verify($chain, $hash);
  143. } elseif (strlen($hash) == 32) {
  144. return dol_verifyHash($chain, $hash, '3'); // md5
  145. } elseif (strlen($hash) == 40) {
  146. return dol_verifyHash($chain, $hash, '2'); // sha1md5
  147. }
  148. return false;
  149. }
  150. return dol_hash($chain, $type) == $hash;
  151. }
  152. /**
  153. * Check permissions of a user to show a page and an object. Check read permission.
  154. * If GETPOST('action','aZ09') defined, we also check write and delete permission.
  155. * This method check permission on module then call checkUserAccessToObject() for permission on object (according to entity and socid of user).
  156. *
  157. * @param User $user User to check
  158. * @param string $features Features to check (it must be module $object->element. Can be a 'or' check with 'levela|levelb'.
  159. * Examples: 'societe', 'contact', 'produit&service', 'produit|service', ...)
  160. * This is used to check permission $user->rights->features->...
  161. * @param int $objectid Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional).
  162. * @param string $tableandshare 'TableName&SharedElement' with Tablename is table where object is stored. SharedElement is an optional key to define where to check entity for multicompany module. Param not used if objectid is null (optional).
  163. * @param string $feature2 Feature to check, second level of permission (optional). Can be a 'or' check with 'sublevela|sublevelb'.
  164. * This is used to check permission $user->rights->features->feature2...
  165. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional)
  166. * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional)
  167. * @param int $isdraft 1=The object with id=$objectid is a draft
  168. * @param int $mode Mode (0=default, 1=return with not die)
  169. * @return int If mode = 0 (default): Always 1, die process if not allowed. If mode = 1: Return 0 if access not allowed.
  170. * @see dol_check_secure_access_document(), checkUserAccessToObject()
  171. */
  172. function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0, $mode = 0)
  173. {
  174. global $db, $conf;
  175. global $hookmanager;
  176. //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
  177. //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid;
  178. //print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
  179. //print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."<br>";
  180. $parentfortableentity = '';
  181. // Fix syntax of $features param
  182. $originalfeatures = $features;
  183. if ($features == 'facturerec') {
  184. $features = 'facture';
  185. }
  186. if ($features == 'mo') {
  187. $features = 'mrp';
  188. }
  189. if ($features == 'member') {
  190. $features = 'adherent';
  191. }
  192. if ($features == 'subscription') {
  193. $features = 'adherent';
  194. $feature2 = 'cotisation';
  195. };
  196. if ($features == 'websitepage') {
  197. $features = 'website';
  198. $tableandshare = 'website_page';
  199. $parentfortableentity = 'fk_website@website';
  200. }
  201. if ($features == 'project') {
  202. $features = 'projet';
  203. }
  204. if ($features == 'product') {
  205. $features = 'produit';
  206. }
  207. // Get more permissions checks from hooks
  208. $parameters = array('features'=>$features, 'originalfeatures'=>$originalfeatures, 'objectid'=>$objectid, 'dbt_select'=>$dbt_select, 'idtype'=>$dbt_select, 'isdraft'=>$isdraft);
  209. $reshook = $hookmanager->executeHooks('restrictedArea', $parameters);
  210. if (isset($hookmanager->resArray['result'])) {
  211. if ($hookmanager->resArray['result'] == 0) {
  212. if ($mode) {
  213. return 0;
  214. } else {
  215. accessforbidden(); // Module returns 0, so access forbidden
  216. }
  217. }
  218. }
  219. if ($reshook > 0) { // No other test done.
  220. return 1;
  221. }
  222. if ($dbt_select != 'rowid' && $dbt_select != 'id') {
  223. $objectid = "'".$objectid."'";
  224. }
  225. // Features/modules to check
  226. $featuresarray = array($features);
  227. if (preg_match('/&/', $features)) {
  228. $featuresarray = explode("&", $features);
  229. } elseif (preg_match('/\|/', $features)) {
  230. $featuresarray = explode("|", $features);
  231. }
  232. // More subfeatures to check
  233. if (!empty($feature2)) {
  234. $feature2 = explode("|", $feature2);
  235. }
  236. $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL);
  237. // Check read permission from module
  238. $readok = 1;
  239. $nbko = 0;
  240. foreach ($featuresarray as $feature) { // first we check nb of test ko
  241. $featureforlistofmodule = $feature;
  242. if ($featureforlistofmodule == 'produit') {
  243. $featureforlistofmodule = 'product';
  244. }
  245. 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
  246. $readok = 0;
  247. $nbko++;
  248. continue;
  249. }
  250. if ($feature == 'societe') {
  251. if (empty($user->rights->societe->lire) && empty($user->rights->fournisseur->lire)) {
  252. $readok = 0;
  253. $nbko++;
  254. }
  255. } elseif ($feature == 'contact') {
  256. if (empty($user->rights->societe->contact->lire)) {
  257. $readok = 0;
  258. $nbko++;
  259. }
  260. } elseif ($feature == 'produit|service') {
  261. if (!$user->rights->produit->lire && !$user->rights->service->lire) {
  262. $readok = 0;
  263. $nbko++;
  264. }
  265. } elseif ($feature == 'prelevement') {
  266. if (!$user->rights->prelevement->bons->lire) {
  267. $readok = 0;
  268. $nbko++;
  269. }
  270. } elseif ($feature == 'cheque') {
  271. if (empty($user->rights->banque->cheque)) {
  272. $readok = 0;
  273. $nbko++;
  274. }
  275. } elseif ($feature == 'projet') {
  276. if (!$user->rights->projet->lire && empty($user->rights->projet->all->lire)) {
  277. $readok = 0;
  278. $nbko++;
  279. }
  280. } elseif ($feature == 'payment') {
  281. if (!$user->rights->facture->lire) {
  282. $readok = 0;
  283. $nbko++;
  284. }
  285. } elseif ($feature == 'payment_supplier') {
  286. if (empty($user->rights->fournisseur->facture->lire)) {
  287. $readok = 0;
  288. $nbko++;
  289. }
  290. } elseif (!empty($feature2)) { // This is for permissions on 2 levels
  291. $tmpreadok = 1;
  292. foreach ($feature2 as $subfeature) {
  293. if ($subfeature == 'user' && $user->id == $objectid) {
  294. continue; // A user can always read its own card
  295. }
  296. if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) {
  297. $tmpreadok = 0;
  298. } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) {
  299. $tmpreadok = 0;
  300. } else {
  301. $tmpreadok = 1;
  302. break;
  303. } // Break is to bypass second test if the first is ok
  304. }
  305. if (!$tmpreadok) { // We found a test on feature that is ko
  306. $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko).
  307. $nbko++;
  308. }
  309. } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level
  310. if (empty($user->rights->$feature->lire)
  311. && empty($user->rights->$feature->read)
  312. && empty($user->rights->$feature->run)) {
  313. $readok = 0;
  314. $nbko++;
  315. }
  316. }
  317. }
  318. // If a or and at least one ok
  319. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  320. $readok = 1;
  321. }
  322. if (!$readok) {
  323. if ($mode) {
  324. return 0;
  325. } else {
  326. accessforbidden();
  327. }
  328. }
  329. //print "Read access is ok";
  330. // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files)
  331. $createok = 1;
  332. $nbko = 0;
  333. $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));
  334. $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
  335. if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) {
  336. foreach ($featuresarray as $feature) {
  337. if ($feature == 'contact') {
  338. if (empty($user->rights->societe->contact->creer)) {
  339. $createok = 0;
  340. $nbko++;
  341. }
  342. } elseif ($feature == 'produit|service') {
  343. if (empty($user->rights->produit->creer) && empty($user->rights->service->creer)) {
  344. $createok = 0;
  345. $nbko++;
  346. }
  347. } elseif ($feature == 'prelevement') {
  348. if (!$user->rights->prelevement->bons->creer) {
  349. $createok = 0;
  350. $nbko++;
  351. }
  352. } elseif ($feature == 'commande_fournisseur') {
  353. if (empty($user->rights->fournisseur->commande->creer) || empty($user->rights->supplier_order->creer)) {
  354. $createok = 0;
  355. $nbko++;
  356. }
  357. } elseif ($feature == 'banque') {
  358. if (empty($user->rights->banque->modifier)) {
  359. $createok = 0;
  360. $nbko++;
  361. }
  362. } elseif ($feature == 'cheque') {
  363. if (empty($user->rights->banque->cheque)) {
  364. $createok = 0;
  365. $nbko++;
  366. }
  367. } elseif ($feature == 'import') {
  368. if (empty($user->rights->import->run)) {
  369. $createok = 0;
  370. $nbko++;
  371. }
  372. } elseif ($feature == 'ecm') {
  373. if (!$user->rights->ecm->upload) {
  374. $createok = 0;
  375. $nbko++;
  376. }
  377. } elseif (!empty($feature2)) { // This is for permissions on one level
  378. foreach ($feature2 as $subfeature) {
  379. if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) {
  380. continue; // User can edit its own card
  381. }
  382. if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) {
  383. continue; // User can edit its own password
  384. }
  385. if ($subfeature == 'user' && $user->id != $objectid && $user->rights->user->user->password) {
  386. continue; // User can edit another user's password
  387. }
  388. if (empty($user->rights->$feature->$subfeature->creer)
  389. && empty($user->rights->$feature->$subfeature->write)
  390. && empty($user->rights->$feature->$subfeature->create)) {
  391. $createok = 0;
  392. $nbko++;
  393. } else {
  394. $createok = 1;
  395. // Break to bypass second test if the first is ok
  396. break;
  397. }
  398. }
  399. } elseif (!empty($feature)) { // This is for permissions on 2 levels ('creer' or 'write')
  400. //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; exit;
  401. if (empty($user->rights->$feature->creer)
  402. && empty($user->rights->$feature->write)
  403. && empty($user->rights->$feature->create)) {
  404. $createok = 0;
  405. $nbko++;
  406. }
  407. }
  408. }
  409. // If a or and at least one ok
  410. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  411. $createok = 1;
  412. }
  413. if ($wemustcheckpermissionforcreate && !$createok) {
  414. if ($mode) {
  415. return 0;
  416. } else {
  417. accessforbidden();
  418. }
  419. }
  420. //print "Write access is ok";
  421. }
  422. // Check create user permission
  423. $createuserok = 1;
  424. if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') {
  425. if (!$user->rights->user->user->creer) {
  426. $createuserok = 0;
  427. }
  428. if (!$createuserok) {
  429. if ($mode) {
  430. return 0;
  431. } else {
  432. accessforbidden();
  433. }
  434. }
  435. //print "Create user access is ok";
  436. }
  437. // Check delete permission from module
  438. $deleteok = 1;
  439. $nbko = 0;
  440. if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') {
  441. foreach ($featuresarray as $feature) {
  442. if ($feature == 'contact') {
  443. if (!$user->rights->societe->contact->supprimer) {
  444. $deleteok = 0;
  445. }
  446. } elseif ($feature == 'produit|service') {
  447. if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) {
  448. $deleteok = 0;
  449. }
  450. } elseif ($feature == 'commande_fournisseur') {
  451. if (!$user->rights->fournisseur->commande->supprimer) {
  452. $deleteok = 0;
  453. }
  454. } elseif ($feature == 'payment_supplier') { // Permission to delete a payment of an invoice is permission to edit an invoice.
  455. if (!$user->rights->fournisseur->facture->creer) {
  456. $deleteok = 0;
  457. }
  458. } elseif ($feature == 'payment') { // Permission to delete a payment of an invoice is permission to edit an invoice.
  459. if (!$user->rights->facture->creer) {
  460. $deleteok = 0;
  461. }
  462. } elseif ($feature == 'banque') {
  463. if (empty($user->rights->banque->modifier)) {
  464. $deleteok = 0;
  465. }
  466. } elseif ($feature == 'cheque') {
  467. if (empty($user->rights->banque->cheque)) {
  468. $deleteok = 0;
  469. }
  470. } elseif ($feature == 'ecm') {
  471. if (!$user->rights->ecm->upload) {
  472. $deleteok = 0;
  473. }
  474. } elseif ($feature == 'ftp') {
  475. if (!$user->rights->ftp->write) {
  476. $deleteok = 0;
  477. }
  478. } elseif ($feature == 'salaries') {
  479. if (!$user->rights->salaries->delete) {
  480. $deleteok = 0;
  481. }
  482. } elseif ($feature == 'adherent') {
  483. if (empty($user->rights->adherent->supprimer)) {
  484. $deleteok = 0;
  485. }
  486. } elseif (!empty($feature2)) { // This is for permissions on 2 levels
  487. foreach ($feature2 as $subfeature) {
  488. if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) {
  489. $deleteok = 0;
  490. } else {
  491. $deleteok = 1;
  492. break;
  493. } // For bypass the second test if the first is ok
  494. }
  495. } elseif (!empty($feature)) { // This is used for permissions on 1 level
  496. //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
  497. if (empty($user->rights->$feature->supprimer)
  498. && empty($user->rights->$feature->delete)
  499. && empty($user->rights->$feature->run)) {
  500. $deleteok = 0;
  501. }
  502. }
  503. }
  504. // If a or and at least one ok
  505. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  506. $deleteok = 1;
  507. }
  508. if (!$deleteok && !($isdraft && $createok)) {
  509. if ($mode) {
  510. return 0;
  511. } else {
  512. accessforbidden();
  513. }
  514. }
  515. //print "Delete access is ok";
  516. }
  517. // If we have a particular object to check permissions on, we check if $user has permission
  518. // for this given object (link to company, is contact for project, ...)
  519. if (!empty($objectid) && $objectid > 0) {
  520. $ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity);
  521. $params = array('objectid' => $objectid, 'features' => join(',', $featuresarray), 'features2' => $feature2);
  522. //print 'checkUserAccessToObject ok='.$ok;
  523. if ($mode) {
  524. return $ok ? 1 : 0;
  525. } else {
  526. return $ok ? 1 : accessforbidden('', 1, 1, 0, $params);
  527. }
  528. }
  529. return 1;
  530. }
  531. /**
  532. * Check access by user to object is ok.
  533. * This function is also called by restrictedArea that check before if module is enabled and if permission of user for $action is ok.
  534. *
  535. * @param User $user User to check
  536. * @param array $featuresarray Features/modules to check. Example: ('user','service','member','project','task',...)
  537. * @param int|string $objectid Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional).
  538. * @param string $tableandshare 'TableName&SharedElement' with Tablename is table where object is stored. SharedElement is an optional key to define where to check entity for multicompany modume. Param not used if objectid is null (optional).
  539. * @param string $feature2 Feature to check, second level of permission (optional). Can be or check with 'level1|level2'.
  540. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional)
  541. * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional)
  542. * @param string $parenttableforentity Parent table for entity. Example 'fk_website@website'
  543. * @return bool True if user has access, False otherwise
  544. * @see restrictedArea()
  545. */
  546. function checkUserAccessToObject($user, array $featuresarray, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid', $parenttableforentity = '')
  547. {
  548. global $db, $conf;
  549. //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
  550. //print "user_id=".$user->id.", features=".join(',', $featuresarray).", feature2=".$feature2.", objectid=".$objectid;
  551. //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."<br>";
  552. // More parameters
  553. $params = explode('&', $tableandshare);
  554. $dbtablename = (!empty($params[0]) ? $params[0] : '');
  555. $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
  556. foreach ($featuresarray as $feature) {
  557. $sql = '';
  558. //var_dump($feature);
  559. // For backward compatibility
  560. if ($feature == 'member') {
  561. $feature = 'adherent';
  562. }
  563. if ($feature == 'project') {
  564. $feature = 'projet';
  565. }
  566. if ($feature == 'task') {
  567. $feature = 'projet_task';
  568. }
  569. $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'payment', 'payment_supplier', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource', 'expensereport', 'holiday', 'salaries', 'website'); // Test on entity only (Objects with no link to company)
  570. $checksoc = array('societe'); // Test for societe object
  571. $checkother = array('contact', 'agenda'); // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...).
  572. $checkproject = array('projet', 'project'); // Test for project object
  573. $checktask = array('projet_task'); // Test for task object
  574. $nocheck = array('barcode', 'stock'); // No test
  575. //$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...).
  576. // If dbtablename not defined, we use same name for table than module name
  577. if (empty($dbtablename)) {
  578. $dbtablename = $feature;
  579. $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
  580. }
  581. // Check permission for object on entity only
  582. if (in_array($feature, $check)) {
  583. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  584. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  585. if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled)) { // Special for multicompany
  586. if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  587. if ($conf->entity == 1 && $user->admin && !$user->entity) {
  588. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  589. $sql .= " AND dbt.entity IS NOT NULL";
  590. } else {
  591. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  592. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  593. $sql .= " AND ((ug.fk_user = dbt.rowid";
  594. $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
  595. $sql .= " OR dbt.entity = 0)"; // Show always superadmin
  596. }
  597. } else {
  598. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  599. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  600. }
  601. } else {
  602. $reg = array();
  603. if ($parenttableforentity && preg_match('/(.*)@(.*)/', $parenttableforentity, $reg)) {
  604. $sql .= ", ".MAIN_DB_PREFIX.$reg[2]." as dbtp";
  605. $sql .= " WHERE dbt.".$reg[1]." = dbtp.rowid AND dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  606. $sql .= " AND dbtp.entity IN (".getEntity($sharedelement, 1).")";
  607. } else {
  608. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  609. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  610. }
  611. }
  612. } elseif (in_array($feature, $checksoc)) { // We check feature = checksoc
  613. // If external user: Check permission for external users
  614. if ($user->socid > 0) {
  615. if ($user->socid <> $objectid) {
  616. return false;
  617. }
  618. } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && empty($user->rights->societe->client->voir))) {
  619. // If internal user: Check permission for internal users that are restricted on their objects
  620. $sql = "SELECT COUNT(sc.fk_soc) as nb";
  621. $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
  622. $sql .= ", ".MAIN_DB_PREFIX."societe as s)";
  623. $sql .= " WHERE sc.fk_soc IN (".$db->sanitize($objectid, 1).")";
  624. $sql .= " AND sc.fk_user = ".((int) $user->id);
  625. $sql .= " AND sc.fk_soc = s.rowid";
  626. $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
  627. } elseif (!empty($conf->multicompany->enabled)) {
  628. // If multicompany and internal users with all permissions, check user is in correct entity
  629. $sql = "SELECT COUNT(s.rowid) as nb";
  630. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  631. $sql .= " WHERE s.rowid IN (".$db->sanitize($objectid, 1).")";
  632. $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
  633. }
  634. } elseif (in_array($feature, $checkother)) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...).
  635. // If external user: Check permission for external users
  636. if ($user->socid > 0) {
  637. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  638. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  639. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  640. $sql .= " AND dbt.fk_soc = ".((int) $user->socid);
  641. } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && empty($user->rights->societe->client->voir))) {
  642. // If internal user: Check permission for internal users that are restricted on their objects
  643. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  644. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  645. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  646. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  647. $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
  648. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  649. } elseif (!empty($conf->multicompany->enabled)) {
  650. // If multicompany and internal users with all permissions, check user is in correct entity
  651. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  652. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  653. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  654. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  655. }
  656. if ($feature == 'agenda') {
  657. // Also check owner or attendee for users without allactions->read
  658. if ($objectid > 0 && empty($user->rights->agenda->allactions->read)) {
  659. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  660. $action = new ActionComm($db);
  661. $action->fetch($objectid);
  662. if ($action->authorid != $user->id && $action->userownerid != $user->id && !(array_key_exists($user->id, $action->userassigned))) {
  663. return false;
  664. }
  665. }
  666. }
  667. } elseif (in_array($feature, $checkproject)) {
  668. if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) {
  669. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  670. $projectstatic = new Project($db);
  671. $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
  672. $tmparray = explode(',', $tmps);
  673. if (!in_array($objectid, $tmparray)) {
  674. return false;
  675. }
  676. } else {
  677. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  678. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  679. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  680. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  681. }
  682. } elseif (in_array($feature, $checktask)) {
  683. if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) {
  684. $task = new Task($db);
  685. $task->fetch($objectid);
  686. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  687. $projectstatic = new Project($db);
  688. $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
  689. $tmparray = explode(',', $tmps);
  690. if (!in_array($task->fk_project, $tmparray)) {
  691. return false;
  692. }
  693. } else {
  694. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  695. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  696. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  697. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  698. }
  699. } elseif (!in_array($feature, $nocheck)) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
  700. // If external user: Check permission for external users
  701. if ($user->socid > 0) {
  702. if (empty($dbt_keyfield)) {
  703. dol_print_error('', 'Param dbt_keyfield is required but not defined');
  704. }
  705. $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
  706. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  707. $sql .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
  708. $sql .= " AND dbt.".$dbt_keyfield." = ".((int) $user->socid);
  709. } elseif (!empty($conf->societe->enabled) && empty($user->rights->societe->client->voir)) {
  710. // If internal user: Check permission for internal users that are restricted on their objects
  711. if ($feature != 'ticket') {
  712. if (empty($dbt_keyfield)) {
  713. dol_print_error('', 'Param dbt_keyfield is required but not defined');
  714. }
  715. $sql = "SELECT COUNT(sc.fk_soc) as nb";
  716. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  717. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  718. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  719. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  720. $sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield;
  721. $sql .= " AND sc.fk_user = ".((int) $user->id);
  722. } else {
  723. // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties.
  724. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  725. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  726. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = dbt.".$dbt_keyfield." AND sc.fk_user = ".((int) $user->id);
  727. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  728. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  729. $sql .= " AND (sc.fk_user = ".((int) $user->id)." OR sc.fk_user IS NULL)";
  730. }
  731. } elseif (!empty($conf->multicompany->enabled)) {
  732. // If multicompany and internal users with all permissions, check user is in correct entity
  733. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  734. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  735. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  736. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  737. }
  738. }
  739. //print $sql;
  740. if ($sql) {
  741. $resql = $db->query($sql);
  742. if ($resql) {
  743. $obj = $db->fetch_object($resql);
  744. if (!$obj || $obj->nb < count(explode(',', $objectid))) {
  745. return false;
  746. }
  747. } else {
  748. dol_syslog("Bad forged sql in checkUserAccessToObject", LOG_WARNING);
  749. return false;
  750. }
  751. }
  752. }
  753. return true;
  754. }
  755. /**
  756. * Show a message to say access is forbidden and stop program
  757. * Calling this function terminate execution of PHP.
  758. *
  759. * @param string $message Force error message
  760. * @param int $printheader Show header before
  761. * @param int $printfooter Show footer after
  762. * @param int $showonlymessage Show only message parameter. Otherwise add more information.
  763. * @param array|null $params More parameters provided to hook
  764. * @return void
  765. */
  766. function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
  767. {
  768. global $conf, $db, $user, $langs, $hookmanager;
  769. if (!is_object($langs)) {
  770. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  771. $langs = new Translate('', $conf);
  772. $langs->setDefaultLang();
  773. }
  774. $langs->load("errors");
  775. if ($printheader) {
  776. if (function_exists("llxHeader")) {
  777. llxHeader('');
  778. } elseif (function_exists("llxHeaderVierge")) {
  779. llxHeaderVierge('');
  780. }
  781. }
  782. print '<div class="error">';
  783. if (!$message) {
  784. print $langs->trans("ErrorForbidden");
  785. } else {
  786. print $message;
  787. }
  788. print '</div>';
  789. print '<br>';
  790. if (empty($showonlymessage)) {
  791. global $action, $object;
  792. if (empty($hookmanager)) {
  793. $hookmanager = new HookManager($db);
  794. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  795. $hookmanager->initHooks(array('main'));
  796. }
  797. $parameters = array('message'=>$message, 'params'=>$params);
  798. $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  799. print $hookmanager->resPrint;
  800. if (empty($reshook)) {
  801. if ($user->login) {
  802. print $langs->trans("CurrentLogin").': <span class="error">'.$user->login.'</span><br>';
  803. print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users"));
  804. } else {
  805. print $langs->trans("ErrorForbidden3");
  806. }
  807. }
  808. }
  809. if ($printfooter && function_exists("llxFooter")) {
  810. llxFooter();
  811. }
  812. exit(0);
  813. }