Ldap.php 51.3 KB
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 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Ldap
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Ldap.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @category   Zend
 * @package    Zend_Ldap
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Ldap
{
    const SEARCH_SCOPE_SUB  = 1;
    const SEARCH_SCOPE_ONE  = 2;
    const SEARCH_SCOPE_BASE = 3;

    const ACCTNAME_FORM_DN        = 1;
    const ACCTNAME_FORM_USERNAME  = 2;
    const ACCTNAME_FORM_BACKSLASH = 3;
    const ACCTNAME_FORM_PRINCIPAL = 4;

    /**
     * String used with ldap_connect for error handling purposes.
     *
     * @var string
     */
    private $_connectString;

    /**
     * The options used in connecting, binding, etc.
     *
     * @var array
     */
    protected $_options = null;

    /**
     * The raw LDAP extension resource.
     *
     * @var resource
     */
    protected $_resource = null;

    /**
     * FALSE if no user is bound to the LDAP resource
     * NULL if there has been an anonymous bind
     * username of the currently bound user
     *
     * @var boolean|null|string
     */
    protected $_boundUser = false;

    /**
     * Caches the RootDSE
     *
     * @var Zend_Ldap_Node
     */
    protected $_rootDse = null;

    /**
     * Caches the schema
     *
     * @var Zend_Ldap_Node
     */
    protected $_schema = null;

    /**
     * @deprecated will be removed, use {@see Zend_Ldap_Filter_Abstract::escapeValue()}
     * @param  string $str The string to escape.
     * @return string The escaped string
     */
    public static function filterEscape($str)
    {
        /**
         * @see Zend_Ldap_Filter_Abstract
         */
        require_once 'Zend/Ldap/Filter/Abstract.php';
        return Zend_Ldap_Filter_Abstract::escapeValue($str);
    }

    /**
     * @deprecated will be removed, use {@see Zend_Ldap_Dn::checkDn()}
     * @param  string $dn   The DN to parse
     * @param  array  $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...)
     * @param  array  $vals An optional array to receive DN values
     * @return boolean True if the DN was successfully parsed or false if the string is
     * not a valid DN.
     */
    public static function explodeDn($dn, array &$keys = null, array &$vals = null)
    {
        /**
         * @see Zend_Ldap_Dn
         */
        require_once 'Zend/Ldap/Dn.php';
        return Zend_Ldap_Dn::checkDn($dn, $keys, $vals);
    }

    /**
     * Constructor.
     *
     * @param  array|Zend_Config $options Options used in connecting, binding, etc.
     * @return void
     * @throws Zend_Ldap_Exception if ext/ldap is not installed
     */
    public function __construct($options = array())
    {
        if (!extension_loaded('ldap')) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception(null, 'LDAP extension not loaded',
                Zend_Ldap_Exception::LDAP_X_EXTENSION_NOT_LOADED);
        }
        $this->setOptions($options);
    }

    /**
     * Destructor.
     *
     * @return void
     */
    public function __destruct()
    {
        $this->disconnect();
    }

    /**
     * @return resource The raw LDAP extension resource.
     */
    public function getResource()
    {
        if (!is_resource($this->_resource) || $this->_boundUser === false) {
            $this->bind();
        }
        return $this->_resource;
    }

    /**
     * Return the LDAP error number of the last LDAP command
     *
     * @return int
     */
    public function getLastErrorCode()
    {
        $ret = @ldap_get_option($this->_resource, LDAP_OPT_ERROR_NUMBER, $err);
        if ($ret === true) {
            if ($err <= -1 && $err >= -17) {
                /**
                 * @see Zend_Ldap_Exception
                 */
                require_once 'Zend/Ldap/Exception.php';
                /* For some reason draft-ietf-ldapext-ldap-c-api-xx.txt error
                 * codes in OpenLDAP are negative values from -1 to -17.
                 */
                $err = Zend_Ldap_Exception::LDAP_SERVER_DOWN + (-$err - 1);
            }
            return $err;
        }
        return 0;
    }

    /**
     * Return the LDAP error message of the last LDAP command
     *
     * @param  int   $errorCode
     * @param  array $errorMessages
     * @return string
     */
    public function getLastError(&$errorCode = null, array &$errorMessages = null)
    {
        $errorCode = $this->getLastErrorCode();
        $errorMessages = array();

        /* The various error retrieval functions can return
         * different things so we just try to collect what we
         * can and eliminate dupes.
         */
        $estr1 = @ldap_error($this->_resource);
        if ($errorCode !== 0 && $estr1 === 'Success') {
            $estr1 = @ldap_err2str($errorCode);
        }
        if (!empty($estr1)) {
            $errorMessages[] = $estr1;
        }

        @ldap_get_option($this->_resource, LDAP_OPT_ERROR_STRING, $estr2);
        if (!empty($estr2) && !in_array($estr2, $errorMessages)) {
            $errorMessages[] = $estr2;
        }

        $message = '';
        if ($errorCode > 0) {
            $message = '0x' . dechex($errorCode) . ' ';
        } else {
            $message = '';
        }
        if (count($errorMessages) > 0) {
            $message .= '(' . implode('; ', $errorMessages) . ')';
        } else {
            $message .= '(no error message from LDAP)';
        }
        return $message;
    }

    /**
     * Get the currently bound user
     *
     * FALSE if no user is bound to the LDAP resource
     * NULL if there has been an anonymous bind
     * username of the currently bound user
     *
     * @return false|null|string
     */
    public function getBoundUser()
    {
        return $this->_boundUser;
    }

    /**
     * Sets the options used in connecting, binding, etc.
     *
     * Valid option keys:
     *  host
     *  port
     *  useSsl
     *  username
     *  password
     *  bindRequiresDn
     *  baseDn
     *  accountCanonicalForm
     *  accountDomainName
     *  accountDomainNameShort
     *  accountFilterFormat
     *  allowEmptyPassword
     *  useStartTls
     *  optRefferals
     *  tryUsernameSplit
     *
     * @param  array|Zend_Config $options Options used in connecting, binding, etc.
     * @return Zend_Ldap Provides a fluent interface
     * @throws Zend_Ldap_Exception
     */
    public function setOptions($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        }

        $permittedOptions = array(
            'host'                   => null,
            'port'                   => 0,
            'useSsl'                 => false,
            'username'               => null,
            'password'               => null,
            'bindRequiresDn'         => false,
            'baseDn'                 => null,
            'accountCanonicalForm'   => null,
            'accountDomainName'      => null,
            'accountDomainNameShort' => null,
            'accountFilterFormat'    => null,
            'allowEmptyPassword'     => false,
            'useStartTls'            => false,
            'optReferrals'           => false,
            'tryUsernameSplit'       => true,
        );

        foreach ($permittedOptions as $key => $val) {
            if (array_key_exists($key, $options)) {
                $val = $options[$key];
                unset($options[$key]);
                /* Enforce typing. This eliminates issues like Zend_Config_Ini
                 * returning '1' as a string (ZF-3163).
                 */
                switch ($key) {
                    case 'port':
                    case 'accountCanonicalForm':
                        $permittedOptions[$key] = (int)$val;
                        break;
                    case 'useSsl':
                    case 'bindRequiresDn':
                    case 'allowEmptyPassword':
                    case 'useStartTls':
                    case 'optReferrals':
                    case 'tryUsernameSplit':
                        $permittedOptions[$key] = ($val === true ||
                                $val === '1' || strcasecmp($val, 'true') == 0);
                        break;
                    default:
                        $permittedOptions[$key] = trim($val);
                        break;
                }
            }
        }
        if (count($options) > 0) {
            $key = key($options);
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception(null, "Unknown Zend_Ldap option: $key");
        }
        $this->_options = $permittedOptions;
        return $this;
    }

    /**
     * @return array The current options.
     */
    public function getOptions()
    {
        return $this->_options;
    }

    /**
     * @return string The hostname of the LDAP server being used to authenticate accounts
     */
    protected function _getHost()
    {
        return $this->_options['host'];
    }

    /**
     * @return int The port of the LDAP server or 0 to indicate that no port value is set
     */
    protected function _getPort()
    {
        return $this->_options['port'];
    }

    /**
     * @return boolean The default SSL / TLS encrypted transport control
     */
    protected function _getUseSsl()
    {
        return $this->_options['useSsl'];
    }

    /**
     * @return string The default acctname for binding
     */
    protected function _getUsername()
    {
        return $this->_options['username'];
    }

    /**
     * @return string The default password for binding
     */
    protected function _getPassword()
    {
        return $this->_options['password'];
    }

    /**
     * @return boolean Bind requires DN
     */
    protected function _getBindRequiresDn()
    {
        return $this->_options['bindRequiresDn'];
    }

    /**
     * Gets the base DN under which objects of interest are located
     *
     * @return string
     */
    public function getBaseDn()
    {
        return $this->_options['baseDn'];
    }

    /**
     * @return integer Either ACCTNAME_FORM_BACKSLASH, ACCTNAME_FORM_PRINCIPAL or
     * ACCTNAME_FORM_USERNAME indicating the form usernames should be canonicalized to.
     */
    protected function _getAccountCanonicalForm()
    {
        /* Account names should always be qualified with a domain. In some scenarios
         * using non-qualified account names can lead to security vulnerabilities. If
         * no account canonical form is specified, we guess based in what domain
         * names have been supplied.
         */

        $accountCanonicalForm = $this->_options['accountCanonicalForm'];
        if (!$accountCanonicalForm) {
            $accountDomainName = $this->_getAccountDomainName();
            $accountDomainNameShort = $this->_getAccountDomainNameShort();
            if ($accountDomainNameShort) {
                $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_BACKSLASH;
            } else if ($accountDomainName) {
                $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_PRINCIPAL;
            } else {
                $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_USERNAME;
            }
        }

        return $accountCanonicalForm;
    }

    /**
     * @return string The account domain name
     */
    protected function _getAccountDomainName()
    {
        return $this->_options['accountDomainName'];
    }

    /**
     * @return string The short account domain name
     */
    protected function _getAccountDomainNameShort()
    {
        return $this->_options['accountDomainNameShort'];
    }

    /**
     * @return string A format string for building an LDAP search filter to match
     * an account
     */
    protected function _getAccountFilterFormat()
    {
        return $this->_options['accountFilterFormat'];
    }

    /**
     * @return boolean Allow empty passwords
     */
    protected function _getAllowEmptyPassword()
    {
        return $this->_options['allowEmptyPassword'];
    }

    /**
     * @return boolean The default SSL / TLS encrypted transport control
     */
    protected function _getUseStartTls()
    {
        return $this->_options['useStartTls'];
    }

    /**
     * @return boolean Opt. Referrals
     */
    protected function _getOptReferrals()
    {
        return $this->_options['optReferrals'];
    }

    /**
     * @return boolean Try splitting the username into username and domain
     */
    protected function _getTryUsernameSplit()
    {
        return $this->_options['tryUsernameSplit'];
    }

    /**
     * @return string The LDAP search filter for matching directory accounts
     */
    protected function _getAccountFilter($acctname)
    {
        /**
         * @see Zend_Ldap_Filter_Abstract
         */
        require_once 'Zend/Ldap/Filter/Abstract.php';
        $this->_splitName($acctname, $dname, $aname);
        $accountFilterFormat = $this->_getAccountFilterFormat();
        $aname = Zend_Ldap_Filter_Abstract::escapeValue($aname);
        if ($accountFilterFormat) {
            return sprintf($accountFilterFormat, $aname);
        }
        if (!$this->_getBindRequiresDn()) {
            // is there a better way to detect this?
            return sprintf("(&(objectClass=user)(sAMAccountName=%s))", $aname);
        }
        return sprintf("(&(objectClass=posixAccount)(uid=%s))", $aname);
    }

    /**
     * @param string $name  The name to split
     * @param string $dname The resulting domain name (this is an out parameter)
     * @param string $aname The resulting account name (this is an out parameter)
     * @return void
     */
    protected function _splitName($name, &$dname, &$aname)
    {
        $dname = null;
        $aname = $name;

        if (!$this->_getTryUsernameSplit()) {
            return;
        }

        $pos = strpos($name, '@');
        if ($pos) {
            $dname = substr($name, $pos + 1);
            $aname = substr($name, 0, $pos);
        } else {
            $pos = strpos($name, '\\');
            if ($pos) {
                $dname = substr($name, 0, $pos);
                $aname = substr($name, $pos + 1);
            }
        }
    }

    /**
     * @param  string $acctname The name of the account
     * @return string The DN of the specified account
     * @throws Zend_Ldap_Exception
     */
    protected function _getAccountDn($acctname)
    {
        /**
         * @see Zend_Ldap_Dn
         */
        require_once 'Zend/Ldap/Dn.php';
        if (Zend_Ldap_Dn::checkDn($acctname)) return $acctname;
        $acctname = $this->getCanonicalAccountName($acctname, Zend_Ldap::ACCTNAME_FORM_USERNAME);
        $acct = $this->_getAccount($acctname, array('dn'));
        return $acct['dn'];
    }

    /**
     * @param  string $dname The domain name to check
     * @return boolean
     */
    protected function _isPossibleAuthority($dname)
    {
        if ($dname === null) {
            return true;
        }
        $accountDomainName = $this->_getAccountDomainName();
        $accountDomainNameShort = $this->_getAccountDomainNameShort();
        if ($accountDomainName === null && $accountDomainNameShort === null) {
            return true;
        }
        if (strcasecmp($dname, $accountDomainName) == 0) {
            return true;
        }
        if (strcasecmp($dname, $accountDomainNameShort) == 0) {
            return true;
        }
        return false;
    }

    /**
     * @param  string $acctname The name to canonicalize
     * @param  int    $type     The desired form of canonicalization
     * @return string The canonicalized name in the desired form
     * @throws Zend_Ldap_Exception
     */
    public function getCanonicalAccountName($acctname, $form = 0)
    {
        $this->_splitName($acctname, $dname, $uname);

        if (!$this->_isPossibleAuthority($dname)) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception(null,
                "Binding domain is not an authority for user: $acctname",
                Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH);
        }

        if (!$uname) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception(null, "Invalid account name syntax: $acctname");
        }

        if (function_exists('mb_strtolower')) {
            $uname = mb_strtolower($uname, 'UTF-8');
        } else {
            $uname = strtolower($uname);
        }

        if ($form === 0) {
            $form = $this->_getAccountCanonicalForm();
        }

        switch ($form) {
            case Zend_Ldap::ACCTNAME_FORM_DN:
                return $this->_getAccountDn($acctname);
            case Zend_Ldap::ACCTNAME_FORM_USERNAME:
                return $uname;
            case Zend_Ldap::ACCTNAME_FORM_BACKSLASH:
                $accountDomainNameShort = $this->_getAccountDomainNameShort();
                if (!$accountDomainNameShort) {
                    /**
                     * @see Zend_Ldap_Exception
                     */
                    require_once 'Zend/Ldap/Exception.php';
                    throw new Zend_Ldap_Exception(null, 'Option required: accountDomainNameShort');
                }
                return "$accountDomainNameShort\\$uname";
            case Zend_Ldap::ACCTNAME_FORM_PRINCIPAL:
                $accountDomainName = $this->_getAccountDomainName();
                if (!$accountDomainName) {
                    /**
                     * @see Zend_Ldap_Exception
                     */
                    require_once 'Zend/Ldap/Exception.php';
                    throw new Zend_Ldap_Exception(null, 'Option required: accountDomainName');
                }
                return "$uname@$accountDomainName";
            default:
                /**
                 * @see Zend_Ldap_Exception
                 */
                require_once 'Zend/Ldap/Exception.php';
                throw new Zend_Ldap_Exception(null, "Unknown canonical name form: $form");
        }
    }

    /**
     * @param  array $attrs An array of names of desired attributes
     * @return array An array of the attributes representing the account
     * @throws Zend_Ldap_Exception
     */
    protected function _getAccount($acctname, array $attrs = null)
    {
        $baseDn = $this->getBaseDn();
        if (!$baseDn) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception(null, 'Base DN not set');
        }

        $accountFilter = $this->_getAccountFilter($acctname);
        if (!$accountFilter) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception(null, 'Invalid account filter');
        }

        if (!is_resource($this->getResource())) {
            $this->bind();
        }

        $accounts = $this->search($accountFilter, $baseDn, self::SEARCH_SCOPE_SUB, $attrs);
        $count = $accounts->count();
        if ($count === 1) {
            $acct = $accounts->getFirst();
            $accounts->close();
            return $acct;
        } else if ($count === 0) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            $code = Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT;
            $str = "No object found for: $accountFilter";
        } else {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            $code = Zend_Ldap_Exception::LDAP_OPERATIONS_ERROR;
            $str = "Unexpected result count ($count) for: $accountFilter";
        }
        $accounts->close();
        /**
         * @see Zend_Ldap_Exception
         */
        require_once 'Zend/Ldap/Exception.php';
        throw new Zend_Ldap_Exception($this, $str, $code);
    }

    /**
     * @return Zend_Ldap Provides a fluent interface
     */
    public function disconnect()
    {
        if (is_resource($this->_resource)) {
            @ldap_unbind($this->_resource);
        }
        $this->_resource = null;
        $this->_boundUser = false;
        return $this;
    }

    /**
     * To connect using SSL it seems the client tries to verify the server
     * certificate by default. One way to disable this behavior is to set
     * 'TLS_REQCERT never' in OpenLDAP's ldap.conf and restarting Apache. Or,
     * if you really care about the server's cert you can put a cert on the
     * web server.
     *
     * @param  string  $host        The hostname of the LDAP server to connect to
     * @param  int     $port        The port number of the LDAP server to connect to
     * @param  boolean $useSsl      Use SSL
     * @param  boolean $useStartTls Use STARTTLS
     * @return Zend_Ldap Provides a fluent interface
     * @throws Zend_Ldap_Exception
     */
    public function connect($host = null, $port = null, $useSsl = null, $useStartTls = null)
    {
        if ($host === null) {
            $host = $this->_getHost();
        }
        if ($port === null) {
            $port = $this->_getPort();
        } else {
            $port = (int)$port;
        }
        if ($useSsl === null) {
            $useSsl = $this->_getUseSsl();
        } else {
            $useSsl = (bool)$useSsl;
        }
        if ($useStartTls === null) {
            $useStartTls = $this->_getUseStartTls();
        } else {
            $useStartTls = (bool)$useStartTls;
        }

        if (!$host) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception(null, 'A host parameter is required');
        }

        $useUri = false;
        /* Because ldap_connect doesn't really try to connect, any connect error
         * will actually occur during the ldap_bind call. Therefore, we save the
         * connect string here for reporting it in error handling in bind().
         */
        $hosts = array();
        if (preg_match_all('~ldap(?:i|s)?://~', $host, $hosts, PREG_SET_ORDER) > 0) {
            $this->_connectString = $host;
            $useUri = true;
            $useSsl = false;
        } else {
            if ($useSsl) {
                $this->_connectString = 'ldaps://' . $host;
                $useUri = true;
            } else {
                $this->_connectString = 'ldap://' . $host;
            }
            if ($port) {
                $this->_connectString .= ':' . $port;
            }
        }

        $this->disconnect();

        /* Only OpenLDAP 2.2 + supports URLs so if SSL is not requested, just
         * use the old form.
         */
        $resource = ($useUri) ? @ldap_connect($this->_connectString) : @ldap_connect($host, $port);

        if (is_resource($resource) === true) {
            $this->_resource = $resource;
            $this->_boundUser = false;

            $optReferrals = ($this->_getOptReferrals()) ? 1 : 0;
            if (@ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3) &&
                        @ldap_set_option($resource, LDAP_OPT_REFERRALS, $optReferrals)) {
                if ($useSsl || !$useStartTls || @ldap_start_tls($resource)) {
                    return $this;
                }
            }

            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            $zle = new Zend_Ldap_Exception($this, "$host:$port");
            $this->disconnect();
            throw $zle;
        }
        /**
         * @see Zend_Ldap_Exception
         */
        require_once 'Zend/Ldap/Exception.php';
        throw new Zend_Ldap_Exception(null, "Failed to connect to LDAP server: $host:$port");
    }

    /**
     * @param  string $username The username for authenticating the bind
     * @param  string $password The password for authenticating the bind
     * @return Zend_Ldap Provides a fluent interface
     * @throws Zend_Ldap_Exception
     */
    public function bind($username = null, $password = null)
    {
        $moreCreds = true;

        if ($username === null) {
            $username = $this->_getUsername();
            $password = $this->_getPassword();
            $moreCreds = false;
        }

        if (empty($username)) {
            /* Perform anonymous bind
             */
            $username = null;
            $password = null;
        } else {
            /* Check to make sure the username is in DN form.
             */
            /**
             * @see Zend_Ldap_Dn
             */
            require_once 'Zend/Ldap/Dn.php';
            if (!Zend_Ldap_Dn::checkDn($username)) {
                if ($this->_getBindRequiresDn()) {
                    /* moreCreds stops an infinite loop if _getUsername does not
                     * return a DN and the bind requires it
                     */
                    if ($moreCreds) {
                        try {
                            $username = $this->_getAccountDn($username);
                        } catch (Zend_Ldap_Exception $zle) {
                            switch ($zle->getCode()) {
                                case Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT:
                                case Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH:
                                case Zend_Ldap_Exception::LDAP_X_EXTENSION_NOT_LOADED:
                                    throw $zle;
                            }
                            throw new Zend_Ldap_Exception(null,
                                'Failed to retrieve DN for account: ' . $username .
                                ' [' . $zle->getMessage() . ']',
                                Zend_Ldap_Exception::LDAP_OPERATIONS_ERROR);
                        }
                    } else {
                        /**
                         * @see Zend_Ldap_Exception
                         */
                        require_once 'Zend/Ldap/Exception.php';
                        throw new Zend_Ldap_Exception(null, 'Binding requires username in DN form');
                    }
                } else {
                    $username = $this->getCanonicalAccountName($username,
                        $this->_getAccountCanonicalForm());
                }
            }
        }

        if (!is_resource($this->_resource)) {
            $this->connect();
        }

        if ($username !== null && $password === '' && $this->_getAllowEmptyPassword() !== true) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            $zle = new Zend_Ldap_Exception(null,
                'Empty password not allowed - see allowEmptyPassword option.');
        } else {
            if (@ldap_bind($this->_resource, $username, $password)) {
                $this->_boundUser = $username;
                return $this;
            }

            $message = ($username === null) ? $this->_connectString : $username;
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            switch ($this->getLastErrorCode()) {
                case Zend_Ldap_Exception::LDAP_SERVER_DOWN:
                    /* If the error is related to establishing a connection rather than binding,
                     * the connect string is more informative than the username.
                     */
                    $message = $this->_connectString;
            }

            $zle = new Zend_Ldap_Exception($this, $message);
        }
        $this->disconnect();
        throw $zle;
    }

    /**
     * A global LDAP search routine for finding information.
     *
     * Options can be either passed as single parameters according to the
     * method signature or as an array with one or more of the following keys
     * - filter
     * - baseDn
     * - scope
     * - attributes
     * - sort
     * - collectionClass
     * - sizelimit
     * - timelimit
     *
     * @param  string|Zend_Ldap_Filter_Abstract|array $filter
     * @param  string|Zend_Ldap_Dn|null               $basedn
     * @param  integer                                $scope
     * @param  array                                  $attributes
     * @param  string|null                            $sort
     * @param  string|null                            $collectionClass
     * @param  integer                                  $sizelimit
     * @param  integer                                  $timelimit
     * @return Zend_Ldap_Collection
     * @throws Zend_Ldap_Exception
     */
    public function search($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, array $attributes = array(),
        $sort = null, $collectionClass = null, $sizelimit = 0, $timelimit = 0)
    {
        if (is_array($filter)) {
            $options = array_change_key_case($filter, CASE_LOWER);
            foreach ($options as $key => $value) {
                switch ($key) {
                    case 'filter':
                    case 'basedn':
                    case 'scope':
                    case 'sort':
                        $$key = $value;
                        break;
                    case 'attributes':
                        if (is_array($value)) {
                            $attributes = $value;
                        }
                        break;
                    case 'collectionclass':
                        $collectionClass = $value;
                        break;
                    case 'sizelimit':
                    case 'timelimit':
                        $$key = (int)$value;
                }
            }
        }

        if ($basedn === null) {
            $basedn = $this->getBaseDn();
        }
        else if ($basedn instanceof Zend_Ldap_Dn) {
            $basedn = $basedn->toString();
        }

        if ($filter instanceof Zend_Ldap_Filter_Abstract) {
            $filter = $filter->toString();
        }

        switch ($scope) {
            case self::SEARCH_SCOPE_ONE:
                $search = @ldap_list($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
                break;
            case self::SEARCH_SCOPE_BASE:
                $search = @ldap_read($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
                break;
            case self::SEARCH_SCOPE_SUB:
            default:
                $search = @ldap_search($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
                break;
        }

        if($search === false) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception($this, 'searching: ' . $filter);
        }
        if ($sort !== null && is_string($sort)) {
            $isSorted = @ldap_sort($this->getResource(), $search, $sort);
            if($isSorted === false) {
                /**
                 * @see Zend_Ldap_Exception
                 */
                require_once 'Zend/Ldap/Exception.php';
                throw new Zend_Ldap_Exception($this, 'sorting: ' . $sort);
            }
        }

        /**
         * Zend_Ldap_Collection_Iterator_Default
         */
        require_once 'Zend/Ldap/Collection/Iterator/Default.php';
        $iterator = new Zend_Ldap_Collection_Iterator_Default($this, $search);
        return $this->_createCollection($iterator, $collectionClass);
    }

    /**
     * Extension point for collection creation
     *
     * @param  Zend_Ldap_Collection_Iterator_Default    $iterator
     * @param  string|null                                $collectionClass
     * @return Zend_Ldap_Collection
     * @throws Zend_Ldap_Exception
     */
    protected function _createCollection(Zend_Ldap_Collection_Iterator_Default $iterator, $collectionClass)
    {
        if ($collectionClass === null) {
            /**
             * Zend_Ldap_Collection
             */
            require_once 'Zend/Ldap/Collection.php';
            return new Zend_Ldap_Collection($iterator);
        } else {
            $collectionClass = (string)$collectionClass;
            if (!class_exists($collectionClass)) {
                /**
                 * @see Zend_Ldap_Exception
                 */
                require_once 'Zend/Ldap/Exception.php';
                throw new Zend_Ldap_Exception(null,
                    "Class '$collectionClass' can not be found");
            }
            if (!is_subclass_of($collectionClass, 'Zend_Ldap_Collection')) {
                /**
                 * @see Zend_Ldap_Exception
                 */
                require_once 'Zend/Ldap/Exception.php';
                throw new Zend_Ldap_Exception(null,
                    "Class '$collectionClass' must subclass 'Zend_Ldap_Collection'");
            }
            return new $collectionClass($iterator);
        }
    }

    /**
     * Count items found by given filter.
     *
     * @param  string|Zend_Ldap_Filter_Abstract $filter
     * @param  string|Zend_Ldap_Dn|null         $basedn
     * @param  integer                          $scope
     * @return integer
     * @throws Zend_Ldap_Exception
     */
    public function count($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB)
    {
        try {
            $result = $this->search($filter, $basedn, $scope, array('dn'), null);
        } catch (Zend_Ldap_Exception $e) {
            if ($e->getCode() === Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) return 0;
            else throw $e;
        }
        return $result->count();
    }

    /**
     * Count children for a given DN.
     *
     * @param  string|Zend_Ldap_Dn $dn
     * @return integer
     * @throws Zend_Ldap_Exception
     */
    public function countChildren($dn)
    {
        return $this->count('(objectClass=*)', $dn, self::SEARCH_SCOPE_ONE);
    }

    /**
     * Check if a given DN exists.
     *
     * @param  string|Zend_Ldap_Dn $dn
     * @return boolean
     * @throws Zend_Ldap_Exception
     */
    public function exists($dn)
    {
        return ($this->count('(objectClass=*)', $dn, self::SEARCH_SCOPE_BASE) == 1);
    }

    /**
     * Search LDAP registry for entries matching filter and optional attributes
     *
     * Options can be either passed as single parameters according to the
     * method signature or as an array with one or more of the following keys
     * - filter
     * - baseDn
     * - scope
     * - attributes
     * - sort
     * - reverseSort
     * - sizelimit
     * - timelimit
     *
     * @param  string|Zend_Ldap_Filter_Abstract|array $filter
     * @param  string|Zend_Ldap_Dn|null               $basedn
     * @param  integer                                $scope
     * @param  array                                  $attributes
     * @param  string|null                            $sort
     * @param  boolean                                $reverseSort
     * @param  integer                                  $sizelimit
     * @param  integer                                  $timelimit
     * @return array
     * @throws Zend_Ldap_Exception
     */
    public function searchEntries($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB,
        array $attributes = array(), $sort = null, $reverseSort = false, $sizelimit = 0, $timelimit = 0)
    {
        if (is_array($filter)) {
            $filter = array_change_key_case($filter, CASE_LOWER);
            if (isset($filter['collectionclass'])) {
                unset($filter['collectionclass']);
            }
            if (isset($filter['reversesort'])) {
                $reverseSort = $filter['reversesort'];
                unset($filter['reversesort']);
            }
        }
        $result = $this->search($filter, $basedn, $scope, $attributes, $sort, null, $sizelimit, $timelimit);
        $items = $result->toArray();
        if ((bool)$reverseSort === true) {
            $items = array_reverse($items, false);
        }
        return $items;
    }

    /**
     * Get LDAP entry by DN
     *
     * @param  string|Zend_Ldap_Dn $dn
     * @param  array               $attributes
     * @param  boolean             $throwOnNotFound
     * @return array
     * @throws Zend_Ldap_Exception
     */
    public function getEntry($dn, array $attributes = array(), $throwOnNotFound = false)
    {
        try {
            $result = $this->search("(objectClass=*)", $dn, self::SEARCH_SCOPE_BASE,
                $attributes, null);
            return $result->getFirst();
        } catch (Zend_Ldap_Exception $e){
            if ($throwOnNotFound !== false) throw $e;
        }
        return null;
    }

    /**
     * Prepares an ldap data entry array for insert/update operation
     *
     * @param  array $entry
     * @return void
     * @throws InvalidArgumentException
     */
    public static function prepareLdapEntryArray(array &$entry)
    {
        if (array_key_exists('dn', $entry)) unset($entry['dn']);
        foreach ($entry as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $i => $v) {
                    if ($v === null) unset($value[$i]);
                    else if (!is_scalar($v)) {
                        throw new InvalidArgumentException('Only scalar values allowed in LDAP data');
                    } else {
                        $v = (string)$v;
                        if (strlen($v) == 0) {
                            unset($value[$i]);
                        } else {
                            $value[$i] = $v;
                        }
                    }
                }
                $entry[$key] = array_values($value);
            } else {
                if ($value === null) $entry[$key] = array();
                else if (!is_scalar($value)) {
                    throw new InvalidArgumentException('Only scalar values allowed in LDAP data');
                } else {
                    $value = (string)$value;
                    if (strlen($value) == 0) {
                        $entry[$key] = array();
                    } else {
                        $entry[$key] = array($value);
                    }
                }
            }
        }
        $entry = array_change_key_case($entry, CASE_LOWER);
    }

    /**
     * Add new information to the LDAP repository
     *
     * @param  string|Zend_Ldap_Dn $dn
     * @param  array               $entry
     * @return Zend_Ldap                  Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function add($dn, array $entry)
    {
        if (!($dn instanceof Zend_Ldap_Dn)) {
            $dn = Zend_Ldap_Dn::factory($dn, null);
        }
        self::prepareLdapEntryArray($entry);
        foreach ($entry as $key => $value) {
            if (is_array($value) && count($value) === 0) {
                unset($entry[$key]);
            }
        }

        $rdnParts = $dn->getRdn(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER);
        foreach ($rdnParts as $key => $value) {
            $value = Zend_Ldap_Dn::unescapeValue($value);
            if (!array_key_exists($key, $entry)) {
                $entry[$key] = array($value);
            } else if (!in_array($value, $entry[$key])) {
                $entry[$key] = array_merge(array($value), $entry[$key]);
            }
        }
        $adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory',
            'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated');
        foreach ($adAttributes as $attr) {
            if (array_key_exists($attr, $entry)) {
                unset($entry[$attr]);
            }
        }

        $isAdded = @ldap_add($this->getResource(), $dn->toString(), $entry);
        if($isAdded === false) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception($this, 'adding: ' . $dn->toString());
        }
        return $this;
    }

    /**
     * Update LDAP registry
     *
     * @param  string|Zend_Ldap_Dn $dn
     * @param  array               $entry
     * @return Zend_Ldap                  Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function update($dn, array $entry)
    {
        if (!($dn instanceof Zend_Ldap_Dn)) {
            $dn = Zend_Ldap_Dn::factory($dn, null);
        }
        self::prepareLdapEntryArray($entry);

        $rdnParts = $dn->getRdn(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER);
        foreach ($rdnParts as $key => $value) {
            $value = Zend_Ldap_Dn::unescapeValue($value);
            if (array_key_exists($key, $entry) && !in_array($value, $entry[$key])) {
                $entry[$key] = array_merge(array($value), $entry[$key]);
            }
        }

        $adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory',
            'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated');
        foreach ($adAttributes as $attr) {
            if (array_key_exists($attr, $entry)) {
                unset($entry[$attr]);
            }
        }

        if (count($entry) > 0) {
            $isModified = @ldap_modify($this->getResource(), $dn->toString(), $entry);
            if($isModified === false) {
                /**
                 * @see Zend_Ldap_Exception
                 */
                require_once 'Zend/Ldap/Exception.php';
                throw new Zend_Ldap_Exception($this, 'updating: ' . $dn->toString());
            }
        }
        return $this;
    }

    /**
     * Save entry to LDAP registry.
     *
     * Internally decides if entry will be updated to added by calling
     * {@link exists()}.
     *
     * @param  string|Zend_Ldap_Dn $dn
     * @param  array               $entry
     * @return Zend_Ldap Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function save($dn, array $entry)
    {
        if ($dn instanceof Zend_Ldap_Dn) {
            $dn = $dn->toString();
        }
        if ($this->exists($dn)) $this->update($dn, $entry);
        else $this->add($dn, $entry);
        return $this;
    }

    /**
     * Delete an LDAP entry
     *
     * @param  string|Zend_Ldap_Dn $dn
     * @param  boolean             $recursively
     * @return Zend_Ldap Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function delete($dn, $recursively = false)
    {
        if ($dn instanceof Zend_Ldap_Dn) {
            $dn = $dn->toString();
        }
        if ($recursively === true) {
            if ($this->countChildren($dn)>0) {
                $children = $this->_getChildrenDns($dn);
                foreach ($children as $c) {
                    $this->delete($c, true);
                }
            }
        }
        $isDeleted = @ldap_delete($this->getResource(), $dn);
        if($isDeleted === false) {
            /**
             * @see Zend_Ldap_Exception
             */
            require_once 'Zend/Ldap/Exception.php';
            throw new Zend_Ldap_Exception($this, 'deleting: ' . $dn);
        }
        return $this;
    }

    /**
     * Retrieve the immediate children DNs of the given $parentDn
     *
     * This method is used in recursive methods like {@see delete()}
     * or {@see copy()}
     *
     * @param  string|Zend_Ldap_Dn $parentDn
     * @return array of DNs
     */
    protected function _getChildrenDns($parentDn)
    {
        if ($parentDn instanceof Zend_Ldap_Dn) {
            $parentDn = $parentDn->toString();
        }
        $children = array();
        $search = @ldap_list($this->getResource(), $parentDn, '(objectClass=*)', array('dn'));
        for ($entry = @ldap_first_entry($this->getResource(), $search);
                $entry !== false;
                $entry = @ldap_next_entry($this->getResource(), $entry)) {
            $childDn = @ldap_get_dn($this->getResource(), $entry);
            if ($childDn === false) {
                /**
                 * @see Zend_Ldap_Exception
                 */
                require_once 'Zend/Ldap/Exception.php';
                throw new Zend_Ldap_Exception($this, 'getting dn');
            }
            $children[] = $childDn;
        }
        @ldap_free_result($search);
        return $children;
    }

    /**
     * Moves a LDAP entry from one DN to another subtree.
     *
     * @param  string|Zend_Ldap_Dn $from
     * @param  string|Zend_Ldap_Dn $to
     * @param  boolean             $recursively
     * @param  boolean             $alwaysEmulate
     * @return Zend_Ldap Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function moveToSubtree($from, $to, $recursively = false, $alwaysEmulate = false)
    {
        if ($from instanceof Zend_Ldap_Dn) {
            $orgDnParts = $from->toArray();
        } else {
            $orgDnParts = Zend_Ldap_Dn::explodeDn($from);
        }

        if ($to instanceof Zend_Ldap_Dn) {
            $newParentDnParts = $to->toArray();
        } else {
            $newParentDnParts = Zend_Ldap_Dn::explodeDn($to);
        }

        $newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts);
        $newDn = Zend_Ldap_Dn::fromArray($newDnParts);
        return $this->rename($from, $newDn, $recursively, $alwaysEmulate);
    }

    /**
     * Moves a LDAP entry from one DN to another DN.
     *
     * This is an alias for {@link rename()}
     *
     * @param  string|Zend_Ldap_Dn $from
     * @param  string|Zend_Ldap_Dn $to
     * @param  boolean             $recursively
     * @param  boolean             $alwaysEmulate
     * @return Zend_Ldap Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function move($from, $to, $recursively = false, $alwaysEmulate = false)
    {
        return $this->rename($from, $to, $recursively, $alwaysEmulate);
    }

    /**
     * Renames a LDAP entry from one DN to another DN.
     *
     * This method implicitely moves the entry to another location within the tree.
     *
     * @param  string|Zend_Ldap_Dn $from
     * @param  string|Zend_Ldap_Dn $to
     * @param  boolean             $recursively
     * @param  boolean             $alwaysEmulate
     * @return Zend_Ldap Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function rename($from, $to, $recursively = false, $alwaysEmulate = false)
    {
        $emulate = (bool)$alwaysEmulate;
        if (!function_exists('ldap_rename')) $emulate = true;
        else if ($recursively) $emulate = true;

        if ($emulate === false) {
            if ($from instanceof Zend_Ldap_Dn) {
                $from = $from->toString();
            }

            if ($to instanceof Zend_Ldap_Dn) {
                $newDnParts = $to->toArray();
            } else {
                $newDnParts = Zend_Ldap_Dn::explodeDn($to);
            }

            $newRdn = Zend_Ldap_Dn::implodeRdn(array_shift($newDnParts));
            $newParent = Zend_Ldap_Dn::implodeDn($newDnParts);
            $isOK = @ldap_rename($this->getResource(), $from, $newRdn, $newParent, true);
            if($isOK === false) {
                /**
                 * @see Zend_Ldap_Exception
                 */
                require_once 'Zend/Ldap/Exception.php';
                throw new Zend_Ldap_Exception($this, 'renaming ' . $from . ' to ' . $to);
            }
            else if (!$this->exists($to)) $emulate = true;
        }
        if ($emulate) {
            $this->copy($from, $to, $recursively);
            $this->delete($from, $recursively);
        }
        return $this;
    }

    /**
     * Copies a LDAP entry from one DN to another subtree.
     *
     * @param  string|Zend_Ldap_Dn $from
     * @param  string|Zend_Ldap_Dn $to
     * @param  boolean             $recursively
     * @return Zend_Ldap Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function copyToSubtree($from, $to, $recursively = false)
    {
        if ($from instanceof Zend_Ldap_Dn) {
            $orgDnParts = $from->toArray();
        } else {
            $orgDnParts = Zend_Ldap_Dn::explodeDn($from);
        }

        if ($to instanceof Zend_Ldap_Dn) {
            $newParentDnParts = $to->toArray();
        } else {
            $newParentDnParts = Zend_Ldap_Dn::explodeDn($to);
        }

        $newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts);
        $newDn = Zend_Ldap_Dn::fromArray($newDnParts);
        return $this->copy($from, $newDn, $recursively);
    }

    /**
     * Copies a LDAP entry from one DN to another DN.
     *
     * @param  string|Zend_Ldap_Dn $from
     * @param  string|Zend_Ldap_Dn $to
     * @param  boolean             $recursively
     * @return Zend_Ldap Provides a fluid interface
     * @throws Zend_Ldap_Exception
     */
    public function copy($from, $to, $recursively = false)
    {
        $entry = $this->getEntry($from, array(), true);

        if ($to instanceof Zend_Ldap_Dn) {
            $toDnParts = $to->toArray();
        } else {
            $toDnParts = Zend_Ldap_Dn::explodeDn($to);
        }
        $this->add($to, $entry);

        if ($recursively === true && $this->countChildren($from)>0) {
            $children = $this->_getChildrenDns($from);
            foreach ($children as $c) {
                $cDnParts = Zend_Ldap_Dn::explodeDn($c);
                $newChildParts = array_merge(array(array_shift($cDnParts)), $toDnParts);
                $newChild = Zend_Ldap_Dn::implodeDn($newChildParts);
                $this->copy($c, $newChild, true);
            }
        }
        return $this;
    }

    /**
     * Returns the specified DN as a Zend_Ldap_Node
     *
     * @param  string|Zend_Ldap_Dn $dn
     * @return Zend_Ldap_Node|null
     * @throws Zend_Ldap_Exception
     */
    public function getNode($dn)
    {
        /**
         * Zend_Ldap_Node
         */
        require_once 'Zend/Ldap/Node.php';
        return Zend_Ldap_Node::fromLdap($dn, $this);
    }

    /**
     * Returns the base node as a Zend_Ldap_Node
     *
     * @return Zend_Ldap_Node
     * @throws Zend_Ldap_Exception
     */
    public function getBaseNode()
    {
        return $this->getNode($this->getBaseDn(), $this);
    }

    /**
     * Returns the RootDSE
     *
     * @return Zend_Ldap_Node_RootDse
     * @throws Zend_Ldap_Exception
     */
    public function getRootDse()
    {
        if ($this->_rootDse === null) {
            /**
             * @see Zend_Ldap_Node_Schema
             */
            require_once 'Zend/Ldap/Node/RootDse.php';
            $this->_rootDse = Zend_Ldap_Node_RootDse::create($this);
        }
        return $this->_rootDse;
    }

    /**
     * Returns the schema
     *
     * @return Zend_Ldap_Node_Schema
     * @throws Zend_Ldap_Exception
     */
    public function getSchema()
    {
        if ($this->_schema === null) {
            /**
             * @see Zend_Ldap_Node_Schema
             */
            require_once 'Zend/Ldap/Node/Schema.php';
            $this->_schema = Zend_Ldap_Node_Schema::create($this);
        }
        return $this->_schema;
    }
}