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 324918 2012-04-06 12:31:04Z clockwerx $
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']);
344 $is_changed = ($num_of_changes > 0 || $entry->willBeDeleted() || $entry->willBeMoved());
346 // write version if not done yet
347 // also write DN of entry
349 if (!$this->_version_written) {
350 $this->write_version();
352 $this->writeDN($entry->currentDN());
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);
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);
387 // finish this entrys data if we had changes
389 $this->finishEntry();
393 // fetch attributes for further processing
394 $entry_attrs = $entry->getValues();
396 // sort and put objectclass-attrs to first position
397 if ($this->_options['sort']) {
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);
407 if (!$this->_version_written) {
408 $this->write_version();
410 $this->writeDN($entry->dn());
411 foreach ($entry_attrs as $attr_name => $attr_values) {
412 $this->writeAttribute($attr_name, $attr_values);
414 $this->finishEntry();
421 * Write version to LDIF
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.
428 public function write_version()
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');
437 * Get or set LDIF version
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.
443 * @param int $version (optional) LDIF version to set
447 public function version($version = null)
449 if ($version !== null) {
451 $this->dropError('Net_LDAP2_LDIF error: illegal LDIF version set');
453 $this->_options['version'] = $version;
456 return $this->_options['version'];
460 * Returns the file handle the Net_LDAP2_LDIF object reads from or writes to.
462 * You can, for example, use this to fetch the content of the LDIF file yourself
464 * @return null|resource
466 public function &handle()
468 if (!is_resource($this->_FH)) {
469 $this->dropError('Net_LDAP2_LDIF error: invalid file resource');
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.
486 public function done()
488 // close FH if we opened it
489 if ($this->_FH_opened) {
490 fclose($this->handle());
494 foreach (get_object_vars($this) as $name => $value) {
500 * Returns last error message if error was found.
504 * $ldif->someAction();
505 * if ($ldif->error()) {
506 * echo "Error: ".$ldif->error()." at input line: ".$ldif->error_lines();
510 * @param boolean $as_string If set to true, only the message is returned
512 * @return false|Net_LDAP2_Error
514 public function error($as_string = false)
516 if (Net_LDAP2::isError($this->_error['error'])) {
517 return ($as_string)? $this->_error['error']->getMessage() : $this->_error['error'];
524 * Returns lines that resulted in error.
526 * Perl returns an array of faulty lines in list context,
527 * but we always just return an int because of PHPs language.
531 public function error_lines()
533 return $this->_error['line'];
537 * Returns the current Net::LDAP::Entry object.
539 * @return Net_LDAP2_Entry|false
541 public function current_entry()
543 return $this->parseLines($this->current_lines());
547 * Parse LDIF lines of one entry into an Net_LDAP2_Entry object
549 * @param array $lines LDIF lines for one entry
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"
554 public function parseLines($lines)
556 // parse lines into an array of attributes and build the entry
557 $attributes = array();
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];
567 $attributes[$attr][] = $data;
568 } elseif ($delim == '::') {
570 $attributes[$attr][] = base64_decode($data);
571 } elseif ($delim == ':<') {
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][] = ...;
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);
582 if (strtolower($attr) == 'dn') {
584 $dn = $attributes[$attr][0]; // save possibly decoded DN
585 unset($attributes[$attr]); // remove wrongly added "dn: " attribute
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.
598 $this->dropError('Net_LDAP2_LDIF parsing error: unable to detect DN for entry');
601 $newentry = Net_LDAP2_Entry::createFresh($dn, $attributes);
607 * Returns the lines that generated the current Net::LDAP::Entry object.
609 * Note that this returns an empty array if no lines have been read so far.
611 * @return array Array of lines
613 public function current_lines()
615 return $this->_lines_cur;
619 * Returns the lines that will generate the next Net::LDAP::Entry object.
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.
625 * Wrapped lines will be unwrapped. Comments are stripped.
627 * @param boolean $force Set this to true if you want to iterate over the lines manually
631 public function next_lines($force = false)
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)
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
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
649 $this->dropError('Net_LDAP2_LDIF error: error reading from file at input line '.$this->_input_line, $this->_input_line);
653 if (count($this->_lines_next) > 0 && preg_match('/^$/', $data)) {
654 // Entry is finished if we have an empty line after we had data
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);
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);
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);
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
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);
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.
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);
700 $last = array_pop($this->_lines_next);
701 $last = $last.$matches[1];
702 $this->_lines_next[] = $last;
706 } elseif (preg_match('/^#/', $data)) {
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;
714 $this->dropError('Net_LDAP2_LDIF error: invalid syntax at input line '.$this->_input_line, $this->_input_line);
722 return $this->_lines_next;
726 * Convert an attribute and value to LDIF string representation
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.
732 * @param string $attr_name Name of the attribute
733 * @param string $attr_value Value of the attribute
736 * @return string LDIF string for that attribute and value
738 protected function convertAttribute($attr_name, $attr_value)
740 // Handle empty attribute or process
741 if (strlen($attr_value) == 0) {
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);
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)) {
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)) {
765 // Test for ending space
766 if (substr($attr_value, -1) == ' ') {
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))) {
774 $attr_value = base64_encode($attr_value);
777 // Lowercase attr names if requested
778 if ($this->_options['lowercase']) $attr_name = strtolower($attr_name);
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);
786 return $attr_name.': '.$attr_value;
790 * Convert an entries DN to LDIF string representation
792 * It honors correct encoding of values according to RFC 2849.
794 * @param string $dn UTF8-Encoded DN
797 * @return string LDIF string for that DN
798 * @todo I am not sure, if the UTF8 stuff is correctly handled right now
800 protected function convertDN($dn)
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);
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)) {
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)) {
823 // Test for ending space
824 if (substr($dn, -1) == ' ') {
828 // if converting is needed, do it
829 return ($base64)? 'dn:: '.base64_encode($dn) : 'dn: '.$dn;
833 * Writes an attribute to the filehandle
835 * @param string $attr_name Name of the attribute
836 * @param string|array $attr_values Single attribute value or array with attribute values
841 protected function writeAttribute($attr_name, $attr_values)
843 // write out attribute content
844 if (!is_array($attr_values)) {
845 $attr_values = array($attr_values);
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);
854 * Writes a DN to the filehandle
856 * @param string $dn DN to write
861 protected function writeDN($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;
871 $this->writeLine($dn, 'Net_LDAP2_LDIF error: unable to write DN of entry '.$this->_entrynum);
875 * Finishes an LDIF entry
880 protected function finishEntry()
882 $this->writeLine(PHP_EOL, 'Net_LDAP2_LDIF error: unable to close entry '.$this->_entrynum);
886 * Just write an arbitary line to the filehandle
888 * @param string $line Content to write
889 * @param string $error If error occurs, drop this message
894 protected function writeLine($line, $error = 'Net_LDAP2_LDIF error: unable to write to filehandle')
896 if (is_resource($this->handle()) && fwrite($this->handle(), $line, strlen($line)) === false) {
897 $this->dropError($error);
905 * Optionally raises an error and pushes the error on the error cache
907 * @param string $msg Errortext
908 * @param int $line Line in the LDIF that caused the error
913 protected function dropError($msg, $line = null)
915 $this->_error['error'] = new Net_LDAP2_Error($msg);
916 if ($line !== null) $this->_error['line'] = $line;
918 if ($this->_options['onerror'] == 'die') {
920 } elseif ($this->_options['onerror'] == 'warn') {