2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
4 * File containing the Net_LDAP2_LDIF interface class.
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 286718 2009-08-03 07:30:49Z beni $
14 * @link http://pear.php.net/package/Net_LDAP2/
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';
26 * LDIF capabilitys for Net_LDAP2, closely taken from PERLs Net::LDAP
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.
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';
41 * $ldif = new Net_LDAP2_LDIF('test.ldif', 'r', $options);
43 * $entry = $ldif->read_entry();
45 * echo " done building entry: $dn\n";
46 * array_push($entries, $entry);
47 * } while (!$ldif->eof());
51 * // write those entries to another file
52 * $ldif = new Net_LDAP2_LDIF('test.out.ldif', 'w', $options);
53 * $ldif->write_entry($entries);
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
66 class Net_LDAP2_LDIF extends PEAR
74 protected $_options = array('encode' => 'base64',
90 protected $_error = array('error' => null,
95 * Filehandle for read/write
100 protected $_FH = null;
103 * Says, if we opened the filehandle ourselves
108 protected $_FH_opened = false;
111 * Linecounter for input file handle
116 protected $_input_line = 0;
119 * counter for processed entries
124 protected $_entrynum = 0;
127 * Mode we are working in
129 * Either 'r', 'a' or 'w'
134 protected $_mode = false;
137 * Tells, if the LDIF version string was already written
142 protected $_version_written = false;
145 * Cache for lines that have build the current entry
150 protected $_lines_cur = array();
153 * Cache for lines that will build the next entry
158 protected $_lines_next = array();
161 * Open LDIF file for reading or for writing
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.
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.
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"!)
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().
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.
193 * Convert attribute names to lowercase when writing.
196 * Sort attribute names when writing entries according to the rule:
197 * objectclass first then all other attributes alphabetically sorted by attribute name
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.
207 * Number of columns where output line wrapping shall occur.
208 * Default is 78. Setting it to 40 or lower inhibits wrapping.
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"
215 * @param string|ressource $file Filename or filehandle
216 * @param string $mode Mode to open filename
217 * @param array $options Options like described above
219 public function __construct($file, $mode = 'r', $options = array())
221 $this->PEAR('Net_LDAP2_Error'); // default error class
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!');
230 $this->_options[$option] = strtolower($value);
235 $this->version($this->_options['version']);
238 if (!preg_match('/^[rwa]\+?$/', $mode)) {
239 $this->dropError('Net_LDAP2_LDIF error: file mode '.$mode.' not supported!');
241 $this->_mode = $mode;
244 if (is_resource($file)) {
245 // TODO: checks on mode possible?
248 $imode = substr($this->_mode, 0, 1);
250 if (!file_exists($file)) {
251 $this->dropError('Unable to open '.$file.' for read: file not found');
252 $this->_mode = false;
254 if (!is_readable($file)) {
255 $this->dropError('Unable to open '.$file.' for read: permission denied');
256 $this->_mode = false;
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;
267 if (!@touch($file)) {
268 $this->dropError('Unable to create '.$file.' for write: permission denied');
269 $this->_mode = false;
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);
280 $this->_FH_opened = true;
288 * Read one entry from the file and return it as a Net::LDAP::Entry object.
290 * @return Net_LDAP2_Entry
292 public function read_entry()
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;
299 return $this->current_entry();
303 * Returns true when the end of the file is reached.
307 public function eof()
309 return feof($this->_FH);
313 * Write the entry or entries to the LDIF file.
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.
319 * @param Net_LDAP2_Entry|array $entries Entry or array of entries
322 * @todo implement operations on whole entries (adding a whole entry)
324 public function write_entry($entries)
326 if (!is_array($entries)) {
327 $entries = array($entries);
330 foreach ($entries as $entry) {
332 if (!$entry instanceof Net_LDAP2_Entry) {
333 $this->dropError('Net_LDAP2_LDIF error: entry '.$this->_entrynum.' is not an Net_LDAP2_Entry object');
335 if ($this->_options['change']) {
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']);
343 $is_changed = ($num_of_changes > 0 || $entry->willBeDeleted() || $entry->willBeMoved());
345 // write version if not done yet
346 // also write DN of entry
348 if (!$this->_version_written) {
349 $this->write_version();
351 $this->writeDN($entry->currentDN());
355 // TODO: consider DN add!
356 if ($entry->willBeDeleted()) {
357 $this->writeLine("changetype: delete".PHP_EOL);
358 } elseif ($entry->willBeMoved()) {
359 $this->writeLine("changetype: modrdn".PHP_EOL);
360 $olddn = Net_LDAP2_Util::ldap_explode_dn($entry->currentDN(), array('casefold' => 'none')); // maybe gives a bug if using multivalued RDNs
361 $oldrdn = array_shift($olddn);
362 $oldparent = implode(',', $olddn);
363 $newdn = Net_LDAP2_Util::ldap_explode_dn($entry->dn(), array('casefold' => 'none')); // maybe gives a bug if using multivalued RDNs
364 $rdn = array_shift($newdn);
365 $parent = implode(',', $newdn);
366 $this->writeLine("newrdn: ".$rdn.PHP_EOL);
367 $this->writeLine("deleteoldrdn: 1".PHP_EOL);
368 if ($parent !== $oldparent) {
369 $this->writeLine("newsuperior: ".$parent.PHP_EOL);
371 // TODO: What if the entry has attribute changes as well?
372 // I think we should check for that and make a dummy
373 // entry with the changes that is written to the LDIF file
374 } elseif ($num_of_changes > 0) {
375 // write attribute change data
376 $this->writeLine("changetype: modify".PHP_EOL);
377 foreach ($entry_attrs_changes as $changetype => $entry_attrs) {
378 foreach ($entry_attrs as $attr_name => $attr_values) {
379 $this->writeLine("$changetype: $attr_name".PHP_EOL);
380 if ($attr_values !== null) $this->writeAttribute($attr_name, $attr_values, $changetype);
381 $this->writeLine("-".PHP_EOL);
386 // finish this entrys data if we had changes
388 $this->finishEntry();
392 // fetch attributes for further processing
393 $entry_attrs = $entry->getValues();
395 // sort and put objectclass-attrs to first position
396 if ($this->_options['sort']) {
398 if (array_key_exists('objectclass', $entry_attrs)) {
399 $oc = $entry_attrs['objectclass'];
400 unset($entry_attrs['objectclass']);
401 $entry_attrs = array_merge(array('objectclass' => $oc), $entry_attrs);
406 if (!$this->_version_written) {
407 $this->write_version();
409 $this->writeDN($entry->dn());
410 foreach ($entry_attrs as $attr_name => $attr_values) {
411 $this->writeAttribute($attr_name, $attr_values);
413 $this->finishEntry();
420 * Write version to LDIF
422 * If the object's version is defined, this method allows to explicitely write the version before an entry is written.
423 * If not called explicitely, it gets called automatically when writing the first entry.
427 public function write_version()
429 $this->_version_written = true;
430 if (!is_null($this->version())) {
431 return $this->writeLine('version: '.$this->version().PHP_EOL, 'Net_LDAP2_LDIF error: unable to write version');
436 * Get or set LDIF version
438 * If called without arguments it returns the version of the LDIF file or NULL if no version has been set.
439 * If called with an argument it sets the LDIF version to VERSION.
440 * According to RFC 2849 currently the only legal value for VERSION is 1.
442 * @param int $version (optional) LDIF version to set
446 public function version($version = null)
448 if ($version !== null) {
450 $this->dropError('Net_LDAP2_LDIF error: illegal LDIF version set');
452 $this->_options['version'] = $version;
455 return $this->_options['version'];
459 * Returns the file handle the Net_LDAP2_LDIF object reads from or writes to.
461 * You can, for example, use this to fetch the content of the LDIF file yourself
463 * @return null|resource
465 public function &handle()
467 if (!is_resource($this->_FH)) {
468 $this->dropError('Net_LDAP2_LDIF error: invalid file resource');
479 * This method signals that the LDIF object is no longer needed.
480 * You can use this to free up some memory and close the file handle.
481 * The file handle is only closed, if it was opened from Net_LDAP2_LDIF.
485 public function done()
487 // close FH if we opened it
488 if ($this->_FH_opened) {
489 fclose($this->handle());
493 foreach (get_object_vars($this) as $name => $value) {
499 * Returns last error message if error was found.
503 * $ldif->someAction();
504 * if ($ldif->error()) {
505 * echo "Error: ".$ldif->error()." at input line: ".$ldif->error_lines();
509 * @param boolean $as_string If set to true, only the message is returned
511 * @return false|Net_LDAP2_Error
513 public function error($as_string = false)
515 if (Net_LDAP2::isError($this->_error['error'])) {
516 return ($as_string)? $this->_error['error']->getMessage() : $this->_error['error'];
523 * Returns lines that resulted in error.
525 * Perl returns an array of faulty lines in list context,
526 * but we always just return an int because of PHPs language.
530 public function error_lines()
532 return $this->_error['line'];
536 * Returns the current Net::LDAP::Entry object.
538 * @return Net_LDAP2_Entry|false
540 public function current_entry()
542 return $this->parseLines($this->current_lines());
546 * Parse LDIF lines of one entry into an Net_LDAP2_Entry object
548 * @param array $lines LDIF lines for one entry
550 * @return Net_LDAP2_Entry|false Net_LDAP2_Entry object for those lines
551 * @todo what about file inclusions and urls? "jpegphoto:< file:///usr/local/directory/photos/fiona.jpg"
553 public function parseLines($lines)
555 // parse lines into an array of attributes and build the entry
556 $attributes = array();
558 foreach ($lines as $line) {
559 if (preg_match('/^(\w+)(:|::|:<)\s(.+)$/', $line, $matches)) {
560 $attr =& $matches[1];
561 $delim =& $matches[2];
562 $data =& $matches[3];
566 $attributes[$attr][] = $data;
567 } elseif ($delim == '::') {
569 $attributes[$attr][] = base64_decode($data);
570 } elseif ($delim == ':<') {
572 // TODO: Is this the job of the LDAP-client or the server?
573 $this->dropError('File inclusions are currently not supported');
574 //$attributes[$attr][] = ...;
576 // since the pattern above, the delimeter cannot be something else.
577 $this->dropError('Net_LDAP2_LDIF parsing error: invalid syntax at parsing entry line: '.$line);
581 if (strtolower($attr) == 'dn') {
583 $dn = $attributes[$attr][0]; // save possibly decoded DN
584 unset($attributes[$attr]); // remove wrongly added "dn: " attribute
587 // line not in "attr: value" format -> ignore
588 // maybe we should rise an error here, but this should be covered by
589 // next_lines() already. A problem arises, if users try to feed data of
590 // several entries to this method - the resulting entry will
591 // get wrong attributes. However, this is already mentioned in the
592 // methods documentation above.
597 $this->dropError('Net_LDAP2_LDIF parsing error: unable to detect DN for entry');
600 $newentry = Net_LDAP2_Entry::createFresh($dn, $attributes);
606 * Returns the lines that generated the current Net::LDAP::Entry object.
608 * Note that this returns an empty array if no lines have been read so far.
610 * @return array Array of lines
612 public function current_lines()
614 return $this->_lines_cur;
618 * Returns the lines that will generate the next Net::LDAP::Entry object.
620 * If you set $force to TRUE then you can iterate over the lines that build
621 * up entries manually. Otherwise, iterating is done using {@link read_entry()}.
622 * Force will move the file pointer forward, thus returning the next entries lines.
624 * Wrapped lines will be unwrapped. Comments are stripped.
626 * @param boolean $force Set this to true if you want to iterate over the lines manually
630 public function next_lines($force = false)
632 // if we already have those lines, just return them, otherwise read
633 if (count($this->_lines_next) == 0 || $force) {
634 $this->_lines_next = array(); // empty in case something was left (if used $force)
636 $fh = &$this->handle();
637 $commentmode = false; // if we are in an comment, for wrapping purposes
638 $datalines_read = 0; // how many lines with data we have read
640 while (!$entry_done && !$this->eof()) {
641 $this->_input_line++;
642 // Read line. Remove line endings, we want only data;
643 // this is okay since ending spaces should be encoded
644 $data = rtrim(fgets($fh));
645 if ($data === false) {
646 // error only, if EOF not reached after fgets() call
648 $this->dropError('Net_LDAP2_LDIF error: error reading from file at input line '.$this->_input_line, $this->_input_line);
652 if (count($this->_lines_next) > 0 && preg_match('/^$/', $data)) {
653 // Entry is finished if we have an empty line after we had data
656 // Look ahead if the next EOF is nearby. Comments and empty
657 // lines at the file end may cause problems otherwise
658 $current_pos = ftell($fh);
661 if (preg_match('/^\s*$/', $data) || preg_match('/^#/', $data)) {
662 // only empty lines or comments, continue to seek
663 // TODO: Known bug: Wrappings for comments are okay but are treaten as
664 // error, since we do not honor comment mode here.
665 // This should be a very theoretically case, however
666 // i am willing to fix this if really necessary.
667 $this->_input_line++;
668 $current_pos = ftell($fh);
671 // Data found if non emtpy line and not a comment!!
672 // Rewind to position prior last read and stop lookahead
673 fseek($fh, $current_pos);
677 // now we have either the file pointer at the beginning of
678 // a new data position or at the end of file causing feof() to return true
682 if (preg_match('/^version:\s(.+)$/', $data, $match)) {
683 // version statement, set version
684 $this->version($match[1]);
685 } elseif (preg_match('/^\w+::?\s.+$/', $data)) {
686 // normal attribute: add line
687 $commentmode = false;
688 $this->_lines_next[] = trim($data);
690 } elseif (preg_match('/^\s(.+)$/', $data, $matches)) {
691 // wrapped data: unwrap if not in comment mode
693 if ($datalines_read == 0) {
694 // first line of entry: wrapped data is illegal
695 $this->dropError('Net_LDAP2_LDIF error: illegal wrapping at input line '.$this->_input_line, $this->_input_line);
697 $last = array_pop($this->_lines_next);
698 $last = $last.trim($matches[1]);
699 $this->_lines_next[] = $last;
703 } elseif (preg_match('/^#/', $data)) {
706 } elseif (preg_match('/^\s*$/', $data)) {
707 // empty line but we had no data for this
708 // entry, so just ignore this line
709 $commentmode = false;
711 $this->dropError('Net_LDAP2_LDIF error: invalid syntax at input line '.$this->_input_line, $this->_input_line);
719 return $this->_lines_next;
723 * Convert an attribute and value to LDIF string representation
725 * It honors correct encoding of values according to RFC 2849.
726 * Line wrapping will occur at the configured maximum but only if
727 * the value is greater than 40 chars.
729 * @param string $attr_name Name of the attribute
730 * @param string $attr_value Value of the attribute
733 * @return string LDIF string for that attribute and value
735 protected function convertAttribute($attr_name, $attr_value)
737 // Handle empty attribute or process
738 if (strlen($attr_value) == 0) {
742 // ASCII-chars that are NOT safe for the
743 // start and for being inside the value.
744 // These are the int values of those chars.
745 $unsafe_init = array(0, 10, 13, 32, 58, 60);
746 $unsafe = array(0, 10, 13);
748 // Test for illegal init char
749 $init_ord = ord(substr($attr_value, 0, 1));
750 if ($init_ord > 127 || in_array($init_ord, $unsafe_init)) {
754 // Test for illegal content char
755 for ($i = 0; $i < strlen($attr_value); $i++) {
756 $char_ord = ord(substr($attr_value, $i, 1));
757 if ($char_ord > 127 || in_array($char_ord, $unsafe)) {
762 // Test for ending space
763 if (substr($attr_value, -1) == ' ') {
767 // If converting is needed, do it
768 // Either we have some special chars or a matching "raw" regex
769 if ($base64 || ($this->_options['raw'] && preg_match($this->_options['raw'], $attr_name))) {
771 $attr_value = base64_encode($attr_value);
774 // Lowercase attr names if requested
775 if ($this->_options['lowercase']) $attr_name = strtolower($attr_name);
777 // Handle line wrapping
778 if ($this->_options['wrap'] > 40 && strlen($attr_value) > $this->_options['wrap']) {
779 $attr_value = wordwrap($attr_value, $this->_options['wrap'], PHP_EOL." ", true);
783 return $attr_name.': '.$attr_value;
787 * Convert an entries DN to LDIF string representation
789 * It honors correct encoding of values according to RFC 2849.
791 * @param string $dn UTF8-Encoded DN
794 * @return string LDIF string for that DN
795 * @todo I am not sure, if the UTF8 stuff is correctly handled right now
797 protected function convertDN($dn)
800 // ASCII-chars that are NOT safe for the
801 // start and for being inside the dn.
802 // These are the int values of those chars.
803 $unsafe_init = array(0, 10, 13, 32, 58, 60);
804 $unsafe = array(0, 10, 13);
806 // Test for illegal init char
807 $init_ord = ord(substr($dn, 0, 1));
808 if ($init_ord >= 127 || in_array($init_ord, $unsafe_init)) {
812 // Test for illegal content char
813 for ($i = 0; $i < strlen($dn); $i++) {
814 $char = substr($dn, $i, 1);
815 if (ord($char) >= 127 || in_array($init_ord, $unsafe)) {
820 // Test for ending space
821 if (substr($dn, -1) == ' ') {
825 // if converting is needed, do it
826 return ($base64)? 'dn:: '.base64_encode($dn) : 'dn: '.$dn;
830 * Writes an attribute to the filehandle
832 * @param string $attr_name Name of the attribute
833 * @param string|array $attr_values Single attribute value or array with attribute values
838 protected function writeAttribute($attr_name, $attr_values)
840 // write out attribute content
841 if (!is_array($attr_values)) {
842 $attr_values = array($attr_values);
844 foreach ($attr_values as $attr_val) {
845 $line = $this->convertAttribute($attr_name, $attr_val).PHP_EOL;
846 $this->writeLine($line, 'Net_LDAP2_LDIF error: unable to write attribute '.$attr_name.' of entry '.$this->_entrynum);
851 * Writes a DN to the filehandle
853 * @param string $dn DN to write
858 protected function writeDN($dn)
861 if ($this->_options['encode'] == 'base64') {
862 $dn = $this->convertDN($dn).PHP_EOL;
863 } elseif ($this->_options['encode'] == 'canonical') {
864 $dn = Net_LDAP2_Util::canonical_dn($dn, array('casefold' => 'none')).PHP_EOL;
868 $this->writeLine($dn, 'Net_LDAP2_LDIF error: unable to write DN of entry '.$this->_entrynum);
872 * Finishes an LDIF entry
877 protected function finishEntry()
879 $this->writeLine(PHP_EOL, 'Net_LDAP2_LDIF error: unable to close entry '.$this->_entrynum);
883 * Just write an arbitary line to the filehandle
885 * @param string $line Content to write
886 * @param string $error If error occurs, drop this message
891 protected function writeLine($line, $error = 'Net_LDAP2_LDIF error: unable to write to filehandle')
893 if (is_resource($this->handle()) && fwrite($this->handle(), $line, strlen($line)) === false) {
894 $this->dropError($error);
902 * Optionally raises an error and pushes the error on the error cache
904 * @param string $msg Errortext
905 * @param int $line Line in the LDIF that caused the error
910 protected function dropError($msg, $line = null)
912 $this->_error['error'] = new Net_LDAP2_Error($msg);
913 if ($line !== null) $this->_error['line'] = $line;
915 if ($this->_options['onerror'] == 'die') {
917 } elseif ($this->_options['onerror'] == 'warn') {