source: github/program/include/rcube_ldap.php @ b1f0846

HEADcourier-fixdev-browser-capabilitiespdorelease-0.7release-0.8
Last change on this file since b1f0846 was b1f0846, checked in by alecpl <alec@…>, 21 months ago
  • Make sure LDAP name fields aren't arrays (#1488108)
  • Property mode set to 100644
File size: 51.4 KB
Line 
1<?php
2/*
3 +-----------------------------------------------------------------------+
4 | program/include/rcube_ldap.php                                        |
5 |                                                                       |
6 | This file is part of the Roundcube Webmail client                     |
7 | Copyright (C) 2006-2011, The Roundcube Dev Team                       |
8 | Copyright (C) 2011, Kolab Systems AG                                  |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Interface to an LDAP address directory                              |
13 |                                                                       |
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 $Id$
21
22*/
23
24
25/**
26 * Model class to access an LDAP address directory
27 *
28 * @package Addressbook
29 */
30class rcube_ldap extends rcube_addressbook
31{
32    /** public properties */
33    public $primary_key = 'ID';
34    public $groups = false;
35    public $readonly = true;
36    public $ready = false;
37    public $group_id = 0;
38    public $list_page = 1;
39    public $page_size = 10;
40    public $coltypes = array();
41
42    /** private properties */
43    protected $conn;
44    protected $prop = array();
45    protected $fieldmap = array();
46
47    protected $filter = '';
48    protected $result = null;
49    protected $ldap_result = null;
50    protected $sort_col = '';
51    protected $mail_domain = '';
52    protected $debug = false;
53
54    private $base_dn = '';
55    private $groups_base_dn = '';
56    private $group_url = null;
57    private $group_members = array();
58    private $cache;
59
60    private $vlv_active = false;
61    private $vlv_count = 0;
62
63
64    /**
65    * Object constructor
66    *
67    * @param array      LDAP connection properties
68    * @param boolean    Enables debug mode
69    * @param string     Current user mail domain name
70    * @param integer User-ID
71    */
72    function __construct($p, $debug=false, $mail_domain=NULL)
73    {
74        $this->prop = $p;
75
76        if (isset($p['searchonly']))
77            $this->searchonly = $p['searchonly'];
78
79        // check if groups are configured
80        if (is_array($p['groups']) && count($p['groups'])) {
81            $this->groups = true;
82            // set member field
83            if (!empty($p['groups']['member_attr']))
84                $this->prop['member_attr'] = strtolower($p['groups']['member_attr']);
85            else if (empty($p['member_attr']))
86                $this->prop['member_attr'] = 'member';
87            // set default name attribute to cn
88            if (empty($this->prop['groups']['name_attr']))
89                $this->prop['groups']['name_attr'] = 'cn';
90        }
91
92        // fieldmap property is given
93        if (is_array($p['fieldmap'])) {
94            foreach ($p['fieldmap'] as $rf => $lf)
95                $this->fieldmap[$rf] = $this->_attr_name(strtolower($lf));
96        }
97        else {
98            // read deprecated *_field properties to remain backwards compatible
99            foreach ($p as $prop => $value)
100                if (preg_match('/^(.+)_field$/', $prop, $matches))
101                    $this->fieldmap[$matches[1]] = $this->_attr_name(strtolower($value));
102        }
103
104        // use fieldmap to advertise supported coltypes to the application
105        foreach ($this->fieldmap as $col => $lf) {
106            list($col, $type) = explode(':', $col);
107            if (!is_array($this->coltypes[$col])) {
108                $subtypes = $type ? array($type) : null;
109                $this->coltypes[$col] = array('limit' => 2, 'subtypes' => $subtypes);
110            }
111            elseif ($type) {
112                $this->coltypes[$col]['subtypes'][] = $type;
113                $this->coltypes[$col]['limit']++;
114            }
115            if ($type && !$this->fieldmap[$col])
116                $this->fieldmap[$col] = $lf;
117        }
118
119        if ($this->fieldmap['street'] && $this->fieldmap['locality'])
120            $this->coltypes['address'] = array('limit' => 1);
121        else if ($this->coltypes['address'])
122            $this->coltypes['address'] = array('type' => 'textarea', 'childs' => null, 'limit' => 1, 'size' => 40);
123
124        // make sure 'required_fields' is an array
125        if (!is_array($this->prop['required_fields']))
126            $this->prop['required_fields'] = (array) $this->prop['required_fields'];
127
128        foreach ($this->prop['required_fields'] as $key => $val)
129            $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
130
131        $this->sort_col    = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
132        $this->debug       = $debug;
133        $this->mail_domain = $mail_domain;
134
135        // initialize cache
136        $rcmail = rcmail::get_instance();
137        $this->cache = $rcmail->get_cache('LDAP.' . asciiwords($this->prop['name']), 'db', 600);
138        $this->cache->expunge();
139
140        $this->_connect();
141    }
142
143
144    /**
145    * Establish a connection to the LDAP server
146    */
147    private function _connect()
148    {
149        global $RCMAIL;
150
151        if (!function_exists('ldap_connect'))
152            raise_error(array('code' => 100, 'type' => 'ldap',
153                'file' => __FILE__, 'line' => __LINE__,
154                'message' => "No ldap support in this installation of PHP"),
155                true, true);
156
157        if (is_resource($this->conn))
158            return true;
159
160        if (!is_array($this->prop['hosts']))
161            $this->prop['hosts'] = array($this->prop['hosts']);
162
163        if (empty($this->prop['ldap_version']))
164            $this->prop['ldap_version'] = 3;
165
166        foreach ($this->prop['hosts'] as $host)
167        {
168            $host = idn_to_ascii(rcube_parse_host($host));
169            $this->_debug("C: Connect [$host".($this->prop['port'] ? ':'.$this->prop['port'] : '')."]");
170
171            if ($lc = @ldap_connect($host, $this->prop['port']))
172            {
173                if ($this->prop['use_tls']===true)
174                    if (!ldap_start_tls($lc))
175                        continue;
176
177                $this->_debug("S: OK");
178
179                ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
180                $this->prop['host'] = $host;
181                $this->conn = $lc;
182                break;
183            }
184            $this->_debug("S: NOT OK");
185        }
186
187        if (is_resource($this->conn))
188        {
189            $this->ready = true;
190
191            $bind_pass = $this->prop['bind_pass'];
192            $bind_user = $this->prop['bind_user'];
193            $bind_dn   = $this->prop['bind_dn'];
194
195            $this->base_dn        = $this->prop['base_dn'];
196            $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
197                $this->prop['groups']['base_dn'] : $this->base_dn;
198
199            // User specific access, generate the proper values to use.
200            if ($this->prop['user_specific']) {
201                // No password set, use the session password
202                if (empty($bind_pass)) {
203                    $bind_pass = $RCMAIL->decrypt($_SESSION['password']);
204                }
205
206                // Get the pieces needed for variable replacement.
207                if ($fu = $RCMAIL->user->get_username())
208                  list($u, $d) = explode('@', $fu);
209                else
210                  $d = $this->mail_domain;
211
212                $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
213
214                $replaces = array('%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
215
216                if ($this->prop['search_base_dn'] && $this->prop['search_filter']) {
217                    // Search for the dn to use to authenticate
218                    $this->prop['search_base_dn'] = strtr($this->prop['search_base_dn'], $replaces);
219                    $this->prop['search_filter'] = strtr($this->prop['search_filter'], $replaces);
220
221                    $this->_debug("S: searching with base {$this->prop['search_base_dn']} for {$this->prop['search_filter']}");
222
223                    $res = @ldap_search($this->conn, $this->prop['search_base_dn'], $this->prop['search_filter'], array('uid'));
224                    if ($res && ($entry = ldap_first_entry($this->conn, $res))) {
225                        $bind_dn = ldap_get_dn($this->conn, $entry);
226
227                        $this->_debug("S: search returned dn: $bind_dn");
228
229                        if ($bind_dn) {
230                            $dn = ldap_explode_dn($bind_dn, 1);
231                            $replaces['%dn'] = $dn[0];
232                        }
233                    }
234                }
235                // Replace the bind_dn and base_dn variables.
236                $bind_dn              = strtr($bind_dn, $replaces);
237                $this->base_dn        = strtr($this->base_dn, $replaces);
238                $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
239
240                if (empty($bind_user)) {
241                    $bind_user = $u;
242                }
243            }
244
245            if (!empty($bind_pass)) {
246                if (!empty($bind_dn)) {
247                    $this->ready = $this->bind($bind_dn, $bind_pass);
248                }
249                else if (!empty($this->prop['auth_cid'])) {
250                    $this->ready = $this->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
251                }
252                else {
253                    $this->ready = $this->sasl_bind($bind_user, $bind_pass);
254                }
255            }
256        }
257        else
258            raise_error(array('code' => 100, 'type' => 'ldap',
259                'file' => __FILE__, 'line' => __LINE__,
260                'message' => "Could not connect to any LDAP server, last tried $host:{$this->prop[port]}"), true);
261
262        // See if the directory is writeable.
263        if ($this->prop['writable']) {
264            $this->readonly = false;
265        } // end if
266    }
267
268
269    /**
270     * Bind connection with (SASL-) user and password
271     *
272     * @param string $authc Authentication user
273     * @param string $pass  Bind password
274     * @param string $authz Autorization user
275     *
276     * @return boolean True on success, False on error
277     */
278    public function sasl_bind($authc, $pass, $authz=null)
279    {
280        if (!$this->conn) {
281            return false;
282        }
283
284        if (!function_exists('ldap_sasl_bind')) {
285            raise_error(array('code' => 100, 'type' => 'ldap',
286                'file' => __FILE__, 'line' => __LINE__,
287                'message' => "Unable to bind: ldap_sasl_bind() not exists"),
288                true, true);
289        }
290
291        if (!empty($authz)) {
292            $authz = 'u:' . $authz;
293        }
294
295        if (!empty($this->prop['auth_method'])) {
296            $method = $this->prop['auth_method'];
297        }
298        else {
299            $method = 'DIGEST-MD5';
300        }
301
302        $this->_debug("C: Bind [mech: $method, authc: $authc, authz: $authz] [pass: $pass]");
303
304        if (ldap_sasl_bind($this->conn, NULL, $pass, $method, NULL, $authc, $authz)) {
305            $this->_debug("S: OK");
306            return true;
307        }
308
309        $this->_debug("S: ".ldap_error($this->conn));
310
311        raise_error(array(
312            'code' => ldap_errno($this->conn), 'type' => 'ldap',
313            'file' => __FILE__, 'line' => __LINE__,
314            'message' => "Bind failed for authcid=$authc ".ldap_error($this->conn)),
315            true);
316
317        return false;
318    }
319
320
321    /**
322     * Bind connection with DN and password
323     *
324     * @param string Bind DN
325     * @param string Bind password
326     *
327     * @return boolean True on success, False on error
328     */
329    public function bind($dn, $pass)
330    {
331        if (!$this->conn) {
332            return false;
333        }
334
335        $this->_debug("C: Bind [dn: $dn] [pass: $pass]");
336
337        if (@ldap_bind($this->conn, $dn, $pass)) {
338            $this->_debug("S: OK");
339            return true;
340        }
341
342        $this->_debug("S: ".ldap_error($this->conn));
343
344        raise_error(array(
345            'code' => ldap_errno($this->conn), 'type' => 'ldap',
346            'file' => __FILE__, 'line' => __LINE__,
347            'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
348            true);
349
350        return false;
351    }
352
353
354    /**
355     * Close connection to LDAP server
356     */
357    function close()
358    {
359        if ($this->conn)
360        {
361            $this->_debug("C: Close");
362            ldap_unbind($this->conn);
363            $this->conn = null;
364        }
365    }
366
367
368    /**
369     * Returns address book name
370     *
371     * @return string Address book name
372     */
373    function get_name()
374    {
375        return $this->prop['name'];
376    }
377
378
379    /**
380     * Set internal list page
381     *
382     * @param number $page Page number to list
383     */
384    function set_page($page)
385    {
386        $this->list_page = (int)$page;
387    }
388
389
390    /**
391     * Set internal page size
392     *
393     * @param number $size Number of messages to display on one page
394     */
395    function set_pagesize($size)
396    {
397        $this->page_size = (int)$size;
398    }
399
400
401    /**
402     * Save a search string for future listings
403     *
404     * @param string $filter Filter string
405     */
406    function set_search_set($filter)
407    {
408        $this->filter = $filter;
409    }
410
411
412    /**
413     * Getter for saved search properties
414     *
415     * @return mixed Search properties used by this class
416     */
417    function get_search_set()
418    {
419        return $this->filter;
420    }
421
422
423    /**
424     * Reset all saved results and search parameters
425     */
426    function reset()
427    {
428        $this->result = null;
429        $this->ldap_result = null;
430        $this->filter = '';
431    }
432
433
434    /**
435     * List the current set of contact records
436     *
437     * @param  array  List of cols to show
438     * @param  int    Only return this number of records
439     *
440     * @return array  Indexed list of contact records, each a hash array
441     */
442    function list_records($cols=null, $subset=0)
443    {
444        if ($this->prop['searchonly'] && empty($this->filter) && !$this->group_id)
445        {
446            $this->result = new rcube_result_set(0);
447            $this->result->searchonly = true;
448            return $this->result;
449        }
450
451        // add general filter to query
452        if (!empty($this->prop['filter']) && empty($this->filter))
453        {
454            $filter = $this->prop['filter'];
455            $this->set_search_set($filter);
456        }
457
458        // query URL is given by the selected group
459        if ($this->group_id && $this->group_url)
460        {
461            // extract components from url
462            if (preg_match('!ldap:///([^\?]+)\?\?(\w+)\?(.*)$!', $this->group_url, $m))
463            {
464                $this->base_dn = $m[1];
465                $this->prop['scope'] = $m[2];
466                $this->filter = $m[3];
467            }
468        }
469
470        // exec LDAP search if no result resource is stored
471        if ($this->conn && !$this->ldap_result)
472            $this->_exec_search();
473
474        // count contacts for this user
475        $this->result = $this->count();
476
477        // we have a search result resource
478        if ($this->ldap_result && $this->result->count > 0)
479        {
480            // sorting still on the ldap server
481            if ($this->sort_col && $this->prop['scope'] !== 'base' && !$this->vlv_active)
482                ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
483
484            // start and end of the page
485            $start_row = $this->vlv_active ? 0 : $this->result->first;
486            $start_row = $subset < 0 ? $start_row + $this->page_size + $subset : $start_row;
487            $last_row = $this->result->first + $this->page_size;
488            $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
489
490            // get all entries from the ldap server
491            $entries = ldap_get_entries($this->conn, $this->ldap_result);
492
493            // filtering for group members
494            if ($this->groups && $this->group_id && !$this->group_url)
495            {
496                $count = 0;
497                $members = array();
498                foreach ($entries as $entry)
499                {
500                    if ($this->group_members[self::dn_encode($entry['dn'])])
501                    {
502                        $members[] = $entry;
503                        $count++;
504                    }
505                }
506                $entries = $members;
507                $entries['count'] = $count;
508                $this->result->count = $count;
509            }
510
511            // filter entries for this page
512            for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
513                $this->result->add($this->_ldap2result($entries[$i]));
514        }
515        return $this->result;
516    }
517
518
519    /**
520     * Search contacts
521     *
522     * @param mixed   $fields   The field name of array of field names to search in
523     * @param mixed   $value    Search value (or array of values when $fields is array)
524     * @param boolean $strict   True for strict, False for partial (fuzzy) matching
525     * @param boolean $select   True if results are requested, False if count only
526     * @param boolean $nocount  (Not used)
527     * @param array   $required List of fields that cannot be empty
528     *
529     * @return array  Indexed list of contact records and 'count' value
530     */
531    function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
532    {
533        // special treatment for ID-based search
534        if ($fields == 'ID' || $fields == $this->primary_key)
535        {
536            $ids = !is_array($value) ? explode(',', $value) : $value;
537            $result = new rcube_result_set();
538            foreach ($ids as $id)
539            {
540                if ($rec = $this->get_record($id, true))
541                {
542                    $result->add($rec);
543                    $result->count++;
544                }
545            }
546            return $result;
547        }
548
549        // use AND operator for advanced searches
550        $filter = is_array($value) ? '(&' : '(|';
551        $wc     = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
552
553        if ($fields == '*')
554        {
555            // search_fields are required for fulltext search
556            if (empty($this->prop['search_fields']))
557            {
558                $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
559                $this->result = new rcube_result_set();
560                return $this->result;
561            }
562            if (is_array($this->prop['search_fields']))
563            {
564                foreach ($this->prop['search_fields'] as $field) {
565                    $filter .= "($field=$wc" . $this->_quote_string($value) . "$wc)";
566                }
567            }
568        }
569        else
570        {
571            foreach ((array)$fields as $idx => $field) {
572                $val = is_array($value) ? $value[$idx] : $value;
573                if ($f = $this->_map_field($field)) {
574                    $filter .= "($f=$wc" . $this->_quote_string($val) . "$wc)";
575                }
576            }
577        }
578        $filter .= ')';
579
580        // add required (non empty) fields filter
581        $req_filter = '';
582        foreach ((array)$required as $field)
583            if ($f = $this->_map_field($field))
584                $req_filter .= "($f=*)";
585
586        if (!empty($req_filter))
587            $filter = '(&' . $req_filter . $filter . ')';
588
589        // avoid double-wildcard if $value is empty
590        $filter = preg_replace('/\*+/', '*', $filter);
591
592        // add general filter to query
593        if (!empty($this->prop['filter']))
594            $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
595
596        // set filter string and execute search
597        $this->set_search_set($filter);
598        $this->_exec_search();
599
600        if ($select)
601            $this->list_records();
602        else
603            $this->result = $this->count();
604
605        return $this->result;
606    }
607
608
609    /**
610     * Count number of available contacts in database
611     *
612     * @return object rcube_result_set Resultset with values for 'count' and 'first'
613     */
614    function count()
615    {
616        $count = 0;
617        if ($this->conn && $this->ldap_result) {
618            $count = $this->vlv_active ? $this->vlv_count : ldap_count_entries($this->conn, $this->ldap_result);
619        } // end if
620        elseif ($this->conn) {
621            // We have a connection but no result set, attempt to get one.
622            if (empty($this->filter)) {
623                // The filter is not set, set it.
624                $this->filter = $this->prop['filter'];
625            } // end if
626            $this->_exec_search(true);
627            if ($this->ldap_result) {
628                $count = ldap_count_entries($this->conn, $this->ldap_result);
629            } // end if
630        } // end else
631
632        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
633    }
634
635
636    /**
637     * Return the last result set
638     *
639     * @return object rcube_result_set Current resultset or NULL if nothing selected yet
640     */
641    function get_result()
642    {
643        return $this->result;
644    }
645
646
647    /**
648     * Get a specific contact record
649     *
650     * @param mixed   Record identifier
651     * @param boolean Return as associative array
652     *
653     * @return mixed  Hash array or rcube_result_set with all record fields
654     */
655    function get_record($dn, $assoc=false)
656    {
657        $res = null;
658        if ($this->conn && $dn)
659        {
660            $dn = self::dn_decode($dn);
661
662            $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
663
664            if ($this->ldap_result = @ldap_read($this->conn, $dn, '(objectclass=*)', array_values($this->fieldmap)))
665                $entry = ldap_first_entry($this->conn, $this->ldap_result);
666            else
667                $this->_debug("S: ".ldap_error($this->conn));
668
669            if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
670            {
671                $this->_debug("S: OK"/* . print_r($rec, true)*/);
672
673                $rec = array_change_key_case($rec, CASE_LOWER);
674
675                // Add in the dn for the entry.
676                $rec['dn'] = $dn;
677                $res = $this->_ldap2result($rec);
678                $this->result = new rcube_result_set(1);
679                $this->result->add($res);
680            }
681        }
682
683        return $assoc ? $res : $this->result;
684    }
685
686
687    /**
688     * Check the given data before saving.
689     * If input not valid, the message to display can be fetched using get_error()
690     *
691     * @param array Assoziative array with data to save
692     *
693     * @return boolean True if input is valid, False if not.
694     */
695    public function validate($save_data)
696    {
697        // check for name input
698        if (empty($save_data['name'])) {
699            $this->set_error('warning', 'nonamewarning');
700            return false;
701        }
702
703        // validate e-mail addresses
704        return parent::validate($save_data);
705    }
706
707
708    /**
709     * Create a new contact record
710     *
711     * @param array    Hash array with save data
712     *
713     * @return encoded record ID on success, False on error
714     */
715    function insert($save_cols)
716    {
717        // Map out the column names to their LDAP ones to build the new entry.
718        $newentry = array();
719        $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
720        foreach ($this->fieldmap as $col => $fld) {
721            $val = $save_cols[$col];
722            if (is_array($val))
723                $val = array_filter($val);  // remove empty entries
724            if ($fld && $val) {
725                // The field does exist, add it to the entry.
726                $newentry[$fld] = $val;
727            } // end if
728        } // end foreach
729
730        // Verify that the required fields are set.
731        $missing = null;
732        foreach ($this->prop['required_fields'] as $fld) {
733            if (!isset($newentry[$fld])) {
734                $missing[] = $fld;
735            }
736        }
737
738        // abort process if requiered fields are missing
739        // TODO: generate message saying which fields are missing
740        if ($missing) {
741            $this->set_error(self::ERROR_INCOMPLETE, 'formincomplete');
742            return false;
743        }
744
745        // Build the new entries DN.
746        $dn = $this->prop['LDAP_rdn'].'='.$this->_quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->base_dn;
747
748        $this->_debug("C: Add [dn: $dn]: ".print_r($newentry, true));
749
750        $res = ldap_add($this->conn, $dn, $newentry);
751        if ($res === FALSE) {
752            $this->_debug("S: ".ldap_error($this->conn));
753            $this->set_error(self::ERROR_SAVING, 'errorsaving');
754            return false;
755        } // end if
756
757        $this->_debug("S: OK");
758
759        $dn = self::dn_encode($dn);
760
761        // add new contact to the selected group
762        if ($this->groups)
763            $this->add_to_group($this->group_id, $dn);
764
765        return $dn;
766    }
767
768
769    /**
770     * Update a specific contact record
771     *
772     * @param mixed Record identifier
773     * @param array Hash array with save data
774     *
775     * @return boolean True on success, False on error
776     */
777    function update($id, $save_cols)
778    {
779        $record = $this->get_record($id, true);
780        $result = $this->get_result();
781        $record = $result->first();
782
783        $newdata = array();
784        $replacedata = array();
785        $deletedata = array();
786
787        // flatten composite fields in $record
788        if (is_array($record['address'])) {
789          foreach ($record['address'] as $i => $struct) {
790            foreach ($struct as $col => $val) {
791              $record[$col][$i] = $val;
792            }
793          }
794        }
795
796        foreach ($this->fieldmap as $col => $fld) {
797            $val = $save_cols[$col];
798            if ($fld) {
799                // remove empty array values
800                if (is_array($val))
801                    $val = array_filter($val);
802                // The field does exist compare it to the ldap record.
803                if ($record[$col] != $val) {
804                    // Changed, but find out how.
805                    if (!isset($record[$col])) {
806                        // Field was not set prior, need to add it.
807                        $newdata[$fld] = $val;
808                    } // end if
809                    elseif ($val == '') {
810                        // Field supplied is empty, verify that it is not required.
811                        if (!in_array($fld, $this->prop['required_fields'])) {
812                            // It is not, safe to clear.
813                            $deletedata[$fld] = $record[$col];
814                        } // end if
815                    } // end elseif
816                    else {
817                        // The data was modified, save it out.
818                        $replacedata[$fld] = $val;
819                    } // end else
820                } // end if
821            } // end if
822        } // end foreach
823
824        $dn = self::dn_decode($id);
825
826        // Update the entry as required.
827        if (!empty($deletedata)) {
828            // Delete the fields.
829            $this->_debug("C: Delete [dn: $dn]: ".print_r($deletedata, true));
830            if (!ldap_mod_del($this->conn, $dn, $deletedata)) {
831                $this->_debug("S: ".ldap_error($this->conn));
832                $this->set_error(self::ERROR_SAVING, 'errorsaving');
833                return false;
834            }
835            $this->_debug("S: OK");
836        } // end if
837
838        if (!empty($replacedata)) {
839            // Handle RDN change
840            if ($replacedata[$this->prop['LDAP_rdn']]) {
841                $newdn = $this->prop['LDAP_rdn'].'='
842                    .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true)
843                    .','.$this->base_dn;
844                if ($dn != $newdn) {
845                    $newrdn = $this->prop['LDAP_rdn'].'='
846                    .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true);
847                    unset($replacedata[$this->prop['LDAP_rdn']]);
848                }
849            }
850            // Replace the fields.
851            if (!empty($replacedata)) {
852                $this->_debug("C: Replace [dn: $dn]: ".print_r($replacedata, true));
853                if (!ldap_mod_replace($this->conn, $dn, $replacedata)) {
854                    $this->_debug("S: ".ldap_error($this->conn));
855                    return false;
856                }
857                $this->_debug("S: OK");
858            } // end if
859        } // end if
860
861        if (!empty($newdata)) {
862            // Add the fields.
863            $this->_debug("C: Add [dn: $dn]: ".print_r($newdata, true));
864            if (!ldap_mod_add($this->conn, $dn, $newdata)) {
865                $this->_debug("S: ".ldap_error($this->conn));
866                $this->set_error(self::ERROR_SAVING, 'errorsaving');
867                return false;
868            }
869            $this->_debug("S: OK");
870        } // end if
871
872        // Handle RDN change
873        if (!empty($newrdn)) {
874            $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
875            if (!ldap_rename($this->conn, $dn, $newrdn, NULL, TRUE)) {
876                $this->_debug("S: ".ldap_error($this->conn));
877                return false;
878            }
879            $this->_debug("S: OK");
880
881            $dn    = self::dn_encode($dn);
882            $newdn = self::dn_encode($newdn);
883
884            // change the group membership of the contact
885            if ($this->groups)
886            {
887                $group_ids = $this->get_record_groups($dn);
888                foreach ($group_ids as $group_id)
889                {
890                    $this->remove_from_group($group_id, $dn);
891                    $this->add_to_group($group_id, $newdn);
892                }
893            }
894
895            return $newdn;
896        }
897
898        return true;
899    }
900
901
902    /**
903     * Mark one or more contact records as deleted
904     *
905     * @param array   Record identifiers
906     * @param boolean Remove record(s) irreversible (unsupported)
907     *
908     * @return boolean True on success, False on error
909     */
910    function delete($ids, $force=true)
911    {
912        if (!is_array($ids)) {
913            // Not an array, break apart the encoded DNs.
914            $ids = explode(',', $ids);
915        } // end if
916
917        foreach ($ids as $id) {
918            $dn = self::dn_decode($id);
919            $this->_debug("C: Delete [dn: $dn]");
920            // Delete the record.
921            $res = ldap_delete($this->conn, $dn);
922            if ($res === FALSE) {
923                $this->_debug("S: ".ldap_error($this->conn));
924                $this->set_error(self::ERROR_SAVING, 'errorsaving');
925                return false;
926            } // end if
927            $this->_debug("S: OK");
928
929            // remove contact from all groups where he was member
930            if ($this->groups) {
931                $dn = self::dn_encode($dn);
932                $group_ids = $this->get_record_groups($dn);
933                foreach ($group_ids as $group_id) {
934                    $this->remove_from_group($group_id, $dn);
935                }
936            }
937        } // end foreach
938
939        return count($ids);
940    }
941
942
943    /**
944     * Execute the LDAP search based on the stored credentials
945     */
946    private function _exec_search($count = false)
947    {
948        if ($this->ready)
949        {
950            $filter = $this->filter ? $this->filter : '(objectclass=*)';
951            $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
952
953            $this->_debug("C: Search [$filter]");
954
955            // when using VLV, we get the total count by...
956            if (!$count && $function != 'ldap_read' && $this->prop['vlv'] && !$this->group_id) {
957                // ...either reading numSubOrdinates attribute
958                if ($this->prop['numsub_filter'] && ($result_count = @$function($this->conn, $this->base_dn, $this->prop['numsub_filter'], array('numSubOrdinates'), 0, 0, 0))) {
959                    $counts = ldap_get_entries($this->conn, $result_count);
960                    for ($this->vlv_count = $j = 0; $j < $counts['count']; $j++)
961                        $this->vlv_count += $counts[$j]['numsubordinates'][0];
962                    $this->_debug("D: total numsubordinates = " . $this->vlv_count);
963                }
964                else  // ...or by fetching all records dn and count them
965                    $this->vlv_count = $this->_exec_search(true);
966
967                $this->vlv_active = $this->_vlv_set_controls();
968            }
969
970            // only fetch dn for count (should keep the payload low)
971            $attrs = $count ? array('dn') : array_values($this->fieldmap);
972            if ($this->ldap_result = @$function($this->conn, $this->base_dn, $filter,
973                $attrs, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit']))
974            {
975                $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
976                if ($err = ldap_errno($this->conn))
977                    $this->_debug("S: Error: " .ldap_err2str($err));
978                return true;
979            }
980            else
981            {
982                $this->_debug("S: ".ldap_error($this->conn));
983            }
984        }
985
986        return false;
987    }
988
989    /**
990     * Set server controls for Virtual List View (paginated listing)
991     */
992    private function _vlv_set_controls()
993    {
994        $sort_ctrl = array('oid' => "1.2.840.113556.1.4.473",  'value' => $this->_sort_ber_encode((array)$this->prop['sort']));
995        $vlv_ctrl  = array('oid' => "2.16.840.1.113730.3.4.9", 'value' => $this->_vlv_ber_encode(($offset = ($this->list_page-1) * $this->page_size + 1), $this->page_size), 'iscritical' => true);
996
997        $this->_debug("C: set controls sort=" . join(' ', unpack('H'.(strlen($sort_ctrl['value'])*2), $sort_ctrl['value'])) . " ({$this->sort_col});"
998            . " vlv=" . join(' ', (unpack('H'.(strlen($vlv_ctrl['value'])*2), $vlv_ctrl['value']))) . " ($offset)");
999
1000        if (!ldap_set_option($this->conn, LDAP_OPT_SERVER_CONTROLS, array($sort_ctrl, $vlv_ctrl))) {
1001            $this->_debug("S: ".ldap_error($this->conn));
1002            $this->set_error(self::ERROR_SEARCH, 'vlvnotsupported');
1003            return false;
1004        }
1005
1006        return true;
1007    }
1008
1009
1010    /**
1011     * Converts LDAP entry into an array
1012     */
1013    private function _ldap2result($rec)
1014    {
1015        $out = array();
1016
1017        if ($rec['dn'])
1018            $out[$this->primary_key] = self::dn_encode($rec['dn']);
1019
1020        foreach ($this->fieldmap as $rf => $lf)
1021        {
1022            for ($i=0; $i < $rec[$lf]['count']; $i++) {
1023                if (!($value = $rec[$lf][$i]))
1024                    continue;
1025                if ($rf == 'email' && $this->mail_domain && !strpos($value, '@'))
1026                    $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
1027                else if (in_array($rf, array('street','zipcode','locality','country','region')))
1028                    $out['address'][$i][$rf] = $value;
1029                else if ($rec[$lf]['count'] > 1)
1030                    $out[$rf][] = $value;
1031                else
1032                    $out[$rf] = $value;
1033            }
1034
1035            // Make sure name fields aren't arrays (#1488108)
1036            if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
1037                $out[$rf] = $out[$rf][0];
1038            }
1039        }
1040
1041        return $out;
1042    }
1043
1044
1045    /**
1046     * Return real field name (from fields map)
1047     */
1048    private function _map_field($field)
1049    {
1050        return $this->fieldmap[$field];
1051    }
1052
1053
1054    /**
1055     * Returns unified attribute name (resolving aliases)
1056     */
1057    private static function _attr_name($name)
1058    {
1059        // list of known attribute aliases
1060        $aliases = array(
1061            'gn' => 'givenname',
1062            'rfc822mailbox' => 'email',
1063            'userid' => 'uid',
1064            'emailaddress' => 'email',
1065            'pkcs9email' => 'email',
1066        );
1067        return isset($aliases[$name]) ? $aliases[$name] : $name;
1068    }
1069
1070
1071    /**
1072     * Prints debug info to the log
1073     */
1074    private function _debug($str)
1075    {
1076        if ($this->debug)
1077            write_log('ldap', $str);
1078    }
1079
1080
1081    /**
1082     * Quotes attribute value string
1083     *
1084     * @param string $str Attribute value
1085     * @param bool   $dn  True if the attribute is a DN
1086     *
1087     * @return string Quoted string
1088     */
1089    private static function _quote_string($str, $dn=false)
1090    {
1091        // take firt entry if array given
1092        if (is_array($str))
1093            $str = reset($str);
1094
1095        if ($dn)
1096            $replace = array(','=>'\2c', '='=>'\3d', '+'=>'\2b', '<'=>'\3c',
1097                '>'=>'\3e', ';'=>'\3b', '\\'=>'\5c', '"'=>'\22', '#'=>'\23');
1098        else
1099            $replace = array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c',
1100                '/'=>'\2f');
1101
1102        return strtr($str, $replace);
1103    }
1104
1105
1106    /**
1107     * Setter for the current group
1108     * (empty, has to be re-implemented by extending class)
1109     */
1110    function set_group($group_id)
1111    {
1112        if ($group_id)
1113        {
1114            if (!($group_cache = $this->cache->get('groups')))
1115                $group_cache = $this->list_groups();
1116
1117            $cache_members = $group_cache[$group_id]['members'];
1118
1119            $members = array();
1120            for ($i=0; $i<$cache_members["count"]; $i++)
1121            {
1122                if (!empty($cache_members[$i]))
1123                    $members[self::dn_encode($cache_members[$i])] = 1;
1124            }
1125            $this->group_members = $members;
1126            $this->group_url = $group_cache[$group_id]['member_url'];
1127            $this->group_id = $group_id;
1128        }
1129        else
1130        {
1131            $this->group_id = 0;
1132            $this->group_url = null;
1133            $this->group_members = array();
1134        }
1135    }
1136
1137    /**
1138     * List all active contact groups of this source
1139     *
1140     * @param string  Optional search string to match group name
1141     * @return array  Indexed list of contact groups, each a hash array
1142     */
1143    function list_groups($search = null)
1144    {
1145        if (!$this->groups)
1146            return array();
1147
1148        $base_dn = $this->groups_base_dn;
1149        $filter = $this->prop['groups']['filter'];
1150        $name_attr = $this->prop['groups']['name_attr'];
1151
1152        $this->_debug("C: Search [$filter][dn: $base_dn]");
1153
1154        $res = @ldap_search($this->conn, $base_dn, $filter);
1155        if ($res === false)
1156        {
1157            $this->_debug("S: ".ldap_error($this->conn));
1158            return array();
1159        }
1160
1161        $ldap_data = ldap_get_entries($this->conn, $res);
1162        $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
1163
1164        $groups = array();
1165        $group_sortnames = array();
1166        for ($i=0; $i<$ldap_data["count"]; $i++)
1167        {
1168            $group_name = $ldap_data[$i][$name_attr][0];
1169            if (!$search || strstr(strtolower($group_name), strtolower($search)))
1170            {
1171                $group_id = self::dn_encode($group_name);
1172                $groups[$group_id]['ID'] = $group_id;
1173                $groups[$group_id]['name'] = $group_name;
1174
1175                // default behavior: check members attribute
1176                if ($this->prop['member_attr']) {
1177                    $groups[$group_id]['members'] = $ldap_data[$i][$this->prop['member_attr']];
1178                    $groups[$group_id]['member_attr'] = $this->prop['member_attr'];
1179                }
1180
1181                // check objectClass attributes of group and act accordingly
1182                for ($j=0; $j < $ldap_data[$i]['objectclass']['count']; $j++) {
1183                    switch (strtolower($ldap_data[$i]['objectclass'][$j])) {
1184                        case 'groupofnames':
1185                            $groups[$group_id]['members'] = $ldap_data[$i]['members'];
1186                            $groups[$group_id]['member_attr'] = 'member';
1187                            break;
1188
1189                        case 'groupofuniquenames':
1190                            $groups[$group_id]['members'] = $ldap_data[$i]['uniqueMember'];
1191                            $groups[$group_id]['member_attr'] = 'uniqueMember';
1192                            break;
1193
1194                        case 'groupofurls':
1195                            $groups[$group_id]['member_url'] = $ldap_data[$i]['memberurl'][0];
1196                            break;
1197                    }
1198                }
1199
1200                $group_sortnames[] = strtolower($group_name);
1201            }
1202        }
1203        array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
1204
1205        // cache this
1206        $this->cache->set('groups', $groups);
1207
1208        return $groups;
1209    }
1210
1211    /**
1212     * Create a contact group with the given name
1213     *
1214     * @param string The group name
1215     * @return mixed False on error, array with record props in success
1216     */
1217    function create_group($group_name)
1218    {
1219        $base_dn = $this->groups_base_dn;
1220        $new_dn = "cn=$group_name,$base_dn";
1221        $new_gid = self::dn_encode($group_name);
1222        $name_attr = $this->prop['groups']['name_attr'];
1223
1224        $new_entry = array(
1225            'objectClass' => $this->prop['groups']['object_classes'],
1226            $name_attr => $group_name,
1227        );
1228
1229        $this->_debug("C: Add [dn: $new_dn]: ".print_r($new_entry, true));
1230
1231        $res = ldap_add($this->conn, $new_dn, $new_entry);
1232        if ($res === false)
1233        {
1234            $this->_debug("S: ".ldap_error($this->conn));
1235            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1236            return false;
1237        }
1238
1239        $this->_debug("S: OK");
1240        $this->cache->remove('groups');
1241
1242        return array('id' => $new_gid, 'name' => $group_name);
1243    }
1244
1245    /**
1246     * Delete the given group and all linked group members
1247     *
1248     * @param string Group identifier
1249     * @return boolean True on success, false if no data was changed
1250     */
1251    function delete_group($group_id)
1252    {
1253        if (!($group_cache = $this->cache->get('groups')))
1254            $group_cache = $this->list_groups();
1255
1256        $base_dn = $this->groups_base_dn;
1257        $group_name = $group_cache[$group_id]['name'];
1258        $del_dn = "cn=$group_name,$base_dn";
1259
1260        $this->_debug("C: Delete [dn: $del_dn]");
1261
1262        $res = ldap_delete($this->conn, $del_dn);
1263        if ($res === false)
1264        {
1265            $this->_debug("S: ".ldap_error($this->conn));
1266            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1267            return false;
1268        }
1269
1270        $this->_debug("S: OK");
1271        $this->cache->remove('groups');
1272
1273        return true;
1274    }
1275
1276    /**
1277     * Rename a specific contact group
1278     *
1279     * @param string Group identifier
1280     * @param string New name to set for this group
1281     * @param string New group identifier (if changed, otherwise don't set)
1282     * @return boolean New name on success, false if no data was changed
1283     */
1284    function rename_group($group_id, $new_name, &$new_gid)
1285    {
1286        if (!($group_cache = $this->cache->get('groups')))
1287            $group_cache = $this->list_groups();
1288
1289        $base_dn = $this->groups_base_dn;
1290        $group_name = $group_cache[$group_id]['name'];
1291        $old_dn = "cn=$group_name,$base_dn";
1292        $new_rdn = "cn=$new_name";
1293        $new_gid = self::dn_encode($new_name);
1294
1295        $this->_debug("C: Rename [dn: $old_dn] [dn: $new_rdn]");
1296
1297        $res = ldap_rename($this->conn, $old_dn, $new_rdn, NULL, TRUE);
1298        if ($res === false)
1299        {
1300            $this->_debug("S: ".ldap_error($this->conn));
1301            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1302            return false;
1303        }
1304
1305        $this->_debug("S: OK");
1306        $this->cache->remove('groups');
1307
1308        return $new_name;
1309    }
1310
1311    /**
1312     * Add the given contact records the a certain group
1313     *
1314     * @param string  Group identifier
1315     * @param array   List of contact identifiers to be added
1316     * @return int    Number of contacts added
1317     */
1318    function add_to_group($group_id, $contact_ids)
1319    {
1320        if (!($group_cache = $this->cache->get('groups')))
1321            $group_cache = $this->list_groups();
1322
1323        $base_dn     = $this->groups_base_dn;
1324        $group_name  = $group_cache[$group_id]['name'];
1325        $member_attr = $group_cache[$group_id]['member_attr'];
1326        $group_dn    = "cn=$group_name,$base_dn";
1327
1328        $new_attrs = array();
1329        foreach (explode(",", $contact_ids) as $id)
1330            $new_attrs[$member_attr][] = self::dn_decode($id);
1331
1332        $this->_debug("C: Add [dn: $group_dn]: ".print_r($new_attrs, true));
1333
1334        $res = ldap_mod_add($this->conn, $group_dn, $new_attrs);
1335        if ($res === false)
1336        {
1337            $this->_debug("S: ".ldap_error($this->conn));
1338            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1339            return 0;
1340        }
1341
1342        $this->_debug("S: OK");
1343        $this->cache->remove('groups');
1344
1345        return count($new_attrs['member']);
1346    }
1347
1348    /**
1349     * Remove the given contact records from a certain group
1350     *
1351     * @param string  Group identifier
1352     * @param array   List of contact identifiers to be removed
1353     * @return int    Number of deleted group members
1354     */
1355    function remove_from_group($group_id, $contact_ids)
1356    {
1357        if (!($group_cache = $this->cache->get('groups')))
1358            $group_cache = $this->list_groups();
1359
1360        $base_dn     = $this->groups_base_dn;
1361        $group_name  = $group_cache[$group_id]['name'];
1362        $member_attr = $group_cache[$group_id]['member_attr'];
1363        $group_dn    = "cn=$group_name,$base_dn";
1364
1365        $del_attrs = array();
1366        foreach (explode(",", $contact_ids) as $id)
1367            $del_attrs[$member_attr][] = self::dn_decode($id);
1368
1369        $this->_debug("C: Delete [dn: $group_dn]: ".print_r($del_attrs, true));
1370
1371        $res = ldap_mod_del($this->conn, $group_dn, $del_attrs);
1372        if ($res === false)
1373        {
1374            $this->_debug("S: ".ldap_error($this->conn));
1375            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1376            return 0;
1377        }
1378
1379        $this->_debug("S: OK");
1380        $this->cache->remove('groups');
1381
1382        return count($del_attrs['member']);
1383    }
1384
1385    /**
1386     * Get group assignments of a specific contact record
1387     *
1388     * @param mixed Record identifier
1389     *
1390     * @return array List of assigned groups as ID=>Name pairs
1391     * @since 0.5-beta
1392     */
1393    function get_record_groups($contact_id)
1394    {
1395        if (!$this->groups)
1396            return array();
1397
1398        $base_dn     = $this->groups_base_dn;
1399        $contact_dn  = self::dn_decode($contact_id);
1400        $name_attr   = $this->prop['groups']['name_attr'];
1401        $member_attr = $this->prop['member_attr'];
1402        $add_filter  = '';
1403        if ($member_attr != 'member' && $member_attr != 'uniqueMember')
1404            $add_filter = "($member_attr=$contact_dn)";
1405        $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
1406
1407        $this->_debug("C: Search [$filter][dn: $base_dn]");
1408
1409        $res = @ldap_search($this->conn, $base_dn, $filter, array($name_attr));
1410        if ($res === false)
1411        {
1412            $this->_debug("S: ".ldap_error($this->conn));
1413            return array();
1414        }
1415        $ldap_data = ldap_get_entries($this->conn, $res);
1416        $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
1417
1418        $groups = array();
1419        for ($i=0; $i<$ldap_data["count"]; $i++)
1420        {
1421            $group_name = $ldap_data[$i][$name_attr][0];
1422            $group_id = self::dn_encode($group_name);
1423            $groups[$group_id] = $group_id;
1424        }
1425        return $groups;
1426    }
1427
1428
1429    /**
1430     * Generate BER encoded string for Virtual List View option
1431     *
1432     * @param integer List offset (first record)
1433     * @param integer Records per page
1434     * @return string BER encoded option value
1435     */
1436    private function _vlv_ber_encode($offset, $rpp)
1437    {
1438        # this string is ber-encoded, php will prefix this value with:
1439        # 04 (octet string) and 10 (length of 16 bytes)
1440        # the code behind this string is broken down as follows:
1441        # 30 = ber sequence with a length of 0e (14) bytes following
1442        # 20 = type integer (in two's complement form) with 2 bytes following (beforeCount): 01 00 (ie 0)
1443        # 20 = type integer (in two's complement form) with 2 bytes following (afterCount):  01 18 (ie 25-1=24)
1444        # a0 = type context-specific/constructed with a length of 06 (6) bytes following
1445        # 20 = type integer with 2 bytes following (offset): 01 01 (ie 1)
1446        # 20 = type integer with 2 bytes following (contentCount):  01 00
1447        # the following info was taken from the ISO/IEC 8825-1:2003 x.690 standard re: the
1448        # encoding of integer values (note: these values are in
1449        # two-complement form so since offset will never be negative bit 8 of the
1450        # leftmost octet should never by set to 1):
1451        # 8.3.2: If the contents octets of an integer value encoding consist
1452        # of more than one octet, then the bits of the first octet (rightmost) and bit 8
1453        # of the second (to the left of first octet) octet:
1454        # a) shall not all be ones; and
1455        # b) shall not all be zero
1456
1457        # construct the string from right to left
1458        $str = "020100"; # contentCount
1459
1460        $ber_val = self::_ber_encode_int($offset);  // returns encoded integer value in hex format
1461
1462        // calculate octet length of $ber_val
1463        $str = self::_ber_addseq($ber_val, '02') . $str;
1464
1465        // now compute length over $str
1466        $str = self::_ber_addseq($str, 'a0');
1467
1468        // now tack on records per page
1469        $str = sprintf("0201000201%02x", min(255, $rpp)-1) . $str;
1470
1471        // now tack on sequence identifier and length
1472        $str = self::_ber_addseq($str, '30');
1473
1474        return pack('H'.strlen($str), $str);
1475    }
1476
1477
1478    /**
1479     * create ber encoding for sort control
1480     *
1481     * @param array List of cols to sort by
1482     * @return string BER encoded option value
1483     */
1484    private function _sort_ber_encode($sortcols)
1485    {
1486        $str = '';
1487        foreach (array_reverse((array)$sortcols) as $col) {
1488            $ber_val = self::_string2hex($col);
1489
1490            # 30 = ber sequence with a length of octet value
1491            # 04 = octet string with a length of the ascii value
1492            $oct = self::_ber_addseq($ber_val, '04');
1493            $str = self::_ber_addseq($oct, '30') . $str;
1494        }
1495
1496        // now tack on sequence identifier and length
1497        $str = self::_ber_addseq($str, '30');
1498
1499        return pack('H'.strlen($str), $str);
1500    }
1501
1502    /**
1503     * Add BER sequence with correct length and the given identifier
1504     */
1505    private static function _ber_addseq($str, $identifier)
1506    {
1507        $len = dechex(strlen($str)/2);
1508        if (strlen($len) % 2 != 0)
1509            $len = '0'.$len;
1510
1511        return $identifier . $len . $str;
1512    }
1513
1514    /**
1515     * Returns BER encoded integer value in hex format
1516     */
1517    private static function _ber_encode_int($offset)
1518    {
1519        $val = dechex($offset);
1520        $prefix = '';
1521
1522        // check if bit 8 of high byte is 1
1523        if (preg_match('/^[89abcdef]/', $val))
1524            $prefix = '00';
1525
1526        if (strlen($val)%2 != 0)
1527            $prefix .= '0';
1528
1529        return $prefix . $val;
1530    }
1531
1532    /**
1533     * Returns ascii string encoded in hex
1534     */
1535    private static function _string2hex($str)
1536    {
1537        $hex = '';
1538        for ($i=0; $i < strlen($str); $i++)
1539            $hex .= dechex(ord($str[$i]));
1540        return $hex;
1541    }
1542
1543    /**
1544     * HTML-safe DN string encoding
1545     *
1546     * @param string $str DN string
1547     *
1548     * @return string Encoded HTML identifier string
1549     */
1550    static function dn_encode($str)
1551    {
1552        // @TODO: to make output string shorter we could probably
1553        //        remove dc=* items from it
1554        return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
1555    }
1556
1557    /**
1558     * Decodes DN string encoded with _dn_encode()
1559     *
1560     * @param string $str Encoded HTML identifier string
1561     *
1562     * @return string DN string
1563     */
1564    static function dn_decode($str)
1565    {
1566        $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
1567        return base64_decode($str);
1568    }
1569}
Note: See TracBrowser for help on using the repository browser.