File: ldap.php

package info (click to toggle)
turba2 2.0.2-1sarge1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,996 kB
  • ctags: 1,071
  • sloc: php: 4,725; xml: 617; sql: 136; makefile: 62; sh: 46; perl: 17
file content (645 lines) | stat: -rw-r--r-- 22,237 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
<?php
/**
 * Turba directory driver implementation for PHP's LDAP extension.
 *
 * $Horde: turba/lib/Driver/ldap.php,v 1.54.4.3 2005/02/09 03:40:27 chuck Exp $
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @author  Jon Parise <jon@csh.rit.edu>
 * @since   Turba 0.0.1
 * @package Turba
 */
class Turba_Driver_ldap extends Turba_Driver {

    /**
     * Handle for the current LDAP connection.
     *
     * @var resource $_ds
     */
    var $_ds = 0;

    /**
     * Net_LDAP schema object.
     *
     * @var Net_LDAP_Schema $_schema
     */
    var $_schema;

    /**
     * Constructs a new Turba LDAP driver object.
     *
     * @access private
     *
     * @param $params       Hash containing additional configuration parameters.
     */
    function Turba_Driver_ldap($params)
    {
        if (!extension_loaded('ldap')) {
            Horde::fatal(PEAR::raiseError(_("LDAP support is required but the LDAP module is not available or not loaded.")), __FILE__, __LINE__);
        }

        if (empty($params['server'])) {
            $params['server'] = 'localhost';
        }
        if (empty($params['port'])) {
            $params['port'] = 389;
        }
        if (empty($params['root'])) {
            $params['root'] = '';
        }
        if (empty($params['multiple_entry_separator'])) {
            $params['multiple_entry_separator'] = ', ';
        }
        if (empty($params['charset'])) {
            $params['charset'] = '';
        }

        parent::Turba_Driver($params);
    }

    function _init()
    {
        if (!($this->_ds = @ldap_connect($this->_params['server'], $this->_params['port']))) {
            return PEAR::raiseError(_("Connection failure"));
        }

        // Set the LDAP protocol version.
        if (!empty($this->_params['version'])) {
            @ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION, $this->_params['version']);
        }

