security.lib.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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': for OpenLdap, '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 !== 'openldap') {
  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 == 'openldap') {
  113. return dolGetLdapPasswordHash($chain, getDolGlobalString('LDAP_PASSWORD_HASH_TYPE', 'md5'));
  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': 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. * Returns a specific ldap hash of a password.
  154. *
  155. * @param string $password Password to hash
  156. * @param string $type Type of hash
  157. * @return string Hash of password
  158. */
  159. function dolGetLdapPasswordHash($password, $type = 'md5')
  160. {
  161. if (empty($type)) {
  162. $type = 'md5';
  163. }
  164. $salt = substr(sha1(time()), 0, 8);
  165. if ($type === 'md5') {
  166. return '{MD5}' . base64_encode(hash("md5", $password, true)); //For OpenLdap with md5 (based on an unencrypted password in base)
  167. } elseif ($type === 'md5frommd5') {
  168. return '{MD5}' . base64_encode(hex2bin($password)); // Create OpenLDAP MD5 password from Dolibarr MD5 password
  169. } elseif ($type === 'smd5') {
  170. return "{SMD5}" . base64_encode(hash("md5", $password . $salt, true) . $salt);
  171. } elseif ($type === 'sha') {
  172. return '{SHA}' . base64_encode(hash("sha1", $password, true));
  173. } elseif ($type === 'ssha') {
  174. return "{SSHA}" . base64_encode(hash("sha1", $password . $salt, true) . $salt);
  175. } elseif ($type === 'sha256') {
  176. return "{SHA256}" . base64_encode(hash("sha256", $password, true));
  177. } elseif ($type === 'ssha256') {
  178. return "{SSHA256}" . base64_encode(hash("sha256", $password . $salt, true) . $salt);
  179. } elseif ($type === 'sha384') {
  180. return "{SHA384}" . base64_encode(hash("sha384", $password, true));
  181. } elseif ($type === 'ssha384') {
  182. return "{SSHA384}" . base64_encode(hash("sha384", $password . $salt, true) . $salt);
  183. } elseif ($type === 'sha512') {
  184. return "{SHA512}" . base64_encode(hash("sha512", $password, true));
  185. } elseif ($type === 'ssha512') {
  186. return "{SSHA512}" . base64_encode(hash("sha512", $password . $salt, true) . $salt);
  187. } elseif ($type === 'crypt') {
  188. return '{CRYPT}' . crypt($password, $salt);
  189. } elseif ($type === 'clear') {
  190. return '{CLEAR}' . $password; // Just for test, plain text password is not secured !
  191. }
  192. }
  193. /**
  194. * Check permissions of a user to show a page and an object. Check read permission.
  195. * If GETPOST('action','aZ09') defined, we also check write and delete permission.
  196. * This method check permission on module then call checkUserAccessToObject() for permission on object (according to entity and socid of user).
  197. *
  198. * @param User $user User to check
  199. * @param string $features Features to check (it must be module $object->element. Can be a 'or' check with 'levela|levelb'.
  200. * Examples: 'societe', 'contact', 'produit&service', 'produit|service', ...)
  201. * This is used to check permission $user->rights->features->...
  202. * @param int $objectid Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional).
  203. * @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).
  204. * @param string $feature2 Feature to check, second level of permission (optional). Can be a 'or' check with 'sublevela|sublevelb'.
  205. * This is used to check permission $user->rights->features->feature2...
  206. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional)
  207. * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional)
  208. * @param int $isdraft 1=The object with id=$objectid is a draft
  209. * @param int $mode Mode (0=default, 1=return with not die)
  210. * @return int If mode = 0 (default): Always 1, die process if not allowed. If mode = 1: Return 0 if access not allowed.
  211. * @see dol_check_secure_access_document(), checkUserAccessToObject()
  212. */
  213. function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0, $mode = 0)
  214. {
  215. global $db, $conf;
  216. global $hookmanager;
  217. $objectid = ((int) $objectid); // For the case value is coming from a non sanitized user input
  218. //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
  219. //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid;
  220. //print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
  221. //print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."<br>";
  222. $parentfortableentity = '';
  223. // Fix syntax of $features param
  224. $originalfeatures = $features;
  225. if ($features == 'facturerec') {
  226. $features = 'facture';
  227. }
  228. if ($features == 'mo') {
  229. $features = 'mrp';
  230. }
  231. if ($features == 'member') {
  232. $features = 'adherent';
  233. }
  234. if ($features == 'subscription') {
  235. $features = 'adherent';
  236. $feature2 = 'cotisation';
  237. };
  238. if ($features == 'websitepage') {
  239. $features = 'website';
  240. $tableandshare = 'website_page';
  241. $parentfortableentity = 'fk_website@website';
  242. }
  243. if ($features == 'project') {
  244. $features = 'projet';
  245. }
  246. if ($features == 'product') {
  247. $features = 'produit';
  248. }
  249. // Get more permissions checks from hooks
  250. $parameters = array('features'=>$features, 'originalfeatures'=>$originalfeatures, 'objectid'=>$objectid, 'dbt_select'=>$dbt_select, 'idtype'=>$dbt_select, 'isdraft'=>$isdraft);
  251. $reshook = $hookmanager->executeHooks('restrictedArea', $parameters);
  252. if (isset($hookmanager->resArray['result'])) {
  253. if ($hookmanager->resArray['result'] == 0) {
  254. if ($mode) {
  255. return 0;
  256. } else {
  257. accessforbidden(); // Module returns 0, so access forbidden
  258. }
  259. }
  260. }
  261. if ($reshook > 0) { // No other test done.
  262. return 1;
  263. }
  264. // Features/modules to check
  265. $featuresarray = array($features);
  266. if (preg_match('/&/', $features)) {
  267. $featuresarray = explode("&", $features);
  268. } elseif (preg_match('/\|/', $features)) {
  269. $featuresarray = explode("|", $features);
  270. }
  271. // More subfeatures to check
  272. if (!empty($feature2)) {
  273. $feature2 = explode("|", $feature2);
  274. }
  275. $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL);
  276. // Check read permission from module
  277. $readok = 1;
  278. $nbko = 0;
  279. foreach ($featuresarray as $feature) { // first we check nb of test ko
  280. $featureforlistofmodule = $feature;
  281. if ($featureforlistofmodule == 'produit') {
  282. $featureforlistofmodule = 'product';
  283. }
  284. 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
  285. $readok = 0;
  286. $nbko++;
  287. continue;
  288. }
  289. if ($feature == 'societe') {
  290. if (empty($user->rights->societe->lire) && empty($user->rights->fournisseur->lire)) {
  291. $readok = 0;
  292. $nbko++;
  293. }
  294. } elseif ($feature == 'contact') {
  295. if (empty($user->rights->societe->contact->lire)) {
  296. $readok = 0;
  297. $nbko++;
  298. }
  299. } elseif ($feature == 'produit|service') {
  300. if (!$user->rights->produit->lire && !$user->rights->service->lire) {
  301. $readok = 0;
  302. $nbko++;
  303. }
  304. } elseif ($feature == 'prelevement') {
  305. if (!$user->rights->prelevement->bons->lire) {
  306. $readok = 0;
  307. $nbko++;
  308. }
  309. } elseif ($feature == 'cheque') {
  310. if (empty($user->rights->banque->cheque)) {
  311. $readok = 0;
  312. $nbko++;
  313. }
  314. } elseif ($feature == 'projet') {
  315. if (!$user->rights->projet->lire && empty($user->rights->projet->all->lire)) {
  316. $readok = 0;
  317. $nbko++;
  318. }
  319. } elseif ($feature == 'payment') {
  320. if (!$user->rights->facture->lire) {
  321. $readok = 0;
  322. $nbko++;
  323. }
  324. } elseif ($feature == 'payment_supplier') {
  325. if (empty($user->rights->fournisseur->facture->lire)) {
  326. $readok = 0;
  327. $nbko++;
  328. }
  329. } elseif (!empty($feature2)) { // This is for permissions on 2 levels
  330. $tmpreadok = 1;
  331. foreach ($feature2 as $subfeature) {
  332. if ($subfeature == 'user' && $user->id == $objectid) {
  333. continue; // A user can always read its own card
  334. }
  335. if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) {
  336. $tmpreadok = 0;
  337. } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) {
  338. $tmpreadok = 0;
  339. } else {
  340. $tmpreadok = 1;
  341. break;
  342. } // Break is to bypass second test if the first is ok
  343. }
  344. if (!$tmpreadok) { // We found a test on feature that is ko
  345. $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko).
  346. $nbko++;
  347. }
  348. } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level
  349. var_dump($user->rights);
  350. if (empty($user->rights->$feature->lire)
  351. && empty($user->rights->$feature->read)
  352. && empty($user->rights->$feature->run)) {
  353. $readok = 0;
  354. $nbko++;
  355. }
  356. }
  357. }
  358. // If a or and at least one ok
  359. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  360. $readok = 1;
  361. }
  362. if (!$readok) {
  363. if ($mode) {
  364. return 0;
  365. } else {
  366. accessforbidden();
  367. }
  368. }
  369. //print "Read access is ok";
  370. // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files)
  371. $createok = 1;
  372. $nbko = 0;
  373. $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));
  374. $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
  375. if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) {
  376. foreach ($featuresarray as $feature) {
  377. if ($feature == 'contact') {
  378. if (empty($user->rights->societe->contact->creer)) {
  379. $createok = 0;
  380. $nbko++;
  381. }
  382. } elseif ($feature == 'produit|service') {
  383. if (empty($user->rights->produit->creer) && empty($user->rights->service->creer)) {
  384. $createok = 0;
  385. $nbko++;
  386. }
  387. } elseif ($feature == 'prelevement') {
  388. if (!$user->rights->prelevement->bons->creer) {
  389. $createok = 0;
  390. $nbko++;
  391. }
  392. } elseif ($feature == 'commande_fournisseur') {
  393. if (empty($user->rights->fournisseur->commande->creer) || empty($user->rights->supplier_order->creer)) {
  394. $createok = 0;
  395. $nbko++;
  396. }
  397. } elseif ($feature == 'banque') {
  398. if (empty($user->rights->banque->modifier)) {
  399. $createok = 0;
  400. $nbko++;
  401. }
  402. } elseif ($feature == 'cheque') {
  403. if (empty($user->rights->banque->cheque)) {
  404. $createok = 0;
  405. $nbko++;
  406. }
  407. } elseif ($feature == 'import') {
  408. if (empty($user->rights->import->run)) {
  409. $createok = 0;
  410. $nbko++;
  411. }
  412. } elseif ($feature == 'ecm') {
  413. if (!$user->rights->ecm->upload) {
  414. $createok = 0;
  415. $nbko++;
  416. }
  417. } elseif (!empty($feature2)) { // This is for permissions on one level
  418. foreach ($feature2 as $subfeature) {
  419. if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) {
  420. continue; // User can edit its own card
  421. }
  422. if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) {
  423. continue; // User can edit its own password
  424. }
  425. if ($subfeature == 'user' && $user->id != $objectid && $user->rights->user->user->password) {
  426. continue; // User can edit another user's password
  427. }
  428. if (empty($user->rights->$feature->$subfeature->creer)
  429. && empty($user->rights->$feature->$subfeature->write)
  430. && empty($user->rights->$feature->$subfeature->create)) {
  431. $createok = 0;
  432. $nbko++;
  433. } else {
  434. $createok = 1;
  435. // Break to bypass second test if the first is ok
  436. break;
  437. }
  438. }
  439. } elseif (!empty($feature)) { // This is for permissions on 2 levels ('creer' or 'write')
  440. //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; exit;
  441. if (empty($user->rights->$feature->creer)
  442. && empty($user->rights->$feature->write)
  443. && empty($user->rights->$feature->create)) {
  444. $createok = 0;
  445. $nbko++;
  446. }
  447. }
  448. }
  449. // If a or and at least one ok
  450. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  451. $createok = 1;
  452. }
  453. if ($wemustcheckpermissionforcreate && !$createok) {
  454. if ($mode) {
  455. return 0;
  456. } else {
  457. accessforbidden();
  458. }
  459. }
  460. //print "Write access is ok";
  461. }
  462. // Check create user permission
  463. $createuserok = 1;
  464. if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') {
  465. if (!$user->rights->user->user->creer) {
  466. $createuserok = 0;
  467. }
  468. if (!$createuserok) {
  469. if ($mode) {
  470. return 0;
  471. } else {
  472. accessforbidden();
  473. }
  474. }
  475. //print "Create user access is ok";
  476. }
  477. // Check delete permission from module
  478. $deleteok = 1;
  479. $nbko = 0;
  480. if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') {
  481. foreach ($featuresarray as $feature) {
  482. if ($feature == 'contact') {
  483. if (!$user->rights->societe->contact->supprimer) {
  484. $deleteok = 0;
  485. }
  486. } elseif ($feature == 'produit|service') {
  487. if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) {
  488. $deleteok = 0;
  489. }
  490. } elseif ($feature == 'commande_fournisseur') {
  491. if (!$user->rights->fournisseur->commande->supprimer) {
  492. $deleteok = 0;
  493. }
  494. } elseif ($feature == 'payment_supplier') { // Permission to delete a payment of an invoice is permission to edit an invoice.
  495. if (!$user->rights->fournisseur->facture->creer) {
  496. $deleteok = 0;
  497. }
  498. } elseif ($feature == 'payment') { // Permission to delete a payment of an invoice is permission to edit an invoice.
  499. if (!$user->rights->facture->creer) {
  500. $deleteok = 0;
  501. }
  502. } elseif ($feature == 'banque') {
  503. if (empty($user->rights->banque->modifier)) {
  504. $deleteok = 0;
  505. }
  506. } elseif ($feature == 'cheque') {
  507. if (empty($user->rights->banque->cheque)) {
  508. $deleteok = 0;
  509. }
  510. } elseif ($feature == 'ecm') {
  511. if (!$user->rights->ecm->upload) {
  512. $deleteok = 0;
  513. }
  514. } elseif ($feature == 'ftp') {
  515. if (!$user->rights->ftp->write) {
  516. $deleteok = 0;
  517. }
  518. } elseif ($feature == 'salaries') {
  519. if (!$user->rights->salaries->delete) {
  520. $deleteok = 0;
  521. }
  522. } elseif ($feature == 'adherent') {
  523. if (empty($user->rights->adherent->supprimer)) {
  524. $deleteok = 0;
  525. }
  526. } elseif ($feature == 'paymentbybanktransfer') {
  527. if (empty($user->rights->paymentbybanktransfer->create)) { // There is no delete permission
  528. $deleteok = 0;
  529. }
  530. } elseif ($feature == 'prelevement') {
  531. if (empty($user->rights->prelevement->bons->creer)) { // There is no delete permission
  532. $deleteok = 0;
  533. }
  534. } elseif (!empty($feature2)) { // This is for permissions on 2 levels
  535. foreach ($feature2 as $subfeature) {
  536. if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) {
  537. $deleteok = 0;
  538. } else {
  539. $deleteok = 1;
  540. break;
  541. } // For bypass the second test if the first is ok
  542. }
  543. } elseif (!empty($feature)) { // This is used for permissions on 1 level
  544. //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
  545. if (empty($user->rights->$feature->supprimer)
  546. && empty($user->rights->$feature->delete)
  547. && empty($user->rights->$feature->run)) {
  548. $deleteok = 0;
  549. }
  550. }
  551. }
  552. // If a or and at least one ok
  553. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  554. $deleteok = 1;
  555. }
  556. if (!$deleteok && !($isdraft && $createok)) {
  557. if ($mode) {
  558. return 0;
  559. } else {
  560. accessforbidden();
  561. }
  562. }
  563. //print "Delete access is ok";
  564. }
  565. // If we have a particular object to check permissions on, we check if $user has permission
  566. // for this given object (link to company, is contact for project, ...)
  567. if (!empty($objectid) && $objectid > 0) {
  568. $ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity);
  569. $params = array('objectid' => $objectid, 'features' => join(',', $featuresarray), 'features2' => $feature2);
  570. //print 'checkUserAccessToObject ok='.$ok;
  571. if ($mode) {
  572. return $ok ? 1 : 0;
  573. } else {
  574. return $ok ? 1 : accessforbidden('', 1, 1, 0, $params);
  575. }
  576. }
  577. return 1;
  578. }
  579. /**
  580. * Check that access by a given user to an object is ok.
  581. * This function is also called by restrictedArea() that check before if module is enabled and if permission of user for $action is ok.
  582. *
  583. * @param User $user User to check
  584. * @param array $featuresarray Features/modules to check. Example: ('user','service','member','project','task',...)
  585. * @param int|string|Object $object Full object or object ID or list of object id. For example if we want to check a particular record (optional) is linked to a owned thirdparty (optional).
  586. * @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).
  587. * @param string $feature2 Feature to check, second level of permission (optional). Can be or check with 'level1|level2'.
  588. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional)
  589. * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional)
  590. * @param string $parenttableforentity Parent table for entity. Example 'fk_website@website'
  591. * @return bool True if user has access, False otherwise
  592. * @see restrictedArea()
  593. */
  594. function checkUserAccessToObject($user, array $featuresarray, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid', $parenttableforentity = '')
  595. {
  596. global $db, $conf;
  597. if (is_object($object)) {
  598. $objectid = $object->id;
  599. } else {
  600. $objectid = $object; // $objectid can be X or 'X,Y,Z'
  601. }
  602. //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
  603. //print "user_id=".$user->id.", features=".join(',', $featuresarray).", feature2=".$feature2.", objectid=".$objectid;
  604. //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."<br>";
  605. // More parameters
  606. $params = explode('&', $tableandshare);
  607. $dbtablename = (!empty($params[0]) ? $params[0] : '');
  608. $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
  609. foreach ($featuresarray as $feature) {
  610. $sql = '';
  611. //var_dump($feature);exit;
  612. // For backward compatibility
  613. if ($feature == 'member') {
  614. $feature = 'adherent';
  615. }
  616. if ($feature == 'project') {
  617. $feature = 'projet';
  618. }
  619. if ($feature == 'task') {
  620. $feature = 'projet_task';
  621. }
  622. $checkonentitydone = 0;
  623. // Array to define rules of checks to do
  624. $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)
  625. $checksoc = array('societe'); // Test for societe object
  626. $checkother = array('contact', 'agenda'); // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...).
  627. $checkproject = array('projet', 'project'); // Test for project object
  628. $checktask = array('projet_task'); // Test for task object
  629. $checkhierarchy = array('expensereport', 'holiday');
  630. $nocheck = array('barcode', 'stock'); // No test
  631. //$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...).
  632. // If dbtablename not defined, we use same name for table than module name
  633. if (empty($dbtablename)) {
  634. $dbtablename = $feature;
  635. $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
  636. }
  637. // Check permission for object on entity only
  638. if (in_array($feature, $check)) {
  639. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  640. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  641. if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled)) { // Special for multicompany
  642. if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  643. if ($conf->entity == 1 && $user->admin && !$user->entity) {
  644. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  645. $sql .= " AND dbt.entity IS NOT NULL";
  646. } else {
  647. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  648. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  649. $sql .= " AND ((ug.fk_user = dbt.rowid";
  650. $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
  651. $sql .= " OR dbt.entity = 0)"; // Show always superadmin
  652. }
  653. } else {
  654. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  655. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  656. }
  657. } else {
  658. $reg = array();
  659. if ($parenttableforentity && preg_match('/(.*)@(.*)/', $parenttableforentity, $reg)) {
  660. $sql .= ", ".MAIN_DB_PREFIX.$reg[2]." as dbtp";
  661. $sql .= " WHERE dbt.".$reg[1]." = dbtp.rowid AND dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  662. $sql .= " AND dbtp.entity IN (".getEntity($sharedelement, 1).")";
  663. } else {
  664. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  665. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  666. }
  667. }
  668. $checkonentitydone = 1;
  669. }
  670. if (in_array($feature, $checksoc)) { // We check feature = checksoc
  671. // If external user: Check permission for external users
  672. if ($user->socid > 0) {
  673. if ($user->socid != $objectid) {
  674. return false;
  675. }
  676. } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && empty($user->rights->societe->client->voir))) {
  677. // If internal user: Check permission for internal users that are restricted on their objects
  678. $sql = "SELECT COUNT(sc.fk_soc) as nb";
  679. $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
  680. $sql .= ", ".MAIN_DB_PREFIX."societe as s)";
  681. $sql .= " WHERE sc.fk_soc IN (".$db->sanitize($objectid, 1).")";
  682. $sql .= " AND sc.fk_user = ".((int) $user->id);
  683. $sql .= " AND sc.fk_soc = s.rowid";
  684. $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
  685. } elseif (!empty($conf->multicompany->enabled)) {
  686. // If multicompany and internal users with all permissions, check user is in correct entity
  687. $sql = "SELECT COUNT(s.rowid) as nb";
  688. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  689. $sql .= " WHERE s.rowid IN (".$db->sanitize($objectid, 1).")";
  690. $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
  691. }
  692. $checkonentitydone = 1;
  693. }
  694. if (in_array($feature, $checkother)) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...).
  695. // If external user: Check permission for external users
  696. if ($user->socid > 0) {
  697. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  698. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  699. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  700. $sql .= " AND dbt.fk_soc = ".((int) $user->socid);
  701. } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && empty($user->rights->societe->client->voir))) {
  702. // If internal user: Check permission for internal users that are restricted on their objects
  703. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  704. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  705. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  706. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  707. $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
  708. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  709. } elseif (!empty($conf->multicompany->enabled)) {
  710. // If multicompany and internal users with all permissions, check user is in correct entity
  711. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  712. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  713. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  714. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  715. }
  716. $checkonentitydone = 1;
  717. }
  718. if (in_array($feature, $checkproject)) {
  719. if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) {
  720. $projectid = $objectid;
  721. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  722. $projectstatic = new Project($db);
  723. $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
  724. $tmparray = explode(',', $tmps);
  725. if (!in_array($projectid, $tmparray)) {
  726. return false;
  727. }
  728. } else {
  729. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  730. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  731. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  732. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  733. }
  734. $checkonentitydone = 1;
  735. }
  736. if (in_array($feature, $checktask)) {
  737. if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) {
  738. $task = new Task($db);
  739. $task->fetch($objectid);
  740. $projectid = $task->fk_project;
  741. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  742. $projectstatic = new Project($db);
  743. $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
  744. $tmparray = explode(',', $tmps);
  745. if (!in_array($projectid, $tmparray)) {
  746. return false;
  747. }
  748. } else {
  749. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  750. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  751. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  752. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  753. }
  754. $checkonentitydone = 1;
  755. }
  756. if (!$checkonentitydone && !in_array($feature, $nocheck)) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
  757. // If external user: Check permission for external users
  758. if ($user->socid > 0) {
  759. if (empty($dbt_keyfield)) {
  760. dol_print_error('', 'Param dbt_keyfield is required but not defined');
  761. }
  762. $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
  763. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  764. $sql .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
  765. $sql .= " AND dbt.".$dbt_keyfield." = ".((int) $user->socid);
  766. } elseif (!empty($conf->societe->enabled) && empty($user->rights->societe->client->voir)) {
  767. // If internal user: Check permission for internal users that are restricted on their objects
  768. if ($feature != 'ticket') {
  769. if (empty($dbt_keyfield)) {
  770. dol_print_error('', 'Param dbt_keyfield is required but not defined');
  771. }
  772. $sql = "SELECT COUNT(sc.fk_soc) as nb";
  773. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  774. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  775. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  776. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  777. $sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield;
  778. $sql .= " AND sc.fk_user = ".((int) $user->id);
  779. } else {
  780. // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties.
  781. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  782. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  783. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = dbt.".$dbt_keyfield." AND sc.fk_user = ".((int) $user->id);
  784. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  785. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  786. $sql .= " AND (sc.fk_user = ".((int) $user->id)." OR sc.fk_user IS NULL)";
  787. }
  788. } elseif (!empty($conf->multicompany->enabled)) {
  789. // If multicompany and internal users with all permissions, check user is in correct entity
  790. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  791. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  792. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  793. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  794. }
  795. }
  796. //print $sql;
  797. // For events, check on users assigned to event
  798. if ($feature === 'agenda') {
  799. // Also check owner or attendee for users without allactions->read
  800. if ($objectid > 0 && empty($user->rights->agenda->allactions->read)) {
  801. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  802. $action = new ActionComm($db);
  803. $action->fetch($objectid);
  804. if ($action->authorid != $user->id && $action->userownerid != $user->id && !(array_key_exists($user->id, $action->userassigned))) {
  805. return false;
  806. }
  807. }
  808. }
  809. // For some object, we also have to check it is in the user hierarchy
  810. // Param $object must be the full object and not a simple id to have this test possible.
  811. if (in_array($feature, $checkhierarchy) && is_object($object)) {
  812. $childids = $user->getAllChildIds(1);
  813. $useridtocheck = 0;
  814. if ($feature == 'holiday') {
  815. $useridtocheck = $object->fk_user;
  816. if (!in_array($useridtocheck, $childids)) {
  817. return false;
  818. }
  819. $useridtocheck = $object->fk_validator;
  820. if (!in_array($useridtocheck, $childids)) {
  821. return false;
  822. }
  823. }
  824. if ($feature == 'expensereport') {
  825. $useridtocheck = $object->fk_user_author;
  826. if (!$user->rights->expensereport->readall) {
  827. if (!in_array($useridtocheck, $childids)) {
  828. return false;
  829. }
  830. }
  831. }
  832. }
  833. if ($sql) {
  834. $resql = $db->query($sql);
  835. if ($resql) {
  836. $obj = $db->fetch_object($resql);
  837. if (!$obj || $obj->nb < count(explode(',', $objectid))) { // error if we found 0 or less record than nb of id provided
  838. return false;
  839. }
  840. } else {
  841. dol_syslog("Bad forged sql in checkUserAccessToObject", LOG_WARNING);
  842. return false;
  843. }
  844. }
  845. }
  846. return true;
  847. }
  848. /**
  849. * Show a message to say access is forbidden and stop program
  850. * Calling this function terminate execution of PHP.
  851. *
  852. * @param string $message Force error message
  853. * @param int $printheader Show header before
  854. * @param int $printfooter Show footer after
  855. * @param int $showonlymessage Show only message parameter. Otherwise add more information.
  856. * @param array|null $params More parameters provided to hook
  857. * @return void
  858. */
  859. function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
  860. {
  861. global $conf, $db, $user, $langs, $hookmanager;
  862. if (!is_object($langs)) {
  863. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  864. $langs = new Translate('', $conf);
  865. $langs->setDefaultLang();
  866. }
  867. $langs->load("errors");
  868. if ($printheader) {
  869. if (function_exists("llxHeader")) {
  870. llxHeader('');
  871. } elseif (function_exists("llxHeaderVierge")) {
  872. llxHeaderVierge('');
  873. }
  874. }
  875. print '<div class="error">';
  876. if (!$message) {
  877. print $langs->trans("ErrorForbidden");
  878. } else {
  879. print $message;
  880. }
  881. print '</div>';
  882. print '<br>';
  883. if (empty($showonlymessage)) {
  884. global $action, $object;
  885. if (empty($hookmanager)) {
  886. $hookmanager = new HookManager($db);
  887. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  888. $hookmanager->initHooks(array('main'));
  889. }
  890. $parameters = array('message'=>$message, 'params'=>$params);
  891. $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  892. print $hookmanager->resPrint;
  893. if (empty($reshook)) {
  894. $langs->loadLangs(array("errors"));
  895. if ($user->login) {
  896. print $langs->trans("CurrentLogin").': <span class="error">'.$user->login.'</span><br>';
  897. print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users"));
  898. print $langs->trans("ErrorForbidden4");
  899. } else {
  900. print $langs->trans("ErrorForbidden3");
  901. }
  902. }
  903. }
  904. if ($printfooter && function_exists("llxFooter")) {
  905. llxFooter();
  906. }
  907. exit(0);
  908. }