security.lib.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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. * Return a string of random bytes (hexa string) with length = $length fro cryptographic purposes.
  87. *
  88. * @param int $length Length of random string
  89. * @return string Random string
  90. */
  91. function dolGetRandomBytes($length)
  92. {
  93. if (function_exists('random_bytes')) { // Available with PHP 7 only.
  94. return bin2hex(random_bytes((int) floor($length / 2))); // the bin2hex will double the number of bytes so we take length / 2
  95. }
  96. return bin2hex(openssl_random_pseudo_bytes((int) floor($length / 2))); // the bin2hex will double the number of bytes so we take length / 2. May be very slow on Windows.
  97. }
  98. /**
  99. * Encode a string with a symetric encryption. Used to encrypt sensitive data into database.
  100. * Note: If a backup is restored onto another instance with a different $dolibarr_main_instance_unique_id, then decoded value will differ.
  101. *
  102. * @param string $chain string to encode
  103. * @param string $key If '', we use $dolibarr_main_instance_unique_id
  104. * @param string $ciphering Default ciphering algorithm
  105. * @param string $forceseed To force the seed
  106. * @return string encoded string
  107. * @see dolDecrypt(), dol_hash()
  108. */
  109. function dolEncrypt($chain, $key = '', $ciphering = 'AES-256-CTR', $forceseed = '')
  110. {
  111. global $dolibarr_main_instance_unique_id;
  112. global $dolibarr_disable_dolcrypt_for_debug;
  113. if ($chain === '' || is_null($chain)) {
  114. return '';
  115. }
  116. $reg = array();
  117. if (preg_match('/^dolcrypt:([^:]+):(.+)$/', $chain, $reg)) {
  118. // The $chain is already a crypted string
  119. return $chain;
  120. }
  121. if (empty($key)) {
  122. $key = $dolibarr_main_instance_unique_id;
  123. }
  124. if (empty($ciphering)) {
  125. $ciphering = 'AES-256-CTR';
  126. }
  127. $newchain = $chain;
  128. if (function_exists('openssl_encrypt') && empty($dolibarr_disable_dolcrypt_for_debug)) {
  129. $ivlen = 16;
  130. if (function_exists('openssl_cipher_iv_length')) {
  131. $ivlen = openssl_cipher_iv_length($ciphering);
  132. }
  133. if ($ivlen === false || $ivlen < 1 || $ivlen > 32) {
  134. $ivlen = 16;
  135. }
  136. if (empty($forceseed)) {
  137. $ivseed = dolGetRandomBytes($ivlen);
  138. } else {
  139. $ivseed = dol_trunc(md5($forceseed), $ivlen, 'right', 'UTF-8', 1);
  140. }
  141. $newchain = openssl_encrypt($chain, $ciphering, $key, 0, $ivseed);
  142. return 'dolcrypt:'.$ciphering.':'.$ivseed.':'.$newchain;
  143. } else {
  144. return $chain;
  145. }
  146. }
  147. /**
  148. * Decode a string with a symetric encryption. Used to decrypt sensitive data saved into database.
  149. * Note: If a backup is restored onto another instance with a different $dolibarr_main_instance_unique_id, then decoded value will differ.
  150. *
  151. * @param string $chain string to encode
  152. * @param string $key If '', we use $dolibarr_main_instance_unique_id
  153. * @return string encoded string
  154. * @see dolEncrypt(), dol_hash()
  155. */
  156. function dolDecrypt($chain, $key = '')
  157. {
  158. global $dolibarr_main_instance_unique_id;
  159. if ($chain === '' || is_null($chain)) {
  160. return '';
  161. }
  162. if (empty($key)) {
  163. $key = $dolibarr_main_instance_unique_id;
  164. }
  165. $reg = array();
  166. if (preg_match('/^dolcrypt:([^:]+):(.+)$/', $chain, $reg)) {
  167. $ciphering = $reg[1];
  168. if (function_exists('openssl_decrypt')) {
  169. $tmpexplode = explode(':', $reg[2]);
  170. if (!empty($tmpexplode[1]) && is_string($tmpexplode[0])) {
  171. $newchain = openssl_decrypt($tmpexplode[1], $ciphering, $key, 0, $tmpexplode[0]);
  172. } else {
  173. $newchain = openssl_decrypt($tmpexplode[0], $ciphering, $key, 0, null);
  174. }
  175. } else {
  176. $newchain = 'Error function openssl_decrypt() not available';
  177. }
  178. return $newchain;
  179. } else {
  180. return $chain;
  181. }
  182. }
  183. /**
  184. * Returns a hash (non reversible encryption) of a string.
  185. * If constant MAIN_SECURITY_HASH_ALGO is defined, we use this function as hashing function (recommanded value is 'password_hash')
  186. * If constant MAIN_SECURITY_SALT is defined, we use it as a salt (used only if hashing algorightm is something else than 'password_hash').
  187. *
  188. * @param string $chain String to hash
  189. * @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'.
  190. * @return string Hash of string
  191. * @see getRandomPassword(), dol_verifyHash()
  192. */
  193. function dol_hash($chain, $type = '0')
  194. {
  195. global $conf;
  196. // No need to add salt for password_hash
  197. if (($type == '0' || $type == 'auto') && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) {
  198. return password_hash($chain, PASSWORD_DEFAULT);
  199. }
  200. // Salt value
  201. if (!empty($conf->global->MAIN_SECURITY_SALT) && $type != '4' && $type !== 'openldap') {
  202. $chain = $conf->global->MAIN_SECURITY_SALT.$chain;
  203. }
  204. if ($type == '1' || $type == 'sha1') {
  205. return sha1($chain);
  206. } elseif ($type == '2' || $type == 'sha1md5') {
  207. return sha1(md5($chain));
  208. } elseif ($type == '3' || $type == 'md5') {
  209. return md5($chain);
  210. } elseif ($type == '4' || $type == 'openldap') {
  211. return dolGetLdapPasswordHash($chain, getDolGlobalString('LDAP_PASSWORD_HASH_TYPE', 'md5'));
  212. } elseif ($type == '5' || $type == 'sha256') {
  213. return hash('sha256', $chain);
  214. } elseif ($type == '6' || $type == 'password_hash') {
  215. return password_hash($chain, PASSWORD_DEFAULT);
  216. } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') {
  217. return sha1($chain);
  218. } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') {
  219. return sha1(md5($chain));
  220. }
  221. // No particular encoding defined, use default
  222. return md5($chain);
  223. }
  224. /**
  225. * Compute a hash and compare it to the given one
  226. * For backward compatibility reasons, if the hash is not in the password_hash format, we will try to match against md5 and sha1md5
  227. * If constant MAIN_SECURITY_HASH_ALGO is defined, we use this function as hashing function.
  228. * If constant MAIN_SECURITY_SALT is defined, we use it as a salt.
  229. *
  230. * @param string $chain String to hash (not hashed string)
  231. * @param string $hash hash to compare
  232. * @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'.
  233. * @return bool True if the computed hash is the same as the given one
  234. * @see dol_hash()
  235. */
  236. function dol_verifyHash($chain, $hash, $type = '0')
  237. {
  238. global $conf;
  239. if ($type == '0' && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) {
  240. if (! empty($hash[0]) && $hash[0] == '$') {
  241. return password_verify($chain, $hash);
  242. } elseif (dol_strlen($hash) == 32) {
  243. return dol_verifyHash($chain, $hash, '3'); // md5
  244. } elseif (dol_strlen($hash) == 40) {
  245. return dol_verifyHash($chain, $hash, '2'); // sha1md5
  246. }
  247. return false;
  248. }
  249. return dol_hash($chain, $type) == $hash;
  250. }
  251. /**
  252. * Returns a specific ldap hash of a password.
  253. *
  254. * @param string $password Password to hash
  255. * @param string $type Type of hash
  256. * @return string Hash of password
  257. */
  258. function dolGetLdapPasswordHash($password, $type = 'md5')
  259. {
  260. if (empty($type)) {
  261. $type = 'md5';
  262. }
  263. $salt = substr(sha1(time()), 0, 8);
  264. if ($type === 'md5') {
  265. return '{MD5}' . base64_encode(hash("md5", $password, true)); //For OpenLdap with md5 (based on an unencrypted password in base)
  266. } elseif ($type === 'md5frommd5') {
  267. return '{MD5}' . base64_encode(hex2bin($password)); // Create OpenLDAP MD5 password from Dolibarr MD5 password
  268. } elseif ($type === 'smd5') {
  269. return "{SMD5}" . base64_encode(hash("md5", $password . $salt, true) . $salt);
  270. } elseif ($type === 'sha') {
  271. return '{SHA}' . base64_encode(hash("sha1", $password, true));
  272. } elseif ($type === 'ssha') {
  273. return "{SSHA}" . base64_encode(hash("sha1", $password . $salt, true) . $salt);
  274. } elseif ($type === 'sha256') {
  275. return "{SHA256}" . base64_encode(hash("sha256", $password, true));
  276. } elseif ($type === 'ssha256') {
  277. return "{SSHA256}" . base64_encode(hash("sha256", $password . $salt, true) . $salt);
  278. } elseif ($type === 'sha384') {
  279. return "{SHA384}" . base64_encode(hash("sha384", $password, true));
  280. } elseif ($type === 'ssha384') {
  281. return "{SSHA384}" . base64_encode(hash("sha384", $password . $salt, true) . $salt);
  282. } elseif ($type === 'sha512') {
  283. return "{SHA512}" . base64_encode(hash("sha512", $password, true));
  284. } elseif ($type === 'ssha512') {
  285. return "{SSHA512}" . base64_encode(hash("sha512", $password . $salt, true) . $salt);
  286. } elseif ($type === 'crypt') {
  287. return '{CRYPT}' . crypt($password, $salt);
  288. } elseif ($type === 'clear') {
  289. return '{CLEAR}' . $password; // Just for test, plain text password is not secured !
  290. }
  291. }
  292. /**
  293. * Check permissions of a user to show a page and an object. Check read permission.
  294. * If GETPOST('action','aZ09') defined, we also check write and delete permission.
  295. * This method check permission on module then call checkUserAccessToObject() for permission on object (according to entity and socid of user).
  296. *
  297. * @param User $user User to check
  298. * @param string $features Features to check (it must be module $object->element. Can be a 'or' check with 'levela|levelb'.
  299. * Examples: 'societe', 'contact', 'produit&service', 'produit|service', ...)
  300. * This is used to check permission $user->rights->features->...
  301. * @param int|string|object $object Object or Object ID or list of Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional).
  302. * @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).
  303. * @param string $feature2 Feature to check, second level of permission (optional). Can be a 'or' check with 'sublevela|sublevelb'.
  304. * This is used to check permission $user->rights->features->feature2...
  305. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional). Can use '' if NA.
  306. * @param string $dbt_select Field name for select if not "rowid". Not used if objectid is null (optional)
  307. * @param int $isdraft 1=The object with id=$objectid is a draft
  308. * @param int $mode Mode (0=default, 1=return without dieing)
  309. * @return int If mode = 0 (default): Always 1, die process if not allowed. If mode = 1: Return 0 if access not allowed.
  310. * @see dol_check_secure_access_document(), checkUserAccessToObject()
  311. */
  312. function restrictedArea(User $user, $features, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $isdraft = 0, $mode = 0)
  313. {
  314. global $db, $conf;
  315. global $hookmanager;
  316. if (is_object($object)) {
  317. $objectid = $object->id;
  318. } else {
  319. $objectid = $object; // $objectid can be X or 'X,Y,Z'
  320. }
  321. if ($objectid) {
  322. $objectid = preg_replace('/[^0-9\.\,]/', '', $objectid); // For the case value is coming from a non sanitized user input
  323. }
  324. //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
  325. //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid;
  326. //print ", dbtablename=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
  327. //print ", perm: ".$features."->".$feature2."=".($user->rights->$features->$feature2->lire)."<br>";
  328. $parentfortableentity = '';
  329. // Fix syntax of $features param
  330. $originalfeatures = $features;
  331. if ($features == 'facturerec') {
  332. $features = 'facture';
  333. }
  334. if ($features == 'mo') {
  335. $features = 'mrp';
  336. }
  337. if ($features == 'member') {
  338. $features = 'adherent';
  339. }
  340. if ($features == 'subscription') {
  341. $features = 'adherent';
  342. $feature2 = 'cotisation';
  343. };
  344. if ($features == 'websitepage') {
  345. $features = 'website';
  346. $tableandshare = 'website_page';
  347. $parentfortableentity = 'fk_website@website';
  348. }
  349. if ($features == 'project') {
  350. $features = 'projet';
  351. }
  352. if ($features == 'product') {
  353. $features = 'produit';
  354. }
  355. // Get more permissions checks from hooks
  356. $parameters = array('features'=>$features, 'originalfeatures'=>$originalfeatures, 'objectid'=>$objectid, 'dbt_select'=>$dbt_select, 'idtype'=>$dbt_select, 'isdraft'=>$isdraft);
  357. $reshook = $hookmanager->executeHooks('restrictedArea', $parameters);
  358. if (isset($hookmanager->resArray['result'])) {
  359. if ($hookmanager->resArray['result'] == 0) {
  360. if ($mode) {
  361. return 0;
  362. } else {
  363. accessforbidden(); // Module returns 0, so access forbidden
  364. }
  365. }
  366. }
  367. if ($reshook > 0) { // No other test done.
  368. return 1;
  369. }
  370. // Features/modules to check
  371. $featuresarray = array($features);
  372. if (preg_match('/&/', $features)) {
  373. $featuresarray = explode("&", $features);
  374. } elseif (preg_match('/\|/', $features)) {
  375. $featuresarray = explode("|", $features);
  376. }
  377. // More subfeatures to check
  378. if (!empty($feature2)) {
  379. $feature2 = explode("|", $feature2);
  380. }
  381. $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL);
  382. // Check read permission from module
  383. $readok = 1;
  384. $nbko = 0;
  385. foreach ($featuresarray as $feature) { // first we check nb of test ko
  386. $featureforlistofmodule = $feature;
  387. if ($featureforlistofmodule == 'produit') {
  388. $featureforlistofmodule = 'product';
  389. }
  390. 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
  391. $readok = 0;
  392. $nbko++;
  393. continue;
  394. }
  395. if ($feature == 'societe') {
  396. if (!$user->hasRight('societe', 'lire') && !$user->hasRight('fournisseur', 'lire')) {
  397. $readok = 0;
  398. $nbko++;
  399. }
  400. } elseif ($feature == 'contact') {
  401. if (empty($user->rights->societe->contact->lire)) {
  402. $readok = 0;
  403. $nbko++;
  404. }
  405. } elseif ($feature == 'produit|service') {
  406. if (empty($user->rights->produit->lire) && empty($user->rights->service->lire)) {
  407. $readok = 0;
  408. $nbko++;
  409. }
  410. } elseif ($feature == 'prelevement') {
  411. if (empty($user->rights->prelevement->bons->lire)) {
  412. $readok = 0;
  413. $nbko++;
  414. }
  415. } elseif ($feature == 'cheque') {
  416. if (empty($user->rights->banque->cheque)) {
  417. $readok = 0;
  418. $nbko++;
  419. }
  420. } elseif ($feature == 'projet') {
  421. if (empty($user->rights->projet->lire) && empty($user->rights->projet->all->lire)) {
  422. $readok = 0;
  423. $nbko++;
  424. }
  425. } elseif ($feature == 'payment') {
  426. if (empty($user->rights->facture->lire)) {
  427. $readok = 0;
  428. $nbko++;
  429. }
  430. } elseif ($feature == 'payment_supplier') {
  431. if (empty($user->rights->fournisseur->facture->lire)) {
  432. $readok = 0;
  433. $nbko++;
  434. }
  435. } elseif ($feature == 'payment_sc') {
  436. if (empty($user->rights->tax->charges->lire)) {
  437. $readok = 0;
  438. $nbko++;
  439. }
  440. } elseif (!empty($feature2)) { // This is for permissions on 2 levels
  441. $tmpreadok = 1;
  442. foreach ($feature2 as $subfeature) {
  443. if ($subfeature == 'user' && $user->id == $objectid) {
  444. continue; // A user can always read its own card
  445. }
  446. if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) {
  447. $tmpreadok = 0;
  448. } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) {
  449. $tmpreadok = 0;
  450. } else {
  451. $tmpreadok = 1;
  452. break;
  453. } // Break is to bypass second test if the first is ok
  454. }
  455. if (!$tmpreadok) { // We found a test on feature that is ko
  456. $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko).
  457. $nbko++;
  458. }
  459. } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level
  460. if (empty($user->rights->$feature->lire)
  461. && empty($user->rights->$feature->read)
  462. && empty($user->rights->$feature->run)) {
  463. $readok = 0;
  464. $nbko++;
  465. }
  466. }
  467. }
  468. // If a or and at least one ok
  469. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  470. $readok = 1;
  471. }
  472. if (!$readok) {
  473. if ($mode) {
  474. return 0;
  475. } else {
  476. accessforbidden();
  477. }
  478. }
  479. //print "Read access is ok";
  480. // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files)
  481. $createok = 1;
  482. $nbko = 0;
  483. $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));
  484. $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete');
  485. if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) {
  486. foreach ($featuresarray as $feature) {
  487. if ($feature == 'contact') {
  488. if (empty($user->rights->societe->contact->creer)) {
  489. $createok = 0;
  490. $nbko++;
  491. }
  492. } elseif ($feature == 'produit|service') {
  493. if (empty($user->rights->produit->creer) && empty($user->rights->service->creer)) {
  494. $createok = 0;
  495. $nbko++;
  496. }
  497. } elseif ($feature == 'prelevement') {
  498. if (!$user->rights->prelevement->bons->creer) {
  499. $createok = 0;
  500. $nbko++;
  501. }
  502. } elseif ($feature == 'commande_fournisseur') {
  503. if (empty($user->rights->fournisseur->commande->creer) || empty($user->rights->supplier_order->creer)) {
  504. $createok = 0;
  505. $nbko++;
  506. }
  507. } elseif ($feature == 'banque') {
  508. if (empty($user->rights->banque->modifier)) {
  509. $createok = 0;
  510. $nbko++;
  511. }
  512. } elseif ($feature == 'cheque') {
  513. if (empty($user->rights->banque->cheque)) {
  514. $createok = 0;
  515. $nbko++;
  516. }
  517. } elseif ($feature == 'import') {
  518. if (empty($user->rights->import->run)) {
  519. $createok = 0;
  520. $nbko++;
  521. }
  522. } elseif ($feature == 'ecm') {
  523. if (!$user->rights->ecm->upload) {
  524. $createok = 0;
  525. $nbko++;
  526. }
  527. } elseif (!empty($feature2)) { // This is for permissions on one level
  528. foreach ($feature2 as $subfeature) {
  529. if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) {
  530. continue; // User can edit its own card
  531. }
  532. if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) {
  533. continue; // User can edit its own password
  534. }
  535. if ($subfeature == 'user' && $user->id != $objectid && $user->rights->user->user->password) {
  536. continue; // User can edit another user's password
  537. }
  538. if (empty($user->rights->$feature->$subfeature->creer)
  539. && empty($user->rights->$feature->$subfeature->write)
  540. && empty($user->rights->$feature->$subfeature->create)) {
  541. $createok = 0;
  542. $nbko++;
  543. } else {
  544. $createok = 1;
  545. // Break to bypass second test if the first is ok
  546. break;
  547. }
  548. }
  549. } elseif (!empty($feature)) { // This is for permissions on 2 levels ('creer' or 'write')
  550. //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; exit;
  551. if (empty($user->rights->$feature->creer)
  552. && empty($user->rights->$feature->write)
  553. && empty($user->rights->$feature->create)) {
  554. $createok = 0;
  555. $nbko++;
  556. }
  557. }
  558. }
  559. // If a or and at least one ok
  560. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  561. $createok = 1;
  562. }
  563. if ($wemustcheckpermissionforcreate && !$createok) {
  564. if ($mode) {
  565. return 0;
  566. } else {
  567. accessforbidden();
  568. }
  569. }
  570. //print "Write access is ok";
  571. }
  572. // Check create user permission
  573. $createuserok = 1;
  574. if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') {
  575. if (!$user->rights->user->user->creer) {
  576. $createuserok = 0;
  577. }
  578. if (!$createuserok) {
  579. if ($mode) {
  580. return 0;
  581. } else {
  582. accessforbidden();
  583. }
  584. }
  585. //print "Create user access is ok";
  586. }
  587. // Check delete permission from module
  588. $deleteok = 1;
  589. $nbko = 0;
  590. if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') {
  591. foreach ($featuresarray as $feature) {
  592. if ($feature == 'bookmark') {
  593. if (!$user->rights->bookmark->supprimer) {
  594. if ($user->id != $object->fk_user || empty($user->rights->bookmark->creer)) {
  595. $deleteok = 0;
  596. }
  597. }
  598. } elseif ($feature == 'contact') {
  599. if (!$user->rights->societe->contact->supprimer) {
  600. $deleteok = 0;
  601. }
  602. } elseif ($feature == 'produit|service') {
  603. if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) {
  604. $deleteok = 0;
  605. }
  606. } elseif ($feature == 'commande_fournisseur') {
  607. if (!$user->rights->fournisseur->commande->supprimer) {
  608. $deleteok = 0;
  609. }
  610. } elseif ($feature == 'payment_supplier') { // Permission to delete a payment of an invoice is permission to edit an invoice.
  611. if (!$user->rights->fournisseur->facture->creer) {
  612. $deleteok = 0;
  613. }
  614. } elseif ($feature == 'payment') {
  615. if (!$user->rights->facture->paiement) {
  616. $deleteok = 0;
  617. }
  618. } elseif ($feature == 'payment_sc') {
  619. if (!$user->rights->tax->charges->creer) {
  620. $deleteok = 0;
  621. }
  622. } elseif ($feature == 'banque') {
  623. if (empty($user->rights->banque->modifier)) {
  624. $deleteok = 0;
  625. }
  626. } elseif ($feature == 'cheque') {
  627. if (empty($user->rights->banque->cheque)) {
  628. $deleteok = 0;
  629. }
  630. } elseif ($feature == 'ecm') {
  631. if (!$user->rights->ecm->upload) {
  632. $deleteok = 0;
  633. }
  634. } elseif ($feature == 'ftp') {
  635. if (!$user->rights->ftp->write) {
  636. $deleteok = 0;
  637. }
  638. } elseif ($feature == 'salaries') {
  639. if (!$user->rights->salaries->delete) {
  640. $deleteok = 0;
  641. }
  642. } elseif ($feature == 'adherent') {
  643. if (empty($user->rights->adherent->supprimer)) {
  644. $deleteok = 0;
  645. }
  646. } elseif ($feature == 'paymentbybanktransfer') {
  647. if (empty($user->rights->paymentbybanktransfer->create)) { // There is no delete permission
  648. $deleteok = 0;
  649. }
  650. } elseif ($feature == 'prelevement') {
  651. if (empty($user->rights->prelevement->bons->creer)) { // There is no delete permission
  652. $deleteok = 0;
  653. }
  654. } elseif (!empty($feature2)) { // This is for permissions on 2 levels
  655. foreach ($feature2 as $subfeature) {
  656. if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) {
  657. $deleteok = 0;
  658. } else {
  659. $deleteok = 1;
  660. break;
  661. } // For bypass the second test if the first is ok
  662. }
  663. } elseif (!empty($feature)) { // This is used for permissions on 1 level
  664. //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
  665. if (empty($user->rights->$feature->supprimer)
  666. && empty($user->rights->$feature->delete)
  667. && empty($user->rights->$feature->run)) {
  668. $deleteok = 0;
  669. }
  670. }
  671. }
  672. // If a or and at least one ok
  673. if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) {
  674. $deleteok = 1;
  675. }
  676. if (!$deleteok && !($isdraft && $createok)) {
  677. if ($mode) {
  678. return 0;
  679. } else {
  680. accessforbidden();
  681. }
  682. }
  683. //print "Delete access is ok";
  684. }
  685. // If we have a particular object to check permissions on, we check if $user has permission
  686. // for this given object (link to company, is contact for project, ...)
  687. if (!empty($objectid) && $objectid > 0) {
  688. $ok = checkUserAccessToObject($user, $featuresarray, $object, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity);
  689. $params = array('objectid' => $objectid, 'features' => join(',', $featuresarray), 'features2' => $feature2);
  690. //print 'checkUserAccessToObject ok='.$ok;
  691. if ($mode) {
  692. return $ok ? 1 : 0;
  693. } else {
  694. if ($ok) {
  695. return 1;
  696. } else {
  697. accessforbidden('', 1, 1, 0, $params);
  698. }
  699. }
  700. }
  701. return 1;
  702. }
  703. /**
  704. * Check that access by a given user to an object is ok.
  705. * This function is also called by restrictedArea() that check before if module is enabled and if permission of user for $action is ok.
  706. *
  707. * @param User $user User to check
  708. * @param array $featuresarray Features/modules to check. Example: ('user','service','member','project','task',...)
  709. * @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).
  710. * @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).
  711. * @param array|string $feature2 Feature to check, second level of permission (optional). Can be or check with 'level1|level2'.
  712. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional). Can use '' if NA.
  713. * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional).
  714. * @param string $parenttableforentity Parent table for entity. Example 'fk_website@website'
  715. * @return bool True if user has access, False otherwise
  716. * @see restrictedArea()
  717. */
  718. function checkUserAccessToObject($user, array $featuresarray, $object = 0, $tableandshare = '', $feature2 = '', $dbt_keyfield = '', $dbt_select = 'rowid', $parenttableforentity = '')
  719. {
  720. global $db, $conf;
  721. if (is_object($object)) {
  722. $objectid = $object->id;
  723. } else {
  724. $objectid = $object; // $objectid can be X or 'X,Y,Z'
  725. }
  726. $objectid = preg_replace('/[^0-9\.\,]/', '', $objectid); // For the case value is coming from a non sanitized user input
  727. //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename, $feature2, $dbt_socfield, $dbt_select, $isdraft");
  728. //print "user_id=".$user->id.", features=".join(',', $featuresarray).", objectid=".$objectid;
  729. //print ", tableandshare=".$tableandshare.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select."<br>";
  730. // More parameters
  731. $params = explode('&', $tableandshare);
  732. $dbtablename = (!empty($params[0]) ? $params[0] : '');
  733. $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);
  734. foreach ($featuresarray as $feature) {
  735. $sql = '';
  736. //var_dump($feature);exit;
  737. // For backward compatibility
  738. if ($feature == 'member') {
  739. $feature = 'adherent';
  740. }
  741. if ($feature == 'project') {
  742. $feature = 'projet';
  743. }
  744. if ($feature == 'task') {
  745. $feature = 'projet_task';
  746. }
  747. $checkonentitydone = 0;
  748. // Array to define rules of checks to do
  749. $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)
  750. $checksoc = array('societe'); // Test for object Societe
  751. $checkother = array('contact', 'agenda', 'contrat'); // Test on entity + link to third party on field $dbt_keyfield. Allowed if link is empty (Ex: contacts...).
  752. $checkproject = array('projet', 'project'); // Test for project object
  753. $checktask = array('projet_task'); // Test for task object
  754. $checkhierarchy = array('expensereport', 'holiday'); // check permission among the hierarchy of user
  755. $checkuser = array('bookmark'); // check permission among the fk_user (must be myself or null)
  756. $nocheck = array('barcode', 'stock'); // No test
  757. //$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...).
  758. // If dbtablename not defined, we use same name for table than module name
  759. if (empty($dbtablename)) {
  760. $dbtablename = $feature;
  761. $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
  762. }
  763. // To avoid an access forbidden with a numeric ref
  764. if ($dbt_select != 'rowid' && $dbt_select != 'id') {
  765. $objectid = "'".$objectid."'"; // Note: $objectid was already cast into int at begin of this method.
  766. }
  767. // Check permission for objectid on entity only
  768. if (in_array($feature, $check) && $objectid > 0) { // For $objectid = 0, no check
  769. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  770. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  771. if (($feature == 'user' || $feature == 'usergroup') && isModEnabled('multicompany')) { // Special for multicompany
  772. if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  773. if ($conf->entity == 1 && $user->admin && !$user->entity) {
  774. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  775. $sql .= " AND dbt.entity IS NOT NULL";
  776. } else {
  777. $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
  778. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  779. $sql .= " AND ((ug.fk_user = dbt.rowid";
  780. $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
  781. $sql .= " OR dbt.entity = 0)"; // Show always superadmin
  782. }
  783. } else {
  784. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  785. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  786. }
  787. } else {
  788. $reg = array();
  789. if ($parenttableforentity && preg_match('/(.*)@(.*)/', $parenttableforentity, $reg)) {
  790. $sql .= ", ".MAIN_DB_PREFIX.$reg[2]." as dbtp";
  791. $sql .= " WHERE dbt.".$reg[1]." = dbtp.rowid AND dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  792. $sql .= " AND dbtp.entity IN (".getEntity($sharedelement, 1).")";
  793. } else {
  794. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  795. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  796. }
  797. }
  798. $checkonentitydone = 1;
  799. }
  800. if (in_array($feature, $checksoc) && $objectid > 0) { // We check feature = checksoc. For $objectid = 0, no check
  801. // If external user: Check permission for external users
  802. if ($user->socid > 0) {
  803. if ($user->socid != $objectid) {
  804. return false;
  805. }
  806. } elseif (isModEnabled("societe") && ($user->hasRight('societe', 'lire') && empty($user->rights->societe->client->voir))) {
  807. // If internal user: Check permission for internal users that are restricted on their objects
  808. $sql = "SELECT COUNT(sc.fk_soc) as nb";
  809. $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
  810. $sql .= ", ".MAIN_DB_PREFIX."societe as s)";
  811. $sql .= " WHERE sc.fk_soc IN (".$db->sanitize($objectid, 1).")";
  812. $sql .= " AND sc.fk_user = ".((int) $user->id);
  813. $sql .= " AND sc.fk_soc = s.rowid";
  814. $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
  815. } elseif (isModEnabled('multicompany')) {
  816. // If multicompany and internal users with all permissions, check user is in correct entity
  817. $sql = "SELECT COUNT(s.rowid) as nb";
  818. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  819. $sql .= " WHERE s.rowid IN (".$db->sanitize($objectid, 1).")";
  820. $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
  821. }
  822. $checkonentitydone = 1;
  823. }
  824. if (in_array($feature, $checkother) && $objectid > 0) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...).
  825. // If external user: Check permission for external users
  826. if ($user->socid > 0) {
  827. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  828. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  829. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  830. $sql .= " AND dbt.fk_soc = ".((int) $user->socid);
  831. } elseif (isModEnabled("societe") && ($user->hasRight('societe', 'lire') && empty($user->rights->societe->client->voir))) {
  832. // If internal user: Check permission for internal users that are restricted on their objects
  833. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  834. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  835. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  836. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  837. $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
  838. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  839. } elseif (isModEnabled('multicompany')) {
  840. // If multicompany and internal users with all permissions, check user is in correct entity
  841. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  842. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  843. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  844. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  845. }
  846. $checkonentitydone = 1;
  847. }
  848. if (in_array($feature, $checkproject) && $objectid > 0) {
  849. if (isModEnabled('project') && empty($user->rights->projet->all->lire)) {
  850. $projectid = $objectid;
  851. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  852. $projectstatic = new Project($db);
  853. $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
  854. $tmparray = explode(',', $tmps);
  855. if (!in_array($projectid, $tmparray)) {
  856. return false;
  857. }
  858. } else {
  859. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  860. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  861. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  862. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  863. }
  864. $checkonentitydone = 1;
  865. }
  866. if (in_array($feature, $checktask) && $objectid > 0) {
  867. if (isModEnabled('project') && empty($user->rights->projet->all->lire)) {
  868. $task = new Task($db);
  869. $task->fetch($objectid);
  870. $projectid = $task->fk_project;
  871. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  872. $projectstatic = new Project($db);
  873. $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
  874. $tmparray = explode(',', $tmps);
  875. if (!in_array($projectid, $tmparray)) {
  876. return false;
  877. }
  878. } else {
  879. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  880. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  881. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  882. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  883. }
  884. $checkonentitydone = 1;
  885. }
  886. if (!$checkonentitydone && !in_array($feature, $nocheck) && $objectid > 0) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
  887. // If external user: Check permission for external users
  888. if ($user->socid > 0) {
  889. if (empty($dbt_keyfield)) {
  890. dol_print_error('', 'Param dbt_keyfield is required but not defined');
  891. }
  892. $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
  893. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  894. $sql .= " WHERE dbt.rowid IN (".$db->sanitize($objectid, 1).")";
  895. $sql .= " AND dbt.".$dbt_keyfield." = ".((int) $user->socid);
  896. } elseif (isModEnabled("societe") && empty($user->rights->societe->client->voir)) {
  897. // If internal user: Check permission for internal users that are restricted on their objects
  898. if ($feature != 'ticket') {
  899. if (empty($dbt_keyfield)) {
  900. dol_print_error('', 'Param dbt_keyfield is required but not defined');
  901. }
  902. $sql = "SELECT COUNT(sc.fk_soc) as nb";
  903. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  904. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  905. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  906. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  907. $sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield;
  908. $sql .= " AND sc.fk_user = ".((int) $user->id);
  909. } else {
  910. // On ticket, the thirdparty is not mandatory, so we need a special test to accept record with no thirdparties.
  911. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  912. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  913. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = dbt.".$dbt_keyfield." AND sc.fk_user = ".((int) $user->id);
  914. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  915. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  916. $sql .= " AND (sc.fk_user = ".((int) $user->id)." OR sc.fk_user IS NULL)";
  917. }
  918. } elseif (isModEnabled('multicompany')) {
  919. // If multicompany and internal users with all permissions, check user is in correct entity
  920. $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
  921. $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
  922. $sql .= " WHERE dbt.".$dbt_select." IN (".$db->sanitize($objectid, 1).")";
  923. $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
  924. }
  925. }
  926. //print $sql;
  927. // For events, check on users assigned to event
  928. if ($feature === 'agenda' && $objectid > 0) {
  929. // Also check owner or attendee for users without allactions->read
  930. if ($objectid > 0 && empty($user->rights->agenda->allactions->read)) {
  931. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  932. $action = new ActionComm($db);
  933. $action->fetch($objectid);
  934. if ($action->authorid != $user->id && $action->userownerid != $user->id && !(array_key_exists($user->id, $action->userassigned))) {
  935. return false;
  936. }
  937. }
  938. }
  939. // For some object, we also have to check it is in the user hierarchy
  940. // Param $object must be the full object and not a simple id to have this test possible.
  941. if (in_array($feature, $checkhierarchy) && is_object($object) && $objectid > 0) {
  942. $childids = $user->getAllChildIds(1);
  943. $useridtocheck = 0;
  944. if ($feature == 'holiday') {
  945. $useridtocheck = $object->fk_user;
  946. if (!in_array($useridtocheck, $childids)) {
  947. return false;
  948. }
  949. $useridtocheck = $object->fk_validator;
  950. if (!in_array($useridtocheck, $childids)) {
  951. return false;
  952. }
  953. }
  954. if ($feature == 'expensereport') {
  955. $useridtocheck = $object->fk_user_author;
  956. if (!$user->rights->expensereport->readall) {
  957. if (!in_array($useridtocheck, $childids)) {
  958. return false;
  959. }
  960. }
  961. }
  962. }
  963. // For some object, we also have to check it is public or owned by user
  964. // Param $object must be the full object and not a simple id to have this test possible.
  965. if (in_array($feature, $checkuser) && is_object($object) && $objectid > 0) {
  966. $useridtocheck = $object->fk_user;
  967. if (!empty($useridtocheck) && $useridtocheck > 0 && $useridtocheck != $user->id && empty($user->admin)) {
  968. return false;
  969. }
  970. }
  971. if ($sql) {
  972. $resql = $db->query($sql);
  973. if ($resql) {
  974. $obj = $db->fetch_object($resql);
  975. if (!$obj || $obj->nb < count(explode(',', $objectid))) { // error if we found 0 or less record than nb of id provided
  976. return false;
  977. }
  978. } else {
  979. dol_syslog("Bad forged sql in checkUserAccessToObject", LOG_WARNING);
  980. return false;
  981. }
  982. }
  983. }
  984. return true;
  985. }
  986. /**
  987. * Show a message to say access is forbidden and stop program.
  988. * This includes only HTTP header.
  989. * Calling this function terminate execution of PHP.
  990. *
  991. * @param string $message Force error message
  992. * @param int $http_response_code HTTP response code
  993. * @param int $stringalreadysanitized 1 if string is already sanitized with HTML entities
  994. * @return void
  995. * @see accessforbidden()
  996. */
  997. function httponly_accessforbidden($message = 1, $http_response_code = 403, $stringalreadysanitized = 0)
  998. {
  999. top_httphead();
  1000. http_response_code($http_response_code);
  1001. if ($stringalreadysanitized) {
  1002. print $message;
  1003. } else {
  1004. print htmlentities($message);
  1005. }
  1006. exit(1);
  1007. }
  1008. /**
  1009. * Show a message to say access is forbidden and stop program.
  1010. * This includes HTTP and HTML header and footer (except if $printheader and $printfooter is 0, use this case inside an already started page).
  1011. * Calling this function terminate execution of PHP.
  1012. *
  1013. * @param string $message Force error message
  1014. * @param int $printheader Show header before
  1015. * @param int $printfooter Show footer after
  1016. * @param int $showonlymessage Show only message parameter. Otherwise add more information.
  1017. * @param array|null $params More parameters provided to hook
  1018. * @return void
  1019. * @see httponly_accessforbidden()
  1020. */
  1021. function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null)
  1022. {
  1023. global $conf, $db, $user, $langs, $hookmanager;
  1024. if (!is_object($langs)) {
  1025. include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  1026. $langs = new Translate('', $conf);
  1027. $langs->setDefaultLang();
  1028. }
  1029. $langs->load("errors");
  1030. if ($printheader) {
  1031. if (function_exists("llxHeader")) {
  1032. llxHeader('');
  1033. } elseif (function_exists("llxHeaderVierge")) {
  1034. llxHeaderVierge('');
  1035. }
  1036. }
  1037. print '<div class="error">';
  1038. if (empty($message)) {
  1039. print $langs->trans("ErrorForbidden");
  1040. } else {
  1041. print $langs->trans($message);
  1042. }
  1043. print '</div>';
  1044. print '<br>';
  1045. if (empty($showonlymessage)) {
  1046. global $action, $object;
  1047. if (empty($hookmanager)) {
  1048. $hookmanager = new HookManager($db);
  1049. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  1050. $hookmanager->initHooks(array('main'));
  1051. }
  1052. $parameters = array('message'=>$message, 'params'=>$params);
  1053. $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1054. print $hookmanager->resPrint;
  1055. if (empty($reshook)) {
  1056. $langs->loadLangs(array("errors"));
  1057. if ($user->login) {
  1058. print $langs->trans("CurrentLogin").': <span class="error">'.$user->login.'</span><br>';
  1059. print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users"));
  1060. print $langs->trans("ErrorForbidden4");
  1061. } else {
  1062. print $langs->trans("ErrorForbidden3");
  1063. }
  1064. }
  1065. }
  1066. if ($printfooter && function_exists("llxFooter")) {
  1067. llxFooter();
  1068. }
  1069. exit(0);
  1070. }
  1071. /**
  1072. * Return the max allowed for file upload.
  1073. * Analyze among: upload_max_filesize, post_max_size, MAIN_UPLOAD_DOC
  1074. *
  1075. * @return array Array with all max size for file upload
  1076. */
  1077. function getMaxFileSizeArray()
  1078. {
  1079. global $conf;
  1080. $max = $conf->global->MAIN_UPLOAD_DOC; // In Kb
  1081. $maxphp = @ini_get('upload_max_filesize'); // In unknown
  1082. if (preg_match('/k$/i', $maxphp)) {
  1083. $maxphp = preg_replace('/k$/i', '', $maxphp);
  1084. $maxphp = $maxphp * 1;
  1085. }
  1086. if (preg_match('/m$/i', $maxphp)) {
  1087. $maxphp = preg_replace('/m$/i', '', $maxphp);
  1088. $maxphp = $maxphp * 1024;
  1089. }
  1090. if (preg_match('/g$/i', $maxphp)) {
  1091. $maxphp = preg_replace('/g$/i', '', $maxphp);
  1092. $maxphp = $maxphp * 1024 * 1024;
  1093. }
  1094. if (preg_match('/t$/i', $maxphp)) {
  1095. $maxphp = preg_replace('/t$/i', '', $maxphp);
  1096. $maxphp = $maxphp * 1024 * 1024 * 1024;
  1097. }
  1098. $maxphp2 = @ini_get('post_max_size'); // In unknown
  1099. if (preg_match('/k$/i', $maxphp2)) {
  1100. $maxphp2 = preg_replace('/k$/i', '', $maxphp2);
  1101. $maxphp2 = $maxphp2 * 1;
  1102. }
  1103. if (preg_match('/m$/i', $maxphp2)) {
  1104. $maxphp2 = preg_replace('/m$/i', '', $maxphp2);
  1105. $maxphp2 = $maxphp2 * 1024;
  1106. }
  1107. if (preg_match('/g$/i', $maxphp2)) {
  1108. $maxphp2 = preg_replace('/g$/i', '', $maxphp2);
  1109. $maxphp2 = $maxphp2 * 1024 * 1024;
  1110. }
  1111. if (preg_match('/t$/i', $maxphp2)) {
  1112. $maxphp2 = preg_replace('/t$/i', '', $maxphp2);
  1113. $maxphp2 = $maxphp2 * 1024 * 1024 * 1024;
  1114. }
  1115. // Now $max and $maxphp and $maxphp2 are in Kb
  1116. $maxmin = $max;
  1117. $maxphptoshow = $maxphptoshowparam = '';
  1118. if ($maxphp > 0) {
  1119. $maxmin = min($maxmin, $maxphp);
  1120. $maxphptoshow = $maxphp;
  1121. $maxphptoshowparam = 'upload_max_filesize';
  1122. }
  1123. if ($maxphp2 > 0) {
  1124. $maxmin = min($maxmin, $maxphp2);
  1125. if ($maxphp2 < $maxphp) {
  1126. $maxphptoshow = $maxphp2;
  1127. $maxphptoshowparam = 'post_max_size';
  1128. }
  1129. }
  1130. //var_dump($maxphp.'-'.$maxphp2);
  1131. //var_dump($maxmin);
  1132. return array('max'=>$max, 'maxmin'=>$maxmin, 'maxphptoshow'=>$maxphptoshow, 'maxphptoshowparam'=>$maxphptoshowparam);
  1133. }