abook_ldap_server.php 32 KB

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