security2.lib.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. <?php
  2. /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2008-2017 Regis Houssin <regis.houssin@inodbox.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. * or see https://www.gnu.org/
  18. */
  19. /**
  20. * \file htdocs/core/lib/security2.lib.php
  21. * \ingroup core
  22. * \brief Set of function used for dolibarr security (not common functions).
  23. * Warning, this file must not depends on other library files, except function.lib.php
  24. * because it is used at low code level.
  25. */
  26. /**
  27. * Return user/group account of web server
  28. *
  29. * @param string $mode 'user' or 'group'
  30. * @return string Return user or group of web server
  31. */
  32. function dol_getwebuser($mode)
  33. {
  34. $t = '?';
  35. if ($mode == 'user') {
  36. $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty
  37. }
  38. if ($mode == 'group') {
  39. $t = getenv('APACHE_RUN_GROUP');
  40. }
  41. return $t;
  42. }
  43. /**
  44. * Return a login if login/pass was successfull
  45. *
  46. * @param string $usertotest Login value to test
  47. * @param string $passwordtotest Password value to test
  48. * @param string $entitytotest Instance of data we must check
  49. * @param array $authmode Array list of selected authentication mode array('http', 'dolibarr', 'xxx'...)
  50. * @param string $context Context checkLoginPassEntity was created for ('api', 'dav', 'ws', '')
  51. * @return string Login or ''
  52. */
  53. function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context = '')
  54. {
  55. global $conf, $langs;
  56. //global $dolauthmode; // To return authentication finally used
  57. // Check parameters
  58. if ($entitytotest == '') {
  59. $entitytotest = 1;
  60. }
  61. dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',', $authmode));
  62. $login = '';
  63. // Validation of login/pass/entity with standard modules
  64. if (empty($login)) {
  65. $test = true;
  66. foreach ($authmode as $mode) {
  67. if ($test && $mode && !$login) {
  68. // Validation of login/pass/entity for mode $mode
  69. $mode = trim($mode);
  70. $authfile = 'functions_'.$mode.'.php';
  71. $fullauthfile = '';
  72. $dirlogin = array_merge(array("/core/login"), (array) $conf->modules_parts['login']);
  73. foreach ($dirlogin as $reldir) {
  74. $dir = dol_buildpath($reldir, 0);
  75. $newdir = dol_osencode($dir);
  76. // Check if file found (do not use dol_is_file to avoid loading files.lib.php)
  77. $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir) ? '' : '/').$authfile;
  78. if (is_file($tmpnewauthfile)) {
  79. $fullauthfile = $tmpnewauthfile;
  80. }
  81. }
  82. $result = false;
  83. if ($fullauthfile) {
  84. $result = include_once $fullauthfile;
  85. }
  86. if ($fullauthfile && $result) {
  87. // Call function to check user/password
  88. $function = 'check_user_password_'.$mode;
  89. $login = call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context);
  90. if ($login && $login != '--bad-login-validity--') { // Login is successfull
  91. $test = false; // To stop once at first login success
  92. $conf->authmode = $mode; // This properties is defined only when logged to say what mode was successfully used
  93. $dol_tz = GETPOST('tz');
  94. $dol_dst = GETPOST('dst');
  95. $dol_screenwidth = GETPOST('screenwidth');
  96. $dol_screenheight = GETPOST('screenheight');
  97. }
  98. } else {
  99. dol_syslog("Authentication KO - failed to load file '".$authfile."'", LOG_ERR);
  100. sleep(1);
  101. // Load translation files required by the page
  102. $langs->loadLangs(array('other', 'main', 'errors'));
  103. $_SESSION["dol_loginmesg"] = (empty($_SESSION["dol_loginmesg"]) ? '' : $_SESSION["dol_loginmesg"].', ').$langs->transnoentitiesnoconv("ErrorFailedToLoadLoginFileForMode", $mode);
  104. }
  105. }
  106. }
  107. }
  108. return $login;
  109. }
  110. if (!function_exists('dol_loginfunction')) {
  111. /**
  112. * Show Dolibarr default login page.
  113. * Part of this code is also duplicated into main.inc.php::top_htmlhead
  114. *
  115. * @param Translate $langs Lang object (must be initialized by a new).
  116. * @param Conf $conf Conf object
  117. * @param Societe $mysoc Company object
  118. * @return void
  119. */
  120. function dol_loginfunction($langs, $conf, $mysoc)
  121. {
  122. global $dolibarr_main_demo, $dolibarr_main_force_https;
  123. global $db, $hookmanager;
  124. $langs->loadLangs(array("main", "other", "help", "admin"));
  125. // Instantiate hooks of thirdparty module only if not already define
  126. $hookmanager->initHooks(array('mainloginpage'));
  127. $main_authentication = $conf->file->main_authentication;
  128. $session_name = session_name(); // Get current session name
  129. $dol_url_root = DOL_URL_ROOT;
  130. // Title
  131. $appli = constant('DOL_APPLICATION_TITLE');
  132. $title = $appli.' '.constant('DOL_VERSION');
  133. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  134. $title = $conf->global->MAIN_APPLICATION_TITLE;
  135. }
  136. $titletruedolibarrversion = constant('DOL_VERSION'); // $title used by login template after the @ to inform of true Dolibarr version
  137. // Note: $conf->css looks like '/theme/eldy/style.css.php'
  138. /*
  139. $conf->css = "/theme/".(GETPOST('theme','aZ09')?GETPOST('theme','aZ09'):$conf->theme)."/style.css.php";
  140. $themepath=dol_buildpath($conf->css,1);
  141. if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application
  142. {
  143. foreach($conf->modules_parts['theme'] as $reldir)
  144. {
  145. if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
  146. {
  147. $themepath=dol_buildpath($reldir.$conf->css, 1);
  148. break;
  149. }
  150. }
  151. }
  152. $conf_css = $themepath."?lang=".$langs->defaultlang;
  153. */
  154. // Select templates dir
  155. if (!empty($conf->modules_parts['tpl'])) { // Using this feature slow down application
  156. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl/'));
  157. foreach ($dirtpls as $reldir) {
  158. $tmp = dol_buildpath($reldir.'login.tpl.php');
  159. if (file_exists($tmp)) {
  160. $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp);
  161. break;
  162. }
  163. }
  164. } else {
  165. $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/";
  166. }
  167. // Set cookie for timeout management. We set it as a cookie so we will be able to use it to set timeout on next page before the session start
  168. // and the conf file is loaded.
  169. $prefix = dol_getprefix('');
  170. $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
  171. if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) {
  172. setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, (empty($dolibarr_main_force_https) ? false : true), true);
  173. }
  174. if (GETPOST('urlfrom', 'alpha')) {
  175. $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha');
  176. } else {
  177. unset($_SESSION["urlfrom"]);
  178. }
  179. if (!GETPOST("username", 'alpha')) {
  180. $focus_element = 'username';
  181. } else {
  182. $focus_element = 'password';
  183. }
  184. $demologin = '';
  185. $demopassword = '';
  186. if (!empty($dolibarr_main_demo)) {
  187. $tab = explode(',', $dolibarr_main_demo);
  188. $demologin = $tab[0];
  189. $demopassword = $tab[1];
  190. }
  191. // Execute hook getLoginPageOptions (for table)
  192. $parameters = array('entity' => GETPOST('entity', 'int'), 'switchentity' => GETPOST('switchentity', 'int'));
  193. $reshook = $hookmanager->executeHooks('getLoginPageOptions', $parameters); // Note that $action and $object may have been modified by some hooks.
  194. $morelogincontent = $hookmanager->resPrint;
  195. // Execute hook getLoginPageExtraOptions (eg for js)
  196. $parameters = array('entity' => GETPOST('entity', 'int'), 'switchentity' => GETPOST('switchentity', 'int'));
  197. $reshook = $hookmanager->executeHooks('getLoginPageExtraOptions', $parameters); // Note that $action and $object may have been modified by some hooks.
  198. $moreloginextracontent = $hookmanager->resPrint;
  199. //Redirect after connection
  200. $parameters = array('entity' => GETPOST('entity', 'int'), 'switchentity' => GETPOST('switchentity', 'int'));
  201. $reshook = $hookmanager->executeHooks('redirectAfterConnection', $parameters); // Note that $action and $object may have been modified by some hooks.
  202. $php_self = $hookmanager->resPrint;
  203. // Login
  204. $login = (!empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username", "alpha") ? GETPOST("username", "alpha") : $demologin));
  205. $password = $demopassword;
  206. // Show logo (search in order: small company logo, large company logo, theme logo, common logo)
  207. $width = 0;
  208. $urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png';
  209. if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) {
  210. $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small);
  211. } elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) {
  212. $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo);
  213. $width = 128;
  214. } elseif (!empty($mysoc->logo_squarred_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_squarred_small)) {
  215. $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_small);
  216. } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) {
  217. $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg';
  218. }
  219. // Security graphical code
  220. $captcha = 0;
  221. $captcha_refresh = '';
  222. if (function_exists("imagecreatefrompng") && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) {
  223. $captcha = 1;
  224. $captcha_refresh = img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"');
  225. }
  226. // Extra link
  227. $forgetpasslink = 0;
  228. $helpcenterlink = 0;
  229. if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) {
  230. if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) {
  231. $forgetpasslink = 1;
  232. }
  233. if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) {
  234. $helpcenterlink = 1;
  235. }
  236. }
  237. // Home message
  238. $main_home = '';
  239. if (!empty($conf->global->MAIN_HOME)) {
  240. $substitutionarray = getCommonSubstitutionArray($langs);
  241. complete_substitutions_array($substitutionarray, $langs);
  242. $texttoshow = make_substitutions($conf->global->MAIN_HOME, $substitutionarray, $langs);
  243. $main_home = dol_htmlcleanlastbr($texttoshow);
  244. }
  245. // Google AD
  246. $main_google_ad_client = ((!empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) ? 1 : 0);
  247. // Set jquery theme
  248. $dol_loginmesg = (!empty($_SESSION["dol_loginmesg"]) ? $_SESSION["dol_loginmesg"] : '');
  249. $favicon = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png';
  250. if (!empty($mysoc->logo_squarred_mini)) {
  251. $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini);
  252. }
  253. if (!empty($conf->global->MAIN_FAVICON_URL)) {
  254. $favicon = $conf->global->MAIN_FAVICON_URL;
  255. }
  256. $jquerytheme = 'base';
  257. if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) {
  258. $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
  259. }
  260. // Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_no_mouse_hover
  261. $dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int');
  262. $dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int');
  263. $dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int');
  264. $dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int');
  265. $dol_use_jmobile = GETPOST('dol_use_jmobile', 'int');
  266. // Include login page template
  267. include $template_dir.'login.tpl.php';
  268. // Global html output events ($mesgs, $errors, $warnings)
  269. dol_htmloutput_events(0);
  270. $_SESSION["dol_loginmesg"] = '';
  271. }
  272. }
  273. /**
  274. * Fonction pour initialiser un salt pour la fonction crypt.
  275. *
  276. * @param int $type 2=>renvoi un salt pour cryptage DES
  277. * 12=>renvoi un salt pour cryptage MD5
  278. * non defini=>renvoi un salt pour cryptage par defaut
  279. * @return string Salt string
  280. */
  281. function makesalt($type = CRYPT_SALT_LENGTH)
  282. {
  283. dol_syslog("makesalt type=".$type);
  284. switch ($type) {
  285. case 12: // 8 + 4
  286. $saltlen = 8;
  287. $saltprefix = '$1$';
  288. $saltsuffix = '$';
  289. break;
  290. case 8: // 8 (Pour compatibilite, ne devrait pas etre utilise)
  291. $saltlen = 8;
  292. $saltprefix = '$1$';
  293. $saltsuffix = '$';
  294. break;
  295. case 2: // 2
  296. default: // by default, fall back on Standard DES (should work everywhere)
  297. $saltlen = 2;
  298. $saltprefix = '';
  299. $saltsuffix = '';
  300. break;
  301. }
  302. $salt = '';
  303. while (dol_strlen($salt) < $saltlen) {
  304. $salt .= chr(mt_rand(64, 126));
  305. }
  306. $result = $saltprefix.$salt.$saltsuffix;
  307. dol_syslog("makesalt return=".$result);
  308. return $result;
  309. }
  310. /**
  311. * Encode or decode database password in config file
  312. *
  313. * @param int $level Encode level: 0 no encoding, 1 encoding
  314. * @return int <0 if KO, >0 if OK
  315. */
  316. function encodedecode_dbpassconf($level = 0)
  317. {
  318. dol_syslog("encodedecode_dbpassconf level=".$level, LOG_DEBUG);
  319. $config = '';
  320. $passwd = '';
  321. $passwd_crypted = '';
  322. if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php', 'r')) {
  323. while (!feof($fp)) {
  324. $buffer = fgets($fp, 4096);
  325. $lineofpass = 0;
  326. $reg = array();
  327. if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { // Old way to save crypted value
  328. $val = trim($reg[1]); // This also remove CR/LF
  329. $val = preg_replace('/^["\']/', '', $val);
  330. $val = preg_replace('/["\'][\s;]*$/', '', $val);
  331. if (!empty($val)) {
  332. $passwd_crypted = $val;
  333. // method dol_encode/dol_decode
  334. $val = dol_decode($val);
  335. //$val = dolEncrypt($val);
  336. $passwd = $val;
  337. $lineofpass = 1;
  338. }
  339. } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) {
  340. $val = trim($reg[1]); // This also remove CR/LF
  341. $val = preg_replace('/^["\']/', '', $val);
  342. $val = preg_replace('/["\'][\s;]*$/', '', $val);
  343. if (preg_match('/crypted:/i', $buffer)) {
  344. // method dol_encode/dol_decode
  345. $val = preg_replace('/crypted:/i', '', $val);
  346. $passwd_crypted = $val;
  347. $val = dol_decode($val);
  348. $passwd = $val;
  349. } elseif (preg_match('/^dolcrypt:([^:]+):(.*)$/i', $buffer, $reg)) {
  350. // method dolEncrypt/dolDecrypt
  351. $val = preg_replace('/crypted:([^:]+):/i', '', $val);
  352. $passwd_crypted = $val;
  353. $val = dolDecrypt($buffer);
  354. $passwd = $val;
  355. } else {
  356. $passwd = $val;
  357. $val = dol_encode($val);
  358. $passwd_crypted = $val;
  359. }
  360. $lineofpass = 1;
  361. }
  362. // Output line
  363. if ($lineofpass) {
  364. // Add value at end of file
  365. if ($level == 0) {
  366. $config .= '$dolibarr_main_db_pass=\''.$passwd.'\';'."\n";
  367. }
  368. if ($level == 1) {
  369. $config .= '$dolibarr_main_db_pass=\'crypted:'.$passwd_crypted.'\';'."\n";
  370. }
  371. //print 'passwd = '.$passwd.' - passwd_crypted = '.$passwd_crypted;
  372. //exit;
  373. } else {
  374. $config .= $buffer;
  375. }
  376. }
  377. fclose($fp);
  378. // Write new conf file
  379. $file = DOL_DOCUMENT_ROOT.'/conf/conf.php';
  380. if ($fp = @fopen($file, 'w')) {
  381. fputs($fp, $config);
  382. fflush($fp);
  383. fclose($fp);
  384. clearstatcache();
  385. // It's config file, so we set read permission for creator only.
  386. // Should set permission to web user and groups for users used by batch
  387. //@chmod($file, octdec('0600'));
  388. return 1;
  389. } else {
  390. dol_syslog("encodedecode_dbpassconf Failed to open conf.php file for writing", LOG_WARNING);
  391. return -1;
  392. }
  393. } else {
  394. dol_syslog("encodedecode_dbpassconf Failed to read conf.php", LOG_ERR);
  395. return -2;
  396. }
  397. }
  398. /**
  399. * Return a generated password using default module
  400. *
  401. * @param boolean $generic true=Create generic password (32 chars/numbers), false=Use the configured password generation module
  402. * @param array $replaceambiguouschars Discard ambigous characters. For example array('I').
  403. * @param int $length Length of random string (Used only if $generic is true)
  404. * @return string New value for password
  405. * @see dol_hash(), dolJSToSetRandomPassword()
  406. */
  407. function getRandomPassword($generic = false, $replaceambiguouschars = null, $length = 32)
  408. {
  409. global $db, $conf, $langs, $user;
  410. $generated_password = '';
  411. if ($generic) {
  412. $lowercase = "qwertyuiopasdfghjklzxcvbnm";
  413. $uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP";
  414. $numbers = "1234567890";
  415. $randomCode = "";
  416. $nbofchar = round($length / 3);
  417. $nbofcharlast = ($length - 2 * $nbofchar);
  418. //var_dump($nbofchar.'-'.$nbofcharlast);
  419. if (function_exists('random_int')) { // Cryptographic random
  420. $max = strlen($lowercase) - 1;
  421. for ($x = 0; $x < $nbofchar; $x++) {
  422. $tmp = random_int(0, $max);
  423. $randomCode .= $lowercase[$tmp];
  424. }
  425. $max = strlen($uppercase) - 1;
  426. for ($x = 0; $x < $nbofchar; $x++) {
  427. $tmp = random_int(0, $max);
  428. $randomCode .= $uppercase[$tmp];
  429. }
  430. $max = strlen($numbers) - 1;
  431. for ($x = 0; $x < $nbofcharlast; $x++) {
  432. $tmp = random_int(0, $max);
  433. $randomCode .= $numbers[$tmp];
  434. }
  435. $generated_password = str_shuffle($randomCode);
  436. } else {
  437. // Old platform, non cryptographic random
  438. $max = strlen($lowercase) - 1;
  439. for ($x = 0; $x < $nbofchar; $x++) {
  440. $tmp = mt_rand(0, $max);
  441. $randomCode .= $lowercase[$tmp];
  442. }
  443. $max = strlen($uppercase) - 1;
  444. for ($x = 0; $x < $nbofchar; $x++) {
  445. $tmp = mt_rand(0, $max);
  446. $randomCode .= $uppercase[$tmp];
  447. }
  448. $max = strlen($numbers) - 1;
  449. for ($x = 0; $x < $nbofcharlast; $x++) {
  450. $tmp = mt_rand(0, $max);
  451. $randomCode .= $numbers[$tmp];
  452. }
  453. $generated_password = str_shuffle($randomCode);
  454. }
  455. } elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) {
  456. $nomclass = "modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED);
  457. $nomfichier = $nomclass.".class.php";
  458. //print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass;
  459. require_once DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomfichier;
  460. $genhandler = new $nomclass($db, $conf, $langs, $user);
  461. $generated_password = $genhandler->getNewGeneratedPassword();
  462. unset($genhandler);
  463. }
  464. // Do we have to discard some alphabetic characters ?
  465. if (is_array($replaceambiguouschars) && count($replaceambiguouschars) > 0) {
  466. $numbers = "ABCDEF";
  467. $max = strlen($numbers) - 1;
  468. if (function_exists('random_int')) { // Cryptographic random
  469. $tmp = random_int(0, $max);
  470. $generated_password = str_replace($replaceambiguouschars, $numbers[$tmp], $generated_password);
  471. } else {
  472. $tmp = mt_rand(0, $max);
  473. $generated_password = str_replace($replaceambiguouschars, $numbers[$tmp], $generated_password);
  474. }
  475. }
  476. return $generated_password;
  477. }
  478. /**
  479. * Ouput javacript to autoset a generated password using default module into a HTML element.
  480. *
  481. * @param string $htmlname HTML name of element to insert key into
  482. * @param string $htmlnameofbutton HTML name of button
  483. * @return string HTML javascript code to set a password
  484. * @see getRandomPassword()
  485. */
  486. function dolJSToSetRandomPassword($htmlname, $htmlnameofbutton = 'generate_token')
  487. {
  488. global $conf;
  489. if (!empty($conf->use_javascript_ajax)) {
  490. print "\n".'<!-- Js code to suggest a security key --><script type="text/javascript">';
  491. print '$(document).ready(function () {
  492. $("#'.dol_escape_js($htmlnameofbutton).'").click(function() {
  493. console.log("We click on the button to suggest a key");
  494. $.get( "'.DOL_URL_ROOT.'/core/ajax/security.php", {
  495. action: \'getrandompassword\',
  496. generic: true,
  497. token: \''.dol_escape_js(newToken()).'\'
  498. },
  499. function(result) {
  500. $("#'.dol_escape_js($htmlname).'").val(result);
  501. });
  502. });
  503. });'."\n";
  504. print '</script>';
  505. }
  506. }