rcube_ldap.php 76 KB

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