PageRenderTime 55ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/user/class/user.class.php

https://bitbucket.org/speedealing/speedealing
PHP | 1603 lines | 1049 code | 226 blank | 328 comment | 271 complexity | 376f7ede3cd7bedd7ca618a0d3ce334e MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-3.0, MIT
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (c) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (c) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
  8. * Copyright (C) 2005 Lionel Cousteix <etm_ltd@tiscali.co.uk>
  9. * Copyright (C) 2011-2012 Herve Prot <herve.prot@symeos.com>
  10. *
  11. * This program is free software; you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation; either version 3 of the License, or
  14. * (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. require_once DOL_DOCUMENT_ROOT . '/core/class/nosqlDocument.class.php';
  25. require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  26. require_once DOL_DOCUMENT_ROOT . '/core/db/couchdb/lib/couchAdmin.php';
  27. require_once DOL_DOCUMENT_ROOT . '/user/class/userdatabase.class.php';
  28. require_once DOL_DOCUMENT_ROOT . '/core/modules/DolibarrModules.class.php';
  29. /**
  30. * Class to manage Dolibarr users
  31. */
  32. class User extends nosqlDocument {
  33. public $element = 'user';
  34. public $table_element = 'user';
  35. protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  36. protected $couchAdmin;
  37. var $id;
  38. var $Lastname;
  39. var $Firstname;
  40. var $note;
  41. var $email;
  42. var $Signature;
  43. var $office_phone;
  44. var $office_fax;
  45. var $user_mobile;
  46. var $admin;
  47. var $login;
  48. //! Clear password in memory
  49. var $pass;
  50. //! Clear password in database (defined if DATABASE_PWD_ENCRYPTED=0)
  51. var $pass_indatabase;
  52. //! Encrypted password in database (always defined)
  53. var $pass_indatabase_crypted;
  54. var $datec;
  55. var $datem;
  56. //! If this is defined, it is an external user
  57. var $societe_id;
  58. var $contact_id;
  59. var $fk_member;
  60. var $datelastlogin;
  61. var $datepreviouslogin;
  62. var $Status;
  63. var $Photo;
  64. var $Lang;
  65. //! Liste des entrepots auquel a acces l'utilisateur
  66. var $entrepots;
  67. var $rights; // Array of permissions user->rights->permx
  68. var $all_permissions_are_loaded; /* * < \private all_permissions_are_loaded */
  69. private $_tab_loaded = array(); // Array of cache of already loaded permissions
  70. var $conf; // To store personal config
  71. /**
  72. * Constructor de la classe
  73. *
  74. * @param DoliDb $db Database handler
  75. */
  76. function __construct($db = null) {
  77. $this->db = $db;
  78. parent::__construct($db);
  79. $this->useDatabase("system");
  80. $this->fk_extrafields = new ExtraFields($db);
  81. $this->fk_extrafields->fetch(get_class($this));
  82. $this->couchAdmin = new couchAdmin($this->couchdb);
  83. // Preference utilisateur
  84. $this->liste_limit = 0;
  85. $this->clicktodial_loaded = 0;
  86. $this->all_permissions_are_loaded = 0;
  87. $this->admin = 0;
  88. $this->conf = new stdClass();
  89. $this->rights = new stdClass();
  90. $this->rights->user = new stdClass();
  91. $this->rights->user->user = new stdClass();
  92. $this->rights->user->self = new stdClass();
  93. }
  94. /**
  95. * Load a user from database with its id or ref (login)
  96. *
  97. * @param string $id Si defini, id a utiliser pour recherche
  98. * @param string $login Si defini, login a utiliser pour recherche
  99. * @param strinf $sid Si defini, sid a utiliser pour recherche
  100. * @param int $loadpersonalconf Also load personal conf of user (in $user->conf->xxx)
  101. * @return int <0 if KO, 0 not found, >0 if OK
  102. */
  103. function fetch($login = "", $cache = false) {
  104. global $conf, $couch;
  105. // Clean parametersadmin
  106. $login = trim($login);
  107. if (empty($login)) {
  108. try {
  109. $login = $this->couchAdmin->getLoginSession();
  110. } catch (Exception $e) {
  111. $login = null;
  112. }
  113. if (empty($login))
  114. return 0;
  115. }
  116. /* if ($conf->Couchdb->name == '_users') { // Login phase
  117. require_once(DOL_DOCUMENT_ROOT . "/useradmin/class/useradmin.class.php");
  118. $user_config = new UserAdmin($this->db);
  119. $user_config->fetch("org.couchdb.user:" . $login); // Load for default entity
  120. $user_config->LastConnection = $user_config->NewConnection;
  121. $user_config->NewConnection = dol_now();
  122. //$user_config->record(); // FIXME no record method in fetch method
  123. //print_r($login);
  124. //exit;
  125. $couch->useDatabase($user_config->entity);
  126. $conf->Couchdb->name = $user_config->entity;
  127. dol_setcache("dol_entity", $user_config->entity);
  128. //$this->useDatabase($user_config->entity);
  129. unset($user_config);
  130. if (!$conf->urlrewrite) {
  131. $this->LastConnection = $this->NewConnection;
  132. $this->NewConnection = dol_now();
  133. //$this->record(true); // FIXME no record method in fetch method
  134. }
  135. } */
  136. try {
  137. /* if (isValidEmail($login)) {
  138. $result = $this->getView("login", array("key" => $login));
  139. $login = $result->rows[0]->value;
  140. } */
  141. //$result = $this->couchAdmin->getUser($login);
  142. //print_r($result);exit;
  143. $login = str_replace('user:', '', $login); // For avoid error
  144. $this->load("user:" . $login, $cache);
  145. } catch (Exception $e) {
  146. error_log("Login error : " . $login . " " . $e->getMessage());
  147. return 0;
  148. }
  149. // Test if User is a global administrator
  150. try {
  151. $admins = $this->couchAdmin->getUserAdmins();
  152. $name = $this->couchAdmin->getLoginSession();
  153. $user = $this->couchAdmin->getUser($name);
  154. if ((isset($admins->$name) || in_array("_admin", $user->roles, true)) && $this->name == $name)
  155. $this->superadmin = true;
  156. else
  157. $this->superadmin = false;
  158. } catch (Exception $e) {
  159. $this->superadmin = false;
  160. }
  161. // Test if User is a local administrator for a specific databses
  162. if ($this->superadmin) {
  163. $this->admin = true;
  164. } else {
  165. $membersAdmin = $this->couchAdmin->getDatabaseAdminUsers();
  166. if (in_array($this->name, $membersAdmin))
  167. $this->admin = true;
  168. else
  169. $this->admin = false;
  170. }
  171. try {
  172. $database = new UserDatabase($this->db);
  173. $database->fetch($conf->Couchdb->name);
  174. $result = $database->couchAdmin->getDatabaseAdminUsers(); // Administrateur local de la bd
  175. if (in_array($this->name, $result)) {
  176. $this->admin = true;
  177. }
  178. } catch (Exception $e) {
  179. }
  180. $this->id = $this->_id;
  181. return 1;
  182. }
  183. /**
  184. * Ajoute un droit a l'utilisateur
  185. *
  186. * @param int $rid id du droit a ajouter
  187. * @param string $allmodule Ajouter tous les droits du module allmodule
  188. * @param string $allperms Ajouter tous les droits du module allmodule, perms allperms
  189. * @return int > 0 if OK, < 0 if KO
  190. */
  191. function addrights($rid, $allmodule = '', $allperms = '') {
  192. global $conf;
  193. dol_syslog(get_class($this) . "::addrights $rid, $allmodule, $allperms");
  194. $err = 0;
  195. $whereforadd = '';
  196. $this->db->begin();
  197. if ($rid) {
  198. // Si on a demande ajout d'un droit en particulier, on recupere
  199. // les caracteristiques (module, perms et subperms) de ce droit.
  200. $sql = "SELECT module, perms, subperms";
  201. $sql.= " FROM " . MAIN_DB_PREFIX . "rights_def";
  202. $sql.= " WHERE id = '" . $rid . "'";
  203. $sql.= " AND entity = " . $conf->entity;
  204. $result = $this->db->query($sql);
  205. if ($result) {
  206. $obj = $this->db->fetch_object($result);
  207. $module = $obj->module;
  208. $perms = $obj->perms;
  209. $subperms = $obj->subperms;
  210. } else {
  211. $err++;
  212. dol_print_error($this->db);
  213. }
  214. // Where pour la liste des droits a ajouter
  215. $whereforadd = "id=" . $rid;
  216. // Ajout des droits induits
  217. if ($subperms)
  218. $whereforadd.=" OR (module='$module' AND perms='$perms' AND (subperms='lire' OR subperms='read'))";
  219. else if ($perms)
  220. $whereforadd.=" OR (module='$module' AND (perms='lire' OR perms='read') AND subperms IS NULL)";
  221. }
  222. else {
  223. // On a pas demande un droit en particulier mais une liste de droits
  224. // sur la base d'un nom de module de de perms
  225. // Where pour la liste des droits a ajouter
  226. if ($allmodule)
  227. $whereforadd = "module='$allmodule'";
  228. if ($allperms)
  229. $whereforadd = " AND perms='$allperms'";
  230. }
  231. // Ajout des droits trouves grace au critere whereforadd
  232. if ($whereforadd) {
  233. //print "$module-$perms-$subperms";
  234. $sql = "SELECT id";
  235. $sql.= " FROM " . MAIN_DB_PREFIX . "rights_def";
  236. $sql.= " WHERE " . $whereforadd;
  237. $sql.= " AND entity = " . $conf->entity;
  238. $result = $this->db->query($sql);
  239. if ($result) {
  240. $num = $this->db->num_rows($result);
  241. $i = 0;
  242. while ($i < $num) {
  243. $obj = $this->db->fetch_object($result);
  244. $nid = $obj->id;
  245. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = " . $this->id . " AND fk_id=" . $nid;
  246. if (!$this->db->query($sql))
  247. $err++;
  248. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_rights (fk_user, fk_id) VALUES (" . $this->id . ", " . $nid . ")";
  249. if (!$this->db->query($sql))
  250. $err++;
  251. $i++;
  252. }
  253. }
  254. else {
  255. $err++;
  256. dol_print_error($this->db);
  257. }
  258. }
  259. if ($err) {
  260. $this->db->rollback();
  261. return -$err;
  262. } else {
  263. $this->db->commit();
  264. return 1;
  265. }
  266. }
  267. /**
  268. * Retire un droit a l'utilisateur
  269. *
  270. * @param int $rid Id du droit a retirer
  271. * @param string $allmodule Retirer tous les droits du module allmodule
  272. * @param string $allperms Retirer tous les droits du module allmodule, perms allperms
  273. * @return int > 0 if OK, < 0 if OK
  274. */
  275. function delrights($rid, $allmodule = '', $allperms = '') {
  276. global $conf;
  277. $err = 0;
  278. $wherefordel = '';
  279. $this->db->begin();
  280. if ($rid) {
  281. // Si on a demande supression d'un droit en particulier, on recupere
  282. // les caracteristiques module, perms et subperms de ce droit.
  283. $sql = "SELECT module, perms, subperms";
  284. $sql.= " FROM " . MAIN_DB_PREFIX . "rights_def";
  285. $sql.= " WHERE id = '" . $rid . "'";
  286. $sql.= " AND entity = " . $conf->entity;
  287. $result = $this->db->query($sql);
  288. if ($result) {
  289. $obj = $this->db->fetch_object($result);
  290. $module = $obj->module;
  291. $perms = $obj->perms;
  292. $subperms = $obj->subperms;
  293. } else {
  294. $err++;
  295. dol_print_error($this->db);
  296. }
  297. // Where pour la liste des droits a supprimer
  298. $wherefordel = "id=" . $rid;
  299. // Suppression des droits induits
  300. if ($subperms == 'lire' || $subperms == 'read')
  301. $wherefordel.=" OR (module='$module' AND perms='$perms' AND subperms IS NOT NULL)";
  302. if ($perms == 'lire' || $perms == 'read')
  303. $wherefordel.=" OR (module='$module')";
  304. }
  305. else {
  306. // On a demande suppression d'un droit sur la base d'un nom de module ou perms
  307. // Where pour la liste des droits a supprimer
  308. if ($allmodule)
  309. $wherefordel = "module='$allmodule'";
  310. if ($allperms)
  311. $wherefordel = " AND perms='$allperms'";
  312. }
  313. // Suppression des droits selon critere defini dans wherefordel
  314. if ($wherefordel) {
  315. //print "$module-$perms-$subperms";
  316. $sql = "SELECT id";
  317. $sql.= " FROM " . MAIN_DB_PREFIX . "rights_def";
  318. $sql.= " WHERE $wherefordel";
  319. $sql.= " AND entity = " . $conf->entity;
  320. $result = $this->db->query($sql);
  321. if ($result) {
  322. $num = $this->db->num_rows($result);
  323. $i = 0;
  324. while ($i < $num) {
  325. $obj = $this->db->fetch_object($result);
  326. $nid = $obj->id;
  327. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights";
  328. $sql.= " WHERE fk_user = " . $this->id . " AND fk_id=" . $nid;
  329. if (!$this->db->query($sql))
  330. $err++;
  331. $i++;
  332. }
  333. }
  334. else {
  335. $err++;
  336. dol_print_error($this->db);
  337. }
  338. }
  339. if ($err) {
  340. $this->db->rollback();
  341. return -$err;
  342. } else {
  343. $this->db->commit();
  344. return 1;
  345. }
  346. }
  347. /**
  348. * Clear all permissions array of user
  349. *
  350. * @return void
  351. */
  352. function clearrights() {
  353. dol_syslog(get_class($this) . "::clearrights reset user->rights");
  354. $this->rights = '';
  355. $this->all_permissions_are_loaded = false;
  356. $this->_tab_loaded = array();
  357. }
  358. /**
  359. * Load permissions granted to user into object user
  360. *
  361. * @param string $moduletag Limit permission for a particular module ('' by default means load all permissions)
  362. * @return void
  363. */
  364. function getrights($moduletag = '') {
  365. global $conf;
  366. if ($moduletag && isset($this->_tab_loaded[$moduletag]) && $this->_tab_loaded[$moduletag]) {
  367. // Le fichier de ce module est deja charge
  368. return;
  369. }
  370. if ($this->all_permissions_are_loaded) {
  371. // Si les permissions ont deja ete charge pour ce user, on quitte
  372. return;
  373. }
  374. $object = new DolibarrModules($this->db);
  375. try {
  376. $result = $object->getView("default_right", '', true);
  377. if (count($this->roles) > 0)
  378. foreach ($this->roles as $aRow) // load groups
  379. $groups[] = $object->load("group:" . $aRow, true);
  380. } catch (Exception $exc) {
  381. print $exc->getMessage();
  382. }
  383. if (count($result->rows)) {
  384. foreach ($result->rows as $aRow) {
  385. //$object->name = $aRow->value->name;
  386. //$object->numero = $aRow->value->numero;
  387. $rights_class = $aRow->value->rights_class;
  388. //$object->id = $aRow->value->id;
  389. $perm = $aRow->value->perm;
  390. // Add default rights
  391. if (!is_object($this->rights->$rights_class))
  392. $this->rights->$rights_class = new stdClass();
  393. if (count($perm) == 1)
  394. $this->rights->$rights_class->$perm[0] = $aRow->value->Status;
  395. elseif (count($perm) == 2) {
  396. if (!is_object($this->rights->$rights_class->$perm[0]))
  397. $this->rights->$rights_class->$perm[0] = new stdClass();
  398. if (isset($this->rights->$rights_class->$perm[0]))
  399. $this->rights->$rights_class->$perm[0]->$perm[1] = $aRow->value->Status;
  400. else
  401. $this->rights->$rights_class->$perm[0]->$perm[1] = $aRow->value->Status;
  402. }
  403. // Add user rights
  404. if ((is_array($this->rights) && isset($this->rights->$key)) || (is_array($this->own_rights) && isset($this->own_rights->$key)) || $this->admin) {
  405. if (count($perm) == 1)
  406. $this->rights->$rights_class->$perm[0] = true;
  407. elseif (count($perm) == 2)
  408. $this->rights->$rights_class->$perm[0]->$perm[1] = true;
  409. }
  410. // Add groups rights
  411. for ($i = 0; $i < count($groups); $i++) {
  412. $key = $aRow->value->id;
  413. if (isset($groups[$i]->rights->$key)) {
  414. if (count($perm) == 1)
  415. $this->rights->$rights_class->$perm[0] = true;
  416. elseif (count($perm) == 2)
  417. $this->rights->$rights_class->$perm[0]->$perm[1] = true;
  418. }
  419. }
  420. }
  421. }
  422. //print_r($this->rights);
  423. // Convert for old right definition
  424. if (!empty($this->rights->societe->creer))
  425. $this->rights->societe->edit = true;
  426. if (!empty($this->rights->societe->supprimer))
  427. $this->rights->societe->delete = true;
  428. if (!empty($this->rights->societe->contact->creer)) {
  429. if (!is_object($this->rights->contact))
  430. $this->rights->contact = new stdClass(); // For avoid error
  431. $this->rights->contact->edit = true;
  432. }
  433. if (!empty($this->rights->societe->contact->supprimer)) {
  434. if (!is_object($this->rights->contact))
  435. $this->rights->contact = new stdClass(); // For avoid error
  436. $this->rights->contact->delete = true;
  437. }
  438. if (!empty($this->rights->agenda->myactions->write))
  439. $this->rights->agenda->edit = true;
  440. if (!empty($this->rights->agenda->myactions->delete))
  441. $this->rights->agenda->delete = true;
  442. if (!empty($this->rights->commande->creer))
  443. $this->rights->commande->edit = true;
  444. if (!empty($this->rights->commande->supprimer))
  445. $this->rights->commande->delete = true;
  446. if (!$moduletag) {
  447. // Si module etait non defini, alors on a tout charge, on peut donc considerer
  448. // que les droits sont en cache (car tous charges) pour cet instance de user
  449. $this->all_permissions_are_loaded = 1;
  450. } else {
  451. // Si module defini, on le marque comme charge en cache
  452. $this->_tab_loaded[$moduletag] = 1;
  453. }
  454. }
  455. /**
  456. * Change status of a user
  457. *
  458. * @param int $statut Status to set
  459. * @return int <0 if KO, 0 if nothing is done, >0 if OK
  460. */
  461. function setstatus($status) {
  462. $error = 0;
  463. if ($status == 0)
  464. $status = "DISABLE";
  465. else
  466. $status = "ENABLE";
  467. // Check parameters
  468. if ($this->Status == $status)
  469. return 0;
  470. else {
  471. $userid = $this->email;
  472. if ($status == 'ENABLE') {
  473. if ($this->admin == true)
  474. $this->couchAdmin->addDatabaseAdminUser($userid);
  475. else
  476. $this->couchAdmin->addDatabaseReaderUser($userid);
  477. }
  478. elseif ($status == 'DISABLE') {
  479. $this->couchAdmin->removeDatabaseAdminUser($userid);
  480. $this->couchAdmin->removeDatabaseReaderUser($userid);
  481. }
  482. $this->set("Status", $status);
  483. dol_delcache($this->id);
  484. }
  485. return 1;
  486. }
  487. /**
  488. * Delete the user
  489. *
  490. * @return int <0 if KO, >0 if OK
  491. */
  492. function delete() {
  493. global $user, $conf, $langs;
  494. $error = 0;
  495. $this->db->begin();
  496. $this->fetch($this->id);
  497. // Supprime droits
  498. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = " . $this->id;
  499. if ($this->db->query($sql)) {
  500. }
  501. // Remove group
  502. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user WHERE fk_user = " . $this->id;
  503. if ($this->db->query($sql)) {
  504. }
  505. // Si contact, supprime lien
  506. if ($this->contact_id) {
  507. $sql = "UPDATE " . MAIN_DB_PREFIX . "socpeople SET fk_user_creat = null WHERE rowid = " . $this->contact_id;
  508. if ($this->db->query($sql)) {
  509. }
  510. }
  511. // Supprime utilisateur
  512. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user WHERE rowid = $this->id";
  513. $result = $this->db->query($sql);
  514. if ($result) {
  515. // Appel des triggers
  516. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  517. $interface = new Interfaces($this->db);
  518. $result = $interface->run_triggers('USER_DELETE', $this, $user, $langs, $conf);
  519. if ($result < 0) {
  520. $error++;
  521. $this->errors = $interface->errors;
  522. }
  523. // Fin appel triggers
  524. $this->db->commit();
  525. return 1;
  526. } else {
  527. $this->db->rollback();
  528. return -1;
  529. }
  530. }
  531. /**
  532. * Create or Update an user into database
  533. *
  534. * @param User $user Objet user qui demande la creation
  535. * @param int $notrigger 1 ne declenche pas les triggers, 0 sinon
  536. * @return int <0 si KO, id compte cree si OK
  537. */
  538. function update($user, $notrigger = 0, $action) {
  539. global $conf, $langs;
  540. // Clean parameters
  541. $this->name = trim($this->name);
  542. $this->pass = trim($this->pass);
  543. $this->Firstname = trim($this->Firstname);
  544. $this->Lastname = trim($this->Lastname);
  545. // Check parameters
  546. /* if (!isValidEMail($this->email)) {
  547. $langs->load("errors");
  548. $this->error = $langs->trans("ErrorBadEMail", $this->email);
  549. return -1;
  550. } */
  551. $error = 0;
  552. try {
  553. $result = $this->couchAdmin->getUser($this->name);
  554. } catch (Exception $e) {
  555. // User doesn-t exist
  556. }
  557. if (isset($result->name) && $action == 'add' && $action != 'install') {
  558. $this->error = 'ErrorLoginAlreadyExists';
  559. return -6;
  560. } else {
  561. if ($action == 'add' || $action == 'install' || empty($result->name)) {
  562. try {
  563. if ($action != 'install') {
  564. if ($this->admin)
  565. $this->couchAdmin->createAdmin($this->name, $this->pass);
  566. else
  567. $this->couchAdmin->createUser($this->name, $this->pass);
  568. }
  569. unset($this->pass);
  570. if (!empty($this->roles)) // use not empty instead count for avoid error
  571. foreach ($this->roles as $group)
  572. $this->couchAdmin->addRoleToUser($this->name, $group);
  573. } catch (Exception $e) {
  574. $this->error = $e->getMessage();
  575. error_log($this->error);
  576. return -4;
  577. }
  578. }
  579. }
  580. try {
  581. /* $user_tmp = $this->couchAdmin->getUser($this->name);
  582. $this->salt = $user_tmp->salt;
  583. $this->password_sha = $user_tmp->password_sha;
  584. $this->type = $user_tmp->type;
  585. $this->roles = $user_tmp->roles;
  586. $this->_id = $user_tmp->_id;
  587. $this->_rev = $user_tmp->_rev; */
  588. if ($action == 'add' || $action == 'install') {
  589. if (empty($this->Status))
  590. $this->Status = "DISABLE";
  591. $this->CreateDate = dol_now();
  592. $this->_id = "user:" . $this->name;
  593. }
  594. $pass = null;
  595. if (!empty($this->pass)) { // For avoid error
  596. $pass = $this->pass;
  597. unset($this->pass);
  598. }
  599. //print_r($this);exit;
  600. $result = $this->record(); // Save all specific parameters
  601. if (empty($user)) //install process
  602. $caneditpassword = 1;
  603. else
  604. $caneditpassword = ((($user->login == $this->name) && $user->rights->user->self->password) || (($user->login != $this->name) && $user->rights->user->user->password)) || $user->admin;
  605. if ($caneditpassword && !empty($pass)) { // Case we can edit only password
  606. $this->couchAdmin->setPassword($this->name, $pass);
  607. }
  608. if ($action == 'update') {
  609. if ($this->admin)
  610. $this->couchAdmin->addRoleToUser($this->name, "_admin");
  611. else
  612. $this->couchAdmin->removeRoleFromUser($this->name, "_admin");
  613. }
  614. } catch (Exception $e) {
  615. $this->error = $e->getMessage();
  616. error_log($this->error);
  617. return -3;
  618. }
  619. if ($result) {
  620. $this->id = $this->name;
  621. $this->_id = $result->id;
  622. $this->_rev = $result->rev;
  623. if (!$notrigger && !empty($user)) {
  624. // Appel des triggers
  625. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  626. $interface = new Interfaces($this->db);
  627. $result = $interface->run_triggers('USER_CREATE', $this, $user, $langs, $conf);
  628. if ($result < 0) {
  629. $error++;
  630. $this->errors = $interface->errors;
  631. }
  632. // Fin appel triggers
  633. }
  634. } else {
  635. $this->error = $this->db->lasterror();
  636. return -2;
  637. }
  638. return $this->id;
  639. }
  640. /**
  641. * Create a user from a contact object. User will be internal but if contact is linked to a third party, user will be external
  642. *
  643. * @param Contact $contact Object for source contact
  644. * @param string $login Login to force
  645. * @param string $password Password to force
  646. * @return int <0 if error, if OK returns id of created user
  647. */
  648. function create_from_contact($contact, $login = '', $password = '') {
  649. global $conf, $user, $langs;
  650. $error = 0;
  651. // Positionne parametres
  652. $this->admin = 0;
  653. $this->nom = $contact->nom; // TODO deprecated
  654. $this->prenom = $contact->prenom; // TODO deprecated
  655. $this->lastname = $contact->nom;
  656. $this->firstname = $contact->prenom;
  657. $this->email = $contact->email;
  658. $this->office_phone = $contact->phone_pro;
  659. $this->office_fax = $contact->fax;
  660. $this->user_mobile = $contact->phone_mobile;
  661. if (empty($login))
  662. $login = strtolower(substr($contact->prenom, 0, 4)) . strtolower(substr($contact->nom, 0, 4));
  663. $this->login = $login;
  664. $this->db->begin();
  665. // Cree et positionne $this->id
  666. $result = $this->create($user);
  667. if ($result > 0) {
  668. $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
  669. $sql.= " SET fk_socpeople=" . $contact->id;
  670. if ($contact->socid)
  671. $sql.=", fk_societe=" . $contact->socid;
  672. $sql.= " WHERE rowid=" . $this->id;
  673. $resql = $this->db->query($sql);
  674. dol_syslog(get_class($this) . "::create_from_contact sql=" . $sql, LOG_DEBUG);
  675. if ($resql) {
  676. // Appel des triggers
  677. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  678. $interface = new Interfaces($this->db);
  679. $result = $interface->run_triggers('USER_CREATE_FROM_CONTACT', $this, $user, $langs, $conf);
  680. if ($result < 0) {
  681. $error++;
  682. $this->errors = $interface->errors;
  683. }
  684. // Fin appel triggers
  685. $this->db->commit();
  686. return $this->id;
  687. } else {
  688. $this->error = $this->db->error();
  689. dol_syslog(get_class($this) . "::create_from_contact " . $this->error, LOG_ERR);
  690. $this->db->rollback();
  691. return -1;
  692. }
  693. } else {
  694. // $this->error deja positionne
  695. dol_syslog(get_class($this) . "::create_from_contact - 0");
  696. $this->db->rollback();
  697. return $result;
  698. }
  699. }
  700. /**
  701. * Create a user into database from a member object
  702. *
  703. * @param Adherent $member Object member source
  704. * @param string $login Login to force
  705. * @return int <0 if KO, if OK, return id of created account
  706. */
  707. function create_from_member($member, $login = '') {
  708. global $conf, $user, $langs;
  709. // Positionne parametres
  710. $this->admin = 0;
  711. $this->lastname = $member->lastname;
  712. $this->firstname = $member->firstname;
  713. $this->email = $member->email;
  714. $this->pass = $member->pass;
  715. if (empty($login))
  716. $login = strtolower(substr($member->firstname, 0, 4)) . strtolower(substr($member->lastname, 0, 4));
  717. $this->login = $login;
  718. $this->db->begin();
  719. // Cree et positionne $this->id
  720. $result = $this->create($user);
  721. if ($result > 0) {
  722. $result = $this->setPassword($user, $this->pass);
  723. $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
  724. $sql.= " SET fk_member=" . $member->id;
  725. if ($member->fk_soc)
  726. $sql.= ", fk_societe=" . $member->fk_soc;
  727. $sql.= " WHERE rowid=" . $this->id;
  728. dol_syslog(get_class($this) . "::create_from_member sql=" . $sql, LOG_DEBUG);
  729. $resql = $this->db->query($sql);
  730. if ($resql) {
  731. $this->db->commit();
  732. return $this->id;
  733. } else {
  734. $this->error = $this->db->error();
  735. dol_syslog(get_class($this) . "::create_from_member - 1 - " . $this->error, LOG_ERR);
  736. $this->db->rollback();
  737. return -1;
  738. }
  739. } else {
  740. // $this->error deja positionne
  741. dol_syslog(get_class($this) . "::create_from_member - 2 - " . $this->error, LOG_ERR);
  742. $this->db->rollback();
  743. return $result;
  744. }
  745. }
  746. /**
  747. * Affectation des permissions par defaut
  748. *
  749. * @return Si erreur <0, si ok renvoi le nbre de droits par defaut positionnes
  750. */
  751. function set_default_rights() {
  752. global $conf;
  753. $sql = "SELECT id FROM " . MAIN_DB_PREFIX . "rights_def";
  754. $sql.= " WHERE bydefault = 1";
  755. $sql.= " AND entity = " . $conf->entity;
  756. $resql = $this->db->query($sql);
  757. if ($resql) {
  758. $num = $this->db->num_rows($resql);
  759. $i = 0;
  760. $rd = array();
  761. while ($i < $num) {
  762. $row = $this->db->fetch_row($resql);
  763. $rd[$i] = $row[0];
  764. $i++;
  765. }
  766. $this->db->free($resql);
  767. }
  768. $i = 0;
  769. while ($i < $num) {
  770. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
  771. $result = $this->db->query($sql);
  772. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
  773. $result = $this->db->query($sql);
  774. if (!$result)
  775. return -1;
  776. $i++;
  777. }
  778. return $i;
  779. }
  780. /**
  781. * Mise e jour en base de la date de deniere connexion d'un utilisateur
  782. * Fonction appelee lors d'une nouvelle connexion
  783. *
  784. * @return <0 si echec, >=0 si ok
  785. */
  786. function update_last_login_date() {
  787. $now = dol_now();
  788. $this->LastConnection = $this->NewConnection;
  789. $this->NewConnection = $now;
  790. $this->record(true);
  791. }
  792. /**
  793. * Change password of a user
  794. *
  795. * @param User $user Object user of user making change
  796. * @param string $password New password in clear text (to generate if not provided)
  797. * @param int $changelater 1=Change password only after clicking on confirm email
  798. * @param int $notrigger 1=Does not launch triggers
  799. * @param int $nosyncmember Do not synchronize linked member
  800. * @return string If OK return clear password, 0 if no change, < 0 if error
  801. */
  802. function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0) {
  803. global $conf, $langs;
  804. require_once(DOL_DOCUMENT_ROOT . "/core/lib/security2.lib.php");
  805. $error = 0;
  806. dol_syslog(get_class($this) . "::setPassword user=" . $user->id . " password=" . preg_replace('/./i', '*', $password) . " changelater=" . $changelater . " notrigger=" . $notrigger . " nosyncmember=" . $nosyncmember, LOG_DEBUG);
  807. // If new password not provided, we generate one
  808. if (!$password) {
  809. $password = getRandomPassword('');
  810. }
  811. // Crypte avec md5
  812. $password_crypted = dol_hash($password);
  813. // Mise a jour
  814. if (!$changelater) {
  815. if (!is_object($this->oldcopy))
  816. $this->oldcopy = dol_clone($this);
  817. $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
  818. $sql.= " SET pass_crypted = '" . $this->db->escape($password_crypted) . "',";
  819. $sql.= " pass_temp = null";
  820. if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
  821. $sql.= ", pass = null";
  822. } else {
  823. $sql.= ", pass = '" . $this->db->escape($password) . "'";
  824. }
  825. $sql.= " WHERE rowid = " . $this->id;
  826. dol_syslog(get_class($this) . "::setPassword sql=hidden", LOG_DEBUG);
  827. $result = $this->db->query($sql);
  828. if ($result) {
  829. if ($this->db->affected_rows($result)) {
  830. $this->pass = $password;
  831. $this->pass_indatabase = $password;
  832. $this->pass_indatabase_crypted = $password_crypted;
  833. if ($this->fk_member && !$nosyncmember) {
  834. require_once(DOL_DOCUMENT_ROOT . "/adherents/class/adherent.class.php");
  835. // This user is linked with a member, so we also update members informations
  836. // if this is an update.
  837. $adh = new Adherent($this->db);
  838. $result = $adh->fetch($this->fk_member);
  839. if ($result >= 0) {
  840. $result = $adh->setPassword($user, $this->pass, 0, 1); // Cryptage non gere dans module adherent
  841. if ($result < 0) {
  842. $this->error = $adh->error;
  843. dol_syslog(get_class($this) . "::setPassword " . $this->error, LOG_ERR);
  844. $error++;
  845. }
  846. } else {
  847. $this->error = $adh->error;
  848. $error++;
  849. }
  850. }
  851. dol_syslog(get_class($this) . "::setPassword notrigger=" . $notrigger . " error=" . $error, LOG_DEBUG);
  852. if (!$error && !$notrigger) {
  853. // Appel des triggers
  854. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  855. $interface = new Interfaces($this->db);
  856. $result = $interface->run_triggers('USER_NEW_PASSWORD', $this, $user, $langs, $conf);
  857. if ($result < 0)
  858. $this->errors = $interface->errors;
  859. // Fin appel triggers
  860. }
  861. return $this->pass;
  862. }
  863. else {
  864. return 0;
  865. }
  866. } else {
  867. dol_print_error($this->db);
  868. return -1;
  869. }
  870. } else {
  871. // We store clear password in password temporary field.
  872. // After receiving confirmation link, we will crypt it and store it in pass_crypted
  873. $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
  874. $sql.= " SET pass_temp = '" . $this->db->escape($password) . "'";
  875. $sql.= " WHERE rowid = " . $this->id;
  876. dol_syslog(get_class($this) . "::setPassword sql=hidden", LOG_DEBUG); // No log
  877. $result = $this->db->query($sql);
  878. if ($result) {
  879. return $password;
  880. } else {
  881. dol_print_error($this->db);
  882. return -3;
  883. }
  884. }
  885. }
  886. /**
  887. * Envoie mot de passe par mail
  888. *
  889. * @param User $user Object user de l'utilisateur qui fait l'envoi
  890. * @param string $password Nouveau mot de passe
  891. * @param int $changelater 1=Change password only after clicking on confirm email
  892. * @return int < 0 si erreur, > 0 si ok
  893. */
  894. function send_password($user, $password = '', $changelater = 0) {
  895. global $conf, $langs;
  896. global $dolibarr_main_url_root;
  897. require_once DOL_DOCUMENT_ROOT . "/core/class/CMailFile.class.php";
  898. $subject = $langs->trans("SubjectNewPassword");
  899. $msgishtml = 0;
  900. // Define $msg
  901. $mesg = '';
  902. $outputlangs = new Translate();
  903. if (isset($this->conf->MAIN_LANG_DEFAULT) && $this->conf->MAIN_LANG_DEFAULT != 'auto') { // If user has defined its own language (rare because in most cases, auto is used)
  904. $outputlangs->getDefaultLang($this->conf->MAIN_LANG_DEFAULT);
  905. } else { // If user has not defined its own language, we used current language
  906. $outputlangs = $langs;
  907. }
  908. // Define urlwithouturlroot
  909. if (!empty($_SERVER["HTTP_HOST"])) { // Autodetect main url root
  910. $urlwithouturlroot = 'http://' . preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', $_SERVER["HTTP_HOST"]);
  911. } else {
  912. $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', $dolibarr_main_url_root);
  913. }
  914. if (!empty($dolibarr_main_force_https))
  915. $urlwithouturlroot = preg_replace('/http:/i', 'https:', $urlwithouturlroot);
  916. // TODO Use outputlangs to translate messages
  917. if (!$changelater) {
  918. $mesg.= "A request to change your Dolibarr password has been received.\n";
  919. $mesg.= "This is your new keys to login:\n\n";
  920. $mesg.= $langs->trans("Login") . " : $this->login\n";
  921. $mesg.= $langs->trans("Password") . " : $password\n\n";
  922. $mesg.= "\n";
  923. $url = $urlwithouturlroot . DOL_URL_ROOT;
  924. $mesg.= 'Click here to go to Dolibarr: ' . $url . "\n\n";
  925. $mesg.= "--\n";
  926. $mesg.= $user->getFullName($langs); // Username that make then sending
  927. } else {
  928. $mesg.= "A request to change your Dolibarr password has been received.\n";
  929. $mesg.= "Your new key to login will be:\n\n";
  930. $mesg.= $langs->trans("Login") . " : $this->login\n";
  931. $mesg.= $langs->trans("Password") . " : $password\n\n";
  932. $mesg.= "\n";
  933. $mesg.= "You must click on the folowing link to validate its change.\n";
  934. $url = $urlwithouturlroot . DOL_URL_ROOT . '/user/passwordforgotten.php?action=validatenewpassword&username=' . $this->login . "&passwordmd5=" . dol_hash($password);
  935. $mesg.= $url . "\n\n";
  936. $mesg.= "If you didn't ask anything, just forget this email\n\n";
  937. dol_syslog(get_class($this) . "::send_password url=" . $url);
  938. }
  939. $mailfile = new CMailFile(
  940. $subject, $this->email, $conf->notification->email_from, $mesg, array(), array(), array(), '', '', 0, $msgishtml
  941. );
  942. if ($mailfile->sendfile()) {
  943. return 1;
  944. } else {
  945. $langs->trans("errors");
  946. $this->error = $langs->trans("ErrorFailedToSendPassword") . ' ' . $mailfile->error;
  947. return -1;
  948. }
  949. }
  950. /**
  951. * Renvoie la derniere erreur fonctionnelle de manipulation de l'objet
  952. *
  953. * @return string chaine erreur
  954. */
  955. function error() {
  956. return $this->error;
  957. }
  958. /**
  959. * Read clicktodial information for user
  960. *
  961. * @return <0 if KO, >0 if OK
  962. */
  963. function fetch_clicktodial() {
  964. $sql = "SELECT login, pass, poste ";
  965. $sql.= " FROM " . MAIN_DB_PREFIX . "user_clicktodial as u";
  966. $sql.= " WHERE u.fk_user = " . $this->id;
  967. $resql = $this->db->query($sql);
  968. if ($resql) {
  969. if ($this->db->num_rows($resql)) {
  970. $obj = $this->db->fetch_object($resql);
  971. $this->clicktodial_login = $obj->login;
  972. $this->clicktodial_password = $obj->pass;
  973. $this->clicktodial_poste = $obj->poste;
  974. }
  975. $this->clicktodial_loaded = 1; // Data loaded (found or not)
  976. $this->db->free($resql);
  977. return 1;
  978. } else {
  979. $this->error = $this->db->error();
  980. return -1;
  981. }
  982. }
  983. /**
  984. * Update clicktodial info
  985. *
  986. * @return void
  987. */
  988. function update_clicktodial() {
  989. $this->db->begin();
  990. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_clicktodial";
  991. $sql .= " WHERE fk_user = " . $this->id;
  992. $result = $this->db->query($sql);
  993. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_clicktodial";
  994. $sql .= " (fk_user,login,pass,poste)";
  995. $sql .= " VALUES (" . $this->id;
  996. $sql .= ", '" . $this->clicktodial_login . "'";
  997. $sql .= ", '" . $this->clicktodial_password . "'";
  998. $sql .= ", '" . $this->clicktodial_poste . "')";
  999. $result = $this->db->query($sql);
  1000. if ($result) {
  1001. $this->db->commit();
  1002. return 0;
  1003. } else {
  1004. $this->db->rollback();
  1005. $this->error = $this->db->error();
  1006. return -1;
  1007. }
  1008. }
  1009. /**
  1010. * Add user into a group
  1011. *
  1012. * @param Group $group Id of group
  1013. * @param int $entity Entity
  1014. * @param int $notrigger Disable triggers
  1015. * @return int <0 if KO, >0 if OK
  1016. */
  1017. function SetInGroup($group, $entity, $notrigger = 0) {
  1018. global $conf, $langs, $user;
  1019. $error = 0;
  1020. $this->db->begin();
  1021. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
  1022. $sql.= " WHERE fk_user = " . $this->id;
  1023. $sql.= " AND fk_usergroup = " . $group;
  1024. $sql.= " AND entity = " . $entity;
  1025. $result = $this->db->query($sql);
  1026. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "usergroup_user (entity, fk_user, fk_usergroup)";
  1027. $sql.= " VALUES (" . $entity . "," . $this->id . "," . $group . ")";
  1028. $result = $this->db->query($sql);
  1029. if ($result) {
  1030. if (!$error && !$notrigger) {
  1031. $this->newgroupid = $group;
  1032. // Appel des triggers
  1033. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  1034. $interface = new Interfaces($this->db);
  1035. $result = $interface->run_triggers('USER_SETINGROUP', $this, $user, $langs, $conf);
  1036. if ($result < 0) {
  1037. $error++;
  1038. $this->errors = $interface->errors;
  1039. }
  1040. // Fin appel triggers
  1041. }
  1042. if (!$error) {
  1043. $this->db->commit();
  1044. return 1;
  1045. } else {
  1046. $this->error = $interface->error;
  1047. dol_syslog(get_class($this) . "::SetInGroup " . $this->error, LOG_ERR);
  1048. $this->db->rollback();
  1049. return -2;
  1050. }
  1051. } else {
  1052. $this->error = $this->db->lasterror();
  1053. dol_syslog(get_class($this) . "::SetInGroup " . $this->error, LOG_ERR);
  1054. $this->db->rollback();
  1055. return -1;
  1056. }
  1057. }
  1058. /**
  1059. * Remove a user from a group
  1060. *
  1061. * @param Group $group Id of group
  1062. * @param int $entity Entity
  1063. * @param int $notrigger Disable triggers
  1064. * @return int <0 if KO, >0 if OK
  1065. */
  1066. function RemoveFromGroup($group, $entity, $notrigger = 0) {
  1067. global $conf, $langs, $user;
  1068. $error = 0;
  1069. $this->db->begin();
  1070. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
  1071. $sql.= " WHERE fk_user = " . $this->id;
  1072. $sql.= " AND fk_usergroup = " . $group;
  1073. $sql.= " AND entity = " . $entity;
  1074. $result = $this->db->query($sql);
  1075. if ($result) {
  1076. if (!$error && !$notrigger) {
  1077. $this->oldgroupid = $group;
  1078. // Appel des triggers
  1079. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  1080. $interface = new Interfaces($this->db);
  1081. $result = $interface->run_triggers('USER_REMOVEFROMGROUP', $this, $user, $langs, $conf);
  1082. if ($result < 0) {
  1083. $error++;
  1084. $this->errors = $interface->errors;
  1085. }
  1086. // Fin appel triggers
  1087. }
  1088. if (!$error) {
  1089. $this->db->commit();
  1090. return 1;
  1091. } else {
  1092. $this->error = $interface->error;
  1093. dol_syslog(get_class($this) . "::RemoveFromGroup " . $this->error, LOG_ERR);
  1094. $this->db->rollback();
  1095. return -2;
  1096. }
  1097. } else {
  1098. $this->error = $this->db->lasterror();
  1099. dol_syslog(get_class($this) . "::RemoveFromGroup " . $this->error, LOG_ERR);
  1100. $this->db->rollback();
  1101. return -1;
  1102. }
  1103. }
  1104. /**
  1105. * Return a link to the user card (with optionnaly the picto)
  1106. * Use this->id,this->nom, this->prenom
  1107. *
  1108. * @param int $withpicto Include picto in link (0=No picto, 1=Inclut le picto dans le lien, 2=Picto seul)
  1109. * @param string $option On what the link point to
  1110. * @return string String with URL
  1111. */
  1112. function getNomUrl($withpicto = 0, $option = '') {
  1113. global $langs;
  1114. $result = '';
  1115. $lien = '<a href="' . DOL_URL_ROOT . '/user/fiche.php?id=' . $this->id . '">';
  1116. $lienfin = '</a>';
  1117. if ($option == 'xxx') {
  1118. $lien = '<a href="' . DOL_URL_ROOT . '/user/fiche.php?id=' . $this->id . '">';
  1119. $lienfin = '</a>';
  1120. }
  1121. if ($option == 'span') {
  1122. $lien = '<span>';
  1123. $lienfin = '</span>';
  1124. }
  1125. if ($withpicto)
  1126. $result.=($lien . img_object($langs->trans("ShowUser"), 'user') . $lienfin);
  1127. if ($withpicto && $withpicto != 2)
  1128. $result.=' ';
  1129. $result.=$lien . $this->getFullName($langs) . $lienfin;
  1130. return $result;
  1131. }
  1132. /**
  1133. * Renvoie login clicable (avec eventuellement le picto)
  1134. *
  1135. * @param int $withpicto Inclut le picto dans le lien
  1136. * @param string $option Sur quoi pointe le lien
  1137. * @return string Chaine avec URL
  1138. */
  1139. function getLoginUrl($withpicto = 0, $option = '') {
  1140. global $langs;
  1141. $result = '';
  1142. $lien = '<a href="' . DOL_URL_ROOT . '/user/fiche.php?id=' . $this->id . '">';
  1143. $lienfin = '</a>';
  1144. if ($option == 'xxx') {
  1145. $lien = '<a href="' . DOL_URL_ROOT . '/user/fiche.php?id=' . $this->id . '">';
  1146. $lienfin = '</a>';
  1147. }
  1148. if ($withpicto)
  1149. $result.=($lien . img_object($langs->trans("ShowUser"), 'user') . $lienfin . ' ');
  1150. $result.=$lien . $this->login . $lienfin;
  1151. return $result;
  1152. }
  1153. /**
  1154. * Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
  1155. *
  1156. * @param string $info Info string loaded by _load_ldap_info
  1157. * @param int $mode 0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
  1158. * 1=
  1159. * 2=Return key only (uid=qqq)
  1160. * @return string DN
  1161. */
  1162. function _load_ldap_dn($info, $mode = 0) {
  1163. global $conf;
  1164. $dn = '';
  1165. if ($mode == 0)
  1166. $dn = $conf->global->LDAP_KEY_USERS . "=" . $info[$conf->global->LDAP_KEY_USERS] . "," . $conf->global->LDAP_USER_DN;
  1167. if ($mode == 1)
  1168. $dn = $conf->global->LDAP_USER_DN;
  1169. if ($mode == 2)
  1170. $dn = $conf->global->LDAP_KEY_USERS . "=" . $info[$conf->global->LDAP_KEY_USERS];
  1171. return $dn;
  1172. }
  1173. /**
  1174. * Initialize the info array (array of LDAP values) that will be used to call LDAP functions
  1175. *
  1176. * @return array Tableau info des attributs
  1177. */
  1178. function _load_ldap_info() {
  1179. global $conf, $langs;
  1180. $info = array();
  1181. // Object classes
  1182. $info["objectclass"] = explode(',', $conf->global->LDAP_USER_OBJECT_CLASS);
  1183. $this->fullname = $this->getFullName($langs);
  1184. // Champs
  1185. if ($this->fullname && $conf->global->LDAP_FIELD_FULLNAME)
  1186. $info[$conf->global->LDAP_FIELD_FULLNAME] = $this->fullname;
  1187. if ($this->lastname && $conf->global->LDAP_FIELD_NAME)
  1188. $info[$conf->global->LDAP_FIELD_NAME] = $this->lastname;
  1189. if ($this->firstname && $conf->global->LDAP_FIELD_FIRSTNAME)
  1190. $info[$conf->global->LDAP_FIELD_FIRSTNAME] = $this->firstname;
  1191. if ($this->login && $conf->global->LDAP_FIELD_LOGIN)
  1192. $info[$conf->global->LDAP_FIELD_LOGIN] = $this->login;
  1193. if ($this->login && $conf->global->LDAP_FIELD_LOGIN_SAMBA)
  1194. $info[$conf->global->LDAP_FIELD_LOGIN_SAMBA] = $this->login;
  1195. if ($this->pass && $conf->global->LDAP_FIELD_PASSWORD)
  1196. $info[$conf->global->LDAP_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte
  1197. if ($this->ldap_sid && $conf->global->LDAP_FIELD_SID)
  1198. $info[$conf->global->LDAP_FIELD_SID] = $this->ldap_sid;
  1199. if ($this->societe_id > 0) {
  1200. $soc = new Societe($this->db);
  1201. $soc->fetch($this->societe_id);
  1202. $info["o"] = $soc->nom;
  1203. if ($soc->client == 1)
  1204. $info["businessCategory"] = "Customers";
  1205. if ($soc->client == 2)
  1206. $info["businessCategory"] = "Prospects";
  1207. if ($soc->fournisseur == 1)
  1208. $info["businessCategory"] = "Suppliers";
  1209. }
  1210. if ($this->address && $conf->global->LDAP_FIELD_ADDRESS)
  1211. $info[$conf->global->LDAP_FIELD_ADDRESS] = $this->address;
  1212. if ($this->zip && $conf->global->LDAP_FIELD_ZIP)
  1213. $info[$conf->global->LDAP_FIELD_ZIP] = $this->zip;
  1214. if ($this->town && $conf->global->LDAP_FIELD_TOWN)
  1215. $info[$conf->global->LDAP_FIELD_TOWN] = $this->town;
  1216. if ($this->office_phone && $conf->global->LDAP_FIELD_PHONE)
  1217. $info[$conf->global->LDAP_FIELD_PHONE] = $this->office_phone;
  1218. if ($this->user_mobile && $conf->global->LDAP_FIELD_MOBILE)
  1219. $info[$conf->global->LDAP_FIELD_MOBILE] = $this->user_mobile;
  1220. if ($this->office_fax && $conf->global->LDAP_FIELD_FAX)
  1221. $info[$conf->global->LDAP_FIELD_FAX] = $this->office_fax;
  1222. if ($this->note && $conf->global->LDAP_FIELD_DESCRIPTION)
  1223. $info[$conf->global->LDAP_FIELD_DESCRIPTION] = $this->note;
  1224. if ($this->email && $conf->global->LDAP_FIELD_MAIL)
  1225. $info[$conf->global->LDAP_FIELD_MAIL] = $this->email;
  1226. if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') {
  1227. $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
  1228. $info['uidnumber'] = $this->id;
  1229. $info['phpgwTz'] = 0;
  1230. $info['phpgwMailType'] = 'INTERNET';
  1231. $info['phpgwMailHomeType'] = 'INTERNET';
  1232. $info["phpgwContactTypeId"] = 'n';
  1233. $info["phpgwContactCatId"] = 0;
  1234. $info["phpgwContactAccess"] = "public";
  1235. if (dol_strlen($this->egroupware_id) == 0) {
  1236. $this->egroupware_id = 1;
  1237. }
  1238. $info["phpgwContactOwner"] = $this->egroupware_id;
  1239. if ($this->email)
  1240. $info["rfc822Mailbox"] = $this->email;
  1241. if ($this->phone_mobile)
  1242. $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
  1243. }
  1244. return $info;
  1245. }
  1246. /**
  1247. * Initialise an instance with random values.
  1248. * Used to build previews or test instances.
  1249. * id must be 0 if object instance is a specimen.
  1250. *
  1251. * @return void
  1252. */
  1253. function initAsSpecimen() {
  1254. global $user, $langs;
  1255. // Initialise parametres
  1256. $this->id = 0;
  1257. $this->ref = 'SPECIMEN';
  1258. $this->specimen = 1;
  1259. $this->nom = 'DOLIBARR'; // deprecated
  1260. $this->prenom = 'SPECIMEN'; // deprecated
  1261. $this->lastname = 'DOLIBARR';
  1262. $this->firstname = 'SPECIMEN';
  1263. $this->note = 'This is a note';
  1264. $this->email = 'email@specimen.com';
  1265. $this->office_phone = '0999999999';
  1266. $this->office_fax = '0999999998';
  1267. $this->user_mobile = '0999999997';
  1268. $this->admin = 0;
  1269. $this->login = 'dolibspec';
  1270. $this->pass = 'dolibspec';
  1271. $this->datec = time();
  1272. $this->datem = time();
  1273. $this->webcal_login = 'dolibspec';
  1274. $this->datelastlogin = time();
  1275. $this->datepreviouslogin = time();
  1276. $this->statut = 1;
  1277. $this->societe_id = 1;
  1278. }
  1279. /**
  1280. * Load info of user object
  1281. *
  1282. * @param int $id Id of user to load
  1283. * @return void
  1284. */
  1285. function info($id) {
  1286. $sql = "SELECT u.rowid, u.login as ref, u.datec,";
  1287. $sql.= " u.tms as date_modification, u.entity";
  1288. $sql.= " FROM " . MAIN_DB_PREFIX . "user as u";
  1289. $sql.= " WHERE u.rowid = " . $id;
  1290. $result = $this->db->query($sql);
  1291. if ($result) {
  1292. if ($this->db->num_rows($result)) {
  1293. $obj = $this->db->fetch_object($result);
  1294. $this->id = $obj->rowid;
  1295. $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
  1296. $this->date_creation = $this->db->jdate($obj->datec);
  1297. $this->date_modification = $this->db->jdate($obj->date_modification);
  1298. $this->entity = $obj->entity;
  1299. }
  1300. $this->db->free($result);
  1301. } else {
  1302. dol_print_error($this->db);
  1303. }
  1304. }
  1305. /**
  1306. * Return number of mass Emailing received by this contacts with its email
  1307. *
  1308. * @return int Number of EMailings
  1309. */
  1310. function getNbOfEMailings() {
  1311. $sql = "SELECT count(mc.email) as nb";
  1312. $sql.= " FROM " . MAIN_DB_PREFIX . "mailing_cibles as mc";
  1313. $sql.= " WHERE mc.email = '" . $this->db->escape($this->email) . "'";
  1314. $sql.= " AND mc.statut=1"; // -1 erreur, 0 non envoye, 1 envoye avec succes
  1315. $resql = $this->db->query($sql);
  1316. if ($resql) {
  1317. $obj = $this->db->fetch_object($resql);
  1318. $nb = $obj->nb;
  1319. $this->db->free($resql);
  1320. return $nb;
  1321. } else {
  1322. $this->error = $this->db->error();
  1323. return -1;
  1324. }
  1325. }
  1326. /**
  1327. * Return number of existing users
  1328. *
  1329. * @param string $limitTo Limit to 'active' or 'superadmin' users
  1330. * @param int $all Return for all entities
  1331. * @return int Number of users
  1332. */
  1333. function getNbOfUsers($limitTo = '') {
  1334. global $conf;
  1335. try {
  1336. $result = $this->couchAdmin->getAllUsers();
  1337. } catch (Exception $e) {
  1338. return 0;
  1339. }
  1340. return count($result);
  1341. }
  1342. function getAllUsers($include_docs) {
  1343. return $this->couchAdmin->getAllUsers($include_docs);
  1344. }
  1345. function getUserAdmins() {
  1346. $result = $this->couchAdmin->getUserAdmins();
  1347. $result_roles = $this->couchAdmin->getAllUsers(true);
  1348. foreach ($result_roles as $aRow) {
  1349. if (in_array("_admin", $aRow->doc->roles, true)) {
  1350. $name = $aRow->doc->name;
  1351. $result->$name = true;
  1352. }
  1353. }
  1354. return $result;
  1355. }
  1356. function getDatabaseAdminUsers() {
  1357. return $this->couchAdmin->getDatabaseAdminUsers();
  1358. }
  1359. function getDatabaseReaderUsers() {
  1360. return $this->couchAdmin->getDatabaseReaderUsers();
  1361. }
  1362. function getLibStatus() {
  1363. return $this->LibStatus($this->Status);
  1364. }
  1365. function addRoleToUser($role) {
  1366. return $this->couchAdmin->addRoleToUser($this->name, $role);
  1367. }
  1368. function removeRoleFromUser($role) {
  1369. return $this->couchAdmin->removeRoleFromUser($this->name, $role);
  1370. }
  1371. }
  1372. ?>