abook_ldap_server.php 32 KB

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