]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LdapCommon/extlib/Net/LDAP2/LDIF.php
Updated LDAP2 extlib to latest version.
[quix0rs-gnu-social.git] / plugins / LdapCommon / extlib / Net / LDAP2 / LDIF.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
3 /**
4 * File containing the Net_LDAP2_LDIF interface class.
5 *
6 * PHP version 5
7 *
8 * @category  Net
9 * @package   Net_LDAP2
10 * @author    Benedikt Hallinger <beni@php.net>
11 * @copyright 2009 Benedikt Hallinger
12 * @license   http://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3
13 * @version   SVN: $Id: LDIF.php 324918 2012-04-06 12:31:04Z clockwerx $
14 * @link      http://pear.php.net/package/Net_LDAP2/
15 */
16
17 /**
18 * Includes
19 */
20 require_once 'PEAR.php';
21 require_once 'Net/LDAP2.php';
22 require_once 'Net/LDAP2/Entry.php';
23 require_once 'Net/LDAP2/Util.php';
24
25 /**
26 * LDIF capabilitys for Net_LDAP2, closely taken from PERLs Net::LDAP
27 *
28 * It provides a means to convert between Net_LDAP2_Entry objects and LDAP entries
29 * represented in LDIF format files. Reading and writing are supported and may
30 * manipulate single entries or lists of entries.
31 *
32 * Usage example:
33 * <code>
34 * // Read and parse an ldif-file into Net_LDAP2_Entry objects
35 * // and print out the DNs. Store the entries for later use.
36 * require 'Net/LDAP2/LDIF.php';
37 * $options = array(
38 *       'onerror' => 'die'
39 * );
40 * $entries = array();
41 * $ldif = new Net_LDAP2_LDIF('test.ldif', 'r', $options);
42 * do {
43 *       $entry = $ldif->read_entry();
44 *       $dn    = $entry->dn();
45 *       echo " done building entry: $dn\n";
46 *       array_push($entries, $entry);
47 * } while (!$ldif->eof());
48 * $ldif->done();
49 *
50 *
51 * // write those entries to another file
52 * $ldif = new Net_LDAP2_LDIF('test.out.ldif', 'w', $options);
53 * $ldif->write_entry($entries);
54 * $ldif->done();
55 * </code>
56 *
57 * @category Net
58 * @package  Net_LDAP2
59 * @author   Benedikt Hallinger <beni@php.net>
60 * @license  http://www.gnu.org/copyleft/lesser.html LGPL
61 * @link     http://pear.php.net/package/Net_LDAP22/
62 * @see      http://www.ietf.org/rfc/rfc2849.txt
63 * @todo     Error handling should be PEARified
64 * @todo     LDAPv3 controls are not implemented yet
65 */
66 class Net_LDAP2_LDIF extends PEAR
67 {
68     /**
69     * Options
70     *
71     * @access protected
72     * @var array
73     */
74     protected $_options = array('encode'    => 'base64',
75                                 'onerror'   => null,
76                                 'change'    => 0,
77                                 'lowercase' => 0,
78                                 'sort'      => 0,
79                                 'version'   => null,
80                                 'wrap'      => 78,
81                                 'raw'       => ''
82                                );
83
84     /**
85     * Errorcache
86     *
87     * @access protected
88     * @var array
89     */
90     protected $_error = array('error' => null,
91                               'line'  => 0
92                              );
93
94     /**
95     * Filehandle for read/write
96     *
97     * @access protected
98     * @var array
99     */
100     protected $_FH = null;
101
102     /**
103     * Says, if we opened the filehandle ourselves
104     *
105     * @access protected
106     * @var array
107     */
108     protected $_FH_opened = false;
109
110     /**
111     * Linecounter for input file handle
112     *
113     * @access protected
114     * @var array
115     */
116     protected $_input_line = 0;
117
118     /**
119     * counter for processed entries
120     *
121     * @access protected
122     * @var int
123     */
124     protected $_entrynum = 0;
125
126     /**
127     * Mode we are working in
128     *
129     * Either 'r', 'a' or 'w'
130     *
131     * @access protected
132     * @var string
133     */
134     protected $_mode = false;
135
136     /**
137     * Tells, if the LDIF version string was already written
138     *
139     * @access protected
140     * @var boolean
141     */
142     protected $_version_written = false;
143
144     /**
145     * Cache for lines that have build the current entry
146     *
147     * @access protected
148     * @var boolean
149     */
150     protected $_lines_cur = array();
151
152     /**
153     * Cache for lines that will build the next entry
154     *
155     * @access protected
156     * @var boolean
157     */
158     protected $_lines_next = array();
159
160     /**
161     * Open LDIF file for reading or for writing
162     *
163     * new (FILE):
164     * Open the file read-only. FILE may be the name of a file
165     * or an already open filehandle.
166     * If the file doesn't exist, it will be created if in write mode.
167     *
168     * new (FILE, MODE, OPTIONS):
169     *     Open the file with the given MODE (see PHPs fopen()), eg "w" or "a".
170     *     FILE may be the name of a file or an already open filehandle.
171     *     PERLs Net_LDAP2 "FILE|" mode does not work curently.
172     *
173     *     OPTIONS is an associative array and may contain:
174     *       encode => 'none' | 'canonical' | 'base64'
175     *         Some DN values in LDIF cannot be written verbatim and have to be encoded in some way:
176     *         'none'       No encoding.
177     *         'canonical'  See "canonical_dn()" in Net::LDAP::Util.
178     *         'base64'     Use base64. (default, this differs from the Perl interface.
179     *                                   The perl default is "none"!)
180     *
181     *       onerror => 'die' | 'warn' | NULL
182     *         Specify what happens when an error is detected.
183     *         'die'  Net_LDAP2_LDIF will croak with an appropriate message.
184     *         'warn' Net_LDAP2_LDIF will warn (echo) with an appropriate message.
185     *         NULL   Net_LDAP2_LDIF will not warn (default), use error().
186     *
187     *       change => 1
188     *         Write entry changes to the LDIF file instead of the entries itself. I.e. write LDAP
189     *         operations acting on the entries to the file instead of the entries contents.
190     *         This writes the changes usually carried out by an update() to the LDIF file.
191     *
192     *       lowercase => 1
193     *         Convert attribute names to lowercase when writing.
194     *
195     *       sort => 1
196     *         Sort attribute names when writing entries according to the rule:
197     *         objectclass first then all other attributes alphabetically sorted by attribute name
198     *
199     *       version => '1'
200     *         Set the LDIF version to write to the resulting LDIF file.
201     *         According to RFC 2849 currently the only legal value for this option is 1.
202     *         When this option is set Net_LDAP2_LDIF tries to adhere more strictly to
203     *         the LDIF specification in RFC2489 in a few places.
204     *         The default is NULL meaning no version information is written to the LDIF file.
205     *
206     *       wrap => 78
207     *         Number of columns where output line wrapping shall occur.
208     *         Default is 78. Setting it to 40 or lower inhibits wrapping.
209     *
210     *       raw => REGEX
211     *         Use REGEX to denote the names of attributes that are to be
212     *         considered binary in search results if writing entries.
213     *         Example: raw => "/(?i:^jpegPhoto|;binary)/i"
214     *
215     * @param string|ressource $file    Filename or filehandle
216     * @param string           $mode    Mode to open filename
217     * @param array            $options Options like described above
218     */
219     public function __construct($file, $mode = 'r', $options = array())
220     {
221         $this->PEAR('Net_LDAP2_Error'); // default error class
222
223         // First, parse options
224         // todo: maybe implement further checks on possible values
225         foreach ($options as $option => $value) {
226             if (!array_key_exists($option, $this->_options)) {
227                 $this->dropError('Net_LDAP2_LDIF error: option '.$option.' not known!');
228                 return;
229             } else {
230                 $this->_options[$option] = strtolower($value);
231             }
232         }
233
234         // setup LDIF class
235         $this->version($this->_options['version']);
236
237         // setup file mode
238         if (!preg_match('/^[rwa]\+?$/', $mode)) {
239             $this->dropError('Net_LDAP2_LDIF error: file mode '.$mode.' not supported!');
240         } else {
241             $this->_mode = $mode;
242
243             // setup filehandle
244             if (is_resource($file)) {
245                 // TODO: checks on mode possible?
246                 $this->_FH =& $file;
247             } else {
248                 $imode = substr($this->_mode, 0, 1);
249                 if ($imode == 'r') {
250                     if (!file_exists($file)) {
251                         $this->dropError('Unable to open '.$file.' for read: file not found');
252                         $this->_mode = false;
253                     }
254                     if (!is_readable($file)) {
255                         $this->dropError('Unable to open '.$file.' for read: permission denied');
256                         $this->_mode = false;
257                     }
258                 }
259
260                 if (($imode == 'w' || $imode == 'a')) {
261                     if (file_exists($file)) {
262                         if (!is_writable($file)) {
263                             $this->dropError('Unable to open '.$file.' for write: permission denied');
264                             $this->_mode = false;
265                         }
266                     } else {
267                         if (!@touch($file)) {
268                             $this->dropError('Unable to create '.$file.' for write: permission denied');
269                             $this->_mode = false;
270                         }
271                     }
272                 }
273
274                 if ($this->_mode) {
275                     $this->_FH = @fopen($file, $this->_mode);
276                     if (false === $this->_FH) {
277                         // Fallback; should never be reached if tests above are good enough!
278                         $this->dropError('Net_LDAP2_LDIF error: Could not open file '.$file);
279                     } else {
280                         $this->_FH_opened = true;
281                     }
282                 }
283             }
284         }
285     }
286
287     /**
288     * Read one entry from the file and return it as a Net::LDAP::Entry object.
289     *
290     * @return Net_LDAP2_Entry
291     */
292     public function read_entry()
293     {
294         // read fresh lines, set them as current lines and create the entry
295         $attrs = $this->next_lines(true);
296         if (count($attrs) > 0) {
297             $this->_lines_cur = $attrs;
298         }
299         return $this->current_entry();
300     }
301
302     /**
303     * Returns true when the end of the file is reached.
304     *
305     * @return boolean
306     */
307     public function eof()
308     {
309         return feof($this->_FH);
310     }
311
312     /**
313     * Write the entry or entries to the LDIF file.
314     *
315     * If you want to build an LDIF file containing several entries AND
316     * you want to call write_entry() several times, you must open the filehandle
317     * in append mode ("a"), otherwise you will always get the last entry only.
318     *
319     * @param Net_LDAP2_Entry|array $entries Entry or array of entries
320     *
321     * @return void
322     * @todo implement operations on whole entries (adding a whole entry)
323     */
324     public function write_entry($entries)
325     {
326         if (!is_array($entries)) {
327             $entries = array($entries);
328         }
329
330         foreach ($entries as $entry) {
331             $this->_entrynum++;
332             if (!$entry instanceof Net_LDAP2_Entry) {
333                 $this->dropError('Net_LDAP2_LDIF error: entry '.$this->_entrynum.' is not an Net_LDAP2_Entry object');
334             } else {
335                 if ($this->_options['change']) {
336                     // LDIF change mode
337                     // fetch change information from entry
338                     $entry_attrs_changes = $entry->getChanges();
339                     $num_of_changes      = count($entry_attrs_changes['add'])
340                                            + count($entry_attrs_changes['replace'])
341                                            + count($entry_attrs_changes['delete']);
342
343
344                     $is_changed = ($num_of_changes > 0 || $entry->willBeDeleted() || $entry->willBeMoved());
345
346                     // write version if not done yet
347                     // also write DN of entry
348                     if ($is_changed) {
349                         if (!$this->_version_written) {
350                             $this->write_version();
351                         }
352                         $this->writeDN($entry->currentDN());
353                     }
354
355                     // process changes
356                     // TODO: consider DN add!
357                     if ($entry->willBeDeleted()) {
358                         $this->writeLine("changetype: delete".PHP_EOL);
359                     } elseif ($entry->willBeMoved()) {
360                         $this->writeLine("changetype: modrdn".PHP_EOL);
361                         $olddn     = Net_LDAP2_Util::ldap_explode_dn($entry->currentDN(), array('casefold' => 'none')); // maybe gives a bug if using multivalued RDNs
362                         $oldrdn    = array_shift($olddn);
363                         $oldparent = implode(',', $olddn);
364                         $newdn     = Net_LDAP2_Util::ldap_explode_dn($entry->dn(), array('casefold' => 'none')); // maybe gives a bug if using multivalued RDNs
365                         $rdn       = array_shift($newdn);
366                         $parent    = implode(',', $newdn);
367                         $this->writeLine("newrdn: ".$rdn.PHP_EOL);
368                         $this->writeLine("deleteoldrdn: 1".PHP_EOL);
369                         if ($parent !== $oldparent) {
370                             $this->writeLine("newsuperior: ".$parent.PHP_EOL);
371                         }
372                         // TODO: What if the entry has attribute changes as well?
373                         //       I think we should check for that and make a dummy
374                         //       entry with the changes that is written to the LDIF file
375                     } elseif ($num_of_changes > 0) {
376                         // write attribute change data
377                         $this->writeLine("changetype: modify".PHP_EOL);
378                         foreach ($entry_attrs_changes as $changetype => $entry_attrs) {
379                             foreach ($entry_attrs as $attr_name => $attr_values) {
380                                 $this->writeLine("$changetype: $attr_name".PHP_EOL);
381                                 if ($attr_values !== null) $this->writeAttribute($attr_name, $attr_values, $changetype);
382                                 $this->writeLine("-".PHP_EOL);
383                             }
384                         }
385                     }
386
387                     // finish this entrys data if we had changes
388                     if ($is_changed) {
389                         $this->finishEntry();
390                     }
391                 } else {
392                     // LDIF-content mode
393                     // fetch attributes for further processing
394                     $entry_attrs = $entry->getValues();
395
396                     // sort and put objectclass-attrs to first position
397                     if ($this->_options['sort']) {
398                         ksort($entry_attrs);
399                         if (array_key_exists('objectclass', $entry_attrs)) {
400                             $oc = $entry_attrs['objectclass'];
401                             unset($entry_attrs['objectclass']);
402                             $entry_attrs = array_merge(array('objectclass' => $oc), $entry_attrs);
403                         }
404                     }
405
406                     // write data
407                     if (!$this->_version_written) {
408                         $this->write_version();
409                     }
410                     $this->writeDN($entry->dn());
411                     foreach ($entry_attrs as $attr_name => $attr_values) {
412                         $this->writeAttribute($attr_name, $attr_values);
413                     }
414                     $this->finishEntry();
415                 }
416             }
417         }
418     }
419
420     /**
421     * Write version to LDIF
422     *
423     * If the object's version is defined, this method allows to explicitely write the version before an entry is written.
424     * If not called explicitely, it gets called automatically when writing the first entry.
425     *
426     * @return void
427     */
428     public function write_version()
429     {
430         $this->_version_written = true;
431         if (!is_null($this->version())) {
432             return $this->writeLine('version: '.$this->version().PHP_EOL, 'Net_LDAP2_LDIF error: unable to write version');
433         }
434     }
435
436     /**
437     * Get or set LDIF version
438     *
439     * If called without arguments it returns the version of the LDIF file or NULL if no version has been set.
440     * If called with an argument it sets the LDIF version to VERSION.
441     * According to RFC 2849 currently the only legal value for VERSION is 1.
442     *
443     * @param int $version (optional) LDIF version to set
444     *
445     * @return int
446     */
447     public function version($version = null)
448     {
449         if ($version !== null) {
450             if ($version != 1) {
451                 $this->dropError('Net_LDAP2_LDIF error: illegal LDIF version set');
452             } else {
453                 $this->_options['version'] = $version;
454             }
455         }
456         return $this->_options['version'];
457     }
458
459     /**
460     * Returns the file handle the Net_LDAP2_LDIF object reads from or writes to.
461     *
462     * You can, for example, use this to fetch the content of the LDIF file yourself
463     *
464     * @return null|resource
465     */
466     public function &handle()
467     {
468         if (!is_resource($this->_FH)) {
469             $this->dropError('Net_LDAP2_LDIF error: invalid file resource');
470             $null = null;
471             return $null;
472         } else {
473             return $this->_FH;
474         }
475     }
476
477     /**
478     * Clean up
479     *
480     * This method signals that the LDIF object is no longer needed.
481     * You can use this to free up some memory and close the file handle.
482     * The file handle is only closed, if it was opened from Net_LDAP2_LDIF.
483     *
484     * @return void
485     */
486     public function done()
487     {
488         // close FH if we opened it
489         if ($this->_FH_opened) {
490             fclose($this->handle());
491         }
492
493         // free variables
494         foreach (get_object_vars($this) as $name => $value) {
495             unset($this->$name);
496         }
497     }
498
499     /**
500     * Returns last error message if error was found.
501     *
502     * Example:
503     * <code>
504     *  $ldif->someAction();
505     *  if ($ldif->error()) {
506     *     echo "Error: ".$ldif->error()." at input line: ".$ldif->error_lines();
507     *  }
508     * </code>
509     *
510     * @param boolean $as_string If set to true, only the message is returned
511     *
512     * @return false|Net_LDAP2_Error
513     */
514     public function error($as_string = false)
515     {
516         if (Net_LDAP2::isError($this->_error['error'])) {
517             return ($as_string)? $this->_error['error']->getMessage() : $this->_error['error'];
518         } else {
519             return false;
520         }
521     }
522
523     /**
524     * Returns lines that resulted in error.
525     *
526     * Perl returns an array of faulty lines in list context,
527     * but we always just return an int because of PHPs language.
528     *
529     * @return int
530     */
531     public function error_lines()
532     {
533         return $this->_error['line'];
534     }
535
536     /**
537     * Returns the current Net::LDAP::Entry object.
538     *
539     * @return Net_LDAP2_Entry|false
540     */
541     public function current_entry()
542     {
543         return $this->parseLines($this->current_lines());
544     }
545
546     /**
547     * Parse LDIF lines of one entry into an Net_LDAP2_Entry object
548     *
549     * @param array $lines LDIF lines for one entry
550     *
551     * @return Net_LDAP2_Entry|false Net_LDAP2_Entry object for those lines
552     * @todo what about file inclusions and urls? "jpegphoto:< file:///usr/local/directory/photos/fiona.jpg"
553     */
554     public function parseLines($lines)
555     {
556         // parse lines into an array of attributes and build the entry
557         $attributes = array();
558         $dn = false;
559         foreach ($lines as $line) {
560             if (preg_match('/^(\w+(;binary)?)(:|::|:<)\s(.+)$/', $line, $matches)) {
561                 $attr  =& $matches[1] . $matches[2];
562                 $delim =& $matches[3];
563                 $data  =& $matches[4];
564
565                 if ($delim == ':') {
566                     // normal data
567                     $attributes[$attr][] = $data;
568                 } elseif ($delim == '::') {
569                     // base64 data
570                     $attributes[$attr][] = base64_decode($data);
571                 } elseif ($delim == ':<') {
572                     // file inclusion
573                     // TODO: Is this the job of the LDAP-client or the server?
574                     $this->dropError('File inclusions are currently not supported');
575                     //$attributes[$attr][] = ...;
576                 } else {
577                     // since the pattern above, the delimeter cannot be something else.
578                     $this->dropError('Net_LDAP2_LDIF parsing error: invalid syntax at parsing entry line: '.$line);
579                     continue;
580                 }
581
582                 if (strtolower($attr) == 'dn') {
583                     // DN line detected
584                     $dn = $attributes[$attr][0];  // save possibly decoded DN
585                     unset($attributes[$attr]);    // remove wrongly added "dn: " attribute
586                 }
587             } else {
588                 // line not in "attr: value" format -> ignore
589                 // maybe we should rise an error here, but this should be covered by
590                 // next_lines() already. A problem arises, if users try to feed data of
591                 // several entries to this method - the resulting entry will
592                 // get wrong attributes. However, this is already mentioned in the
593                 // methods documentation above.
594             }
595         }
596
597         if (false === $dn) {
598             $this->dropError('Net_LDAP2_LDIF parsing error: unable to detect DN for entry');
599             return false;
600         } else {
601             $newentry = Net_LDAP2_Entry::createFresh($dn, $attributes);
602             return $newentry;
603         }
604     }
605
606     /**
607     * Returns the lines that generated the current Net::LDAP::Entry object.
608     *
609     * Note that this returns an empty array if no lines have been read so far.
610     *
611     * @return array Array of lines
612     */
613     public function current_lines()
614     {
615         return $this->_lines_cur;
616     }
617
618     /**
619     * Returns the lines that will generate the next Net::LDAP::Entry object.
620     *
621     * If you set $force to TRUE then you can iterate over the lines that build
622     * up entries manually. Otherwise, iterating is done using {@link read_entry()}.
623     * Force will move the file pointer forward, thus returning the next entries lines.
624     *
625     * Wrapped lines will be unwrapped. Comments are stripped.
626     *
627     * @param boolean $force Set this to true if you want to iterate over the lines manually
628     *
629     * @return array
630     */
631     public function next_lines($force = false)
632     {
633         // if we already have those lines, just return them, otherwise read
634         if (count($this->_lines_next) == 0 || $force) {
635             $this->_lines_next = array(); // empty in case something was left (if used $force)
636             $entry_done        = false;
637             $fh                = &$this->handle();
638             $commentmode       = false; // if we are in an comment, for wrapping purposes
639             $datalines_read    = 0;     // how many lines with data we have read
640
641             while (!$entry_done && !$this->eof()) {
642                 $this->_input_line++;
643                 // Read line. Remove line endings, we want only data;
644                 // this is okay since ending spaces should be encoded
645                 $data = rtrim(fgets($fh));
646                 if ($data === false) {
647                     // error only, if EOF not reached after fgets() call
648                     if (!$this->eof()) {
649                         $this->dropError('Net_LDAP2_LDIF error: error reading from file at input line '.$this->_input_line, $this->_input_line);
650                     }
651                     break;
652                 } else {
653                     if (count($this->_lines_next) > 0 && preg_match('/^$/', $data)) {
654                         // Entry is finished if we have an empty line after we had data
655                         $entry_done = true;
656
657                         // Look ahead if the next EOF is nearby. Comments and empty
658                         // lines at the file end may cause problems otherwise
659                         $current_pos = ftell($fh);
660                         $data        = fgets($fh);
661                         while (!feof($fh)) {
662                             if (preg_match('/^\s*$/', $data) || preg_match('/^#/', $data)) {
663                                 // only empty lines or comments, continue to seek
664                                 // TODO: Known bug: Wrappings for comments are okay but are treaten as
665                                 //       error, since we do not honor comment mode here.
666                                 //       This should be a very theoretically case, however
667                                 //       i am willing to fix this if really necessary.
668                                 $this->_input_line++;
669                                 $current_pos = ftell($fh);
670                                 $data        = fgets($fh);
671                             } else {
672                                 // Data found if non emtpy line and not a comment!!
673                                 // Rewind to position prior last read and stop lookahead
674                                 fseek($fh, $current_pos);
675                                 break;
676                             }
677                         }
678                         // now we have either the file pointer at the beginning of
679                         // a new data position or at the end of file causing feof() to return true
680
681                     } else {
682                         // build lines
683                         if (preg_match('/^version:\s(.+)$/', $data, $match)) {
684                             // version statement, set version
685                             $this->version($match[1]);
686                         } elseif (preg_match('/^\w+(;binary)?::?\s.+$/', $data)) {
687                             // normal attribute: add line
688                             $commentmode         = false;
689                             $this->_lines_next[] = trim($data);
690                             $datalines_read++;
691                         } elseif (preg_match('/^\s(.+)$/', $data, $matches)) {
692                             // wrapped data: unwrap if not in comment mode
693                             // note that the \s above is some more liberal than
694                             // the RFC requests as it also matches tabs etc.
695                             if (!$commentmode) {
696                                 if ($datalines_read == 0) {
697                                     // first line of entry: wrapped data is illegal
698                                     $this->dropError('Net_LDAP2_LDIF error: illegal wrapping at input line '.$this->_input_line, $this->_input_line);
699                                 } else {
700                                     $last                = array_pop($this->_lines_next);
701                                     $last                = $last.$matches[1];
702                                     $this->_lines_next[] = $last;
703                                     $datalines_read++;
704                                 }
705                             }
706                         } elseif (preg_match('/^#/', $data)) {
707                             // LDIF comments
708                             $commentmode = true;
709                         } elseif (preg_match('/^\s*$/', $data)) {
710                             // empty line but we had no data for this
711                             // entry, so just ignore this line
712                             $commentmode = false;
713                         } else {
714                             $this->dropError('Net_LDAP2_LDIF error: invalid syntax at input line '.$this->_input_line, $this->_input_line);
715                             continue;
716                         }
717
718                     }
719                 }
720             }
721         }
722         return $this->_lines_next;
723     }
724
725     /**
726     * Convert an attribute and value to LDIF string representation
727     *
728     * It honors correct encoding of values according to RFC 2849.
729     * Line wrapping will occur at the configured maximum but only if
730     * the value is greater than 40 chars.
731     *
732     * @param string $attr_name  Name of the attribute
733     * @param string $attr_value Value of the attribute
734     *
735     * @access protected
736     * @return string LDIF string for that attribute and value
737     */
738     protected function convertAttribute($attr_name, $attr_value)
739     {
740         // Handle empty attribute or process
741         if (strlen($attr_value) == 0) {
742             $attr_value = " ";
743         } else {
744             $base64 = false;
745             // ASCII-chars that are NOT safe for the
746             // start and for being inside the value.
747             // These are the int values of those chars.
748             $unsafe_init = array(0, 10, 13, 32, 58, 60);
749             $unsafe      = array(0, 10, 13);
750
751             // Test for illegal init char
752             $init_ord = ord(substr($attr_value, 0, 1));
753             if ($init_ord > 127 || in_array($init_ord, $unsafe_init)) {
754                 $base64 = true;
755             }
756
757             // Test for illegal content char
758             for ($i = 0; $i < strlen($attr_value); $i++) {
759                 $char_ord = ord(substr($attr_value, $i, 1));
760                 if ($char_ord > 127 || in_array($char_ord, $unsafe)) {
761                     $base64 = true;
762                 }
763             }
764
765             // Test for ending space
766             if (substr($attr_value, -1) == ' ') {
767                 $base64 = true;
768             }
769
770             // If converting is needed, do it
771             // Either we have some special chars or a matching "raw" regex
772             if ($base64 || ($this->_options['raw'] && preg_match($this->_options['raw'], $attr_name))) {
773                 $attr_name .= ':';
774                 $attr_value = base64_encode($attr_value);
775             }
776
777             // Lowercase attr names if requested
778             if ($this->_options['lowercase']) $attr_name = strtolower($attr_name);
779
780             // Handle line wrapping
781             if ($this->_options['wrap'] > 40 && strlen($attr_value) > $this->_options['wrap']) {
782                 $attr_value = wordwrap($attr_value, $this->_options['wrap'], PHP_EOL." ", true);
783             }
784         }
785
786         return $attr_name.': '.$attr_value;
787     }
788
789     /**
790     * Convert an entries DN to LDIF string representation
791     *
792     * It honors correct encoding of values according to RFC 2849.
793     *
794     * @param string $dn UTF8-Encoded DN
795     *
796     * @access protected
797     * @return string LDIF string for that DN
798     * @todo I am not sure, if the UTF8 stuff is correctly handled right now
799     */
800     protected function convertDN($dn)
801     {
802         $base64 = false;
803         // ASCII-chars that are NOT safe for the
804         // start and for being inside the dn.
805         // These are the int values of those chars.
806         $unsafe_init = array(0, 10, 13, 32, 58, 60);
807         $unsafe      = array(0, 10, 13);
808
809         // Test for illegal init char
810         $init_ord = ord(substr($dn, 0, 1));
811         if ($init_ord >= 127 || in_array($init_ord, $unsafe_init)) {
812             $base64 = true;
813         }
814
815         // Test for illegal content char
816         for ($i = 0; $i < strlen($dn); $i++) {
817             $char = substr($dn, $i, 1);
818             if (ord($char) >= 127 || in_array($init_ord, $unsafe)) {
819                 $base64 = true;
820             }
821         }
822
823         // Test for ending space
824         if (substr($dn, -1) == ' ') {
825             $base64 = true;
826         }
827
828         // if converting is needed, do it
829         return ($base64)? 'dn:: '.base64_encode($dn) : 'dn: '.$dn;
830     }
831
832     /**
833     * Writes an attribute to the filehandle
834     *
835     * @param string       $attr_name   Name of the attribute
836     * @param string|array $attr_values Single attribute value or array with attribute values
837     *
838     * @access protected
839     * @return void
840     */
841     protected function writeAttribute($attr_name, $attr_values)
842     {
843         // write out attribute content
844         if (!is_array($attr_values)) {
845             $attr_values = array($attr_values);
846         }
847         foreach ($attr_values as $attr_val) {
848             $line = $this->convertAttribute($attr_name, $attr_val).PHP_EOL;
849             $this->writeLine($line, 'Net_LDAP2_LDIF error: unable to write attribute '.$attr_name.' of entry '.$this->_entrynum);
850         }
851     }
852
853     /**
854     * Writes a DN to the filehandle
855     *
856     * @param string $dn DN to write
857     *
858     * @access protected
859     * @return void
860     */
861     protected function writeDN($dn)
862     {
863         // prepare DN
864         if ($this->_options['encode'] == 'base64') {
865             $dn = $this->convertDN($dn).PHP_EOL;
866         } elseif ($this->_options['encode'] == 'canonical') {
867             $dn = Net_LDAP2_Util::canonical_dn($dn, array('casefold' => 'none')).PHP_EOL;
868         } else {
869             $dn = $dn.PHP_EOL;
870         }
871         $this->writeLine($dn, 'Net_LDAP2_LDIF error: unable to write DN of entry '.$this->_entrynum);
872     }
873
874     /**
875     * Finishes an LDIF entry
876     *
877     * @access protected
878     * @return void
879     */
880     protected function finishEntry()
881     {
882         $this->writeLine(PHP_EOL, 'Net_LDAP2_LDIF error: unable to close entry '.$this->_entrynum);
883     }
884
885     /**
886     * Just write an arbitary line to the filehandle
887     *
888     * @param string $line  Content to write
889     * @param string $error If error occurs, drop this message
890     *
891     * @access protected
892     * @return true|false
893     */
894     protected function writeLine($line, $error = 'Net_LDAP2_LDIF error: unable to write to filehandle')
895     {
896         if (is_resource($this->handle()) && fwrite($this->handle(), $line, strlen($line)) === false) {
897             $this->dropError($error);
898             return false;
899         } else {
900             return true;
901         }
902     }
903
904     /**
905     * Optionally raises an error and pushes the error on the error cache
906     *
907     * @param string $msg  Errortext
908     * @param int    $line Line in the LDIF that caused the error
909     *
910     * @access protected
911     * @return void
912     */
913     protected function dropError($msg, $line = null)
914     {
915         $this->_error['error'] = new Net_LDAP2_Error($msg);
916         if ($line !== null) $this->_error['line'] = $line;
917
918         if ($this->_options['onerror'] == 'die') {
919             die($msg.PHP_EOL);
920         } elseif ($this->_options['onerror'] == 'warn') {
921             echo $msg.PHP_EOL;
922         }
923     }
924 }
925 ?>