abook_ldap_server.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. <?php
  2. /**
  3. * abook_ldap_server.php
  4. *
  5. * Address book backend for LDAP server
  6. *
  7. * LDAP filtering code by Tim Bell
  8. * <bhat at users.sourceforge.net> (#539534)
  9. * ADS limit_scope code by Michael Brown
  10. * <mcb30 at users.sourceforge.net> (#1035454)
  11. * StartTLS code by John Lane
  12. * <starfry at users.sourceforge.net> (#1197703)
  13. * Code for remove, add, modify, lookup by David Härdeman
  14. * <david at 2gen.com> (#1495763)
  15. *
  16. * This backend uses LDAP person (RFC2256), organizationalPerson (RFC2256)
  17. * and inetOrgPerson (RFC2798) objects and dn, description, sn, givenname,
  18. * cn, mail attributes. Other attributes are ignored.
  19. *
  20. * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  21. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  22. * @version $Id$
  23. * @package squirrelmail
  24. * @subpackage addressbook
  25. */
  26. /**
  27. * Address book backend for LDAP server
  28. *
  29. * An array with the following elements must be passed to
  30. * the class constructor (elements marked ? are optional)
  31. *
  32. * Main settings:
  33. * <pre>
  34. * host => LDAP server hostname, IP-address or any other URI compatible
  35. * with used LDAP library.
  36. * base => LDAP server root (base dn). Empty string allowed.
  37. * ? port => LDAP server TCP port number (default: 389)
  38. * ? charset => LDAP server charset (default: utf-8)
  39. * ? name => Name for LDAP server (default "LDAP: hostname")
  40. * Used to tag the result data
  41. * ? maxrows => Maximum # of rows in search result
  42. * ? timeout => Timeout for LDAP operations (in seconds, default: 30)
  43. * Might not work for all LDAP libraries or servers.
  44. * ? binddn => LDAP Bind DN.
  45. * ? bindpw => LDAP Bind Password.
  46. * ? protocol => LDAP Bind protocol.
  47. * </pre>
  48. * Advanced settings:
  49. * <pre>
  50. * ? filter => Filter expression to limit ldap searches
  51. * ? limit_scope => Limits scope to base DN (Specific to Win2k3 ADS).
  52. * ? listing => Controls listing of LDAP directory.
  53. * ? writeable => Controls write access to address book
  54. * ? search_tree => Controls subtree or one level search.
  55. * ? starttls => Controls use of StartTLS on LDAP connections
  56. * </pre>
  57. * NOTE. This class should not be used directly. Use addressbook_init()
  58. * function instead.
  59. * @package squirrelmail
  60. * @subpackage addressbook
  61. */
  62. class abook_ldap_server extends addressbook_backend {
  63. /**
  64. * @var string backend type
  65. */
  66. var $btype = 'remote';
  67. /**
  68. * @var string backend name
  69. */
  70. var $bname = 'ldap_server';
  71. /* Parameters changed by class */
  72. /**
  73. * @var string displayed name
  74. */
  75. var $sname = 'LDAP'; /* Service name */
  76. /**
  77. * @var string LDAP server name or address or url
  78. */
  79. var $server = '';
  80. /**
  81. * @var integer LDAP server port
  82. */
  83. var $port = 389;
  84. /**
  85. * @var string LDAP base DN
  86. */
  87. var $basedn = '';
  88. /**
  89. * @var string charset used for entries in LDAP server
  90. */
  91. var $charset = 'utf-8';
  92. /**
  93. * @var object PHP LDAP link ID
  94. */
  95. var $linkid = false;
  96. /**
  97. * @var bool True if LDAP server is bound
  98. */
  99. var $bound = false;
  100. /**
  101. * @var integer max rows in result
  102. */
  103. var $maxrows = 250;
  104. /**
  105. * @var string ldap filter
  106. * @since 1.5.1
  107. */
  108. var $filter = '';
  109. /**
  110. * @var integer timeout of LDAP operations (in seconds)
  111. */
  112. var $timeout = 30;
  113. /**
  114. * @var string DN to bind to (non-anonymous bind)
  115. * @since 1.5.0 and 1.4.3
  116. */
  117. var $binddn = '';
  118. /**
  119. * @var string password to bind with (non-anonymous bind)
  120. * @since 1.5.0 and 1.4.3
  121. */
  122. var $bindpw = '';
  123. /**
  124. * @var integer protocol used to connect to ldap server
  125. * @since 1.5.0 and 1.4.3
  126. */
  127. var $protocol = '';
  128. /**
  129. * @var boolean limits scope to base dn
  130. * @since 1.5.1
  131. */
  132. var $limit_scope = false;
  133. /**
  134. * @var boolean controls listing of directory
  135. * @since 1.5.1
  136. */
  137. var $listing = false;
  138. /**
  139. * @var boolean true if removing/adding/modifying entries is allowed
  140. * @since 1.5.2
  141. */
  142. var $writeable = true;
  143. /**
  144. * @var boolean controls ldap search type.
  145. * only first level entries are displayed if set to false
  146. * @since 1.5.1
  147. */
  148. var $search_tree = true;
  149. /**
  150. * @var boolean controls use of StartTLS on ldap
  151. * connections. Requires php 4.2+ and protocol >= 3
  152. * @since 1.5.1
  153. */
  154. var $starttls = false;
  155. /**
  156. * Constructor. Connects to database
  157. * @param array connection options
  158. */
  159. function abook_ldap_server($param) {
  160. if(!function_exists('ldap_connect')) {
  161. $this->set_error(_("PHP install does not have LDAP support."));
  162. return;
  163. }
  164. if(is_array($param)) {
  165. $this->server = $param['host'];
  166. // remove whitespace from basedn
  167. $this->basedn = preg_replace('/,\s*/',',',trim($param['base']));
  168. if(!empty($param['port']))
  169. $this->port = $param['port'];
  170. if(!empty($param['charset']))
  171. $this->charset = strtolower($param['charset']);
  172. if(isset($param['maxrows']))
  173. $this->maxrows = $param['maxrows'];
  174. if(isset($param['timeout']))
  175. $this->timeout = $param['timeout'];
  176. if(isset($param['binddn']))
  177. $this->binddn = $param['binddn'];
  178. if(isset($param['bindpw']))
  179. $this->bindpw = $param['bindpw'];
  180. if(isset($param['protocol']))
  181. $this->protocol = (int) $param['protocol'];
  182. if(isset($param['filter']))
  183. $this->filter = trim($param['filter']);
  184. if(isset($param['limit_scope']))
  185. $this->limit_scope = (bool) $param['limit_scope'];
  186. if(isset($param['listing']))
  187. $this->listing = (bool) $param['listing'];
  188. if(isset($param['writeable'])) {
  189. $this->writeable = (bool) $param['writeable'];
  190. // switch backend type to local, if it is writable
  191. if($this->writeable) $this->btype = 'local';
  192. }
  193. if(isset($param['search_tree']))
  194. $this->search_tree = (bool) $param['search_tree'];
  195. if(isset($param['starttls']))
  196. $this->starttls = (bool) $param['starttls'];
  197. if(empty($param['name'])) {
  198. $this->sname = 'LDAP: ' . $param['host'];
  199. } else {
  200. $this->sname = $param['name'];
  201. }
  202. /*
  203. * don't open LDAP server on addressbook_init(),
  204. * open ldap connection only on search. Speeds up
  205. * addressbook_init() call.
  206. */
  207. // $this->open(true);
  208. } else {
  209. $this->set_error('Invalid argument to constructor');
  210. }
  211. }
  212. /**
  213. * Open the LDAP server.
  214. * @param bool $new is it a new connection
  215. * @return bool
  216. */
  217. function open($new = false) {
  218. $this->error = '';
  219. /* Connection is already open */
  220. if($this->linkid != false && !$new) {
  221. return true;
  222. }
  223. $this->linkid = @ldap_connect($this->server, $this->port);
  224. /**
  225. * check if connection was successful
  226. * It does not work with OpenLDAP 2.x libraries. Connect error will be
  227. * displayed only on ldap command that tries to make connection
  228. * (ldap_start_tls or ldap_bind).
  229. */
  230. if(!$this->linkid) {
  231. return $this->set_error($this->ldap_error('ldap_connect failed'));
  232. }
  233. if(!empty($this->protocol)) {
  234. // make sure that ldap_set_option() is available before using it
  235. if(! function_exists('ldap_set_option') ||
  236. !@ldap_set_option($this->linkid, LDAP_OPT_PROTOCOL_VERSION, $this->protocol)) {
  237. return $this->set_error('unable to set ldap protocol number');
  238. }
  239. }
  240. /**
  241. * http://www.php.net/ldap-start-tls
  242. * Check if v3 or newer protocol is used,
  243. * check if ldap_start_tls function is available.
  244. * Silently ignore setting, if these requirements are not satisfied.
  245. * Break with error message if somebody tries to start TLS on
  246. * ldaps or socket connection.
  247. */
  248. if($this->starttls &&
  249. !empty($this->protocol) && $this->protocol >= 3 &&
  250. function_exists('ldap_start_tls') ) {
  251. // make sure that $this->server is not ldaps:// or ldapi:// URL.
  252. if (preg_match("/^ldap[si]:\/\/.+/i",$this->server)) {
  253. return $this->set_error("you can't enable starttls on ldaps and ldapi connections.");
  254. }
  255. // try starting tls
  256. if (! @ldap_start_tls($this->linkid)) {
  257. // set error if call fails
  258. return $this->set_error($this->ldap_error('ldap_start_tls failed'));
  259. }
  260. }
  261. if(!empty($this->limit_scope) && $this->limit_scope) {
  262. if(empty($this->protocol) || intval($this->protocol) < 3) {
  263. return $this->set_error('limit_scope requires protocol >= 3');
  264. }
  265. // See http://msdn.microsoft.com/library/en-us/ldap/ldap/ldap_server_domain_scope_oid.asp
  266. $ctrl = array ( "oid" => "1.2.840.113556.1.4.1339", "iscritical" => TRUE );
  267. /*
  268. * Option is set only during connection.
  269. * It does not cause immediate errors with OpenLDAP 2.x libraries.
  270. */
  271. if(! function_exists('ldap_set_option') ||
  272. !@ldap_set_option($this->linkid, LDAP_OPT_SERVER_CONTROLS, array($ctrl))) {
  273. return $this->set_error($this->ldap_error('limit domain scope failed'));
  274. }
  275. }
  276. // authenticated bind
  277. if(!empty($this->binddn)) {
  278. if(!@ldap_bind($this->linkid, $this->binddn, $this->bindpw)) {
  279. return $this->set_error($this->ldap_error('authenticated ldap_bind failed'));
  280. }
  281. } else {
  282. // anonymous bind
  283. if(!@ldap_bind($this->linkid)) {
  284. return $this->set_error($this->ldap_error('anonymous ldap_bind failed'));
  285. }
  286. }
  287. $this->bound = true;
  288. return true;
  289. }
  290. /**
  291. * Encode string to the charset used by this LDAP server
  292. * @param string string that has to be encoded
  293. * @return string encoded string
  294. */
  295. function charset_encode($str) {
  296. global $default_charset;
  297. if($this->charset != $default_charset) {
  298. return charset_convert($default_charset,$str,$this->charset,false);
  299. } else {
  300. return $str;
  301. }
  302. }
  303. /**
  304. * Decode from charset used by this LDAP server to charset used by translation
  305. *
  306. * Uses SquirrelMail charset_decode functions
  307. * @param string string that has to be decoded
  308. * @return string decoded string
  309. */
  310. function charset_decode($str) {
  311. global $default_charset;
  312. if ($this->charset != $default_charset) {
  313. return charset_convert($this->charset,$str,$default_charset,false);
  314. } else {
  315. return $str;
  316. }
  317. }
  318. /**
  319. * Sanitizes ldap search strings.
  320. * See rfc2254
  321. * @link http://www.faqs.org/rfcs/rfc2254.html
  322. * @since 1.5.1 and 1.4.5
  323. * @param string $string
  324. * @return string sanitized string
  325. */
  326. function ldapspecialchars($string) {
  327. $sanitized=array('\\' => '\5c',
  328. '*' => '\2a',
  329. '(' => '\28',
  330. ')' => '\29',
  331. "\x00" => '\00');
  332. return str_replace(array_keys($sanitized),array_values($sanitized),$string);
  333. }
  334. /**
  335. * Prepares user input for use in a ldap query.
  336. *
  337. * Function converts input string to character set used in LDAP server
  338. * (charset_encode() method) and sanitizes it (ldapspecialchars()).
  339. *
  340. * @param string $string string to encode
  341. * @return string ldap encoded string
  342. * @since 1.5.2
  343. */
  344. function quotevalue($string) {
  345. $sanitized = $this->charset_encode($string);
  346. return $this->ldapspecialchars($sanitized);
  347. }
  348. /**
  349. * Search LDAP server.
  350. *
  351. * Warning: You must make sure that ldap query is correctly formated and
  352. * sanitize use of special ldap keywords.
  353. * @param string $expression ldap query
  354. * @param boolean $singleentry (since 1.5.2) whether we are looking for a
  355. * single entry. Boolean true forces LDAP_SCOPE_BASE search.
  356. * @return array search results (false on error)
  357. * @since 1.5.1
  358. */
  359. function ldap_search($expression, $singleentry = false) {
  360. /* Make sure connection is there */
  361. if(!$this->open()) {
  362. return false;
  363. }
  364. $attributes = array('dn', 'description', 'sn', 'givenname', 'cn', 'mail');
  365. if ($singleentry) {
  366. // ldap_read - search for one single entry
  367. $sret = @ldap_read($this->linkid, $expression, "objectClass=*",
  368. $attributes, 0, $this->maxrows, $this->timeout);
  369. } elseif ($this->search_tree) {
  370. // ldap_search - search subtree
  371. $sret = @ldap_search($this->linkid, $this->basedn, $expression,
  372. $attributes, 0, $this->maxrows, $this->timeout);
  373. } else {
  374. // ldap_list - search one level
  375. $sret = @ldap_list($this->linkid, $this->basedn, $expression,
  376. $attributes, 0, $this->maxrows, $this->timeout);
  377. }
  378. /* Return error if search failed */
  379. if(!$sret) {
  380. // Check for LDAP_NO_SUCH_OBJECT (0x20 or 32) error
  381. if (ldap_errno($this->linkid)==32) {
  382. return array();
  383. } else {
  384. return $this->set_error($this->ldap_error('ldap_search failed'));
  385. }
  386. }
  387. if(@ldap_count_entries($this->linkid, $sret) <= 0) {
  388. return array();
  389. }
  390. /* Get results */
  391. $ret = array();
  392. $returned_rows = 0;
  393. $res = @ldap_get_entries($this->linkid, $sret);
  394. for($i = 0 ; $i < $res['count'] ; $i++) {
  395. $row = $res[$i];
  396. /* Extract data common for all e-mail addresses
  397. * of an object. Use only the first name */
  398. $nickname = $this->charset_decode($row['dn']);
  399. /**
  400. * remove trailing basedn
  401. * remove whitespaces between RDNs
  402. * remove leading "cn="
  403. * which gives nicknames which are shorter while still unique
  404. */
  405. $nickname = preg_replace('/,\s*/',',', trim($nickname));
  406. $offset = strlen($nickname) - strlen($this->basedn);
  407. if($offset > 0 && substr($nickname, $offset) == $this->basedn) {
  408. $nickname = substr($nickname, 0, $offset);
  409. if(substr($nickname, -1) == ",")
  410. $nickname = substr($nickname, 0, -1);
  411. }
  412. if(strncasecmp($nickname, "cn=", 3) == 0)
  413. $nickname=substr($nickname, 3);
  414. if(empty($row['description'][0])) {
  415. $label = '';
  416. } else {
  417. $label = $this->charset_decode($row['description'][0]);
  418. }
  419. if(empty($row['givenname'][0])) {
  420. $firstname = '';
  421. } else {
  422. $firstname = $this->charset_decode($row['givenname'][0]);
  423. }
  424. if(empty($row['sn'][0])) {
  425. $surname = '';
  426. } else {
  427. // remove whitespace in order to handle sn set to empty string
  428. $surname = trim($this->charset_decode($row['sn'][0]));
  429. }
  430. // FIXME: Write generic function to handle name order
  431. $fullname = trim($firstname . " " . $surname);
  432. /* Add one row to result for each e-mail address */
  433. if(isset($row['mail']['count'])) {
  434. for($j = 0 ; $j < $row['mail']['count'] ; $j++) {
  435. array_push($ret, array('nickname' => $nickname,
  436. 'name' => $fullname,
  437. 'firstname' => $firstname,
  438. 'lastname' => $surname,
  439. 'email' => $row['mail'][$j],
  440. 'label' => $label,
  441. 'backend' => $this->bnum,
  442. 'source' => &$this->sname));
  443. // Limit number of hits
  444. $returned_rows++;
  445. if(($returned_rows >= $this->maxrows) &&
  446. ($this->maxrows > 0) ) {
  447. ldap_free_result($sret);
  448. return $ret;
  449. }
  450. } // for($j ...)
  451. } // isset($row['mail']['count'])
  452. }
  453. ldap_free_result($sret);
  454. return $ret;
  455. }
  456. /**
  457. * Add an entry to LDAP server.
  458. *
  459. * Warning: You must make sure that the arguments are correctly formated and
  460. * sanitize use of special ldap keywords.
  461. * @param string $dn the dn of the entry to be added
  462. * @param array $data the values of the entry to be added
  463. * @return boolean result (false on error)
  464. * @since 1.5.2
  465. */
  466. function ldap_add($dn, $data) {
  467. /* Make sure connection is there */
  468. if(!$this->open()) {
  469. return false;
  470. }
  471. if(!@ldap_add($this->linkid, $dn, $data)) {
  472. $this->set_error(_("Write to address book failed"));
  473. return false;
  474. }
  475. return true;
  476. }
  477. /**
  478. * Remove an entry from LDAP server.
  479. *
  480. * Warning: You must make sure that the argument is correctly formated and
  481. * sanitize use of special ldap keywords.
  482. * @param string $dn the dn of the entry to remove
  483. * @return boolean result (false on error)
  484. * @since 1.5.2
  485. */
  486. function ldap_remove($dn) {
  487. /* Make sure connection is there */
  488. if(!$this->open()) {
  489. return false;
  490. }
  491. if(!@ldap_delete($this->linkid, $dn)) {
  492. $this->set_error(_("Removing entry from address book failed"));
  493. return false;
  494. }
  495. return true;
  496. }
  497. /**
  498. * Rename an entry on LDAP server.
  499. *
  500. * Warning: You must make sure that the arguments are correctly formated and
  501. * sanitize use of special ldap keywords.
  502. * @param string $sourcedn the dn of the entry to be renamed
  503. * @param string $targetdn the dn which $sourcedn should be renamed to
  504. * @param string $parent the dn of the parent entry
  505. * @return boolean result (false on error)
  506. * @since 1.5.2
  507. */
  508. function ldap_rename($sourcedn, $targetdn, $parent) {
  509. /* Make sure connection is there */
  510. if(!$this->open()) {
  511. return false;
  512. }
  513. /* Make sure that the protocol version supports rename */
  514. if($this->protocol < 3) {
  515. $this->set_error(_("LDAP rename is not supported by used protocol version"));
  516. return false;
  517. }
  518. /**
  519. * Function is available only in OpenLDAP 2.x.x or Netscape Directory
  520. * SDK x.x, and was added in PHP 4.0.5
  521. * @todo maybe we can use copy + delete instead of ldap_rename()
  522. */
  523. if(!function_exists('ldap_rename')) {
  524. $this->set_error(_("LDAP rename is not supported by used LDAP library. You can't change nickname"));
  525. return false;
  526. }
  527. /* OK, go for it */
  528. if(!@ldap_rename($this->linkid, $sourcedn, $targetdn, $parent, true)) {
  529. $this->set_error(_("LDAP rename failed"));
  530. return false;
  531. }
  532. return true;
  533. }
  534. /**
  535. * Modify the values of an entry on LDAP server.
  536. *
  537. * Warning: You must make sure that the arguments are correctly formated and
  538. * sanitize use of special ldap keywords.
  539. * @param string $dn the dn of the entry to be modified
  540. * @param array $data the new values of the entry
  541. * @param array $deleted_attribs attributes that should be deleted.
  542. * @return bool result (false on error)
  543. * @since 1.5.2
  544. */
  545. function ldap_modify($dn, $data, $deleted_attribs) {
  546. /* Make sure connection is there */
  547. if(!$this->open()) {
  548. return false;
  549. }
  550. if(!@ldap_modify($this->linkid, $dn, $data)) {
  551. $this->set_error(_("Write to address book failed"));
  552. return false;
  553. }
  554. if (!@ldap_mod_del($this->linkid, $dn, $deleted_attribs)) {
  555. $this->set_error(_("Unable to remove some field values"));
  556. return false;
  557. }
  558. return true;
  559. }
  560. /**
  561. * Get error from LDAP resource if possible
  562. *
  563. * Should get error from server using the ldap_errno() and ldap_err2str() functions
  564. * @param string $sError error message used when ldap error functions
  565. * and connection resource are unavailable
  566. * @return string error message
  567. * @since 1.5.1
  568. */
  569. function ldap_error($sError) {
  570. // it is possible that function_exists() tests are not needed
  571. if(function_exists('ldap_err2str') &&
  572. function_exists('ldap_errno') &&
  573. is_resource($this->linkid)) {
  574. return ldap_err2str(ldap_errno($this->linkid));
  575. // return ldap_error($this->linkid);
  576. } else {
  577. return $sError;
  578. }
  579. }
  580. /* ========================== Public ======================== */
  581. /**
  582. * Search the LDAP server
  583. * @param string $expr search expression
  584. * @return array search results
  585. */
  586. function search($expr) {
  587. /* To be replaced by advanded search expression parsing */
  588. if(is_array($expr)) return false;
  589. // don't allow wide search when listing is disabled.
  590. if ($expr=='*' && ! $this->listing) {
  591. return array();
  592. } elseif ($expr=='*') {
  593. // allow use of wildcard when listing is enabled.
  594. $expression = '(cn=*)';
  595. } else {
  596. /* Convert search from user's charset to the one used in ldap and sanitize */
  597. $expr = $this->quotevalue($expr);
  598. /* Search for same string in cn, main and sn */
  599. $expression = '(|(cn=*'.$expr.'*)(mail=*'.$expr.'*)(sn=*'.$expr.'*))';
  600. /* Undo sanitizing of * symbol */
  601. $expression = str_replace('\2a','*',$expression);
  602. }
  603. /* Add search filtering */
  604. if ($this->filter!='')
  605. $expression = '(&' . $this->filter . $expression . ')';
  606. /* Use internal search function and return search results */
  607. return $this->ldap_search($expression);
  608. }
  609. /**
  610. * Lookup an alias
  611. * @param string $alias alias
  612. * @return array search results
  613. * @since 1.5.2
  614. */
  615. function lookup($alias) {
  616. /* Generate the dn and try to retrieve that single entry */
  617. $cn = $this->quotevalue($alias);
  618. $dn = 'cn=' . $cn . ',' . $this->basedn;
  619. /* Do the search */
  620. $result = $this->ldap_search($dn, true);
  621. if (!is_array($result) || count($result) < 1)
  622. return array();
  623. return $result[0];
  624. }
  625. /**
  626. * List all entries present in LDAP server
  627. *
  628. * maxrows setting might limit list of returned entries.
  629. * Careful with this -- it could get quite large for big sites.
  630. * @return array all entries in ldap server
  631. */
  632. function list_addr() {
  633. if (! $this->listing)
  634. return array();
  635. /* set wide search expression */
  636. $expression = '(cn=*)';
  637. /* add filtering */
  638. if ($this->filter!='')
  639. $expression = '(&' . $this->filter . $expression .')';
  640. /* use internal search function and return search results */
  641. return $this->ldap_search($expression);
  642. }
  643. /**
  644. * Add address
  645. * @param array $userdata new data
  646. * @return boolean
  647. * @since 1.5.2
  648. */
  649. function add($userdata) {
  650. if(!$this->writeable) {
  651. return $this->set_error(_("Address book is read-only"));
  652. }
  653. /* Convert search from user's charset to the one used in ldap and sanitize */
  654. $cn = $this->quotevalue($userdata['nickname']);
  655. $dn = 'cn=' . $cn . ',' . trim($this->basedn);
  656. /* See if user exists already */
  657. $user = $this->ldap_search($dn, true);
  658. if (!is_array($user)) {
  659. return false;
  660. } elseif (count($user) > 0) {
  661. return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
  662. }
  663. /* init variable */
  664. $data = array();
  665. /* Prepare data */
  666. $data['cn'] = $cn;
  667. $data['mail'] = $this->quotevalue($userdata['email']);
  668. $data["objectclass"][0] = "top";
  669. $data["objectclass"][1] = "person";
  670. $data["objectclass"][2] = "organizationalPerson";
  671. $data["objectclass"][3] = "inetOrgPerson";
  672. /* sn is required in person object */
  673. if(!empty($userdata['lastname'])) {
  674. $data['sn'] = $this->quotevalue($userdata['lastname']);
  675. } else {
  676. $data['sn'] = ' ';
  677. }
  678. /* optional fields */
  679. if(!empty($userdata['firstname']))
  680. $data['givenName'] = $this->quotevalue($userdata['firstname']);
  681. if(!empty($userdata['label'])) {
  682. $data['description'] = $this->quotevalue($userdata['label']);
  683. }
  684. return $this->ldap_add($dn, $data);
  685. }
  686. /**
  687. * Delete address
  688. * @param array $aliases array of entries that have to be removed.
  689. * @return boolean
  690. * @since 1.5.2
  691. */
  692. function remove($aliases) {
  693. if(!$this->writeable) {
  694. return $this->set_error(_("Address book is read-only"));
  695. }
  696. foreach ($aliases as $alias) {
  697. /* Convert nickname from user's charset and derive cn/dn */
  698. $cn = $this->quotevalue($alias);
  699. $dn = 'cn=' . $cn . ',' . $this->basedn;
  700. if (!$this->ldap_remove($dn))
  701. return false;
  702. }
  703. return true;
  704. }
  705. /**
  706. * Modify address
  707. * @param string $alias modified alias
  708. * @param array $userdata new data
  709. * @return boolean
  710. * @since 1.5.2
  711. */
  712. function modify($alias, $userdata) {
  713. if(!$this->writeable) {
  714. return $this->set_error(_("Address book is read-only"));
  715. }
  716. /* Convert search from user's charset to the one used in ldap and sanitize */
  717. $sourcecn = $this->quotevalue($alias);
  718. $sourcedn = 'cn=' . $sourcecn . ',' . trim($this->basedn);
  719. $targetcn = $this->quotevalue($userdata['nickname']);
  720. $targetdn = 'cn=' . $targetcn . ',' . trim($this->basedn);
  721. /* Check that the dn to modify exists */
  722. $sourceuser = $this->lookup($alias);
  723. if (!is_array($sourceuser) || count($sourceuser) < 1)
  724. return false;
  725. /* Check if dn is going to change */
  726. if ($alias != $userdata['nickname']) {
  727. /* Check that the target dn doesn't exist */
  728. $targetuser = $this->lookup($userdata['nickname']);
  729. if (is_array($targetuser) && count($targetuser) > 0)
  730. return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
  731. /* Rename from the source dn to target dn */
  732. if (!$this->ldap_rename($sourcedn, 'cn=' . $targetcn, $this->basedn))
  733. return $this->set_error(sprintf(_("Unable to rename user \"%s\" to \"%s\""), $alias, $userdata['nickname']));
  734. }
  735. // initial vars
  736. $data = array();
  737. $deleted_attribs = array();
  738. /* Prepare data */
  739. $data['cn'] = $this->quotevalue($targetcn);
  740. $data['mail'] = $this->quotevalue($userdata['email']);
  741. $data["objectclass"][0] = "top";
  742. $data["objectclass"][1] = "person";
  743. $data["objectclass"][2] = "organizationalPerson";
  744. $data["objectclass"][3] = "inetOrgPerson";
  745. if(!empty($userdata['firstname'])) {
  746. $data['givenName'] = $this->quotevalue($userdata['firstname']);
  747. } elseif (!empty($sourceuser['firstname'])) {
  748. $deleted_attribs['givenName'] = $this->quotevalue($sourceuser['firstname']);
  749. }
  750. if(!empty($userdata['lastname'])) {
  751. $data['sn'] = $this->quotevalue($userdata['lastname']);
  752. } else {
  753. // sn is required attribute in LDAP person object.
  754. // SquirrelMail requires givenName or Surname
  755. $data['sn'] = ' ';
  756. }
  757. if(!empty($userdata['label'])) {
  758. $data['description'] = $this->quotevalue($userdata['label']);
  759. } elseif (!empty($sourceuser['label'])) {
  760. $deleted_attribs['description'] = $this->quotevalue($sourceuser['label']);
  761. }
  762. return $this->ldap_modify($targetdn, $data, $deleted_attribs);
  763. }
  764. }