        // Start TLS if we're using it.
        if (!empty($this->_params['tls'])) {
            if (!@ldap_start_tls($this->_ds)) {
                return PEAR::raiseError(sprintf(_("STARTTLS failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
            }
        }

        // Bind to the server.
        if (isset($this->_params['bind_dn']) &&
            isset($this->_params['bind_password'])) {
            if (!@ldap_bind($this->_ds, $this->_params['bind_dn'], $this->_params['bind_password'])) {
                return PEAR::raiseError(sprintf(_("Bind failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
            }
        } else if (!(@ldap_bind($this->_ds))) {
            return PEAR::raiseError(sprintf(_("Bind failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
        }

        return true;
    }

    /**
     * Searches the LDAP directory with the given criteria and returns
     * a filtered list of results. If no criteria are specified, all
     * records are returned.
     *
     * @param $criteria      Array containing the search criteria.
     * @param $fields        List of fields to return.
     *
     * @return array  Hash containing the search results.
     */
    function _search($criteria, $fields)
    {
        /* Build the LDAP filter. */
        $filter = '';
        if (count($criteria)) {
            foreach ($criteria as $key => $vals) {
                if ($key == 'OR') {
                    $filter .= '(|' . $this->_buildSearchQuery($vals) . ')';
                } elseif ($key == 'AND') {
                    $filter .= '(&' . $this->_buildSearchQuery($vals) . ')';
                }
            }
        } else {
            // Filter on objectclass.
            $filter = $this->_buildObjectclassFilter();
        }

        /* Add source-wide filters, which are _always_ AND-ed. */
        if (!empty($this->_params['filter'])) {
            $filter = '(&' . '(' . $this->_params['filter'] . ')' . $filter . ')';
        }

        /* Four11 (at least) doesn't seem to return 'cn' if you don't
         * ask for 'sn' as well. Add 'sn' implicitly. */
        $attr = $fields;
        if (!in_array('sn', $attr)) {
            $attr[] = 'sn';
        }

        /* Add a sizelimit, if specified. Default is 0, which means no
         * limit.  Note: You cannot override a server-side limit with
         * this. */
        $sizelimit = 0;
        if (!empty($this->_params['sizelimit'])) {
            $sizelimit = $this->_params['sizelimit'];
        }

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('LDAP query by Turba_Driver_ldap::_search(): user = %s, root = %s (%s); filter = "%s"; attributes = "%s"; sizelimit = %d',
                                  Auth::getAuth(), $this->_params['root'], $this->_params['server'], $filter, implode(', ', $attr), $sizelimit),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Send the query to the LDAP server and fetch the matching
         * entries. */
        if (!($res = @ldap_search($this->_ds, $this->_params['root'], $filter, $attr, 0, $sizelimit))) {
            return PEAR::raiseError(sprintf(_("Query failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
        }

        return $this->_getResults($fields, $res);
    }

    /**
     * Reads the LDAP directory for a given element and returns
     * the result's fields.
     *
     * @param string $criteria  Search criteria (must be 'dn').
     * @param mixed  $dn        The dn of the object to read.
     * @param array  $fields    List of fields to return.
     *
     * @return array  Hash containing the search results.
     */
    function _read($criteria, $dn, $fields)
    {
        /* Only DN. */
        if ($criteria != 'dn') {
            return array();
        }

        $filter = $this->_buildObjectclassFilter();

        /* Four11 (at least) doesn't seem to return 'cn' if you don't
         * ask for 'sn' as well. Add 'sn' implicitly. */
        $attr = $fields;
        if (!in_array('sn', $attr)) {
            $attr[] = 'sn';
        }

        /* Handle a request for multiple records. */
        if (is_array($dn)) {
            $results = array();
            foreach ($dn as $d) {
                $res = @ldap_read($this->_ds, $d, $filter, $attr);
                if ($res) {
                    if (!is_a($result = $this->_getResults($fields, $res), 'PEAR_Error')) {
                        $results += $result;
                    } else {
                        return $result;
                    }
                } else {
                    return PEAR::raiseError(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
                }
            }
            return $results;
        }

        $res = @ldap_read($this->_ds, $dn, $filter, $attr);
        if (!$res) {
            return PEAR::raiseError(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
        }

        return $this->_getResults($fields, $res);
    }

    /**
     * Adds the specified entry to the LDAP directory.
     *
     * @param array $attributes  The initial attributes for the new object.
     */
    function _add($attributes)
    {
        if (empty($attributes['dn'])) {
            return PEAR::raiseError('Tried to add an object with no dn: [' . serialize($attributes) . '].');
        } elseif (empty($this->_params['objectclass'])) {
            return PEAR::raiseError('Tried to add an object with no objectclass: [' . serialize($attributes) . '].');
        }

        // Take the DN out of the attributes array
        $dn = $attributes['dn'];
        unset($attributes['dn']);

        // Put the Objectclass into the attributes array
        if (!is_array($this->_params['objectclass'])) {
            $attributes['objectclass'] = $this->_params['objectclass'];
        } else {
            $i = 0;
            foreach ($this->_params['objectclass'] as $objectclass) {
                $attributes['objectclass'][$i] = $objectclass;
                $i++;
            }
        }

        // Don't add empty attributes.
        $attributes = array_filter($attributes, array($this, '_emptyAttributeFilter'));

        // if a required attribute doesn't exist, add a dummy value.
        if (!empty($this->_params['checkrequired'])) {

            $required = $this->_checkRequiredAttributes($this->_params['objectclass']);
            if (is_a($required, 'PEAR_Error')) {
                return $required;
            }

            foreach ($required as $k => $v) {
                if (!isset($attributes[$v])) {
                    $attributes[$v] = $this->_params['checkrequired_string'];
                }
            }
        }

        // Encode entries.
        foreach ($attributes as $key => $val) {
            if (!is_array($val)) {
                $attributes[$key] = String::convertCharset($val, NLS::getCharset(), $this->_params['charset']);
            }
        }

        if (!@ldap_add($this->_ds, $dn, $attributes)) {
            return PEAR::raiseError('Failed to add an object: [' . ldap_errno($this->_ds) . '] "' . ldap_error($this->_ds) . '" (attributes: [' . serialize($attributes) . ']).' . "Charset:" . NLS::getCharset());
        } else {
            return true;
        }
    }

    /**
     * Deletes the specified entry from the LDAP directory.
     */
    function _delete($object_key, $object_id)
    {
        if ($object_key != 'dn') {
            return PEAR::raiseError(_("Invalid key specified."));
        }

        if (!@ldap_delete($this->_ds, $object_id)) {
            return PEAR::raiseError(sprintf(_("Delete failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
        } else {
            return true;
        }
    }

    /**
     * Modifies the specified entry in the LDAP directory.
     *
     * @return string  The object id, possibly updated.
     */
    function _save($object_key, $object_id, $attributes)
    {
        // Get the old entry so that we can access the old
        // values. These are needed so that we can delete any
        // attributes that have been removed by using ldap_mod_del.
        $filter = $this->_buildObjectclassFilter();
        $oldres = @ldap_read($this->_ds, $object_id, $filter, array_keys($attributes));
        $info = ldap_get_attributes($this->_ds, ldap_first_entry($this->_ds, $oldres));

        // Check if we need to rename the object.
        if ($this->_params['version'] == 3 &&
            String::lower($this->_makeKey($attributes)) != String::lower($object_id)) {
            if (isset($this->_params['dn']) && is_array($this->_params['dn']) && count($this->_params['dn'])) {
                $pairs = array();
                foreach ($this->_params['dn'] as $param) {
                    if (isset($attributes[$param])) {
                        $pairs[] = array($param, $attributes[$param]);
                    }
                }
                $newrdn = $this->_quoteDN($pairs);
            } else {
                return PEAR::raiseError(_("Missing DN in LDAP source configuration."));
            }

            if (ldap_rename($this->_ds, $object_id, $newrdn, $this->_params['root'], true)) {
                $object_id = $newrdn . ',' . $this->_params['root'];
            } else {
                return PEAR::raiseError(sprintf(_("Failed to change name: (%s) %s; Old DN = %s, New DN = %s, Root = %s"),
                                                ldap_errno($this->_ds), ldap_error($this->_ds), $object_id, $newrdn, $this->_params['root']));
            }
        }

        // The attributes in the attributes array are all lower case
        // while they are mixedCase in the search result. So convert
        // the keys to lower.
        $info = array_change_key_case($info, CASE_LOWER);

        foreach ($info as $key => $value) {
            $var = $info[$key];
            $oldval = null;

            // Check to see if the old value and the new value are
            // different and that the new value is empty. If so then
            // we use ldap_mod_del to delete the attribute.
            if (isset($attributes[$key]) &&
                ($var[0] != $attributes[$key]) &&
                $attributes[$key] == '') {

                $oldval[$key] = $var[0];
                if (!@ldap_mod_del($this->_ds, $object_id, $oldval)) {
                    return PEAR::raiseError(sprintf(_("Modify failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
                }
                unset($attributes[$key]);
            }
        }

        // Encode entries.
        foreach ($attributes as $key => $val) {
            if (!is_array($val)) {
                $attributes[$key] = String::convertCharset($val, NLS::getCharset(), $this->_params['charset']);
            }
        }

        unset($attributes[$object_key]);
        $attributes = array_filter($attributes, array($this, '_emptyAttributeFilter'));

        if (!@ldap_modify($this->_ds, $object_id, $attributes)) {
            return PEAR::raiseError(sprintf(_("Modify failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
        } else {
            return $object_id;
        }
    }

    /**
     * Build a DN based on a set of attributes and what attributes
     * make a DN for the current source.
     *
     * @param array $attributes The attributes (in driver keys) of the
     *                          object being added.
     *
     * @return string  The DN for the new object.
     */
    function _makeKey($attributes)
    {
        $dn = '';
        if (is_array($this->_params['dn'])) {
            foreach ($this->_params['dn'] as $param) {
                if (isset($attributes[$param])) {
                    $dn .= $param . '=' . $attributes[$param] . ',';
                }
            }
        }

        $dn .= $this->_params['root'];
        return $dn;
    }

    /**
     * Build a piece of a search query.
     *
     * @param array  $criteria  The array of criteria.
     *
     * @return string  An LDAP query fragment.
     */
    function _buildSearchQuery($criteria)
    {
        require_once 'Horde/LDAP.php';

        $clause = '';
        foreach ($criteria as $key => $vals) {
            if (!empty($vals['OR'])) {
                $clause .= '(|' . $this->_buildSearchQuery($vals) . ')';
            } elseif (!empty($vals['AND'])) {
                $clause .= '(&' . $this->_buildSearchQuery($vals) . ')';
            } else {
                if (isset($vals['field'])) {
                    $rhs = String::convertCharset($vals['test'], NLS::getCharset(), $this->_params['charset']);
                    $clause .= Horde_LDAP::buildClause($vals['field'], $vals['op'], $rhs);
                } else {
                    foreach ($vals as $test) {
                        if (!empty($test['OR'])) {
                            $clause .= '(|' . $this->_buildSearchQuery($test) . ')';
                        } elseif (!empty($test['AND'])) {
                            $clause .= '(&' . $this->_buildSearchQuery($test) . ')';
                        } else {
                            $rhs = String::convertCharset($test['test'], NLS::getCharset(), $this->_params['charset']);
                            $clause .= Horde_LDAP::buildClause($test['field'], $test['op'], $rhs);
                        }
                    }
                }
            }
        }

        return $clause;
    }

    /**
     * Get some results from a result identifier and clean them up.
     *
     * @param array    $fields  List of fields to return.
     * @param resource $res     Result identifier.
     *
     * @return array  Hash containing the results.
     */
    function _getResults($fields, $res)
    {
        if (!($entries = @ldap_get_entries($this->_ds, $res))) {
            return PEAR::raiseError(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
        }

        /* Return only the requested fields (from $fields, above). */
        $results = array();
        for ($i = 0; $i < $entries['count']; $i++) {
            $entry = $entries[$i];
            $result = array();

            foreach ($fields as $field) {
                $field_l = String::lower($field);
                if ($field == 'dn') {
                    $result[$field] = $entry[$field_l];
                } else {
                    $result[$field] = '';
                    if (!empty($entry[$field_l])) {
                        for ($j = 0; $j < $entry[$field_l]['count']; $j++) {
                            if (!empty($result[$field])) {
                                $result[$field] .= $this->_params['multiple_entry_separator'];
                            }
                            $result[$field] .= String::convertCharset($entry[$field_l][$j], $this->_params['charset']);
                        }
                    }
                }
            }

            $results[] = $result;
        }

        return $results;
    }

    /**
     * Remove empty attributes from attributes array
     *
     * @param mixed $val    Value from attributes array.
     * @return bool         Boolean used by array_filter.
     */
    function _emptyAttributeFilter($var)
    {
        if (!is_array($var)) {
            return ($var != '');
        } else {
            foreach ($var as $v) {
                if ($v == '') {
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * Build an LDAP filter based on the objectclass parameter.
     *
     * @return string An LDAP filter.
     */
    function _buildObjectclassFilter()
    {
        $filter = '';
        if (!empty($this->_params['objectclass'])) {
            if (!is_array($this->_params['objectclass'])) {
                $filter = '(objectclass=' . $this->_params['objectclass'] . ')';
            } else {
                $filter = '(|';
                foreach ($this->_params['objectclass'] as $objectclass) {
                    $filter .= '(objectclass=' . $objectclass . ')';
                }
                $filter .= ')';
            }
        }
        return $filter;
    }

    /**
     * Returns a list of required attributes.
     *
     * @access private
     *
     * @param array $objectclasses  List of objectclasses that should be
     *                              checked for required attributes.
     *
     * @return array  List of attribute names of the specified objectclasses
     *                that have been configured as being required.
     */
    function _checkRequiredAttributes($objectclasses)
    {
       require_once 'Net/LDAP.php';

       $config = array('host' => $this->_params['server'],
                       'port' => $this->_params['port']);

       $retval = array();

       $ldap = &new Net_LDAP($config);
       $ldap->_link = $this->_ds;

       if (!is_object($this->_schema)) {
           $this->_schema = &$ldap->schema();
       }

       if (is_a($this->_schema, 'PEAR_Error')) {
           return $this->_schema;
       }

       foreach ($objectclasses as $oc) {
           if (String::lower($oc) == 'top') {
               continue;
           }

           $required = $this->_schema->must($oc);

           if (is_array($required)) {
               foreach ($required as $v) {
                   if ($this->_isString($v)) {
                       $retval[] = String::lower($v);
                   }
               }
           }
       }

       return $retval;
    }

    /**
     * Checks if an attribute refers to a string.
     *
     * @access private
     *
     * @param string $attribute  An attribute name.
     *
     * @return bool  True if the specified attribute refers to a string.
     */
    function _isString($attribute)
    {
        $syntax = $this->_getSyntax($attribute);

        /* syntaxes we want to allow, i.e. no integers.
         * syntaxes have the form:
         * 1.3.6.1.4.1.1466.115.121.1.$n{$y}
         * where $n is the integer used below and $y is a sizelimmit. */
        $okSyntax = array(44 => 1,  // Printable String
                          41 => 1,  // Postal Address
                          39 => 1,  // Other Mailbox
                          34 => 1,  // Name And Optional UID
                          26 => 1,  // IA5 String
                          15 => 1,  // Directory String
                         );

        if (preg_match('/(\d+)\{\d+\}$/', $syntax, $matches) &&
            isset($okSyntax[$matches[1]])) {
            return true;
        }
        return false;
    }

    /**
     * Returns the syntax of an attribute, if necessary recursively.
     *
     * @access private
     *
     * @param string $att  Attribute name.
     *
     * @return string  Attribute syntax.
     */
    function _getSyntax($att)
    {
        $attv = $this->_schema->get('attribute', $att);

        if (isset($attv['syntax'])) {
            return $attv['syntax'];
        } else {
            return $this->_getSyntax($attv['sup'][0]);
        }
    }

    /**
     * Take an array of DN elements and properly quote it according to
     * RFC 1485.
     *
     * @see Horde_LDAP::quoteDN()
     *
     * @param array $parts  An array of tuples containing the attribute
     *                      name and that attribute's value which make
     *                      up the DN. Example:
     *
     *    $parts = array(0 => array('cn', 'John Smith'),
     *                   1 => array('dc', 'example'),
     *                   2 => array('dc', 'com'));
     *
     * @return string  The properly quoted string DN.
     */
    function _quoteDN($parts)
    {
        $dn = '';
        $count = count($parts);
        for ($i = 0; $i < $count; $i++) {
            if ($i > 0) {
                $dn .= ',';
            }
            $dn .= $parts[$i][0] . '=';

            // See if we need to quote the value.
            if (preg_match('/^\s|\s$|\s\s|[,+="\r\n<>#;]/', $parts[$i][1])) {
                $dn .= '"' . str_replace('"', '\\"', $parts[$i][1]) . '"';
            } else {
                $dn .= $parts[$i][1];
            }
        }

        return $dn;
    }

}