You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_ldap.php 74KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2006-2013, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2013, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | Interface to an LDAP address directory |
  14. +-----------------------------------------------------------------------+
  15. | Author: Thomas Bruederli <roundcube@gmail.com> |
  16. | Andreas Dick <andudi (at) gmx (dot) ch> |
  17. | Aleksander Machniak <machniak@kolabsys.com> |
  18. +-----------------------------------------------------------------------+
  19. */
  20. /**
  21. * Model class to access an LDAP address directory
  22. *
  23. * @package Framework
  24. * @subpackage Addressbook
  25. */
  26. class rcube_ldap extends rcube_addressbook
  27. {
  28. // public properties
  29. public $primary_key = 'ID';
  30. public $groups = false;
  31. public $readonly = true;
  32. public $ready = false;
  33. public $group_id = 0;
  34. public $coltypes = array();
  35. public $export_groups = false;
  36. // private properties
  37. protected $ldap;
  38. protected $formats = array();
  39. protected $prop = array();
  40. protected $fieldmap = array();
  41. protected $filter = '';
  42. protected $sub_filter;
  43. protected $result;
  44. protected $ldap_result;
  45. protected $mail_domain = '';
  46. protected $debug = false;
  47. /**
  48. * Group objectclass (lowercase) to member attribute mapping
  49. *
  50. * @var array
  51. */
  52. private $group_types = array(
  53. 'group' => 'member',
  54. 'groupofnames' => 'member',
  55. 'kolabgroupofnames' => 'member',
  56. 'groupofuniquenames' => 'uniqueMember',
  57. 'kolabgroupofuniquenames' => 'uniqueMember',
  58. 'univentiongroup' => 'uniqueMember',
  59. 'groupofurls' => null,
  60. );
  61. private $base_dn = '';
  62. private $groups_base_dn = '';
  63. private $group_data;
  64. private $group_search_cache;
  65. private $cache;
  66. /**
  67. * Object constructor
  68. *
  69. * @param array $p LDAP connection properties
  70. * @param boolean $debug Enables debug mode
  71. * @param string $mail_domain Current user mail domain name
  72. */
  73. function __construct($p, $debug = false, $mail_domain = null)
  74. {
  75. $this->prop = $p;
  76. $fetch_attributes = array('objectClass');
  77. // check if groups are configured
  78. if (is_array($p['groups']) && count($p['groups'])) {
  79. $this->groups = true;
  80. // set member field
  81. if (!empty($p['groups']['member_attr']))
  82. $this->prop['member_attr'] = strtolower($p['groups']['member_attr']);
  83. else if (empty($p['member_attr']))
  84. $this->prop['member_attr'] = 'member';
  85. // set default name attribute to cn
  86. if (empty($this->prop['groups']['name_attr']))
  87. $this->prop['groups']['name_attr'] = 'cn';
  88. if (empty($this->prop['groups']['scope']))
  89. $this->prop['groups']['scope'] = 'sub';
  90. // extend group objectclass => member attribute mapping
  91. if (!empty($this->prop['groups']['class_member_attr']))
  92. $this->group_types = array_merge($this->group_types, $this->prop['groups']['class_member_attr']);
  93. // add group name attrib to the list of attributes to be fetched
  94. $fetch_attributes[] = $this->prop['groups']['name_attr'];
  95. }
  96. if (is_array($p['group_filters'])) {
  97. $this->groups = $this->groups || count($p['group_filters']);
  98. foreach ($p['group_filters'] as $k => $group_filter) {
  99. // set default name attribute to cn
  100. if (empty($group_filter['name_attr']) && empty($this->prop['groups']['name_attr']))
  101. $this->prop['group_filters'][$k]['name_attr'] = $group_filter['name_attr'] = 'cn';
  102. if ($group_filter['name_attr'])
  103. $fetch_attributes[] = $group_filter['name_attr'];
  104. }
  105. }
  106. // fieldmap property is given
  107. if (is_array($p['fieldmap'])) {
  108. $p['fieldmap'] = array_filter($p['fieldmap']);
  109. foreach ($p['fieldmap'] as $rf => $lf)
  110. $this->fieldmap[$rf] = $this->_attr_name($lf);
  111. }
  112. else if (!empty($p)) {
  113. // read deprecated *_field properties to remain backwards compatible
  114. foreach ($p as $prop => $value)
  115. if (!empty($value) && preg_match('/^(.+)_field$/', $prop, $matches))
  116. $this->fieldmap[$matches[1]] = $this->_attr_name($value);
  117. }
  118. // use fieldmap to advertise supported coltypes to the application
  119. foreach ($this->fieldmap as $colv => $lfv) {
  120. list($col, $type) = explode(':', $colv);
  121. $params = explode(':', $lfv);
  122. $lf = array_shift($params);
  123. $limit = 1;
  124. foreach ($params as $idx => $param) {
  125. // field format specification
  126. if (preg_match('/^(date)\[(.+)\]$/i', $param, $m)) {
  127. $this->formats[$lf] = array('type' => strtolower($m[1]), 'format' => $m[2]);
  128. }
  129. // first argument is a limit
  130. else if ($idx === 0) {
  131. if ($param == '*') $limit = null;
  132. else $limit = max(1, intval($param));
  133. }
  134. // second is a composite field separator
  135. else if ($idx === 1 && $param) {
  136. $this->coltypes[$col]['serialized'][$type] = $param;
  137. }
  138. }
  139. if (!is_array($this->coltypes[$col])) {
  140. $subtypes = $type ? array($type) : null;
  141. $this->coltypes[$col] = array('limit' => $limit, 'subtypes' => $subtypes, 'attributes' => array($lf));
  142. }
  143. elseif ($type) {
  144. $this->coltypes[$col]['subtypes'][] = $type;
  145. $this->coltypes[$col]['attributes'][] = $lf;
  146. $this->coltypes[$col]['limit'] += $limit;
  147. }
  148. $this->fieldmap[$colv] = $lf;
  149. }
  150. // support for composite address
  151. if ($this->coltypes['street'] && $this->coltypes['locality']) {
  152. $this->coltypes['address'] = array(
  153. 'limit' => max(1, $this->coltypes['locality']['limit'] + $this->coltypes['address']['limit']),
  154. 'subtypes' => array_merge((array)$this->coltypes['address']['subtypes'], (array)$this->coltypes['locality']['subtypes']),
  155. 'childs' => array(),
  156. ) + (array)$this->coltypes['address'];
  157. foreach (array('street','locality','zipcode','region','country') as $childcol) {
  158. if ($this->coltypes[$childcol]) {
  159. $this->coltypes['address']['childs'][$childcol] = array('type' => 'text');
  160. unset($this->coltypes[$childcol]); // remove address child col from global coltypes list
  161. }
  162. }
  163. // at least one address type must be specified
  164. if (empty($this->coltypes['address']['subtypes'])) {
  165. $this->coltypes['address']['subtypes'] = array('home');
  166. }
  167. }
  168. else if ($this->coltypes['address']) {
  169. $this->coltypes['address'] += array('type' => 'textarea', 'childs' => null, 'size' => 40);
  170. // 'serialized' means the UI has to present a composite address field
  171. if ($this->coltypes['address']['serialized']) {
  172. $childprop = array('type' => 'text');
  173. $this->coltypes['address']['type'] = 'composite';
  174. $this->coltypes['address']['childs'] = array('street' => $childprop, 'locality' => $childprop, 'zipcode' => $childprop, 'country' => $childprop);
  175. }
  176. }
  177. // make sure 'required_fields' is an array
  178. if (!is_array($this->prop['required_fields'])) {
  179. $this->prop['required_fields'] = (array) $this->prop['required_fields'];
  180. }
  181. // make sure LDAP_rdn field is required
  182. if (!empty($this->prop['LDAP_rdn']) && !in_array($this->prop['LDAP_rdn'], $this->prop['required_fields'])
  183. && !in_array($this->prop['LDAP_rdn'], array_keys((array)$this->prop['autovalues']))) {
  184. $this->prop['required_fields'][] = $this->prop['LDAP_rdn'];
  185. }
  186. foreach ($this->prop['required_fields'] as $key => $val) {
  187. $this->prop['required_fields'][$key] = $this->_attr_name($val);
  188. }
  189. // Build sub_fields filter
  190. if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
  191. $this->sub_filter = '';
  192. foreach ($this->prop['sub_fields'] as $class) {
  193. if (!empty($class)) {
  194. $class = is_array($class) ? array_pop($class) : $class;
  195. $this->sub_filter .= '(objectClass=' . $class . ')';
  196. }
  197. }
  198. if (count($this->prop['sub_fields']) > 1) {
  199. $this->sub_filter = '(|' . $this->sub_filter . ')';
  200. }
  201. }
  202. $this->sort_col = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
  203. $this->debug = $debug;
  204. $this->mail_domain = $mail_domain;
  205. // initialize cache
  206. $rcube = rcube::get_instance();
  207. if ($cache_type = $rcube->config->get('ldap_cache', 'db')) {
  208. $cache_ttl = $rcube->config->get('ldap_cache_ttl', '10m');
  209. $cache_name = 'LDAP.' . asciiwords($this->prop['name']);
  210. $this->cache = $rcube->get_cache($cache_name, $cache_type, $cache_ttl);
  211. }
  212. // determine which attributes to fetch
  213. $this->prop['list_attributes'] = array_unique($fetch_attributes);
  214. $this->prop['attributes'] = array_merge(array_values($this->fieldmap), $fetch_attributes);
  215. foreach ($rcube->config->get('contactlist_fields') as $col) {
  216. $this->prop['list_attributes'] = array_merge($this->prop['list_attributes'], $this->_map_field($col));
  217. }
  218. // initialize ldap wrapper object
  219. $this->ldap = new rcube_ldap_generic($this->prop);
  220. $this->ldap->config_set(array('cache' => $this->cache, 'debug' => $this->debug));
  221. $this->_connect();
  222. }
  223. /**
  224. * Establish a connection to the LDAP server
  225. */
  226. private function _connect()
  227. {
  228. $rcube = rcube::get_instance();
  229. if ($this->ready)
  230. return true;
  231. if (!is_array($this->prop['hosts']))
  232. $this->prop['hosts'] = array($this->prop['hosts']);
  233. // try to connect + bind for every host configured
  234. // with OpenLDAP 2.x ldap_connect() always succeeds but ldap_bind will fail if host isn't reachable
  235. // see http://www.php.net/manual/en/function.ldap-connect.php
  236. foreach ($this->prop['hosts'] as $host) {
  237. // skip host if connection failed
  238. if (!$this->ldap->connect($host)) {
  239. continue;
  240. }
  241. // See if the directory is writeable.
  242. if ($this->prop['writable']) {
  243. $this->readonly = false;
  244. }
  245. $bind_pass = $this->prop['bind_pass'];
  246. $bind_user = $this->prop['bind_user'];
  247. $bind_dn = $this->prop['bind_dn'];
  248. $this->base_dn = $this->prop['base_dn'];
  249. $this->groups_base_dn = $this->prop['groups']['base_dn'] ?: $this->base_dn;
  250. // User specific access, generate the proper values to use.
  251. if ($this->prop['user_specific']) {
  252. // No password set, use the session password
  253. if (empty($bind_pass)) {
  254. $bind_pass = $rcube->get_user_password();
  255. }
  256. // Get the pieces needed for variable replacement.
  257. if ($fu = $rcube->get_user_email()) {
  258. list($u, $d) = explode('@', $fu);
  259. }
  260. else {
  261. $d = $this->mail_domain;
  262. }
  263. $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
  264. // resolve $dc through LDAP
  265. if (!empty($this->prop['domain_filter']) && !empty($this->prop['search_bind_dn']) &&
  266. method_exists($this->ldap, 'domain_root_dn')) {
  267. $this->ldap->bind($this->prop['search_bind_dn'], $this->prop['search_bind_pw']);
  268. $dc = $this->ldap->domain_root_dn($d);
  269. }
  270. $replaces = array('%dn' => '', '%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
  271. // Search for the dn to use to authenticate
  272. if ($this->prop['search_base_dn'] && $this->prop['search_filter']
  273. && (strstr($bind_dn, '%dn') || strstr($this->base_dn, '%dn') || strstr($this->groups_base_dn, '%dn'))
  274. ) {
  275. $search_attribs = array('uid');
  276. if ($search_bind_attrib = (array)$this->prop['search_bind_attrib']) {
  277. foreach ($search_bind_attrib as $r => $attr) {
  278. $search_attribs[] = $attr;
  279. $replaces[$r] = '';
  280. }
  281. }
  282. $search_bind_dn = strtr($this->prop['search_bind_dn'], $replaces);
  283. $search_base_dn = strtr($this->prop['search_base_dn'], $replaces);
  284. $search_filter = strtr($this->prop['search_filter'], $replaces);
  285. $cache_key = 'DN.' . md5("$host:$search_bind_dn:$search_base_dn:$search_filter:"
  286. .$this->prop['search_bind_pw']);
  287. if ($this->cache && ($dn = $this->cache->get($cache_key))) {
  288. $replaces['%dn'] = $dn;
  289. }
  290. else {
  291. $ldap = $this->ldap;
  292. if (!empty($search_bind_dn) && !empty($this->prop['search_bind_pw'])) {
  293. // To protect from "Critical extension is unavailable" error
  294. // we need to use a separate LDAP connection
  295. if (!empty($this->prop['vlv'])) {
  296. $ldap = new rcube_ldap_generic($this->prop);
  297. $ldap->config_set(array('cache' => $this->cache, 'debug' => $this->debug));
  298. if (!$ldap->connect($host)) {
  299. continue;
  300. }
  301. }
  302. if (!$ldap->bind($search_bind_dn, $this->prop['search_bind_pw'])) {
  303. continue; // bind failed, try next host
  304. }
  305. }
  306. $res = $ldap->search($search_base_dn, $search_filter, 'sub', $search_attribs);
  307. if ($res) {
  308. $res->rewind();
  309. $replaces['%dn'] = key($res->entries(TRUE));
  310. // add more replacements from 'search_bind_attrib' config
  311. if ($search_bind_attrib) {
  312. $res = $res->current();
  313. foreach ($search_bind_attrib as $r => $attr) {
  314. $replaces[$r] = $res[$attr][0];
  315. }
  316. }
  317. }
  318. if ($ldap != $this->ldap) {
  319. $ldap->close();
  320. }
  321. }
  322. // DN not found
  323. if (empty($replaces['%dn'])) {
  324. if (!empty($this->prop['search_dn_default']))
  325. $replaces['%dn'] = $this->prop['search_dn_default'];
  326. else {
  327. rcube::raise_error(array(
  328. 'code' => 100, 'type' => 'ldap',
  329. 'file' => __FILE__, 'line' => __LINE__,
  330. 'message' => "DN not found using LDAP search."), true);
  331. continue;
  332. }
  333. }
  334. if ($this->cache && !empty($replaces['%dn'])) {
  335. $this->cache->set($cache_key, $replaces['%dn']);
  336. }
  337. }
  338. // Replace the bind_dn and base_dn variables.
  339. $bind_dn = strtr($bind_dn, $replaces);
  340. $this->base_dn = strtr($this->base_dn, $replaces);
  341. $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
  342. // replace placeholders in filter settings
  343. if (!empty($this->prop['filter']))
  344. $this->prop['filter'] = strtr($this->prop['filter'], $replaces);
  345. foreach (array('base_dn','filter','member_filter') as $k) {
  346. if (!empty($this->prop['groups'][$k]))
  347. $this->prop['groups'][$k] = strtr($this->prop['groups'][$k], $replaces);
  348. }
  349. if (is_array($this->prop['group_filters'])) {
  350. foreach ($this->prop['group_filters'] as $i => $gf) {
  351. if (!empty($gf['base_dn']))
  352. $this->prop['group_filters'][$i]['base_dn'] = strtr($gf['base_dn'], $replaces);
  353. if (!empty($gf['filter']))
  354. $this->prop['group_filters'][$i]['filter'] = strtr($gf['filter'], $replaces);
  355. }
  356. }
  357. if (empty($bind_user)) {
  358. $bind_user = $u;
  359. }
  360. }
  361. if (empty($bind_pass)) {
  362. $this->ready = true;
  363. }
  364. else {
  365. if (!empty($bind_dn)) {
  366. $this->ready = $this->ldap->bind($bind_dn, $bind_pass);
  367. }
  368. else if (!empty($this->prop['auth_cid'])) {
  369. $this->ready = $this->ldap->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
  370. }
  371. else {
  372. $this->ready = $this->ldap->sasl_bind($bind_user, $bind_pass);
  373. }
  374. }
  375. // connection established, we're done here
  376. if ($this->ready) {
  377. break;
  378. }
  379. } // end foreach hosts
  380. if (!is_resource($this->ldap->conn)) {
  381. rcube::raise_error(array('code' => 100, 'type' => 'ldap',
  382. 'file' => __FILE__, 'line' => __LINE__,
  383. 'message' => "Could not connect to any LDAP server, last tried $host"), true);
  384. return false;
  385. }
  386. return $this->ready;
  387. }
  388. /**
  389. * Close connection to LDAP server
  390. */
  391. function close()
  392. {
  393. if ($this->ldap) {
  394. $this->ldap->close();
  395. }
  396. }
  397. /**
  398. * Returns address book name
  399. *
  400. * @return string Address book name
  401. */
  402. function get_name()
  403. {
  404. return $this->prop['name'];
  405. }
  406. /**
  407. * Set internal list page
  408. *
  409. * @param number Page number to list
  410. */
  411. function set_page($page)
  412. {
  413. $this->list_page = (int)$page;
  414. $this->ldap->set_vlv_page($this->list_page, $this->page_size);
  415. }
  416. /**
  417. * Set internal page size
  418. *
  419. * @param number Number of records to display on one page
  420. */
  421. function set_pagesize($size)
  422. {
  423. $this->page_size = (int)$size;
  424. $this->ldap->set_vlv_page($this->list_page, $this->page_size);
  425. }
  426. /**
  427. * Set internal sort settings
  428. *
  429. * @param string $sort_col Sort column
  430. * @param string $sort_order Sort order
  431. */
  432. function set_sort_order($sort_col, $sort_order = null)
  433. {
  434. if ($this->coltypes[$sort_col]['attributes'])
  435. $this->sort_col = $this->coltypes[$sort_col]['attributes'][0];
  436. }
  437. /**
  438. * Save a search string for future listings
  439. *
  440. * @param string $filter Filter string
  441. */
  442. function set_search_set($filter)
  443. {
  444. $this->filter = $filter;
  445. }
  446. /**
  447. * Getter for saved search properties
  448. *
  449. * @return mixed Search properties used by this class
  450. */
  451. function get_search_set()
  452. {
  453. return $this->filter;
  454. }
  455. /**
  456. * Reset all saved results and search parameters
  457. */
  458. function reset()
  459. {
  460. $this->result = null;
  461. $this->ldap_result = null;
  462. $this->filter = '';
  463. }
  464. /**
  465. * List the current set of contact records
  466. *
  467. * @param array List of cols to show
  468. * @param int Only return this number of records
  469. *
  470. * @return array Indexed list of contact records, each a hash array
  471. */
  472. function list_records($cols=null, $subset=0)
  473. {
  474. if ($this->prop['searchonly'] && empty($this->filter) && !$this->group_id) {
  475. $this->result = new rcube_result_set(0);
  476. $this->result->searchonly = true;
  477. return $this->result;
  478. }
  479. // fetch group members recursively
  480. if ($this->group_id && $this->group_data['dn']) {
  481. $entries = $this->list_group_members($this->group_data['dn']);
  482. // make list of entries unique and sort it
  483. $seen = array();
  484. foreach ($entries as $i => $rec) {
  485. if ($seen[$rec['dn']]++)
  486. unset($entries[$i]);
  487. }
  488. usort($entries, array($this, '_entry_sort_cmp'));
  489. $entries['count'] = count($entries);
  490. $this->result = new rcube_result_set($entries['count'], ($this->list_page-1) * $this->page_size);
  491. }
  492. else {
  493. $prop = $this->group_id ? $this->group_data : $this->prop;
  494. $base_dn = $this->group_id ? $prop['base_dn'] : $this->base_dn;
  495. // use global search filter
  496. if (!empty($this->filter))
  497. $prop['filter'] = $this->filter;
  498. // exec LDAP search if no result resource is stored
  499. if ($this->ready && !$this->ldap_result)
  500. $this->ldap_result = $this->ldap->search($base_dn, $prop['filter'], $prop['scope'], $this->prop['attributes'], $prop);
  501. // count contacts for this user
  502. $this->result = $this->count();
  503. // we have a search result resource
  504. if ($this->ldap_result && $this->result->count > 0) {
  505. // sorting still on the ldap server
  506. if ($this->sort_col && $prop['scope'] !== 'base' && !$this->ldap->vlv_active)
  507. $this->ldap_result->sort($this->sort_col);
  508. // get all entries from the ldap server
  509. $entries = $this->ldap_result->entries();
  510. }
  511. } // end else
  512. // start and end of the page
  513. $start_row = $this->ldap->vlv_active ? 0 : $this->result->first;
  514. $start_row = $subset < 0 ? $start_row + $this->page_size + $subset : $start_row;
  515. $last_row = $this->result->first + $this->page_size;
  516. $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
  517. // filter entries for this page
  518. for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
  519. $this->result->add($this->_ldap2result($entries[$i]));
  520. return $this->result;
  521. }
  522. /**
  523. * Get all members of the given group
  524. *
  525. * @param string Group DN
  526. * @param boolean Count only
  527. * @param array Group entries (if called recursively)
  528. * @return array Accumulated group members
  529. */
  530. function list_group_members($dn, $count = false, $entries = null)
  531. {
  532. $group_members = array();
  533. // fetch group object
  534. if (empty($entries)) {
  535. $attribs = array_merge(array('dn','objectClass','memberURL'), array_values($this->group_types));
  536. $entries = $this->ldap->read_entries($dn, '(objectClass=*)', $attribs);
  537. if ($entries === false) {
  538. return $group_members;
  539. }
  540. }
  541. for ($i=0; $i < $entries['count']; $i++) {
  542. $entry = $entries[$i];
  543. $attrs = array();
  544. foreach ((array)$entry['objectclass'] as $objectclass) {
  545. if (($member_attr = $this->get_group_member_attr(array($objectclass), ''))
  546. && ($member_attr = strtolower($member_attr)) && !in_array($member_attr, $attrs)
  547. ) {
  548. $members = $this->_list_group_members($dn, $entry, $member_attr, $count);
  549. $group_members = array_merge($group_members, $members);
  550. $attrs[] = $member_attr;
  551. }
  552. else if (!empty($entry['memberurl'])) {
  553. $members = $this->_list_group_memberurl($dn, $entry, $count);
  554. $group_members = array_merge($group_members, $members);
  555. }
  556. if ($this->prop['sizelimit'] && count($group_members) > $this->prop['sizelimit']) {
  557. break 2;
  558. }
  559. }
  560. }
  561. return array_filter($group_members);
  562. }
  563. /**
  564. * Fetch members of the given group entry from server
  565. *
  566. * @param string Group DN
  567. * @param array Group entry
  568. * @param string Member attribute to use
  569. * @param boolean Count only
  570. * @return array Accumulated group members
  571. */
  572. private function _list_group_members($dn, $entry, $attr, $count)
  573. {
  574. // Use the member attributes to return an array of member ldap objects
  575. // NOTE that the member attribute is supposed to contain a DN
  576. $group_members = array();
  577. if (empty($entry[$attr])) {
  578. return $group_members;
  579. }
  580. // read these attributes for all members
  581. $attrib = $count ? array('dn','objectClass') : $this->prop['list_attributes'];
  582. $attrib = array_merge($attrib, array_values($this->group_types));
  583. $attrib[] = 'memberURL';
  584. $filter = $this->prop['groups']['member_filter'] ?: '(objectclass=*)';
  585. for ($i=0; $i < $entry[$attr]['count']; $i++) {
  586. if (empty($entry[$attr][$i]))
  587. continue;
  588. $members = $this->ldap->read_entries($entry[$attr][$i], $filter, $attrib);
  589. if ($members == false) {
  590. $members = array();
  591. }
  592. // for nested groups, call recursively
  593. $nested_group_members = $this->list_group_members($entry[$attr][$i], $count, $members);
  594. unset($members['count']);
  595. $group_members = array_merge($group_members, array_filter($members), $nested_group_members);
  596. }
  597. return $group_members;
  598. }
  599. /**
  600. * List members of group class groupOfUrls
  601. *
  602. * @param string Group DN
  603. * @param array Group entry
  604. * @param boolean True if only used for counting
  605. * @return array Accumulated group members
  606. */
  607. private function _list_group_memberurl($dn, $entry, $count)
  608. {
  609. $group_members = array();
  610. for ($i=0; $i < $entry['memberurl']['count']; $i++) {
  611. // extract components from url
  612. if (!preg_match('!ldap://[^/]*/([^\?]+)\?\?(\w+)\?(.*)$!', $entry['memberurl'][$i], $m)) {
  613. continue;
  614. }
  615. // add search filter if any
  616. $filter = $this->filter ? '(&(' . $m[3] . ')(' . $this->filter . '))' : $m[3];
  617. $attrs = $count ? array('dn','objectClass') : $this->prop['list_attributes'];
  618. if ($result = $this->ldap->search($m[1], $filter, $m[2], $attrs, $this->group_data)) {
  619. $entries = $result->entries();
  620. for ($j = 0; $j < $entries['count']; $j++) {
  621. if ($this->is_group_entry($entries[$j]) && ($nested_group_members = $this->list_group_members($entries[$j]['dn'], $count)))
  622. $group_members = array_merge($group_members, $nested_group_members);
  623. else
  624. $group_members[] = $entries[$j];
  625. }
  626. }
  627. }
  628. return $group_members;
  629. }
  630. /**
  631. * Callback for sorting entries
  632. */
  633. function _entry_sort_cmp($a, $b)
  634. {
  635. return strcmp($a[$this->sort_col][0], $b[$this->sort_col][0]);
  636. }
  637. /**
  638. * Search contacts
  639. *
  640. * @param mixed $fields The field name of array of field names to search in
  641. * @param mixed $value Search value (or array of values when $fields is array)
  642. * @param int $mode Matching mode:
  643. * 0 - partial (*abc*),
  644. * 1 - strict (=),
  645. * 2 - prefix (abc*)
  646. * @param boolean $select True if results are requested, False if count only
  647. * @param boolean $nocount (Not used)
  648. * @param array $required List of fields that cannot be empty
  649. *
  650. * @return array Indexed list of contact records and 'count' value
  651. */
  652. function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
  653. {
  654. $mode = intval($mode);
  655. // special treatment for ID-based search
  656. if ($fields == 'ID' || $fields == $this->primary_key) {
  657. $ids = !is_array($value) ? explode(',', $value) : $value;
  658. $result = new rcube_result_set();
  659. foreach ($ids as $id) {
  660. if ($rec = $this->get_record($id, true)) {
  661. $result->add($rec);
  662. $result->count++;
  663. }
  664. }
  665. return $result;
  666. }
  667. // use VLV pseudo-search for autocompletion
  668. $rcube = rcube::get_instance();
  669. $list_fields = $rcube->config->get('contactlist_fields');
  670. if ($this->prop['vlv_search'] && $this->ready && join(',', (array)$fields) == join(',', $list_fields)) {
  671. $this->result = new rcube_result_set(0);
  672. $this->ldap->config_set('fuzzy_search', intval($this->prop['fuzzy_search'] && $mode != 1));
  673. $ldap_data = $this->ldap->search($this->base_dn, $this->prop['filter'], $this->prop['scope'], $this->prop['attributes'],
  674. array('search' => $value /*, 'sort' => $this->prop['sort'] */));
  675. if ($ldap_data === false) {
  676. return $this->result;
  677. }
  678. // get all entries of this page and post-filter those that really match the query
  679. $search = mb_strtolower($value);
  680. foreach ($ldap_data as $entry) {
  681. $rec = $this->_ldap2result($entry);
  682. foreach ($fields as $f) {
  683. foreach ((array)$rec[$f] as $val) {
  684. if ($this->compare_search_value($f, $val, $search, $mode)) {
  685. $this->result->add($rec);
  686. $this->result->count++;
  687. break 2;
  688. }
  689. }
  690. }
  691. }
  692. return $this->result;
  693. }
  694. // advanced per-attribute search
  695. if (is_array($value)) {
  696. // use AND operator for advanced searches
  697. $filter = '(&';
  698. // set wildcards
  699. $wp = $ws = '';
  700. if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
  701. $ws = '*';
  702. if (!$mode) {
  703. $wp = '*';
  704. }
  705. }
  706. foreach ((array)$fields as $idx => $field) {
  707. $val = $value[$idx];
  708. if (!strlen($val))
  709. continue;
  710. if ($attrs = $this->_map_field($field)) {
  711. if (count($attrs) > 1)
  712. $filter .= '(|';
  713. foreach ($attrs as $f)
  714. $filter .= "($f=$wp" . rcube_ldap_generic::quote_string($val) . "$ws)";
  715. if (count($attrs) > 1)
  716. $filter .= ')';
  717. }
  718. }
  719. $filter .= ')';
  720. }
  721. else {
  722. if ($fields == '*') {
  723. // search_fields are required for fulltext search
  724. if (empty($this->prop['search_fields'])) {
  725. $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
  726. $this->result = new rcube_result_set();
  727. return $this->result;
  728. }
  729. $attributes = (array)$this->prop['search_fields'];
  730. }
  731. else {
  732. // map address book fields into ldap attributes
  733. $attributes = array();
  734. foreach ((array) $fields as $field) {
  735. if ($this->coltypes[$field] && ($attrs = $this->coltypes[$field]['attributes'])) {
  736. $attributes = array_merge($attributes, (array) $attrs);
  737. }
  738. }
  739. }
  740. // compose a full-text-like search filter
  741. $filter = rcube_ldap_generic::fulltext_search_filter($value, $attributes, $mode);
  742. }
  743. // add required (non empty) fields filter
  744. $req_filter = '';
  745. foreach ((array)$required as $field) {
  746. if (in_array($field, (array)$fields)) // required field is already in search filter
  747. continue;
  748. if ($attrs = $this->_map_field($field)) {
  749. if (count($attrs) > 1)
  750. $req_filter .= '(|';
  751. foreach ($attrs as $f)
  752. $req_filter .= "($f=*)";
  753. if (count($attrs) > 1)
  754. $req_filter .= ')';
  755. }
  756. }
  757. if (!empty($req_filter))
  758. $filter = '(&' . $req_filter . $filter . ')';
  759. // avoid double-wildcard if $value is empty
  760. $filter = preg_replace('/\*+/', '*', $filter);
  761. // add general filter to query
  762. if (!empty($this->prop['filter']))
  763. $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
  764. // set filter string and execute search
  765. $this->set_search_set($filter);
  766. if ($select)
  767. $this->list_records();
  768. else
  769. $this->result = $this->count();
  770. return $this->result;
  771. }
  772. /**
  773. * Count number of available contacts in database
  774. *
  775. * @return object rcube_result_set Resultset with values for 'count' and 'first'
  776. */
  777. function count()
  778. {
  779. $count = 0;
  780. if ($this->ldap_result) {
  781. $count = $this->ldap_result->count();
  782. }
  783. else if ($this->group_id && $this->group_data['dn']) {
  784. $count = count($this->list_group_members($this->group_data['dn'], true));
  785. }
  786. // We have a connection but no result set, attempt to get one.
  787. else if ($this->ready) {
  788. $prop = $this->group_id ? $this->group_data : $this->prop;
  789. $base_dn = $this->group_id ? $this->group_base_dn : $this->base_dn;
  790. if (!empty($this->filter)) { // Use global search filter
  791. $prop['filter'] = $this->filter;
  792. }
  793. $count = $this->ldap->search($base_dn, $prop['filter'], $prop['scope'], array('dn'), $prop, true);
  794. }
  795. return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
  796. }
  797. /**
  798. * Return the last result set
  799. *
  800. * @return object rcube_result_set Current resultset or NULL if nothing selected yet
  801. */
  802. function get_result()
  803. {
  804. return $this->result;
  805. }
  806. /**
  807. * Get a specific contact record
  808. *
  809. * @param mixed Record identifier
  810. * @param boolean Return as associative array
  811. *
  812. * @return mixed Hash array or rcube_result_set with all record fields
  813. */
  814. function get_record($dn, $assoc=false)
  815. {
  816. $res = $this->result = null;
  817. if ($this->ready && $dn) {
  818. $dn = self::dn_decode($dn);
  819. if ($rec = $this->ldap->get_entry($dn)) {
  820. $rec = array_change_key_case($rec, CASE_LOWER);
  821. }
  822. // Use ldap_list to get subentries like country (c) attribute (#1488123)
  823. if (!empty($rec) && $this->sub_filter) {
  824. if ($entries = $this->ldap->list_entries($dn, $this->sub_filter, array_keys($this->prop['sub_fields']))) {
  825. foreach ($entries as $entry) {
  826. $lrec = array_change_key_case($entry, CASE_LOWER);
  827. $rec = array_merge($lrec, $rec);
  828. }
  829. }
  830. }
  831. if (!empty($rec)) {
  832. // Add in the dn for the entry.
  833. $rec['dn'] = $dn;
  834. $res = $this->_ldap2result($rec);
  835. $this->result = new rcube_result_set(1);
  836. $this->result->add($res);
  837. }
  838. }
  839. return $assoc ? $res : $this->result;
  840. }
  841. /**
  842. * Returns the last error occurred (e.g. when updating/inserting failed)
  843. *
  844. * @return array Hash array with the following fields: type, message
  845. */
  846. function get_error()
  847. {
  848. $err = $this->error;
  849. // check ldap connection for errors
  850. if (!$err && $this->ldap->get_error()) {
  851. $err = array(self::ERROR_SEARCH, $this->ldap->get_error());
  852. }
  853. return $err;
  854. }
  855. /**
  856. * Check the given data before saving.
  857. * If input not valid, the message to display can be fetched using get_error()
  858. *
  859. * @param array Assoziative array with data to save
  860. * @param boolean Try to fix/complete record automatically
  861. * @return boolean True if input is valid, False if not.
  862. */
  863. public function validate(&$save_data, $autofix = false)
  864. {
  865. // validate e-mail addresses
  866. if (!parent::validate($save_data, $autofix)) {
  867. return false;
  868. }
  869. // check for name input
  870. if (empty($save_data['name'])) {
  871. $this->set_error(self::ERROR_VALIDATE, 'nonamewarning');
  872. return false;
  873. }
  874. // Verify that the required fields are set.
  875. $missing = null;
  876. $ldap_data = $this->_map_data($save_data);
  877. foreach ($this->prop['required_fields'] as $fld) {
  878. if (!isset($ldap_data[$fld]) || $ldap_data[$fld] === '') {
  879. $missing[$fld] = 1;
  880. }
  881. }
  882. if ($missing) {
  883. // try to complete record automatically
  884. if ($autofix) {
  885. $sn_field = $this->fieldmap['surname'];
  886. $fn_field = $this->fieldmap['firstname'];
  887. $mail_field = $this->fieldmap['email'];
  888. // try to extract surname and firstname from displayname
  889. $name_parts = preg_split('/[\s,.]+/', $save_data['name']);
  890. if ($sn_field && $missing[$sn_field]) {
  891. $save_data['surname'] = array_pop($name_parts);
  892. unset($missing[$sn_field]);
  893. }
  894. if ($fn_field && $missing[$fn_field]) {
  895. $save_data['firstname'] = array_shift($name_parts);
  896. unset($missing[$fn_field]);
  897. }
  898. // try to fix missing e-mail, very often on import
  899. // from vCard we have email:other only defined
  900. if ($mail_field && $missing[$mail_field]) {
  901. $emails = $this->get_col_values('email', $save_data, true);
  902. if (!empty($emails) && ($email = array_shift($emails))) {
  903. $save_data['email'] = $email;
  904. unset($missing[$mail_field]);
  905. }
  906. }
  907. }
  908. // TODO: generate message saying which fields are missing
  909. if (!empty($missing)) {
  910. $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
  911. return false;
  912. }
  913. }
  914. return true;
  915. }
  916. /**
  917. * Create a new contact record
  918. *
  919. * @param array Associative array with save data
  920. * Keys: Field name with optional section in the form FIELD:SECTION
  921. * Values: Field value. Can be either a string or an array of strings for multiple values
  922. * @param boolean True to check for duplicates first
  923. *
  924. * @return mixed The created record ID on success, False on error
  925. */
  926. function insert($save_cols, $check = false)
  927. {
  928. // Map out the column names to their LDAP ones to build the new entry.
  929. $newentry = $this->_map_data($save_cols);
  930. $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
  931. // add automatically generated attributes
  932. $this->add_autovalues($newentry);
  933. // Verify that the required fields are set.
  934. $missing = null;
  935. foreach ($this->prop['required_fields'] as $fld) {
  936. if (!isset($newentry[$fld])) {
  937. $missing[] = $fld;
  938. }
  939. }
  940. // abort process if requiered fields are missing
  941. // TODO: generate message saying which fields are missing
  942. if ($missing) {
  943. $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
  944. return false;
  945. }
  946. // Build the new entries DN.
  947. $dn = $this->prop['LDAP_rdn'].'='.rcube_ldap_generic::quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->base_dn;
  948. // Remove attributes that need to be added separately (child objects)
  949. $xfields = array();
  950. if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
  951. foreach (array_keys($this->prop['sub_fields']) as $xf) {
  952. if (!empty($newentry[$xf])) {
  953. $xfields[$xf] = $newentry[$xf];
  954. unset($newentry[$xf]);
  955. }
  956. }
  957. }
  958. if (!$this->ldap->add_entry($dn, $newentry)) {
  959. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  960. return false;
  961. }
  962. foreach ($xfields as $xidx => $xf) {
  963. $xdn = $xidx.'='.rcube_ldap_generic::quote_string($xf).','.$dn;
  964. $xf = array(
  965. $xidx => $xf,
  966. 'objectClass' => (array) $this->prop['sub_fields'][$xidx],
  967. );
  968. $this->ldap->add_entry($xdn, $xf);
  969. }
  970. $dn = self::dn_encode($dn);
  971. // add new contact to the selected group
  972. if ($this->group_id)
  973. $this->add_to_group($this->group_id, $dn);
  974. return $dn;
  975. }
  976. /**
  977. * Update a specific contact record
  978. *
  979. * @param mixed Record identifier
  980. * @param array Hash array with save data
  981. *
  982. * @return boolean True on success, False on error
  983. */
  984. function update($id, $save_cols)
  985. {
  986. $record = $this->get_record($id, true);
  987. $newdata = array();
  988. $replacedata = array();
  989. $deletedata = array();
  990. $subdata = array();
  991. $subdeldata = array();
  992. $subnewdata = array();
  993. $ldap_data = $this->_map_data($save_cols);
  994. $old_data = $record['_raw_attrib'];
  995. // special handling of photo col
  996. if ($photo_fld = $this->fieldmap['photo']) {
  997. // undefined means keep old photo
  998. if (!array_key_exists('photo', $save_cols)) {
  999. $ldap_data[$photo_fld] = $record['photo'];
  1000. }
  1001. }
  1002. foreach ($this->fieldmap as $fld) {
  1003. if ($fld) {
  1004. $val = $ldap_data[$fld];
  1005. $old = $old_data[$fld];
  1006. // remove empty array values
  1007. if (is_array($val))
  1008. $val = array_filter($val);
  1009. // $this->_map_data() result and _raw_attrib use different format
  1010. // make sure comparing array with one element with a string works as expected
  1011. if (is_array($old) && count($old) == 1 && !is_array($val)) {
  1012. $old = array_pop($old);
  1013. }
  1014. if (is_array($val) && count($val) == 1 && !is_array($old)) {
  1015. $val = array_pop($val);
  1016. }
  1017. // Subentries must be handled separately
  1018. if (!empty($this->prop['sub_fields']) && isset($this->prop['sub_fields'][$fld])) {
  1019. if ($old != $val) {
  1020. if ($old !== null) {
  1021. $subdeldata[$fld] = $old;
  1022. }
  1023. if ($val) {
  1024. $subnewdata[$fld] = $val;
  1025. }
  1026. }
  1027. else if ($old !== null) {
  1028. $subdata[$fld] = $old;
  1029. }
  1030. continue;
  1031. }
  1032. // The field does exist compare it to the ldap record.
  1033. if ($old != $val) {
  1034. // Changed, but find out how.
  1035. if ($old === null) {
  1036. // Field was not set prior, need to add it.
  1037. $newdata[$fld] = $val;
  1038. }
  1039. else if ($val == '') {
  1040. // Field supplied is empty, verify that it is not required.
  1041. if (!in_array($fld, $this->prop['required_fields'])) {
  1042. // ...It is not, safe to clear.
  1043. // #1488420: Workaround "ldap_mod_del(): Modify: Inappropriate matching in..."
  1044. // jpegPhoto attribute require an array() here. It looks to me that it works for other attribs too
  1045. $deletedata[$fld] = array();
  1046. //$deletedata[$fld] = $old_data[$fld];
  1047. }
  1048. }
  1049. else {
  1050. // The data was modified, save it out.
  1051. $replacedata[$fld] = $val;
  1052. }
  1053. } // end if
  1054. } // end if
  1055. } // end foreach
  1056. // console($old_data, $ldap_data, '----', $newdata, $replacedata, $deletedata, '----', $subdata, $subnewdata, $subdeldata);
  1057. $dn = self::dn_decode($id);
  1058. // Update the entry as required.
  1059. if (!empty($deletedata)) {
  1060. // Delete the fields.
  1061. if (!$this->ldap->mod_del($dn, $deletedata)) {
  1062. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1063. return false;
  1064. }
  1065. } // end if
  1066. if (!empty($replacedata)) {
  1067. // Handle RDN change
  1068. if ($replacedata[$this->prop['LDAP_rdn']]) {
  1069. $newdn = $this->prop['LDAP_rdn'].'='
  1070. .rcube_ldap_generic::quote_string($replacedata[$this->prop['LDAP_rdn']], true)
  1071. .','.$this->base_dn;
  1072. if ($dn != $newdn) {
  1073. $newrdn = $this->prop['LDAP_rdn'].'='
  1074. .rcube_ldap_generic::quote_string($replacedata[$this->prop['LDAP_rdn']], true);
  1075. unset($replacedata[$this->prop['LDAP_rdn']]);
  1076. }
  1077. }
  1078. // Replace the fields.
  1079. if (!empty($replacedata)) {
  1080. if (!$this->ldap->mod_replace($dn, $replacedata)) {
  1081. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1082. return false;
  1083. }
  1084. }
  1085. } // end if
  1086. // RDN change, we need to remove all sub-entries
  1087. if (!empty($newrdn)) {
  1088. $subdeldata = array_merge($subdeldata, $subdata);
  1089. $subnewdata = array_merge($subnewdata, $subdata);
  1090. }
  1091. // remove sub-entries
  1092. if (!empty($subdeldata)) {
  1093. foreach ($subdeldata as $fld => $val) {
  1094. $subdn = $fld.'='.rcube_ldap_generic::quote_string($val).','.$dn;
  1095. if (!$this->ldap->delete_entry($subdn)) {
  1096. return false;
  1097. }
  1098. }
  1099. }
  1100. if (!empty($newdata)) {
  1101. // Add the fields.
  1102. if (!$this->ldap->mod_add($dn, $newdata)) {
  1103. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1104. return false;
  1105. }
  1106. } // end if
  1107. // Handle RDN change
  1108. if (!empty($newrdn)) {
  1109. if (!$this->ldap->rename($dn, $newrdn, null, true)) {
  1110. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1111. return false;
  1112. }
  1113. $dn = self::dn_encode($dn);
  1114. $newdn = self::dn_encode($newdn);
  1115. // change the group membership of the contact
  1116. if ($this->groups) {
  1117. $group_ids = $this->get_record_groups($dn);
  1118. foreach (array_keys($group_ids) as $group_id) {
  1119. $this->remove_from_group($group_id, $dn);
  1120. $this->add_to_group($group_id, $newdn);
  1121. }
  1122. }
  1123. $dn = self::dn_decode($newdn);
  1124. }
  1125. // add sub-entries
  1126. if (!empty($subnewdata)) {
  1127. foreach ($subnewdata as $fld => $val) {
  1128. $subdn = $fld.'='.rcube_ldap_generic::quote_string($val).','.$dn;
  1129. $xf = array(
  1130. $fld => $val,
  1131. 'objectClass' => (array) $this->prop['sub_fields'][$fld],
  1132. );
  1133. $this->ldap->add_entry($subdn, $xf);
  1134. }
  1135. }
  1136. return $newdn ?: true;
  1137. }
  1138. /**
  1139. * Mark one or more contact records as deleted
  1140. *
  1141. * @param array Record identifiers
  1142. * @param boolean Remove record(s) irreversible (unsupported)
  1143. *
  1144. * @return boolean True on success, False on error
  1145. */
  1146. function delete($ids, $force=true)
  1147. {
  1148. if (!is_array($ids)) {
  1149. // Not an array, break apart the encoded DNs.
  1150. $ids = explode(',', $ids);
  1151. } // end if
  1152. foreach ($ids as $id) {
  1153. $dn = self::dn_decode($id);
  1154. // Need to delete all sub-entries first
  1155. if ($this->sub_filter) {
  1156. if ($entries = $this->ldap->list_entries($dn, $this->sub_filter)) {
  1157. foreach ($entries as $entry) {
  1158. if (!$this->ldap->delete_entry($entry['dn'])) {
  1159. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1160. return false;
  1161. }
  1162. }
  1163. }
  1164. }
  1165. // Delete the record.
  1166. if (!$this->ldap->delete_entry($dn)) {
  1167. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1168. return false;
  1169. }
  1170. // remove contact from all groups where he was a member
  1171. if ($this->groups) {
  1172. $dn = self::dn_encode($dn);
  1173. $group_ids = $this->get_record_groups($dn);
  1174. foreach (array_keys($group_ids) as $group_id) {
  1175. $this->remove_from_group($group_id, $dn);
  1176. }
  1177. }
  1178. } // end foreach
  1179. return count($ids);
  1180. }
  1181. /**
  1182. * Remove all contact records
  1183. *
  1184. * @param bool $with_groups Delete also groups if enabled
  1185. */
  1186. function delete_all($with_groups = false)
  1187. {
  1188. // searching for contact entries
  1189. $dn_list = $this->ldap->list_entries($this->base_dn, $this->prop['filter'] ?: '(objectclass=*)');
  1190. if (!empty($dn_list)) {
  1191. foreach ($dn_list as $idx => $entry) {
  1192. $dn_list[$idx] = self::dn_encode($entry['dn']);
  1193. }
  1194. $this->delete($dn_list);
  1195. }
  1196. if ($with_groups && $this->groups && ($groups = $this->_fetch_groups()) && count($groups)) {
  1197. foreach ($groups as $group) {
  1198. $this->ldap->delete_entry($group['dn']);
  1199. }
  1200. if ($this->cache) {
  1201. $this->cache->remove('groups');
  1202. }
  1203. }
  1204. }
  1205. /**
  1206. * Generate missing attributes as configured
  1207. *
  1208. * @param array LDAP record attributes
  1209. */
  1210. protected function add_autovalues(&$attrs)
  1211. {
  1212. if (empty($this->prop['autovalues'])) {
  1213. return;
  1214. }
  1215. $attrvals = array();
  1216. foreach ($attrs as $k => $v) {
  1217. $attrvals['{'.$k.'}'] = is_array($v) ? $v[0] : $v;
  1218. }
  1219. foreach ((array)$this->prop['autovalues'] as $lf => $templ) {
  1220. if (empty($attrs[$lf])) {
  1221. if (strpos($templ, '(') !== false) {
  1222. // replace {attr} placeholders with (escaped!) attribute values to be safely eval'd
  1223. $code = preg_replace('/\{\w+\}/', '', strtr($templ, array_map('addslashes', $attrvals)));
  1224. $fn = create_function('', "return ($code);");
  1225. if (!$fn) {
  1226. rcube::raise_error(array(
  1227. 'code' => 505, 'type' => 'php',
  1228. 'file' => __FILE__, 'line' => __LINE__,
  1229. 'message' => "Expression parse error on: ($code)"), true, false);
  1230. continue;
  1231. }
  1232. $attrs[$lf] = $fn();
  1233. }
  1234. else {
  1235. // replace {attr} placeholders with concrete attribute values
  1236. $attrs[$lf] = preg_replace('/\{\w+\}/', '', strtr($templ, $attrvals));
  1237. }
  1238. }
  1239. }
  1240. }
  1241. /**
  1242. * Converts LDAP entry into an array
  1243. */
  1244. private function _ldap2result($rec)
  1245. {
  1246. $out = array('_type' => 'person');
  1247. $fieldmap = $this->fieldmap;
  1248. if ($rec['dn'])
  1249. $out[$this->primary_key] = self::dn_encode($rec['dn']);
  1250. // determine record type
  1251. if ($this->is_group_entry($rec)) {
  1252. $out['_type'] = 'group';
  1253. $out['readonly'] = true;
  1254. $fieldmap['name'] = $this->group_data['name_attr'] ?: $this->prop['groups']['name_attr'];
  1255. }
  1256. // assign object type from object class mapping
  1257. if (!empty($this->prop['class_type_map'])) {
  1258. foreach (array_map('strtolower', (array)$rec['objectclass']) as $objcls) {
  1259. if (!empty($this->prop['class_type_map'][$objcls])) {
  1260. $out['_type'] = $this->prop['class_type_map'][$objcls];
  1261. break;
  1262. }
  1263. }
  1264. }
  1265. foreach ($fieldmap as $rf => $lf)
  1266. {
  1267. for ($i=0; $i < $rec[$lf]['count']; $i++) {
  1268. if (!($value = $rec[$lf][$i]))
  1269. continue;
  1270. list($col, $subtype) = explode(':', $rf);
  1271. $out['_raw_attrib'][$lf][$i] = $value;
  1272. if ($col == 'email' && $this->mail_domain && !strpos($value, '@'))
  1273. $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
  1274. else if (in_array($col, array('street','zipcode','locality','country','region')))
  1275. $out['address' . ($subtype ? ':' : '') . $subtype][$i][$col] = $value;
  1276. else if ($col == 'address' && strpos($value, '$') !== false) // address data is represented as string separated with $
  1277. list($out[$rf][$i]['street'], $out[$rf][$i]['locality'], $out[$rf][$i]['zipcode'], $out[$rf][$i]['country']) = explode('$', $value);
  1278. else if ($rec[$lf]['count'] > 1)
  1279. $out[$rf][] = $value;
  1280. else
  1281. $out[$rf] = $value;
  1282. }
  1283. // Make sure name fields aren't arrays (#1488108)
  1284. if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
  1285. $out[$rf] = $out['_raw_attrib'][$lf] = $out[$rf][0];
  1286. }
  1287. }
  1288. return $out;
  1289. }
  1290. /**
  1291. * Return LDAP attribute(s) for the given field
  1292. */
  1293. private function _map_field($field)
  1294. {
  1295. return (array)$this->coltypes[$field]['attributes'];
  1296. }
  1297. /**
  1298. * Convert a record data set into LDAP field attributes
  1299. */
  1300. private function _map_data($save_cols)
  1301. {
  1302. // flatten composite fields first
  1303. foreach ($this->coltypes as $col => $colprop) {
  1304. if (is_array($colprop['childs']) && ($values = $this->get_col_values($col, $save_cols, false))) {
  1305. foreach ($values as $subtype => $childs) {
  1306. $subtype = $subtype ? ':'.$subtype : '';
  1307. foreach ($childs as $i => $child_values) {
  1308. foreach ((array)$child_values as $childcol => $value) {
  1309. $save_cols[$childcol.$subtype][$i] = $value;
  1310. }
  1311. }
  1312. }
  1313. }
  1314. // if addresses are to be saved as serialized string, do so
  1315. if (is_array($colprop['serialized'])) {
  1316. foreach ($colprop['serialized'] as $subtype => $delim) {
  1317. $key = $col.':'.$subtype;
  1318. foreach ((array)$save_cols[$key] as $i => $val) {
  1319. $values = array($val['street'], $val['locality'], $val['zipcode'], $val['country']);
  1320. $save_cols[$key][$i] = count(array_filter($values)) ? join($delim, $values) : null;
  1321. }
  1322. }
  1323. }
  1324. }
  1325. $ldap_data = array();
  1326. foreach ($this->fieldmap as $rf => $fld) {
  1327. $val = $save_cols[$rf];
  1328. // check for value in base field (eg.g email instead of email:foo)
  1329. list($col, $subtype) = explode(':', $rf);
  1330. if (!$val && !empty($save_cols[$col])) {
  1331. $val = $save_cols[$col];
  1332. unset($save_cols[$col]); // only use this value once
  1333. }
  1334. else if (!$val && !$subtype) { // extract values from subtype cols
  1335. $val = $this->get_col_values($col, $save_cols, true);
  1336. }
  1337. if (is_array($val))
  1338. $val = array_filter($val); // remove empty entries
  1339. if ($fld && $val) {
  1340. // The field does exist, add it to the entry.
  1341. $ldap_data[$fld] = $val;
  1342. }
  1343. }
  1344. foreach ($this->formats as $fld => $format) {
  1345. if (empty($ldap_data[$fld])) {
  1346. continue;
  1347. }
  1348. switch ($format['type']) {
  1349. case 'date':
  1350. if ($dt = rcube_utils::anytodatetime($ldap_data[$fld])) {
  1351. $ldap_data[$fld] = $dt->format($format['format']);
  1352. }
  1353. break;
  1354. }
  1355. }
  1356. return $ldap_data;
  1357. }
  1358. /**
  1359. * Returns unified attribute name (resolving aliases)
  1360. */
  1361. private static function _attr_name($namev)
  1362. {
  1363. // list of known attribute aliases
  1364. static $aliases = array(
  1365. 'gn' => 'givenname',
  1366. 'rfc822mailbox' => 'email',
  1367. 'userid' => 'uid',
  1368. 'emailaddress' => 'email',
  1369. 'pkcs9email' => 'email',
  1370. );
  1371. list($name, $limit) = explode(':', $namev, 2);
  1372. $suffix = $limit ? ':'.$limit : '';
  1373. $name = strtolower($name);
  1374. return (isset($aliases[$name]) ? $aliases[$name] : $name) . $suffix;
  1375. }
  1376. /**
  1377. * Determines whether the given LDAP entry is a group record
  1378. */
  1379. private function is_group_entry($entry)
  1380. {
  1381. $classes = array_map('strtolower', (array)$entry['objectclass']);
  1382. return count(array_intersect(array_keys($this->group_types), $classes)) > 0;
  1383. }
  1384. /**
  1385. * Activate/deactivate debug mode
  1386. *
  1387. * @param boolean $dbg True if LDAP commands should be logged
  1388. */
  1389. function set_debug($dbg = true)
  1390. {
  1391. $this->debug = $dbg;
  1392. if ($this->ldap) {
  1393. $this->ldap->config_set('debug', $dbg);
  1394. }
  1395. }
  1396. /**
  1397. * Setter for the current group
  1398. */
  1399. function set_group($group_id)
  1400. {
  1401. if ($group_id) {
  1402. $this->group_id = $group_id;
  1403. $this->group_data = $this->get_group_entry($group_id);
  1404. }
  1405. else {
  1406. $this->group_id = 0;
  1407. $this->group_data = null;
  1408. }
  1409. }
  1410. /**
  1411. * List all active contact groups of this source
  1412. *
  1413. * @param string Optional search string to match group name
  1414. * @param int Matching mode:
  1415. * 0 - partial (*abc*),
  1416. * 1 - strict (=),
  1417. * 2 - prefix (abc*)
  1418. *
  1419. * @return array Indexed list of contact groups, each a hash array
  1420. */
  1421. function list_groups($search = null, $mode = 0)
  1422. {
  1423. if (!$this->groups) {
  1424. return array();
  1425. }
  1426. $group_cache = $this->_fetch_groups($search, $mode);
  1427. $groups = array();
  1428. if ($search) {
  1429. foreach ($group_cache as $group) {
  1430. if ($this->compare_search_value('name', $group['name'], mb_strtolower($search), $mode)) {
  1431. $groups[] = $group;
  1432. }
  1433. }
  1434. }
  1435. else {
  1436. $groups = $group_cache;
  1437. }
  1438. return array_values($groups);
  1439. }
  1440. /**
  1441. * Fetch groups from server
  1442. */
  1443. private function _fetch_groups($search = null, $mode = 0, $vlv_page = null)
  1444. {
  1445. // reset group search cache
  1446. if ($search !== null && $vlv_page === null) {
  1447. $this->group_search_cache = null;
  1448. }
  1449. // return in-memory cache from previous search results
  1450. else if (is_array($this->group_search_cache) && $vlv_page === null) {
  1451. return $this->group_search_cache;
  1452. }
  1453. // special case: list groups from 'group_filters' config
  1454. if ($vlv_page === null && $search === null && is_array($this->prop['group_filters'])) {
  1455. $groups = array();
  1456. $rcube = rcube::get_instance();
  1457. // list regular groups configuration as special filter
  1458. if (!empty($this->prop['groups']['filter'])) {
  1459. $id = '__groups__';
  1460. $groups[$id] = array('ID' => $id, 'name' => $rcube->gettext('groups'), 'virtual' => true) + $this->prop['groups'];
  1461. }
  1462. foreach ($this->prop['group_filters'] as $id => $prop) {
  1463. $groups[$id] = $prop + array('ID' => $id, 'name' => ucfirst($id), 'virtual' => true, 'base_dn' => $this->base_dn);
  1464. }
  1465. return $groups;
  1466. }
  1467. if ($this->cache && $search === null && $vlv_page === null && ($groups = $this->cache->get('groups')) !== null) {
  1468. return $groups;
  1469. }
  1470. $base_dn = $this->groups_base_dn;
  1471. $filter = $this->prop['groups']['filter'];
  1472. $scope = $this->prop['groups']['scope'];
  1473. $name_attr = $this->prop['groups']['name_attr'];
  1474. $email_attr = $this->prop['groups']['email_attr'] ?: 'mail';
  1475. $sort_attrs = $this->prop['groups']['sort'] ? (array)$this->prop['groups']['sort'] : array($name_attr);
  1476. $sort_attr = $sort_attrs[0];
  1477. $ldap = $this->ldap;
  1478. // use vlv to list groups
  1479. if ($this->prop['groups']['vlv']) {
  1480. $page_size = 200;
  1481. if (!$this->prop['groups']['sort']) {
  1482. $this->prop['groups']['sort'] = $sort_attrs;
  1483. }
  1484. $ldap = clone $this->ldap;
  1485. $ldap->config_set($this->prop['groups']);
  1486. $ldap->set_vlv_page($vlv_page+1, $page_size);
  1487. }
  1488. $props = array('sort' => $this->prop['groups']['sort']);
  1489. $attrs = array_unique(array('dn', 'objectClass', $name_attr, $email_attr, $sort_attr));
  1490. // add search filter
  1491. if ($search !== null) {
  1492. // set wildcards
  1493. $wp = $ws = '';
  1494. if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
  1495. $ws = '*';
  1496. $wp = !$mode ? '*' : '';
  1497. }
  1498. $filter = "(&$filter($name_attr=$wp" . rcube_ldap_generic::quote_string($search) . "$ws))";
  1499. $props['search'] = $wp . $search . $ws;
  1500. }
  1501. $ldap_data = $ldap->search($base_dn, $filter, $scope, $attrs, $props);
  1502. if ($ldap_data === false) {
  1503. return array();
  1504. }
  1505. $groups = array();
  1506. $group_sortnames = array();
  1507. $group_count = $ldap_data->count();
  1508. foreach ($ldap_data as $entry) {
  1509. if (!$entry['dn']) // DN is mandatory
  1510. $entry['dn'] = $ldap_data->get_dn();
  1511. $group_name = is_array($entry[$name_attr]) ? $entry[$name_attr][0] : $entry[$name_attr];
  1512. $group_id = self::dn_encode($entry['dn']);
  1513. $groups[$group_id]['ID'] = $group_id;
  1514. $groups[$group_id]['dn'] = $entry['dn'];
  1515. $groups[$group_id]['name'] = $group_name;
  1516. $groups[$group_id]['member_attr'] = $this->get_group_member_attr($entry['objectclass']);
  1517. // list email attributes of a group
  1518. for ($j=0; $entry[$email_attr] && $j < $entry[$email_attr]['count']; $j++) {
  1519. if (strpos($entry[$email_attr][$j], '@') > 0)
  1520. $groups[$group_id]['email'][] = $entry[$email_attr][$j];
  1521. }
  1522. $group_sortnames[] = mb_strtolower($entry[$sort_attr][0]);
  1523. }
  1524. // recursive call can exit here
  1525. if ($vlv_page > 0) {
  1526. return $groups;
  1527. }
  1528. // call recursively until we have fetched all groups
  1529. while ($this->prop['groups']['vlv'] && $group_count == $page_size) {
  1530. $next_page = $this->_fetch_groups($search, $mode, ++$vlv_page);
  1531. $groups = array_merge($groups, $next_page);
  1532. $group_count = count($next_page);
  1533. }
  1534. // when using VLV the list of groups is already sorted
  1535. if (!$this->prop['groups']['vlv']) {
  1536. array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
  1537. }
  1538. // cache this
  1539. if ($this->cache && $search === null) {
  1540. $this->cache->set('groups', $groups);
  1541. }
  1542. else if ($search !== null) {
  1543. $this->group_search_cache = $groups;
  1544. }
  1545. return $groups;
  1546. }
  1547. /**
  1548. * Fetch a group entry from LDAP and save in local cache
  1549. */
  1550. private function get_group_entry($group_id)
  1551. {
  1552. $group_cache = $this->_fetch_groups();
  1553. // add group record to cache if it isn't yet there
  1554. if (!isset($group_cache[$group_id])) {
  1555. $name_attr = $this->prop['groups']['name_attr'];
  1556. $dn = self::dn_decode($group_id);
  1557. if ($list = $this->ldap->read_entries($dn, '(objectClass=*)', array('dn','objectClass','member','uniqueMember','memberURL',$name_attr,$this->fieldmap['email']))) {
  1558. $entry = $list[0];
  1559. $group_name = is_array($entry[$name_attr]) ? $entry[$name_attr][0] : $entry[$name_attr];
  1560. $group_cache[$group_id]['ID'] = $group_id;
  1561. $group_cache[$group_id]['dn'] = $dn;
  1562. $group_cache[$group_id]['name'] = $group_name;
  1563. $group_cache[$group_id]['member_attr'] = $this->get_group_member_attr($entry['objectclass']);
  1564. }
  1565. else {
  1566. $group_cache[$group_id] = false;
  1567. }
  1568. if ($this->cache) {
  1569. $this->cache->set('groups', $group_cache);
  1570. }
  1571. }
  1572. return $group_cache[$group_id];
  1573. }
  1574. /**
  1575. * Get group properties such as name and email address(es)
  1576. *
  1577. * @param string Group identifier
  1578. * @return array Group properties as hash array
  1579. */
  1580. function get_group($group_id)
  1581. {
  1582. $group_data = $this->get_group_entry($group_id);
  1583. unset($group_data['dn'], $group_data['member_attr']);
  1584. return $group_data;
  1585. }
  1586. /**
  1587. * Create a contact group with the given name
  1588. *
  1589. * @param string The group name
  1590. * @return mixed False on error, array with record props in success
  1591. */
  1592. function create_group($group_name)
  1593. {
  1594. $new_dn = 'cn=' . rcube_ldap_generic::quote_string($group_name, true) . ',' . $this->groups_base_dn;
  1595. $new_gid = self::dn_encode($new_dn);
  1596. $member_attr = $this->get_group_member_attr();
  1597. $name_attr = $this->prop['groups']['name_attr'] ?: 'cn';
  1598. $new_entry = array(
  1599. 'objectClass' => $this->prop['groups']['object_classes'],
  1600. $name_attr => $group_name,
  1601. $member_attr => '',
  1602. );
  1603. if (!$this->ldap->add_entry($new_dn, $new_entry)) {
  1604. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1605. return false;
  1606. }
  1607. if ($this->cache) {
  1608. $this->cache->remove('groups');
  1609. }
  1610. return array('id' => $new_gid, 'name' => $group_name);
  1611. }
  1612. /**
  1613. * Delete the given group and all linked group members
  1614. *
  1615. * @param string Group identifier
  1616. * @return boolean True on success, false if no data was changed
  1617. */
  1618. function delete_group($group_id)
  1619. {
  1620. $group_cache = $this->_fetch_groups();
  1621. $del_dn = $group_cache[$group_id]['dn'];
  1622. if (!$this->ldap->delete_entry($del_dn)) {
  1623. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1624. return false;
  1625. }
  1626. if ($this->cache) {
  1627. unset($group_cache[$group_id]);
  1628. $this->cache->set('groups', $group_cache);
  1629. }
  1630. return true;
  1631. }
  1632. /**
  1633. * Rename a specific contact group
  1634. *
  1635. * @param string Group identifier
  1636. * @param string New name to set for this group
  1637. * @param string New group identifier (if changed, otherwise don't set)
  1638. * @return boolean New name on success, false if no data was changed
  1639. */
  1640. function rename_group($group_id, $new_name, &$new_gid)
  1641. {
  1642. $group_cache = $this->_fetch_groups();
  1643. $old_dn = $group_cache[$group_id]['dn'];
  1644. $new_rdn = "cn=" . rcube_ldap_generic::quote_string($new_name, true);
  1645. $new_gid = self::dn_encode($new_rdn . ',' . $this->groups_base_dn);
  1646. if (!$this->ldap->rename($old_dn, $new_rdn, null, true)) {
  1647. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1648. return false;
  1649. }
  1650. if ($this->cache) {
  1651. $this->cache->remove('groups');
  1652. }
  1653. return $new_name;
  1654. }
  1655. /**
  1656. * Add the given contact records the a certain group
  1657. *
  1658. * @param string Group identifier
  1659. * @param array|string List of contact identifiers to be added
  1660. *
  1661. * @return int Number of contacts added
  1662. */
  1663. function add_to_group($group_id, $contact_ids)
  1664. {
  1665. $group_cache = $this->_fetch_groups();
  1666. $member_attr = $group_cache[$group_id]['member_attr'];
  1667. $group_dn = $group_cache[$group_id]['dn'];
  1668. $new_attrs = array();
  1669. if (!is_array($contact_ids)) {
  1670. $contact_ids = explode(',', $contact_ids);
  1671. }
  1672. foreach ($contact_ids as $id) {
  1673. $new_attrs[$member_attr][] = self::dn_decode($id);
  1674. }
  1675. if (!$this->ldap->mod_add($group_dn, $new_attrs)) {
  1676. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1677. return 0;
  1678. }
  1679. if ($this->cache) {
  1680. $this->cache->remove('groups');
  1681. }
  1682. return count($new_attrs[$member_attr]);
  1683. }
  1684. /**
  1685. * Remove the given contact records from a certain group
  1686. *
  1687. * @param string Group identifier
  1688. * @param array|string List of contact identifiers to be removed
  1689. *
  1690. * @return int Number of deleted group members
  1691. */
  1692. function remove_from_group($group_id, $contact_ids)
  1693. {
  1694. $group_cache = $this->_fetch_groups();
  1695. $member_attr = $group_cache[$group_id]['member_attr'];
  1696. $group_dn = $group_cache[$group_id]['dn'];
  1697. $del_attrs = array();
  1698. if (!is_array($contact_ids)) {
  1699. $contact_ids = explode(',', $contact_ids);
  1700. }
  1701. foreach ($contact_ids as $id) {
  1702. $del_attrs[$member_attr][] = self::dn_decode($id);
  1703. }
  1704. if (!$this->ldap->mod_del($group_dn, $del_attrs)) {
  1705. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1706. return 0;
  1707. }
  1708. if ($this->cache) {
  1709. $this->cache->remove('groups');
  1710. }
  1711. return count($del_attrs[$member_attr]);
  1712. }
  1713. /**
  1714. * Get group assignments of a specific contact record
  1715. *
  1716. * @param mixed Record identifier
  1717. *
  1718. * @return array List of assigned groups as ID=>Name pairs
  1719. * @since 0.5-beta
  1720. */
  1721. function get_record_groups($contact_id)
  1722. {
  1723. if (!$this->groups) {
  1724. return array();
  1725. }
  1726. $base_dn = $this->groups_base_dn;
  1727. $contact_dn = self::dn_decode($contact_id);
  1728. $name_attr = $this->prop['groups']['name_attr'] ?: 'cn';
  1729. $member_attr = $this->get_group_member_attr();
  1730. $add_filter = '';
  1731. if ($member_attr != 'member' && $member_attr != 'uniqueMember')
  1732. $add_filter = "($member_attr=$contact_dn)";
  1733. $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
  1734. $ldap_data = $this->ldap->search($base_dn, $filter, 'sub', array('dn', $name_attr));
  1735. if ($ldap_data === false) {
  1736. return array();
  1737. }
  1738. $groups = array();
  1739. foreach ($ldap_data as $entry) {
  1740. if (!$entry['dn'])
  1741. $entry['dn'] = $ldap_data->get_dn();
  1742. $group_name = $entry[$name_attr][0];
  1743. $group_id = self::dn_encode($entry['dn']);
  1744. $groups[$group_id] = $group_name;
  1745. }
  1746. return $groups;
  1747. }
  1748. /**
  1749. * Detects group member attribute name
  1750. */
  1751. private function get_group_member_attr($object_classes = array(), $default = 'member')
  1752. {
  1753. if (empty($object_classes)) {
  1754. $object_classes = $this->prop['groups']['object_classes'];
  1755. }
  1756. if (!empty($object_classes)) {
  1757. foreach ((array)$object_classes as $oc) {
  1758. if ($attr = $this->group_types[strtolower($oc)]) {
  1759. return $attr;
  1760. }
  1761. }
  1762. }
  1763. if (!empty($this->prop['groups']['member_attr'])) {
  1764. return $this->prop['groups']['member_attr'];
  1765. }
  1766. return $default;
  1767. }
  1768. /**
  1769. * HTML-safe DN string encoding
  1770. *
  1771. * @param string $str DN string
  1772. *
  1773. * @return string Encoded HTML identifier string
  1774. */
  1775. static function dn_encode($str)
  1776. {
  1777. // @TODO: to make output string shorter we could probably
  1778. // remove dc=* items from it
  1779. return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
  1780. }
  1781. /**
  1782. * Decodes DN string encoded with _dn_encode()
  1783. *
  1784. * @param string $str Encoded HTML identifier string
  1785. *
  1786. * @return string DN string
  1787. */
  1788. static function dn_decode($str)
  1789. {
  1790. $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
  1791. return base64_decode($str);
  1792. }
  1793. }