security.lib.php 44 KB

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