1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2014 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Amitay Isaacs  <amitay@w-o-i.com>                           |
16   |          Eric Warnke    <ericw@albany.edu>                           |
17   |          Rasmus Lerdorf <rasmus@php.net>                             |
18   |          Gerrit Thomson <334647@swin.edu.au>                         |
19   |          Jani Taskinen  <sniper@iki.fi>                              |
20   |          Stig Venaas    <venaas@uninett.no>                          |
21   |          Doug Goldstein <cardoe@cardoe.com>                          |
22   | PHP 4.0 updates:  Zeev Suraski <zeev@zend.com>                       |
23   +----------------------------------------------------------------------+
24 */
25
26/* $Id: f00799e946491a9e9311b740f9f6e16537b42fb9 $ */
27#define IS_EXT_MODULE
28
29#ifdef HAVE_CONFIG_H
30#include "config.h"
31#endif
32
33/* Additional headers for NetWare */
34#if defined(NETWARE) && (NEW_LIBC)
35#include <sys/select.h>
36#include <sys/timeval.h>
37#endif
38
39#include "php.h"
40#include "php_ini.h"
41
42#include <stddef.h>
43
44#include "ext/standard/dl.h"
45#include "php_ldap.h"
46
47#ifdef PHP_WIN32
48#include <string.h>
49#include "config.w32.h"
50#if HAVE_NSLDAP
51#include <winsock2.h>
52#endif
53#define strdup _strdup
54#undef WINDOWS
55#undef strcasecmp
56#undef strncasecmp
57#define WINSOCK 1
58#define __STDC__ 1
59#endif
60
61#include "ext/standard/php_string.h"
62#include "ext/standard/info.h"
63
64#ifdef HAVE_LDAP_SASL_H
65#include <sasl.h>
66#elif defined(HAVE_LDAP_SASL_SASL_H)
67#include <sasl/sasl.h>
68#endif
69
70#define PHP_LDAP_ESCAPE_FILTER 0x01
71#define PHP_LDAP_ESCAPE_DN     0x02
72
73typedef struct {
74    LDAP *link;
75#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
76    zval rebindproc;
77#endif
78} ldap_linkdata;
79
80typedef struct {
81    LDAPMessage *data;
82    BerElement  *ber;
83    zval         res;
84} ldap_resultentry;
85
86ZEND_DECLARE_MODULE_GLOBALS(ldap)
87static PHP_GINIT_FUNCTION(ldap);
88
89static int le_link, le_result, le_result_entry;
90
91#ifdef COMPILE_DL_LDAP
92ZEND_GET_MODULE(ldap)
93#endif
94
95static void _close_ldap_link(zend_resource *rsrc TSRMLS_DC) /* {{{ */
96{
97    ldap_linkdata *ld = (ldap_linkdata *)rsrc->ptr;
98
99    ldap_unbind_s(ld->link);
100#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
101    zval_ptr_dtor(&ld->rebindproc);
102#endif
103    efree(ld);
104    LDAPG(num_links)--;
105}
106/* }}} */
107
108static void _free_ldap_result(zend_resource *rsrc TSRMLS_DC) /* {{{ */
109{
110    LDAPMessage *result = (LDAPMessage *)rsrc->ptr;
111    ldap_msgfree(result);
112}
113/* }}} */
114
115static void _free_ldap_result_entry(zend_resource *rsrc TSRMLS_DC) /* {{{ */
116{
117    ldap_resultentry *entry = (ldap_resultentry *)rsrc->ptr;
118
119    if (entry->ber != NULL) {
120        ber_free(entry->ber, 0);
121        entry->ber = NULL;
122    }
123    zval_ptr_dtor(&entry->res);
124    efree(entry);
125}
126/* }}} */
127
128/* {{{ PHP_INI_BEGIN
129 */
130PHP_INI_BEGIN()
131    STD_PHP_INI_ENTRY_EX("ldap.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_links, zend_ldap_globals, ldap_globals, display_link_numbers)
132PHP_INI_END()
133/* }}} */
134
135/* {{{ PHP_GINIT_FUNCTION
136 */
137static PHP_GINIT_FUNCTION(ldap)
138{
139    ldap_globals->num_links = 0;
140}
141/* }}} */
142
143/* {{{ PHP_MINIT_FUNCTION
144 */
145PHP_MINIT_FUNCTION(ldap)
146{
147    REGISTER_INI_ENTRIES();
148
149    /* Constants to be used with deref-parameter in php_ldap_do_search() */
150    REGISTER_LONG_CONSTANT("LDAP_DEREF_NEVER", LDAP_DEREF_NEVER, CONST_PERSISTENT | CONST_CS);
151    REGISTER_LONG_CONSTANT("LDAP_DEREF_SEARCHING", LDAP_DEREF_SEARCHING, CONST_PERSISTENT | CONST_CS);
152    REGISTER_LONG_CONSTANT("LDAP_DEREF_FINDING", LDAP_DEREF_FINDING, CONST_PERSISTENT | CONST_CS);
153    REGISTER_LONG_CONSTANT("LDAP_DEREF_ALWAYS", LDAP_DEREF_ALWAYS, CONST_PERSISTENT | CONST_CS);
154
155    /* Constants to be used with ldap_modify_batch() */
156    REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_ADD", LDAP_MODIFY_BATCH_ADD, CONST_PERSISTENT | CONST_CS);
157    REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REMOVE", LDAP_MODIFY_BATCH_REMOVE, CONST_PERSISTENT | CONST_CS);
158    REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REMOVE_ALL", LDAP_MODIFY_BATCH_REMOVE_ALL, CONST_PERSISTENT | CONST_CS);
159    REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REPLACE", LDAP_MODIFY_BATCH_REPLACE, CONST_PERSISTENT | CONST_CS);
160    REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_ATTRIB", LDAP_MODIFY_BATCH_ATTRIB, CONST_PERSISTENT | CONST_CS);
161    REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_MODTYPE", LDAP_MODIFY_BATCH_MODTYPE, CONST_PERSISTENT | CONST_CS);
162    REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_VALUES", LDAP_MODIFY_BATCH_VALUES, CONST_PERSISTENT | CONST_CS);
163
164#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
165    /* LDAP options */
166    REGISTER_LONG_CONSTANT("LDAP_OPT_DEREF", LDAP_OPT_DEREF, CONST_PERSISTENT | CONST_CS);
167    REGISTER_LONG_CONSTANT("LDAP_OPT_SIZELIMIT", LDAP_OPT_SIZELIMIT, CONST_PERSISTENT | CONST_CS);
168    REGISTER_LONG_CONSTANT("LDAP_OPT_TIMELIMIT", LDAP_OPT_TIMELIMIT, CONST_PERSISTENT | CONST_CS);
169#ifdef LDAP_OPT_NETWORK_TIMEOUT
170    REGISTER_LONG_CONSTANT("LDAP_OPT_NETWORK_TIMEOUT", LDAP_OPT_NETWORK_TIMEOUT, CONST_PERSISTENT | CONST_CS);
171#elif defined (LDAP_X_OPT_CONNECT_TIMEOUT)
172    REGISTER_LONG_CONSTANT("LDAP_OPT_NETWORK_TIMEOUT", LDAP_X_OPT_CONNECT_TIMEOUT, CONST_PERSISTENT | CONST_CS);
173#endif
174    REGISTER_LONG_CONSTANT("LDAP_OPT_PROTOCOL_VERSION", LDAP_OPT_PROTOCOL_VERSION, CONST_PERSISTENT | CONST_CS);
175    REGISTER_LONG_CONSTANT("LDAP_OPT_ERROR_NUMBER", LDAP_OPT_ERROR_NUMBER, CONST_PERSISTENT | CONST_CS);
176    REGISTER_LONG_CONSTANT("LDAP_OPT_REFERRALS", LDAP_OPT_REFERRALS, CONST_PERSISTENT | CONST_CS);
177#ifdef LDAP_OPT_RESTART
178    REGISTER_LONG_CONSTANT("LDAP_OPT_RESTART", LDAP_OPT_RESTART, CONST_PERSISTENT | CONST_CS);
179#endif
180#ifdef LDAP_OPT_HOST_NAME
181    REGISTER_LONG_CONSTANT("LDAP_OPT_HOST_NAME", LDAP_OPT_HOST_NAME, CONST_PERSISTENT | CONST_CS);
182#endif
183    REGISTER_LONG_CONSTANT("LDAP_OPT_ERROR_STRING", LDAP_OPT_ERROR_STRING, CONST_PERSISTENT | CONST_CS);
184#ifdef LDAP_OPT_MATCHED_DN
185    REGISTER_LONG_CONSTANT("LDAP_OPT_MATCHED_DN", LDAP_OPT_MATCHED_DN, CONST_PERSISTENT | CONST_CS);
186#endif
187    REGISTER_LONG_CONSTANT("LDAP_OPT_SERVER_CONTROLS", LDAP_OPT_SERVER_CONTROLS, CONST_PERSISTENT | CONST_CS);
188    REGISTER_LONG_CONSTANT("LDAP_OPT_CLIENT_CONTROLS", LDAP_OPT_CLIENT_CONTROLS, CONST_PERSISTENT | CONST_CS);
189#endif
190#ifdef LDAP_OPT_DEBUG_LEVEL
191    REGISTER_LONG_CONSTANT("LDAP_OPT_DEBUG_LEVEL", LDAP_OPT_DEBUG_LEVEL, CONST_PERSISTENT | CONST_CS);
192#endif
193
194#ifdef HAVE_LDAP_SASL
195    REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_MECH", LDAP_OPT_X_SASL_MECH, CONST_PERSISTENT | CONST_CS);
196    REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_REALM", LDAP_OPT_X_SASL_REALM, CONST_PERSISTENT | CONST_CS);
197    REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_AUTHCID", LDAP_OPT_X_SASL_AUTHCID, CONST_PERSISTENT | CONST_CS);
198    REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_AUTHZID", LDAP_OPT_X_SASL_AUTHZID, CONST_PERSISTENT | CONST_CS);
199#endif
200
201#ifdef ORALDAP
202    REGISTER_LONG_CONSTANT("GSLC_SSL_NO_AUTH", GSLC_SSL_NO_AUTH, CONST_PERSISTENT | CONST_CS);
203    REGISTER_LONG_CONSTANT("GSLC_SSL_ONEWAY_AUTH", GSLC_SSL_ONEWAY_AUTH, CONST_PERSISTENT | CONST_CS);
204    REGISTER_LONG_CONSTANT("GSLC_SSL_TWOWAY_AUTH", GSLC_SSL_TWOWAY_AUTH, CONST_PERSISTENT | CONST_CS);
205#endif
206
207    REGISTER_LONG_CONSTANT("LDAP_ESCAPE_FILTER", PHP_LDAP_ESCAPE_FILTER, CONST_PERSISTENT | CONST_CS);
208    REGISTER_LONG_CONSTANT("LDAP_ESCAPE_DN", PHP_LDAP_ESCAPE_DN, CONST_PERSISTENT | CONST_CS);
209
210    le_link = zend_register_list_destructors_ex(_close_ldap_link, NULL, "ldap link", module_number);
211    le_result = zend_register_list_destructors_ex(_free_ldap_result, NULL, "ldap result", module_number);
212    le_result_entry = zend_register_list_destructors_ex(_free_ldap_result_entry, NULL, "ldap result entry", module_number);
213
214    ldap_module_entry.type = type;
215
216    return SUCCESS;
217}
218/* }}} */
219
220/* {{{ PHP_MSHUTDOWN_FUNCTION
221 */
222PHP_MSHUTDOWN_FUNCTION(ldap)
223{
224    UNREGISTER_INI_ENTRIES();
225    return SUCCESS;
226}
227/* }}} */
228
229/* {{{ PHP_MINFO_FUNCTION
230 */
231PHP_MINFO_FUNCTION(ldap)
232{
233    char tmp[32];
234#if HAVE_NSLDAP
235    LDAPVersion ver;
236    double SDKVersion;
237#endif
238
239    php_info_print_table_start();
240    php_info_print_table_row(2, "LDAP Support", "enabled");
241    php_info_print_table_row(2, "RCS Version", "$Id: f00799e946491a9e9311b740f9f6e16537b42fb9 $");
242
243    if (LDAPG(max_links) == -1) {
244        snprintf(tmp, 31, ZEND_LONG_FMT "/unlimited", LDAPG(num_links));
245    } else {
246        snprintf(tmp, 31, ZEND_LONG_FMT "/" ZEND_LONG_FMT, LDAPG(num_links), LDAPG(max_links));
247    }
248    php_info_print_table_row(2, "Total Links", tmp);
249
250#ifdef LDAP_API_VERSION
251    snprintf(tmp, 31, "%d", LDAP_API_VERSION);
252    php_info_print_table_row(2, "API Version", tmp);
253#endif
254
255#ifdef LDAP_VENDOR_NAME
256    php_info_print_table_row(2, "Vendor Name", LDAP_VENDOR_NAME);
257#endif
258
259#ifdef LDAP_VENDOR_VERSION
260    snprintf(tmp, 31, "%d", LDAP_VENDOR_VERSION);
261    php_info_print_table_row(2, "Vendor Version", tmp);
262#endif
263
264#if HAVE_NSLDAP
265    SDKVersion = ldap_version(&ver);
266    snprintf(tmp, 31, "%F", SDKVersion/100.0);
267    php_info_print_table_row(2, "SDK Version", tmp);
268
269    snprintf(tmp, 31, "%F", ver.protocol_version/100.0);
270    php_info_print_table_row(2, "Highest LDAP Protocol Supported", tmp);
271
272    snprintf(tmp, 31, "%F", ver.SSL_version/100.0);
273    php_info_print_table_row(2, "SSL Level Supported", tmp);
274
275    if (ver.security_level != LDAP_SECURITY_NONE) {
276        snprintf(tmp, 31, "%d", ver.security_level);
277    } else {
278        strcpy(tmp, "SSL not enabled");
279    }
280    php_info_print_table_row(2, "Level of Encryption", tmp);
281#endif
282
283#ifdef HAVE_LDAP_SASL
284    php_info_print_table_row(2, "SASL Support", "Enabled");
285#endif
286
287    php_info_print_table_end();
288    DISPLAY_INI_ENTRIES();
289}
290/* }}} */
291
292/* {{{ proto resource ldap_connect([string host [, int port [, string wallet [, string wallet_passwd [, int authmode]]]]])
293   Connect to an LDAP server */
294PHP_FUNCTION(ldap_connect)
295{
296    char *host = NULL;
297    size_t hostlen;
298    zend_long port = 389; /* Default port */
299#ifdef HAVE_ORALDAP
300    char *wallet = NULL, *walletpasswd = NULL;
301    size_t walletlen = 0, walletpasswdlen = 0;
302    zend_long authmode = GSLC_SSL_NO_AUTH;
303    int ssl=0;
304#endif
305    ldap_linkdata *ld;
306    LDAP *ldap;
307
308#ifdef HAVE_ORALDAP
309    if (ZEND_NUM_ARGS() == 3 || ZEND_NUM_ARGS() == 4) {
310        WRONG_PARAM_COUNT;
311    }
312
313    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|slssl", &host, &hostlen, &port, &wallet, &walletlen, &walletpasswd, &walletpasswdlen, &authmode) != SUCCESS) {
314        RETURN_FALSE;
315    }
316
317    if (ZEND_NUM_ARGS() == 5) {
318        ssl = 1;
319    }
320#else
321    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sl", &host, &hostlen, &port) != SUCCESS) {
322        RETURN_FALSE;
323    }
324#endif
325
326    if (LDAPG(max_links) != -1 && LDAPG(num_links) >= LDAPG(max_links)) {
327        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Too many open links (%pd)", LDAPG(num_links));
328        RETURN_FALSE;
329    }
330
331    ld = ecalloc(1, sizeof(ldap_linkdata));
332
333#ifdef LDAP_API_FEATURE_X_OPENLDAP
334    if (host != NULL && strchr(host, '/')) {
335        int rc;
336
337        rc = ldap_initialize(&ldap, host);
338        if (rc != LDAP_SUCCESS) {
339            efree(ld);
340            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not create session handle: %s", ldap_err2string(rc));
341            RETURN_FALSE;
342        }
343    } else {
344        ldap = ldap_init(host, port);
345    }
346#else
347    ldap = ldap_open(host, port);
348#endif
349
350    if (ldap == NULL) {
351        efree(ld);
352        RETURN_FALSE;
353    } else {
354#ifdef HAVE_ORALDAP
355        if (ssl) {
356            if (ldap_init_SSL(&ldap->ld_sb, wallet, walletpasswd, authmode)) {
357                efree(ld);
358                php_error_docref(NULL TSRMLS_CC, E_WARNING, "SSL init failed");
359                RETURN_FALSE;
360            }
361        }
362#endif
363        LDAPG(num_links)++;
364        ld->link = ldap;
365        ZEND_REGISTER_RESOURCE(return_value, ld, le_link);
366    }
367
368}
369/* }}} */
370
371/* {{{ _get_lderrno
372 */
373static int _get_lderrno(LDAP *ldap)
374{
375#if !HAVE_NSLDAP
376#if LDAP_API_VERSION > 2000 || HAVE_ORALDAP
377    int lderr;
378
379    /* New versions of OpenLDAP do it this way */
380    ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr);
381    return lderr;
382#else
383    return ldap->ld_errno;
384#endif
385#else
386    return ldap_get_lderrno(ldap, NULL, NULL);
387#endif
388}
389/* }}} */
390
391/* {{{ proto bool ldap_bind(resource link [, string dn [, string password]])
392   Bind to LDAP directory */
393PHP_FUNCTION(ldap_bind)
394{
395    zval *link;
396    char *ldap_bind_dn = NULL, *ldap_bind_pw = NULL;
397    size_t ldap_bind_dnlen, ldap_bind_pwlen;
398    ldap_linkdata *ld;
399    int rc;
400
401    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|ss", &link, &ldap_bind_dn, &ldap_bind_dnlen, &ldap_bind_pw, &ldap_bind_pwlen) != SUCCESS) {
402        RETURN_FALSE;
403    }
404
405    if (ldap_bind_dn != NULL && memchr(ldap_bind_dn, '\0', ldap_bind_dnlen) != NULL) {
406        php_error_docref(NULL TSRMLS_CC, E_WARNING, "DN contains a null byte");
407        RETURN_FALSE;
408    }
409
410    if (ldap_bind_pw != NULL && memchr(ldap_bind_pw, '\0', ldap_bind_pwlen) != NULL) {
411        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Password contains a null byte");
412        RETURN_FALSE;
413    }
414
415    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
416
417    if ((rc = ldap_bind_s(ld->link, ldap_bind_dn, ldap_bind_pw, LDAP_AUTH_SIMPLE)) != LDAP_SUCCESS) {
418        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc));
419        RETURN_FALSE;
420    } else {
421        RETURN_TRUE;
422    }
423}
424/* }}} */
425
426#ifdef HAVE_LDAP_SASL
427typedef struct {
428    char *mech;
429    char *realm;
430    char *authcid;
431    char *passwd;
432    char *authzid;
433} php_ldap_bictx;
434
435/* {{{ _php_sasl_setdefs
436 */
437static php_ldap_bictx *_php_sasl_setdefs(LDAP *ld, char *sasl_mech, char *sasl_realm, char *sasl_authc_id, char *passwd, char *sasl_authz_id)
438{
439    php_ldap_bictx *ctx;
440
441    ctx = ber_memalloc(sizeof(php_ldap_bictx));
442    ctx->mech    = (sasl_mech) ? ber_strdup(sasl_mech) : NULL;
443    ctx->realm   = (sasl_realm) ? ber_strdup(sasl_realm) : NULL;
444    ctx->authcid = (sasl_authc_id) ? ber_strdup(sasl_authc_id) : NULL;
445    ctx->passwd  = (passwd) ? ber_strdup(passwd) : NULL;
446    ctx->authzid = (sasl_authz_id) ? ber_strdup(sasl_authz_id) : NULL;
447
448    if (ctx->mech == NULL) {
449        ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &ctx->mech);
450    }
451    if (ctx->realm == NULL) {
452        ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &ctx->realm);
453    }
454    if (ctx->authcid == NULL) {
455        ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &ctx->authcid);
456    }
457    if (ctx->authzid == NULL) {
458        ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &ctx->authzid);
459    }
460
461    return ctx;
462}
463/* }}} */
464
465/* {{{ _php_sasl_freedefs
466 */
467static void _php_sasl_freedefs(php_ldap_bictx *ctx)
468{
469    if (ctx->mech) ber_memfree(ctx->mech);
470    if (ctx->realm) ber_memfree(ctx->realm);
471    if (ctx->authcid) ber_memfree(ctx->authcid);
472    if (ctx->passwd) ber_memfree(ctx->passwd);
473    if (ctx->authzid) ber_memfree(ctx->authzid);
474    ber_memfree(ctx);
475}
476/* }}} */
477
478/* {{{ _php_sasl_interact
479   Internal interact function for SASL */
480static int _php_sasl_interact(LDAP *ld, unsigned flags, void *defaults, void *in)
481{
482    sasl_interact_t *interact = in;
483    const char *p;
484    php_ldap_bictx *ctx = defaults;
485
486    for (;interact->id != SASL_CB_LIST_END;interact++) {
487        p = NULL;
488        switch(interact->id) {
489            case SASL_CB_GETREALM:
490                p = ctx->realm;
491                break;
492            case SASL_CB_AUTHNAME:
493                p = ctx->authcid;
494                break;
495            case SASL_CB_USER:
496                p = ctx->authzid;
497                break;
498            case SASL_CB_PASS:
499                p = ctx->passwd;
500                break;
501        }
502        if (p) {
503            interact->result = p;
504            interact->len = strlen(interact->result);
505        }
506    }
507    return LDAP_SUCCESS;
508}
509/* }}} */
510
511/* {{{ proto bool ldap_sasl_bind(resource link [, string binddn [, string password [, string sasl_mech [, string sasl_realm [, string sasl_authc_id [, string sasl_authz_id [, string props]]]]]]])
512   Bind to LDAP directory using SASL */
513PHP_FUNCTION(ldap_sasl_bind)
514{
515    zval *link;
516    ldap_linkdata *ld;
517    char *binddn = NULL;
518    char *passwd = NULL;
519    char *sasl_mech = NULL;
520    char *sasl_realm = NULL;
521    char *sasl_authz_id = NULL;
522    char *sasl_authc_id = NULL;
523    char *props = NULL;
524    size_t rc, dn_len, passwd_len, mech_len, realm_len, authc_id_len, authz_id_len, props_len;
525    php_ldap_bictx *ctx;
526
527    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|sssssss", &link, &binddn, &dn_len, &passwd, &passwd_len, &sasl_mech, &mech_len, &sasl_realm, &realm_len, &sasl_authc_id, &authc_id_len, &sasl_authz_id, &authz_id_len, &props, &props_len) != SUCCESS) {
528        RETURN_FALSE;
529    }
530
531    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
532
533    ctx = _php_sasl_setdefs(ld->link, sasl_mech, sasl_realm, sasl_authc_id, passwd, sasl_authz_id);
534
535    if (props) {
536        ldap_set_option(ld->link, LDAP_OPT_X_SASL_SECPROPS, props);
537    }
538
539    rc = ldap_sasl_interactive_bind_s(ld->link, binddn, ctx->mech, NULL, NULL, LDAP_SASL_QUIET, _php_sasl_interact, ctx);
540    if (rc != LDAP_SUCCESS) {
541        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc));
542        RETVAL_FALSE;
543    } else {
544        RETVAL_TRUE;
545    }
546    _php_sasl_freedefs(ctx);
547}
548/* }}} */
549#endif /* HAVE_LDAP_SASL */
550
551/* {{{ proto bool ldap_unbind(resource link)
552   Unbind from LDAP directory */
553PHP_FUNCTION(ldap_unbind)
554{
555    zval *link;
556    ldap_linkdata *ld;
557
558    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &link) != SUCCESS) {
559        RETURN_FALSE;
560    }
561
562    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
563
564    zend_list_close(Z_RES_P(link));
565    RETURN_TRUE;
566}
567/* }}} */
568
569/* {{{ php_set_opts
570 */
571static void php_set_opts(LDAP *ldap, int sizelimit, int timelimit, int deref, int *old_sizelimit, int *old_timelimit, int *old_deref)
572{
573    /* sizelimit */
574    if (sizelimit > -1) {
575#if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP
576        ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_sizelimit);
577        ldap_set_option(ldap, LDAP_OPT_SIZELIMIT, &sizelimit);
578#else
579        *old_sizelimit = ldap->ld_sizelimit;
580        ldap->ld_sizelimit = sizelimit;
581#endif
582    }
583
584    /* timelimit */
585    if (timelimit > -1) {
586#if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP
587        ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_timelimit);
588        ldap_set_option(ldap, LDAP_OPT_TIMELIMIT, &timelimit);
589#else
590        *old_timelimit = ldap->ld_timelimit;
591        ldap->ld_timelimit = timelimit;
592#endif
593    }
594
595    /* deref */
596    if (deref > -1) {
597#if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP
598        ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_deref);
599        ldap_set_option(ldap, LDAP_OPT_DEREF, &deref);
600#else
601        *old_deref = ldap->ld_deref;
602        ldap->ld_deref = deref;
603#endif
604    }
605}
606/* }}} */
607
608/* {{{ php_ldap_do_search
609 */
610static void php_ldap_do_search(INTERNAL_FUNCTION_PARAMETERS, int scope)
611{
612    zval *link, *base_dn, *filter, *attrs = NULL, *attr;
613    zend_long attrsonly, sizelimit, timelimit, deref;
614    char *ldap_base_dn = NULL, *ldap_filter = NULL, **ldap_attrs = NULL;
615    ldap_linkdata *ld = NULL;
616    LDAPMessage *ldap_res;
617    int ldap_attrsonly = 0, ldap_sizelimit = -1, ldap_timelimit = -1, ldap_deref = -1;
618    int old_ldap_sizelimit = -1, old_ldap_timelimit = -1, old_ldap_deref = -1;
619    int num_attribs = 0, ret = 1, i, errno, argcount = ZEND_NUM_ARGS();
620
621    if (zend_parse_parameters(argcount TSRMLS_CC, "zzz|allll", &link, &base_dn, &filter, &attrs, &attrsonly,
622        &sizelimit, &timelimit, &deref) == FAILURE) {
623        return;
624    }
625
626    /* Reverse -> fall through */
627    switch (argcount) {
628        case 8:
629            ldap_deref = deref;
630        case 7:
631            ldap_timelimit = timelimit;
632        case 6:
633            ldap_sizelimit = sizelimit;
634        case 5:
635            ldap_attrsonly = attrsonly;
636        case 4:
637            num_attribs = zend_hash_num_elements(Z_ARRVAL_P(attrs));
638            ldap_attrs = safe_emalloc((num_attribs+1), sizeof(char *), 0);
639
640            for (i = 0; i<num_attribs; i++) {
641                if ((attr = zend_hash_index_find(Z_ARRVAL_P(attrs), i)) == NULL) {
642                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array initialization wrong");
643                    ret = 0;
644                    goto cleanup;
645                }
646
647                SEPARATE_ZVAL(attr);
648                convert_to_string_ex(attr);
649                ldap_attrs[i] = Z_STRVAL_P(attr);
650            }
651            ldap_attrs[num_attribs] = NULL;
652        default:
653            break;
654    }
655
656    /* parallel search? */
657    if (Z_TYPE_P(link) == IS_ARRAY) {
658        int i, nlinks, nbases, nfilters, *rcs;
659        ldap_linkdata **lds;
660        zval *entry, resource;
661
662        nlinks = zend_hash_num_elements(Z_ARRVAL_P(link));
663        if (nlinks == 0) {
664            php_error_docref(NULL TSRMLS_CC, E_WARNING, "No links in link array");
665            ret = 0;
666            goto cleanup;
667        }
668
669        if (Z_TYPE_P(base_dn) == IS_ARRAY) {
670            nbases = zend_hash_num_elements(Z_ARRVAL_P(base_dn));
671            if (nbases != nlinks) {
672                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Base must either be a string, or an array with the same number of elements as the links array");
673                ret = 0;
674                goto cleanup;
675            }
676            zend_hash_internal_pointer_reset(Z_ARRVAL_P(base_dn));
677        } else {
678            nbases = 0; /* this means string, not array */
679            /* If anything else than string is passed, ldap_base_dn = NULL */
680            if (Z_TYPE_P(base_dn) == IS_STRING) {
681                ldap_base_dn = Z_STRVAL_P(base_dn);
682            } else {
683                ldap_base_dn = NULL;
684            }
685        }
686
687        if (Z_TYPE_P(filter) == IS_ARRAY) {
688            nfilters = zend_hash_num_elements(Z_ARRVAL_P(filter));
689            if (nfilters != nlinks) {
690                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filter must either be a string, or an array with the same number of elements as the links array");
691                ret = 0;
692                goto cleanup;
693            }
694            zend_hash_internal_pointer_reset(Z_ARRVAL_P(filter));
695        } else {
696            nfilters = 0; /* this means string, not array */
697            convert_to_string_ex(filter);
698            ldap_filter = Z_STRVAL_P(filter);
699        }
700
701        lds = safe_emalloc(nlinks, sizeof(ldap_linkdata), 0);
702        rcs = safe_emalloc(nlinks, sizeof(*rcs), 0);
703
704        zend_hash_internal_pointer_reset(Z_ARRVAL_P(link));
705        for (i=0; i<nlinks; i++) {
706            entry = zend_hash_get_current_data(Z_ARRVAL_P(link));
707
708            ld = (ldap_linkdata *) zend_fetch_resource(entry TSRMLS_CC, -1, "ldap link", NULL, 1, le_link);
709            if (ld == NULL) {
710                ret = 0;
711                goto cleanup_parallel;
712            }
713            if (nbases != 0) { /* base_dn an array? */
714                entry = zend_hash_get_current_data(Z_ARRVAL_P(base_dn));
715                zend_hash_move_forward(Z_ARRVAL_P(base_dn));
716
717                /* If anything else than string is passed, ldap_base_dn = NULL */
718                if (Z_TYPE_P(entry) == IS_STRING) {
719                    ldap_base_dn = Z_STRVAL_P(entry);
720                } else {
721                    ldap_base_dn = NULL;
722                }
723            }
724            if (nfilters != 0) { /* filter an array? */
725                entry = zend_hash_get_current_data(Z_ARRVAL_P(filter));
726                zend_hash_move_forward(Z_ARRVAL_P(filter));
727                convert_to_string_ex(entry);
728                ldap_filter = Z_STRVAL_P(entry);
729            }
730
731            php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref);
732
733            /* Run the actual search */
734            rcs[i] = ldap_search(ld->link, ldap_base_dn, scope, ldap_filter, ldap_attrs, ldap_attrsonly);
735            lds[i] = ld;
736            zend_hash_move_forward(Z_ARRVAL_P(link));
737        }
738
739        array_init(return_value);
740
741        /* Collect results from the searches */
742        for (i=0; i<nlinks; i++) {
743            if (rcs[i] != -1) {
744                rcs[i] = ldap_result(lds[i]->link, LDAP_RES_ANY, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
745            }
746            if (rcs[i] != -1) {
747                ZEND_REGISTER_RESOURCE(&resource, ldap_res, le_result);
748                add_next_index_zval(return_value, &resource);
749            } else {
750                add_next_index_bool(return_value, 0);
751            }
752        }
753
754cleanup_parallel:
755        efree(lds);
756        efree(rcs);
757    } else {
758        convert_to_string_ex(filter);
759        ldap_filter = Z_STRVAL_P(filter);
760
761        /* If anything else than string is passed, ldap_base_dn = NULL */
762        if (Z_TYPE_P(base_dn) == IS_STRING) {
763            ldap_base_dn = Z_STRVAL_P(base_dn);
764        }
765
766        ld = (ldap_linkdata *) zend_fetch_resource(link TSRMLS_CC, -1, "ldap link", NULL, 1, le_link);
767        if (ld == NULL) {
768            ret = 0;
769            goto cleanup;
770        }
771
772        php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref);
773
774        /* Run the actual search */
775        errno = ldap_search_s(ld->link, ldap_base_dn, scope, ldap_filter, ldap_attrs, ldap_attrsonly, &ldap_res);
776
777        if (errno != LDAP_SUCCESS
778            && errno != LDAP_SIZELIMIT_EXCEEDED
779#ifdef LDAP_ADMINLIMIT_EXCEEDED
780            && errno != LDAP_ADMINLIMIT_EXCEEDED
781#endif
782#ifdef LDAP_REFERRAL
783            && errno != LDAP_REFERRAL
784#endif
785        ) {
786            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Search: %s", ldap_err2string(errno));
787            ret = 0;
788        } else {
789            if (errno == LDAP_SIZELIMIT_EXCEEDED) {
790                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Partial search results returned: Sizelimit exceeded");
791            }
792#ifdef LDAP_ADMINLIMIT_EXCEEDED
793            else if (errno == LDAP_ADMINLIMIT_EXCEEDED) {
794                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Partial search results returned: Adminlimit exceeded");
795            }
796#endif
797
798            ZEND_REGISTER_RESOURCE(return_value, ldap_res, le_result);
799        }
800    }
801
802cleanup:
803    if (ld) {
804        /* Restoring previous options */
805        php_set_opts(ld->link, old_ldap_sizelimit, old_ldap_timelimit, old_ldap_deref, &ldap_sizelimit, &ldap_timelimit, &ldap_deref);
806    }
807    if (ldap_attrs != NULL) {
808        efree(ldap_attrs);
809    }
810    if (!ret) {
811        RETVAL_BOOL(ret);
812    }
813}
814/* }}} */
815
816/* {{{ proto resource ldap_read(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])
817   Read an entry */
818PHP_FUNCTION(ldap_read)
819{
820    php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_BASE);
821}
822/* }}} */
823
824/* {{{ proto resource ldap_list(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])
825   Single-level search */
826PHP_FUNCTION(ldap_list)
827{
828    php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_ONELEVEL);
829}
830/* }}} */
831
832/* {{{ proto resource ldap_search(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])
833   Search LDAP tree under base_dn */
834PHP_FUNCTION(ldap_search)
835{
836    php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_SUBTREE);
837}
838/* }}} */
839
840/* {{{ proto bool ldap_free_result(resource result)
841   Free result memory */
842PHP_FUNCTION(ldap_free_result)
843{
844    zval *result;
845    LDAPMessage *ldap_result;
846
847    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) != SUCCESS) {
848        return;
849    }
850
851    ZEND_FETCH_RESOURCE(ldap_result, LDAPMessage *, result, -1, "ldap result", le_result);
852
853    zend_list_close(Z_RES_P(result));  /* Delete list entry */
854    RETVAL_TRUE;
855}
856/* }}} */
857
858/* {{{ proto int ldap_count_entries(resource link, resource result)
859   Count the number of entries in a search result */
860PHP_FUNCTION(ldap_count_entries)
861{
862    zval *link, *result;
863    ldap_linkdata *ld;
864    LDAPMessage *ldap_result;
865
866    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &link, &result) != SUCCESS) {
867        return;
868    }
869
870    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
871    ZEND_FETCH_RESOURCE(ldap_result, LDAPMessage *, result, -1, "ldap result", le_result);
872
873    RETURN_LONG(ldap_count_entries(ld->link, ldap_result));
874}
875/* }}} */
876
877/* {{{ proto resource ldap_first_entry(resource link, resource result)
878   Return first result id */
879PHP_FUNCTION(ldap_first_entry)
880{
881    zval *link, *result;
882    ldap_linkdata *ld;
883    ldap_resultentry *resultentry;
884    LDAPMessage *ldap_result, *entry;
885
886    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &link, &result) != SUCCESS) {
887        return;
888    }
889
890    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
891    ZEND_FETCH_RESOURCE(ldap_result, LDAPMessage *, result, -1, "ldap result", le_result);
892
893    if ((entry = ldap_first_entry(ld->link, ldap_result)) == NULL) {
894        RETVAL_FALSE;
895    } else {
896        resultentry = emalloc(sizeof(ldap_resultentry));
897        ZEND_REGISTER_RESOURCE(return_value, resultentry, le_result_entry);
898        ZVAL_COPY(&resultentry->res, result);
899        resultentry->data = entry;
900        resultentry->ber = NULL;
901    }
902}
903/* }}} */
904
905/* {{{ proto resource ldap_next_entry(resource link, resource result_entry)
906   Get next result entry */
907PHP_FUNCTION(ldap_next_entry)
908{
909    zval *link, *result_entry;
910    ldap_linkdata *ld;
911    ldap_resultentry *resultentry, *resultentry_next;
912    LDAPMessage *entry_next;
913
914    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &link, &result_entry) != SUCCESS) {
915        return;
916    }
917
918    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
919    ZEND_FETCH_RESOURCE(resultentry, ldap_resultentry *, result_entry, -1, "ldap result entry", le_result_entry);
920
921    if ((entry_next = ldap_next_entry(ld->link, resultentry->data)) == NULL) {
922        RETVAL_FALSE;
923    } else {
924        resultentry_next = emalloc(sizeof(ldap_resultentry));
925        ZEND_REGISTER_RESOURCE(return_value, resultentry_next, le_result_entry);
926        ZVAL_COPY(&resultentry_next->res, &resultentry->res);
927        resultentry_next->data = entry_next;
928        resultentry_next->ber = NULL;
929    }
930}
931/* }}} */
932
933/* {{{ proto array ldap_get_entries(resource link, resource result)
934   Get all result entries */
935PHP_FUNCTION(ldap_get_entries)
936{
937    zval *link, *result;
938    LDAPMessage *ldap_result, *ldap_result_entry;
939    zval tmp1, tmp2;
940    ldap_linkdata *ld;
941    LDAP *ldap;
942    int num_entries, num_attrib, num_values, i;
943    BerElement *ber;
944    char *attribute;
945    size_t attr_len;
946    struct berval **ldap_value;
947    char *dn;
948
949    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &link, &result) != SUCCESS) {
950        return;
951    }
952
953    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
954    ZEND_FETCH_RESOURCE(ldap_result, LDAPMessage *, result, -1, "ldap result", le_result);
955
956    ldap = ld->link;
957    num_entries = ldap_count_entries(ldap, ldap_result);
958
959    array_init(return_value);
960    add_assoc_long(return_value, "count", num_entries);
961
962    if (num_entries == 0) {
963        return;
964    }
965
966    ldap_result_entry = ldap_first_entry(ldap, ldap_result);
967    if (ldap_result_entry == NULL) {
968        zval_dtor(return_value);
969        RETURN_FALSE;
970    }
971
972    num_entries = 0;
973    while (ldap_result_entry != NULL) {
974        array_init(&tmp1);
975
976        num_attrib = 0;
977        attribute = ldap_first_attribute(ldap, ldap_result_entry, &ber);
978
979        while (attribute != NULL) {
980            ldap_value = ldap_get_values_len(ldap, ldap_result_entry, attribute);
981            num_values = ldap_count_values_len(ldap_value);
982
983            array_init(&tmp2);
984            add_assoc_long(&tmp2, "count", num_values);
985            for (i = 0; i < num_values; i++) {
986                add_index_stringl(&tmp2, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len);
987            }
988            ldap_value_free_len(ldap_value);
989
990            attr_len = strlen(attribute);
991            zend_hash_str_update(Z_ARRVAL(tmp1), php_strtolower(attribute, attr_len), attr_len, &tmp2);
992            add_index_string(&tmp1, num_attrib, attribute);
993
994            num_attrib++;
995#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
996            ldap_memfree(attribute);
997#endif
998            attribute = ldap_next_attribute(ldap, ldap_result_entry, ber);
999        }
1000#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1001        if (ber != NULL) {
1002            ber_free(ber, 0);
1003        }
1004#endif
1005
1006        add_assoc_long(&tmp1, "count", num_attrib);
1007        dn = ldap_get_dn(ldap, ldap_result_entry);
1008        add_assoc_string(&tmp1, "dn", dn);
1009#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1010        ldap_memfree(dn);
1011#else
1012        free(dn);
1013#endif
1014
1015        zend_hash_index_update(Z_ARRVAL_P(return_value), num_entries, &tmp1);
1016
1017        num_entries++;
1018        ldap_result_entry = ldap_next_entry(ldap, ldap_result_entry);
1019    }
1020
1021    add_assoc_long(return_value, "count", num_entries);
1022
1023}
1024/* }}} */
1025
1026/* {{{ proto string ldap_first_attribute(resource link, resource result_entry)
1027   Return first attribute */
1028PHP_FUNCTION(ldap_first_attribute)
1029{
1030    zval *link, *result_entry;
1031    ldap_linkdata *ld;
1032    ldap_resultentry *resultentry;
1033    char *attribute;
1034    zend_long dummy_ber;
1035
1036    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr|l", &link, &result_entry, &dummy_ber) != SUCCESS) {
1037        return;
1038    }
1039
1040    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1041    ZEND_FETCH_RESOURCE(resultentry, ldap_resultentry *, result_entry, -1, "ldap result entry", le_result_entry);
1042
1043    if ((attribute = ldap_first_attribute(ld->link, resultentry->data, &resultentry->ber)) == NULL) {
1044        RETURN_FALSE;
1045    } else {
1046        RETVAL_STRING(attribute);
1047#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1048        ldap_memfree(attribute);
1049#endif
1050    }
1051}
1052/* }}} */
1053
1054/* {{{ proto string ldap_next_attribute(resource link, resource result_entry)
1055   Get the next attribute in result */
1056PHP_FUNCTION(ldap_next_attribute)
1057{
1058    zval *link, *result_entry;
1059    ldap_linkdata *ld;
1060    ldap_resultentry *resultentry;
1061    char *attribute;
1062    zend_long dummy_ber;
1063
1064    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr|l", &link, &result_entry, &dummy_ber) != SUCCESS) {
1065        return;
1066    }
1067
1068    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1069    ZEND_FETCH_RESOURCE(resultentry, ldap_resultentry *, result_entry, -1, "ldap result entry", le_result_entry);
1070
1071    if (resultentry->ber == NULL) {
1072        php_error_docref(NULL TSRMLS_CC, E_WARNING, "called before calling ldap_first_attribute() or no attributes found in result entry");
1073        RETURN_FALSE;
1074    }
1075
1076    if ((attribute = ldap_next_attribute(ld->link, resultentry->data, resultentry->ber)) == NULL) {
1077#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1078        if (resultentry->ber != NULL) {
1079            ber_free(resultentry->ber, 0);
1080            resultentry->ber = NULL;
1081        }
1082#endif
1083        RETURN_FALSE;
1084    } else {
1085        RETVAL_STRING(attribute);
1086#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1087        ldap_memfree(attribute);
1088#endif
1089    }
1090}
1091/* }}} */
1092
1093/* {{{ proto array ldap_get_attributes(resource link, resource result_entry)
1094   Get attributes from a search result entry */
1095PHP_FUNCTION(ldap_get_attributes)
1096{
1097    zval *link, *result_entry;
1098    zval tmp;
1099    ldap_linkdata *ld;
1100    ldap_resultentry *resultentry;
1101    char *attribute;
1102    struct berval **ldap_value;
1103    int i, num_values, num_attrib;
1104    BerElement *ber;
1105
1106    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &link, &result_entry) != SUCCESS) {
1107        return;
1108    }
1109
1110    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1111    ZEND_FETCH_RESOURCE(resultentry, ldap_resultentry *, result_entry, -1, "ldap result entry", le_result_entry);
1112
1113    array_init(return_value);
1114    num_attrib = 0;
1115
1116    attribute = ldap_first_attribute(ld->link, resultentry->data, &ber);
1117    while (attribute != NULL) {
1118        ldap_value = ldap_get_values_len(ld->link, resultentry->data, attribute);
1119        num_values = ldap_count_values_len(ldap_value);
1120
1121        array_init(&tmp);
1122        add_assoc_long(&tmp, "count", num_values);
1123        for (i = 0; i < num_values; i++) {
1124            add_index_stringl(&tmp, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len);
1125        }
1126        ldap_value_free_len(ldap_value);
1127
1128        zend_hash_str_update(Z_ARRVAL_P(return_value), attribute, strlen(attribute), &tmp);
1129        add_index_string(return_value, num_attrib, attribute);
1130
1131        num_attrib++;
1132#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1133        ldap_memfree(attribute);
1134#endif
1135        attribute = ldap_next_attribute(ld->link, resultentry->data, ber);
1136    }
1137#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1138    if (ber != NULL) {
1139        ber_free(ber, 0);
1140    }
1141#endif
1142
1143    add_assoc_long(return_value, "count", num_attrib);
1144}
1145/* }}} */
1146
1147/* {{{ proto array ldap_get_values_len(resource link, resource result_entry, string attribute)
1148   Get all values with lengths from a result entry */
1149PHP_FUNCTION(ldap_get_values_len)
1150{
1151    zval *link, *result_entry;
1152    ldap_linkdata *ld;
1153    ldap_resultentry *resultentry;
1154    char *attr;
1155    struct berval **ldap_value_len;
1156    int i, num_values;
1157    size_t attr_len;
1158
1159    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrs", &link, &result_entry, &attr, &attr_len) != SUCCESS) {
1160        return;
1161    }
1162
1163    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1164    ZEND_FETCH_RESOURCE(resultentry, ldap_resultentry *, result_entry, -1, "ldap result entry", le_result_entry);
1165
1166    if ((ldap_value_len = ldap_get_values_len(ld->link, resultentry->data, attr)) == NULL) {
1167        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot get the value(s) of attribute %s", ldap_err2string(_get_lderrno(ld->link)));
1168        RETURN_FALSE;
1169    }
1170
1171    num_values = ldap_count_values_len(ldap_value_len);
1172    array_init(return_value);
1173
1174    for (i=0; i<num_values; i++) {
1175        add_next_index_stringl(return_value, ldap_value_len[i]->bv_val, ldap_value_len[i]->bv_len);
1176    }
1177
1178    add_assoc_long(return_value, "count", num_values);
1179    ldap_value_free_len(ldap_value_len);
1180
1181}
1182/* }}} */
1183
1184/* {{{ proto string ldap_get_dn(resource link, resource result_entry)
1185   Get the DN of a result entry */
1186PHP_FUNCTION(ldap_get_dn)
1187{
1188    zval *link, *result_entry;
1189    ldap_linkdata *ld;
1190    ldap_resultentry *resultentry;
1191    char *text;
1192
1193    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &link, &result_entry) != SUCCESS) {
1194        return;
1195    }
1196
1197    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1198    ZEND_FETCH_RESOURCE(resultentry, ldap_resultentry *, result_entry, -1, "ldap result entry", le_result_entry);
1199
1200    text = ldap_get_dn(ld->link, resultentry->data);
1201    if (text != NULL) {
1202        RETVAL_STRING(text);
1203#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1204        ldap_memfree(text);
1205#else
1206        free(text);
1207#endif
1208    } else {
1209        RETURN_FALSE;
1210    }
1211}
1212/* }}} */
1213
1214/* {{{ proto array ldap_explode_dn(string dn, int with_attrib)
1215   Splits DN into its component parts */
1216PHP_FUNCTION(ldap_explode_dn)
1217{
1218    zend_long with_attrib;
1219    char *dn, **ldap_value;
1220    int i, count;
1221    size_t dn_len;
1222
1223    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl", &dn, &dn_len, &with_attrib) != SUCCESS) {
1224        return;
1225    }
1226
1227    if (!(ldap_value = ldap_explode_dn(dn, with_attrib))) {
1228        /* Invalid parameters were passed to ldap_explode_dn */
1229        RETURN_FALSE;
1230    }
1231
1232    i=0;
1233    while (ldap_value[i] != NULL) i++;
1234    count = i;
1235
1236    array_init(return_value);
1237
1238    add_assoc_long(return_value, "count", count);
1239    for (i = 0; i<count; i++) {
1240        add_index_string(return_value, i, ldap_value[i]);
1241    }
1242
1243    ldap_value_free(ldap_value);
1244}
1245/* }}} */
1246
1247/* {{{ proto string ldap_dn2ufn(string dn)
1248   Convert DN to User Friendly Naming format */
1249PHP_FUNCTION(ldap_dn2ufn)
1250{
1251    char *dn, *ufn;
1252    size_t dn_len;
1253
1254    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &dn, &dn_len) != SUCCESS) {
1255        return;
1256    }
1257
1258    ufn = ldap_dn2ufn(dn);
1259
1260    if (ufn != NULL) {
1261        RETVAL_STRING(ufn);
1262#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1263        ldap_memfree(ufn);
1264#endif
1265    } else {
1266        RETURN_FALSE;
1267    }
1268}
1269/* }}} */
1270
1271
1272/* added to fix use of ldap_modify_add for doing an ldap_add, gerrit thomson. */
1273#define PHP_LD_FULL_ADD 0xff
1274/* {{{ php_ldap_do_modify
1275 */
1276static void php_ldap_do_modify(INTERNAL_FUNCTION_PARAMETERS, int oper)
1277{
1278    zval *link, *entry, *value, *ivalue;
1279    ldap_linkdata *ld;
1280    char *dn;
1281    LDAPMod **ldap_mods;
1282    int i, j, num_attribs, num_values;
1283    size_t dn_len;
1284    int *num_berval;
1285    zend_string *attribute;
1286    zend_ulong index;
1287    int is_full_add=0; /* flag for full add operation so ldap_mod_add can be put back into oper, gerrit THomson */
1288
1289    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsa", &link, &dn, &dn_len, &entry) != SUCCESS) {
1290        return;
1291    }
1292
1293    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1294
1295    num_attribs = zend_hash_num_elements(Z_ARRVAL_P(entry));
1296    ldap_mods = safe_emalloc((num_attribs+1), sizeof(LDAPMod *), 0);
1297    num_berval = safe_emalloc(num_attribs, sizeof(int), 0);
1298    zend_hash_internal_pointer_reset(Z_ARRVAL_P(entry));
1299
1300    /* added by gerrit thomson to fix ldap_add using ldap_mod_add */
1301    if (oper == PHP_LD_FULL_ADD) {
1302        oper = LDAP_MOD_ADD;
1303        is_full_add = 1;
1304    }
1305    /* end additional , gerrit thomson */
1306
1307    for (i = 0; i < num_attribs; i++) {
1308        ldap_mods[i] = emalloc(sizeof(LDAPMod));
1309        ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
1310        ldap_mods[i]->mod_type = NULL;
1311
1312        if (zend_hash_get_current_key(Z_ARRVAL_P(entry), &attribute, &index, 0) == HASH_KEY_IS_STRING) {
1313            ldap_mods[i]->mod_type = estrndup(attribute->val, attribute->len);
1314        } else {
1315            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown attribute in the data");
1316            /* Free allocated memory */
1317            while (i >= 0) {
1318                if (ldap_mods[i]->mod_type) {
1319                    efree(ldap_mods[i]->mod_type);
1320                }
1321                efree(ldap_mods[i]);
1322                i--;
1323            }
1324            efree(num_berval);
1325            efree(ldap_mods);
1326            RETURN_FALSE;
1327        }
1328
1329        value = zend_hash_get_current_data(Z_ARRVAL_P(entry));
1330
1331        if (Z_TYPE_P(value) != IS_ARRAY) {
1332            num_values = 1;
1333        } else {
1334            num_values = zend_hash_num_elements(Z_ARRVAL_P(value));
1335        }
1336
1337        num_berval[i] = num_values;
1338        ldap_mods[i]->mod_bvalues = safe_emalloc((num_values + 1), sizeof(struct berval *), 0);
1339
1340/* allow for arrays with one element, no allowance for arrays with none but probably not required, gerrit thomson. */
1341        if ((num_values == 1) && (Z_TYPE_P(value) != IS_ARRAY)) {
1342            convert_to_string_ex(value);
1343            ldap_mods[i]->mod_bvalues[0] = (struct berval *) emalloc (sizeof(struct berval));
1344            ldap_mods[i]->mod_bvalues[0]->bv_len = Z_STRLEN_P(value);
1345            ldap_mods[i]->mod_bvalues[0]->bv_val = Z_STRVAL_P(value);
1346        } else {
1347            for (j = 0; j < num_values; j++) {
1348                if ((ivalue = zend_hash_index_find(Z_ARRVAL_P(value), j)) == NULL) {
1349                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Value array must have consecutive indices 0, 1, ...");
1350                    num_berval[i] = j;
1351                    num_attribs = i + 1;
1352                    RETVAL_FALSE;
1353                    goto errexit;
1354                }
1355                convert_to_string_ex(ivalue);
1356                ldap_mods[i]->mod_bvalues[j] = (struct berval *) emalloc (sizeof(struct berval));
1357                ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(ivalue);
1358                ldap_mods[i]->mod_bvalues[j]->bv_val = Z_STRVAL_P(ivalue);
1359            }
1360        }
1361        ldap_mods[i]->mod_bvalues[num_values] = NULL;
1362        zend_hash_move_forward(Z_ARRVAL_P(entry));
1363    }
1364    ldap_mods[num_attribs] = NULL;
1365
1366/* check flag to see if do_mod was called to perform full add , gerrit thomson */
1367    if (is_full_add == 1) {
1368        if ((i = ldap_add_s(ld->link, dn, ldap_mods)) != LDAP_SUCCESS) {
1369            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Add: %s", ldap_err2string(i));
1370            RETVAL_FALSE;
1371        } else RETVAL_TRUE;
1372    } else {
1373        if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) {
1374            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Modify: %s", ldap_err2string(i));
1375            RETVAL_FALSE;
1376        } else RETVAL_TRUE;
1377    }
1378
1379errexit:
1380    for (i = 0; i < num_attribs; i++) {
1381        efree(ldap_mods[i]->mod_type);
1382        for (j = 0; j < num_berval[i]; j++) {
1383            efree(ldap_mods[i]->mod_bvalues[j]);
1384        }
1385        efree(ldap_mods[i]->mod_bvalues);
1386        efree(ldap_mods[i]);
1387    }
1388    efree(num_berval);
1389    efree(ldap_mods);
1390
1391    return;
1392}
1393/* }}} */
1394
1395/* {{{ proto bool ldap_add(resource link, string dn, array entry)
1396   Add entries to LDAP directory */
1397PHP_FUNCTION(ldap_add)
1398{
1399    /* use a newly define parameter into the do_modify so ldap_mod_add can be used the way it is supposed to be used , Gerrit THomson */
1400    php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD);
1401}
1402/* }}} */
1403
1404/* three functions for attribute base modifications, gerrit Thomson */
1405
1406/* {{{ proto bool ldap_mod_replace(resource link, string dn, array entry)
1407   Replace attribute values with new ones */
1408PHP_FUNCTION(ldap_mod_replace)
1409{
1410    php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE);
1411}
1412/* }}} */
1413
1414/* {{{ proto bool ldap_mod_add(resource link, string dn, array entry)
1415   Add attribute values to current */
1416PHP_FUNCTION(ldap_mod_add)
1417{
1418    php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD);
1419}
1420/* }}} */
1421
1422/* {{{ proto bool ldap_mod_del(resource link, string dn, array entry)
1423   Delete attribute values */
1424PHP_FUNCTION(ldap_mod_del)
1425{
1426    php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE);
1427}
1428/* }}} */
1429
1430/* {{{ proto bool ldap_delete(resource link, string dn)
1431   Delete an entry from a directory */
1432PHP_FUNCTION(ldap_delete)
1433{
1434    zval *link;
1435    ldap_linkdata *ld;
1436    char *dn;
1437    int rc;
1438    size_t dn_len;
1439
1440    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &link, &dn, &dn_len) != SUCCESS) {
1441        return;
1442    }
1443
1444    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1445
1446    if ((rc = ldap_delete_s(ld->link, dn)) != LDAP_SUCCESS) {
1447        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Delete: %s", ldap_err2string(rc));
1448        RETURN_FALSE;
1449    }
1450
1451    RETURN_TRUE;
1452}
1453/* }}} */
1454
1455/* {{{ _ldap_str_equal_to_const
1456 */
1457static int _ldap_str_equal_to_const(const char *str, uint str_len, const char *cstr)
1458{
1459    int i;
1460
1461    if (strlen(cstr) != str_len)
1462        return 0;
1463
1464    for (i = 0; i < str_len; ++i) {
1465        if (str[i] != cstr[i]) {
1466            return 0;
1467        }
1468    }
1469
1470    return 1;
1471}
1472/* }}} */
1473
1474/* {{{ _ldap_strlen_max
1475 */
1476static int _ldap_strlen_max(const char *str, uint max_len)
1477{
1478    int i;
1479
1480    for (i = 0; i < max_len; ++i) {
1481        if (str[i] == '\0') {
1482            return i;
1483        }
1484    }
1485
1486    return max_len;
1487}
1488/* }}} */
1489
1490/* {{{ _ldap_hash_fetch
1491 */
1492static void _ldap_hash_fetch(zval *hashTbl, const char *key, zval **out)
1493{
1494    *out = zend_hash_str_find(Z_ARRVAL_P(hashTbl), key, strlen(key));
1495}
1496/* }}} */
1497
1498/* {{{ proto bool ldap_modify_batch(resource link, string dn, array modifs)
1499   Perform multiple modifications as part of one operation */
1500PHP_FUNCTION(ldap_modify_batch)
1501{
1502    ldap_linkdata *ld;
1503    zval *link, *mods, *mod, *modinfo, *modval;
1504    zval *attrib, *modtype, *vals;
1505    zval *fetched;
1506    char *dn;
1507    size_t dn_len;
1508    int i, j, k;
1509    int num_mods, num_modprops, num_modvals;
1510    LDAPMod **ldap_mods;
1511    uint oper;
1512
1513    /*
1514    $mods = array(
1515        array(
1516            "attrib" => "unicodePwd",
1517            "modtype" => LDAP_MODIFY_BATCH_REMOVE,
1518            "values" => array($oldpw)
1519        ),
1520        array(
1521            "attrib" => "unicodePwd",
1522            "modtype" => LDAP_MODIFY_BATCH_ADD,
1523            "values" => array($newpw)
1524        ),
1525        array(
1526            "attrib" => "userPrincipalName",
1527            "modtype" => LDAP_MODIFY_BATCH_REPLACE,
1528            "values" => array("janitor@corp.contoso.com")
1529        ),
1530        array(
1531            "attrib" => "userCert",
1532            "modtype" => LDAP_MODIFY_BATCH_REMOVE_ALL
1533        )
1534    );
1535    */
1536
1537    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsa", &link, &dn, &dn_len, &mods) != SUCCESS) {
1538        return;
1539    }
1540
1541    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1542
1543    /* perform validation */
1544    {
1545        zend_string *modkey;
1546        zend_long modtype;
1547
1548        /* to store the wrongly-typed keys */
1549        zend_ulong tmpUlong;
1550
1551        /* make sure the DN contains no NUL bytes */
1552        if (_ldap_strlen_max(dn, dn_len) != dn_len) {
1553            php_error_docref(NULL TSRMLS_CC, E_WARNING, "DN must not contain NUL bytes");
1554            RETURN_FALSE;
1555        }
1556
1557        /* make sure the top level is a normal array */
1558        zend_hash_internal_pointer_reset(Z_ARRVAL_P(mods));
1559        if (zend_hash_get_current_key_type(Z_ARRVAL_P(mods)) != HASH_KEY_IS_LONG) {
1560            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Modifications array must not be string-indexed");
1561            RETURN_FALSE;
1562        }
1563
1564        num_mods = zend_hash_num_elements(Z_ARRVAL_P(mods));
1565
1566        for (i = 0; i < num_mods; i++) {
1567            /* is the numbering consecutive? */
1568            if ((fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i)) == NULL) {
1569                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Modifications array must have consecutive indices 0, 1, ...");
1570                RETURN_FALSE;
1571            }
1572            mod = fetched;
1573
1574            /* is it an array? */
1575            if (Z_TYPE_P(mod) != IS_ARRAY) {
1576                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Each entry of modifications array must be an array itself");
1577                RETURN_FALSE;
1578            }
1579
1580            /* for the modification hashtable... */
1581            zend_hash_internal_pointer_reset(Z_ARRVAL_P(mod));
1582            num_modprops = zend_hash_num_elements(Z_ARRVAL_P(mod));
1583
1584            for (j = 0; j < num_modprops; j++) {
1585                /* are the keys strings? */
1586                if (zend_hash_get_current_key(Z_ARRVAL_P(mod), &modkey, &tmpUlong, 0) != HASH_KEY_IS_STRING) {
1587                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Each entry of modifications array must be string-indexed");
1588                    RETURN_FALSE;
1589                }
1590
1591                /* is this a valid entry? */
1592                if (
1593                    !_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_ATTRIB) &&
1594                    !_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_MODTYPE) &&
1595                    !_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_VALUES)
1596                ) {
1597                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "The only allowed keys in entries of the modifications array are '" LDAP_MODIFY_BATCH_ATTRIB "', '" LDAP_MODIFY_BATCH_MODTYPE "' and '" LDAP_MODIFY_BATCH_VALUES "'");
1598                    RETURN_FALSE;
1599                }
1600
1601                fetched = zend_hash_get_current_data(Z_ARRVAL_P(mod));
1602                modinfo = fetched;
1603
1604                /* does the value type match the key? */
1605                if (_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_ATTRIB)) {
1606                    if (Z_TYPE_P(modinfo) != IS_STRING) {
1607                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "A '" LDAP_MODIFY_BATCH_ATTRIB "' value must be a string");
1608                        RETURN_FALSE;
1609                    }
1610
1611                    if (Z_STRLEN_P(modinfo) != _ldap_strlen_max(Z_STRVAL_P(modinfo), Z_STRLEN_P(modinfo))) {
1612                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "A '" LDAP_MODIFY_BATCH_ATTRIB "' value must not contain NUL bytes");
1613                        RETURN_FALSE;
1614                    }
1615                }
1616                else if (_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_MODTYPE)) {
1617                    if (Z_TYPE_P(modinfo) != IS_LONG) {
1618                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "A '" LDAP_MODIFY_BATCH_MODTYPE "' value must be a long");
1619                        RETURN_FALSE;
1620                    }
1621
1622                    /* is the value in range? */
1623                    modtype = Z_LVAL_P(modinfo);
1624                    if (
1625                        modtype != LDAP_MODIFY_BATCH_ADD &&
1626                        modtype != LDAP_MODIFY_BATCH_REMOVE &&
1627                        modtype != LDAP_MODIFY_BATCH_REPLACE &&
1628                        modtype != LDAP_MODIFY_BATCH_REMOVE_ALL
1629                    ) {
1630                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "The '" LDAP_MODIFY_BATCH_MODTYPE "' value must match one of the LDAP_MODIFY_BATCH_* constants");
1631                        RETURN_FALSE;
1632                    }
1633
1634                    /* if it's REMOVE_ALL, there must not be a values array; otherwise, there must */
1635                    if (modtype == LDAP_MODIFY_BATCH_REMOVE_ALL) {
1636                        if (zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
1637                            php_error_docref(NULL TSRMLS_CC, E_WARNING, "If '" LDAP_MODIFY_BATCH_MODTYPE "' is LDAP_MODIFY_BATCH_REMOVE_ALL, a '" LDAP_MODIFY_BATCH_VALUES "' array must not be provided");
1638                            RETURN_FALSE;
1639                        }
1640                    }
1641                    else {
1642                        if (!zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
1643                            php_error_docref(NULL TSRMLS_CC, E_WARNING, "If '" LDAP_MODIFY_BATCH_MODTYPE "' is not LDAP_MODIFY_BATCH_REMOVE_ALL, a '" LDAP_MODIFY_BATCH_VALUES "' array must be provided");
1644                            RETURN_FALSE;
1645                        }
1646                    }
1647                }
1648                else if (_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_VALUES)) {
1649                    if (Z_TYPE_P(modinfo) != IS_ARRAY) {
1650                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' value must be an array");
1651                        RETURN_FALSE;
1652                    }
1653
1654                    /* is the array not empty? */
1655                    zend_hash_internal_pointer_reset(Z_ARRVAL_P(modinfo));
1656                    num_modvals = zend_hash_num_elements(Z_ARRVAL_P(modinfo));
1657                    if (num_modvals == 0) {
1658                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must have at least one element");
1659                        RETURN_FALSE;
1660                    }
1661
1662                    /* are its keys integers? */
1663                    if (zend_hash_get_current_key_type(Z_ARRVAL_P(modinfo)) != HASH_KEY_IS_LONG) {
1664                        php_error_docref(NULL TSRMLS_CC, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must not be string-indexed");
1665                        RETURN_FALSE;
1666                    }
1667
1668                    /* are the keys consecutive? */
1669                    for (k = 0; k < num_modvals; k++) {
1670                        if ((fetched = zend_hash_index_find(Z_ARRVAL_P(modinfo), k)) == NULL) {
1671                            php_error_docref(NULL TSRMLS_CC, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must have consecutive indices 0, 1, ...");
1672                            RETURN_FALSE;
1673                        }
1674                        modval = fetched;
1675
1676                        /* is the data element a string? */
1677                        if (Z_TYPE_P(modval) != IS_STRING) {
1678                            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Each element of a '" LDAP_MODIFY_BATCH_VALUES "' array must be a string");
1679                            RETURN_FALSE;
1680                        }
1681                    }
1682                }
1683
1684                zend_hash_move_forward(Z_ARRVAL_P(mod));
1685            }
1686        }
1687    }
1688    /* validation was successful */
1689
1690    /* allocate array of modifications */
1691    ldap_mods = safe_emalloc((num_mods+1), sizeof(LDAPMod *), 0);
1692
1693    /* for each modification */
1694    for (i = 0; i < num_mods; i++) {
1695        /* allocate the modification struct */
1696        ldap_mods[i] = safe_emalloc(1, sizeof(LDAPMod), 0);
1697
1698        /* fetch the relevant data */
1699        fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i);
1700        mod = fetched;
1701
1702        _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_ATTRIB, &attrib);
1703        _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_MODTYPE, &modtype);
1704        _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_VALUES, &vals);
1705
1706        /* map the modification type */
1707        switch (Z_LVAL_P(modtype)) {
1708            case LDAP_MODIFY_BATCH_ADD:
1709                oper = LDAP_MOD_ADD;
1710                break;
1711            case LDAP_MODIFY_BATCH_REMOVE:
1712            case LDAP_MODIFY_BATCH_REMOVE_ALL:
1713                oper = LDAP_MOD_DELETE;
1714                break;
1715            case LDAP_MODIFY_BATCH_REPLACE:
1716                oper = LDAP_MOD_REPLACE;
1717                break;
1718            default:
1719                php_error_docref(NULL TSRMLS_CC, E_ERROR, "Unknown and uncaught modification type.");
1720                RETURN_FALSE;
1721        }
1722
1723        /* fill in the basic info */
1724        ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
1725        ldap_mods[i]->mod_type = estrndup(Z_STRVAL_P(attrib), Z_STRLEN_P(attrib));
1726
1727        if (Z_LVAL_P(modtype) == LDAP_MODIFY_BATCH_REMOVE_ALL) {
1728            /* no values */
1729            ldap_mods[i]->mod_bvalues = NULL;
1730        }
1731        else {
1732            /* allocate space for the values as part of this modification */
1733            num_modvals = zend_hash_num_elements(Z_ARRVAL_P(vals));
1734            ldap_mods[i]->mod_bvalues = safe_emalloc((num_modvals+1), sizeof(struct berval *), 0);
1735
1736            /* for each value */
1737            for (j = 0; j < num_modvals; j++) {
1738                /* fetch it */
1739                fetched = zend_hash_index_find(Z_ARRVAL_P(vals), j);
1740                modval = fetched;
1741
1742                /* allocate the data struct */
1743                ldap_mods[i]->mod_bvalues[j] = safe_emalloc(1, sizeof(struct berval), 0);
1744
1745                /* fill it */
1746                ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(modval);
1747                ldap_mods[i]->mod_bvalues[j]->bv_val = estrndup(Z_STRVAL_P(modval), Z_STRLEN_P(modval));
1748            }
1749
1750            /* NULL-terminate values */
1751            ldap_mods[i]->mod_bvalues[num_modvals] = NULL;
1752        }
1753    }
1754
1755    /* NULL-terminate modifications */
1756    ldap_mods[num_mods] = NULL;
1757
1758    /* perform (finally) */
1759    if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) {
1760        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Batch Modify: %s", ldap_err2string(i));
1761        RETVAL_FALSE;
1762    } else RETVAL_TRUE;
1763
1764    /* clean up */
1765    {
1766        for (i = 0; i < num_mods; i++) {
1767            /* attribute */
1768            efree(ldap_mods[i]->mod_type);
1769
1770            if (ldap_mods[i]->mod_bvalues != NULL) {
1771                /* each BER value */
1772                for (j = 0; ldap_mods[i]->mod_bvalues[j] != NULL; j++) {
1773                    /* free the data bytes */
1774                    efree(ldap_mods[i]->mod_bvalues[j]->bv_val);
1775
1776                    /* free the bvalue struct */
1777                    efree(ldap_mods[i]->mod_bvalues[j]);
1778                }
1779
1780                /* the BER value array */
1781                efree(ldap_mods[i]->mod_bvalues);
1782            }
1783
1784            /* the modification */
1785            efree(ldap_mods[i]);
1786        }
1787
1788        /* the modifications array */
1789        efree(ldap_mods);
1790    }
1791}
1792/* }}} */
1793
1794/* {{{ proto int ldap_errno(resource link)
1795   Get the current ldap error number */
1796PHP_FUNCTION(ldap_errno)
1797{
1798    zval *link;
1799    ldap_linkdata *ld;
1800
1801    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &link) != SUCCESS) {
1802        return;
1803    }
1804
1805    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1806
1807    RETURN_LONG(_get_lderrno(ld->link));
1808}
1809/* }}} */
1810
1811/* {{{ proto string ldap_err2str(int errno)
1812   Convert error number to error string */
1813PHP_FUNCTION(ldap_err2str)
1814{
1815    zend_long perrno;
1816
1817    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &perrno) != SUCCESS) {
1818        return;
1819    }
1820
1821    RETURN_STRING(ldap_err2string(perrno));
1822}
1823/* }}} */
1824
1825/* {{{ proto string ldap_error(resource link)
1826   Get the current ldap error string */
1827PHP_FUNCTION(ldap_error)
1828{
1829    zval *link;
1830    ldap_linkdata *ld;
1831    int ld_errno;
1832
1833    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &link) != SUCCESS) {
1834        return;
1835    }
1836
1837    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1838
1839    ld_errno = _get_lderrno(ld->link);
1840
1841    RETURN_STRING(ldap_err2string(ld_errno));
1842}
1843/* }}} */
1844
1845/* {{{ proto bool ldap_compare(resource link, string dn, string attr, string value)
1846   Determine if an entry has a specific value for one of its attributes */
1847PHP_FUNCTION(ldap_compare)
1848{
1849    zval *link;
1850    char *dn, *attr, *value;
1851    size_t dn_len, attr_len, value_len;
1852    ldap_linkdata *ld;
1853    int errno;
1854
1855    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsss", &link, &dn, &dn_len, &attr, &attr_len, &value, &value_len) != SUCCESS) {
1856        return;
1857    }
1858
1859    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1860
1861    errno = ldap_compare_s(ld->link, dn, attr, value);
1862
1863    switch (errno) {
1864        case LDAP_COMPARE_TRUE:
1865            RETURN_TRUE;
1866            break;
1867
1868        case LDAP_COMPARE_FALSE:
1869            RETURN_FALSE;
1870            break;
1871    }
1872
1873    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Compare: %s", ldap_err2string(errno));
1874    RETURN_LONG(-1);
1875}
1876/* }}} */
1877
1878/* {{{ proto bool ldap_sort(resource link, resource result, string sortfilter)
1879   Sort LDAP result entries */
1880PHP_FUNCTION(ldap_sort)
1881{
1882    zval *link, *result;
1883    ldap_linkdata *ld;
1884    char *sortfilter;
1885    size_t sflen;
1886    zend_resource *le;
1887
1888    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrs", &link, &result, &sortfilter, &sflen) != SUCCESS) {
1889        RETURN_FALSE;
1890    }
1891
1892    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1893
1894    if ((le = zend_hash_index_find_ptr(&EG(regular_list), Z_RES_HANDLE_P(result))) == NULL || le->type != le_result) {
1895        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Supplied resource is not a valid ldap result resource");
1896        RETURN_FALSE;
1897    }
1898
1899    if (ldap_sort_entries(ld->link, (LDAPMessage **) &le->ptr, sflen ? sortfilter : NULL, strcmp) != LDAP_SUCCESS) {
1900        php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ldap_err2string(errno));
1901        RETURN_FALSE;
1902    }
1903
1904    RETURN_TRUE;
1905}
1906/* }}} */
1907
1908#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
1909/* {{{ proto bool ldap_get_option(resource link, int option, mixed retval)
1910   Get the current value of various session-wide parameters */
1911PHP_FUNCTION(ldap_get_option)
1912{
1913    zval *link, *retval;
1914    ldap_linkdata *ld;
1915    zend_long option;
1916
1917    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlz/", &link, &option, &retval) != SUCCESS) {
1918        return;
1919    }
1920
1921    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
1922
1923    switch (option) {
1924    /* options with int value */
1925    case LDAP_OPT_DEREF:
1926    case LDAP_OPT_SIZELIMIT:
1927    case LDAP_OPT_TIMELIMIT:
1928    case LDAP_OPT_PROTOCOL_VERSION:
1929    case LDAP_OPT_ERROR_NUMBER:
1930    case LDAP_OPT_REFERRALS:
1931#ifdef LDAP_OPT_RESTART
1932    case LDAP_OPT_RESTART:
1933#endif
1934        {
1935            int val;
1936
1937            if (ldap_get_option(ld->link, option, &val)) {
1938                RETURN_FALSE;
1939            }
1940            zval_ptr_dtor(retval);
1941            ZVAL_LONG(retval, val);
1942        } break;
1943#ifdef LDAP_OPT_NETWORK_TIMEOUT
1944    case LDAP_OPT_NETWORK_TIMEOUT:
1945        {
1946            struct timeval *timeout = NULL;
1947
1948            if (ldap_get_option(ld->link, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
1949                if (timeout) {
1950                    ldap_memfree(timeout);
1951                }
1952                RETURN_FALSE;
1953            }
1954            if (!timeout) {
1955                RETURN_FALSE;
1956            }
1957            zval_ptr_dtor(retval);
1958            ZVAL_LONG(retval, timeout->tv_sec);
1959            ldap_memfree(timeout);
1960        } break;
1961#elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
1962    case LDAP_X_OPT_CONNECT_TIMEOUT:
1963        {
1964            int timeout;
1965
1966            if (ldap_get_option(ld->link, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
1967                RETURN_FALSE;
1968            }
1969            zval_ptr_dtor(retval);
1970            ZVAL_LONG(retval, (timeout / 1000));
1971        } break;
1972#endif
1973    /* options with string value */
1974    case LDAP_OPT_ERROR_STRING:
1975#ifdef LDAP_OPT_HOST_NAME
1976    case LDAP_OPT_HOST_NAME:
1977#endif
1978#ifdef HAVE_LDAP_SASL
1979    case LDAP_OPT_X_SASL_MECH:
1980    case LDAP_OPT_X_SASL_REALM:
1981    case LDAP_OPT_X_SASL_AUTHCID:
1982    case LDAP_OPT_X_SASL_AUTHZID:
1983#endif
1984#ifdef LDAP_OPT_MATCHED_DN
1985    case LDAP_OPT_MATCHED_DN:
1986#endif
1987        {
1988            char *val = NULL;
1989
1990            if (ldap_get_option(ld->link, option, &val) || val == NULL || *val == '\0') {
1991                if (val) {
1992                    ldap_memfree(val);
1993                }
1994                RETURN_FALSE;
1995            }
1996            zval_ptr_dtor(retval);
1997            ZVAL_STRING(retval, val);
1998            ldap_memfree(val);
1999        } break;
2000/* options not implemented
2001    case LDAP_OPT_SERVER_CONTROLS:
2002    case LDAP_OPT_CLIENT_CONTROLS:
2003    case LDAP_OPT_API_INFO:
2004    case LDAP_OPT_API_FEATURE_INFO:
2005*/
2006    default:
2007        RETURN_FALSE;
2008    }
2009    RETURN_TRUE;
2010}
2011/* }}} */
2012
2013/* {{{ proto bool ldap_set_option(resource link, int option, mixed newval)
2014   Set the value of various session-wide parameters */
2015PHP_FUNCTION(ldap_set_option)
2016{
2017    zval *link, *newval;
2018    ldap_linkdata *ld;
2019    LDAP *ldap;
2020    zend_long option;
2021
2022    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zlz", &link, &option, &newval) != SUCCESS) {
2023        return;
2024    }
2025
2026    if (Z_TYPE_P(link) == IS_NULL) {
2027        ldap = NULL;
2028    } else {
2029        ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2030        ldap = ld->link;
2031    }
2032
2033    switch (option) {
2034    /* options with int value */
2035    case LDAP_OPT_DEREF:
2036    case LDAP_OPT_SIZELIMIT:
2037    case LDAP_OPT_TIMELIMIT:
2038    case LDAP_OPT_PROTOCOL_VERSION:
2039    case LDAP_OPT_ERROR_NUMBER:
2040#ifdef LDAP_OPT_DEBUG_LEVEL
2041    case LDAP_OPT_DEBUG_LEVEL:
2042#endif
2043        {
2044            int val;
2045
2046            convert_to_long_ex(newval);
2047            val = Z_LVAL_P(newval);
2048            if (ldap_set_option(ldap, option, &val)) {
2049                RETURN_FALSE;
2050            }
2051        } break;
2052#ifdef LDAP_OPT_NETWORK_TIMEOUT
2053    case LDAP_OPT_NETWORK_TIMEOUT:
2054        {
2055            struct timeval timeout;
2056
2057            convert_to_long_ex(newval);
2058            timeout.tv_sec = Z_LVAL_P(newval);
2059            timeout.tv_usec = 0;
2060            if (ldap_set_option(ldap, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
2061                RETURN_FALSE;
2062            }
2063        } break;
2064#elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
2065    case LDAP_X_OPT_CONNECT_TIMEOUT:
2066        {
2067            int timeout;
2068
2069            convert_to_long_ex(newval);
2070            timeout = 1000 * Z_LVAL_P(newval); /* Convert to milliseconds */
2071            if (ldap_set_option(ldap, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
2072                RETURN_FALSE;
2073            }
2074        } break;
2075#endif
2076        /* options with string value */
2077    case LDAP_OPT_ERROR_STRING:
2078#ifdef LDAP_OPT_HOST_NAME
2079    case LDAP_OPT_HOST_NAME:
2080#endif
2081#ifdef HAVE_LDAP_SASL
2082    case LDAP_OPT_X_SASL_MECH:
2083    case LDAP_OPT_X_SASL_REALM:
2084    case LDAP_OPT_X_SASL_AUTHCID:
2085    case LDAP_OPT_X_SASL_AUTHZID:
2086#endif
2087#ifdef LDAP_OPT_MATCHED_DN
2088    case LDAP_OPT_MATCHED_DN:
2089#endif
2090        {
2091            char *val;
2092            convert_to_string_ex(newval);
2093            val = Z_STRVAL_P(newval);
2094            if (ldap_set_option(ldap, option, val)) {
2095                RETURN_FALSE;
2096            }
2097        } break;
2098        /* options with boolean value */
2099    case LDAP_OPT_REFERRALS:
2100#ifdef LDAP_OPT_RESTART
2101    case LDAP_OPT_RESTART:
2102#endif
2103        {
2104            void *val;
2105            convert_to_boolean_ex(newval);
2106            val = Z_TYPE_P(newval) == IS_TRUE
2107                ? LDAP_OPT_ON : LDAP_OPT_OFF;
2108            if (ldap_set_option(ldap, option, val)) {
2109                RETURN_FALSE;
2110            }
2111        } break;
2112        /* options with control list value */
2113    case LDAP_OPT_SERVER_CONTROLS:
2114    case LDAP_OPT_CLIENT_CONTROLS:
2115        {
2116            LDAPControl *ctrl, **ctrls, **ctrlp;
2117            zval *ctrlval, *val;
2118            int ncontrols;
2119            char error=0;
2120
2121            if ((Z_TYPE_P(newval) != IS_ARRAY) || !(ncontrols = zend_hash_num_elements(Z_ARRVAL_P(newval)))) {
2122                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expected non-empty array value for this option");
2123                RETURN_FALSE;
2124            }
2125            ctrls = safe_emalloc((1 + ncontrols), sizeof(*ctrls), 0);
2126            *ctrls = NULL;
2127            ctrlp = ctrls;
2128            ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(newval), ctrlval) {
2129                if (Z_TYPE_P(ctrlval) != IS_ARRAY) {
2130                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "The array value must contain only arrays, where each array is a control");
2131                    error = 1;
2132                    break;
2133                }
2134                if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "oid", sizeof("oid") - 1)) == NULL) {
2135                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Control must have an oid key");
2136                    error = 1;
2137                    break;
2138                }
2139                ctrl = *ctrlp = emalloc(sizeof(**ctrlp));
2140                convert_to_string_ex(val);
2141                ctrl->ldctl_oid = Z_STRVAL_P(val);
2142                if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "value", sizeof("value") - 1)) != NULL) {
2143                    convert_to_string_ex(val);
2144                    ctrl->ldctl_value.bv_val = Z_STRVAL_P(val);
2145                    ctrl->ldctl_value.bv_len = Z_STRLEN_P(val);
2146                } else {
2147                    ctrl->ldctl_value.bv_val = NULL;
2148                    ctrl->ldctl_value.bv_len = 0;
2149                }
2150                if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "iscritical", sizeof("iscritical") - 1)) != NULL) {
2151                    convert_to_boolean_ex(val);
2152                    ctrl->ldctl_iscritical = Z_TYPE_P(val) == IS_TRUE;
2153                } else {
2154                    ctrl->ldctl_iscritical = 0;
2155                }
2156
2157                ++ctrlp;
2158                *ctrlp = NULL;
2159            } ZEND_HASH_FOREACH_END();
2160            if (!error) {
2161                error = ldap_set_option(ldap, option, ctrls);
2162            }
2163            ctrlp = ctrls;
2164            while (*ctrlp) {
2165                efree(*ctrlp);
2166                ctrlp++;
2167            }
2168            efree(ctrls);
2169            if (error) {
2170                RETURN_FALSE;
2171            }
2172        } break;
2173    default:
2174        RETURN_FALSE;
2175    }
2176    RETURN_TRUE;
2177}
2178/* }}} */
2179
2180#ifdef HAVE_LDAP_PARSE_RESULT
2181/* {{{ proto bool ldap_parse_result(resource link, resource result, int errcode, string matcheddn, string errmsg, array referrals)
2182   Extract information from result */
2183PHP_FUNCTION(ldap_parse_result)
2184{
2185    zval *link, *result, *errcode, *matcheddn, *errmsg, *referrals;
2186    ldap_linkdata *ld;
2187    LDAPMessage *ldap_result;
2188    char **lreferrals, **refp;
2189    char *lmatcheddn, *lerrmsg;
2190    int rc, lerrcode, myargcount = ZEND_NUM_ARGS();
2191
2192    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrz/|z/z/z/", &link, &result, &errcode, &matcheddn, &errmsg, &referrals) != SUCCESS) {
2193        return;
2194    }
2195
2196    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2197    ZEND_FETCH_RESOURCE(ldap_result, LDAPMessage *, result, -1, "ldap result", le_result);
2198
2199    rc = ldap_parse_result(ld->link, ldap_result, &lerrcode,
2200                myargcount > 3 ? &lmatcheddn : NULL,
2201                myargcount > 4 ? &lerrmsg : NULL,
2202                myargcount > 5 ? &lreferrals : NULL,
2203                NULL /* &serverctrls */,
2204                0);
2205    if (rc != LDAP_SUCCESS) {
2206        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to parse result: %s", ldap_err2string(rc));
2207        RETURN_FALSE;
2208    }
2209
2210    zval_ptr_dtor(errcode);
2211    ZVAL_LONG(errcode, lerrcode);
2212
2213    /* Reverse -> fall through */
2214    switch (myargcount) {
2215        case 6:
2216            zval_ptr_dtor(referrals);
2217            array_init(referrals);
2218            if (lreferrals != NULL) {
2219                refp = lreferrals;
2220                while (*refp) {
2221                    add_next_index_string(referrals, *refp);
2222                    refp++;
2223                }
2224                ldap_value_free(lreferrals);
2225            }
2226        case 5:
2227            zval_ptr_dtor(errmsg);
2228            if (lerrmsg == NULL) {
2229                ZVAL_EMPTY_STRING(errmsg);
2230            } else {
2231                ZVAL_STRING(errmsg, lerrmsg);
2232                ldap_memfree(lerrmsg);
2233            }
2234        case 4:
2235            zval_ptr_dtor(matcheddn);
2236            if (lmatcheddn == NULL) {
2237                ZVAL_EMPTY_STRING(matcheddn);
2238            } else {
2239                ZVAL_STRING(matcheddn, lmatcheddn);
2240                ldap_memfree(lmatcheddn);
2241            }
2242    }
2243    RETURN_TRUE;
2244}
2245/* }}} */
2246#endif
2247
2248/* {{{ proto resource ldap_first_reference(resource link, resource result)
2249   Return first reference */
2250PHP_FUNCTION(ldap_first_reference)
2251{
2252    zval *link, *result;
2253    ldap_linkdata *ld;
2254    ldap_resultentry *resultentry;
2255    LDAPMessage *ldap_result, *entry;
2256
2257    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &link, &result) != SUCCESS) {
2258        return;
2259    }
2260
2261    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2262    ZEND_FETCH_RESOURCE(ldap_result, LDAPMessage *, result, -1, "ldap result", le_result);
2263
2264    if ((entry = ldap_first_reference(ld->link, ldap_result)) == NULL) {
2265        RETVAL_FALSE;
2266    } else {
2267        resultentry = emalloc(sizeof(ldap_resultentry));
2268        ZEND_REGISTER_RESOURCE(return_value, resultentry, le_result_entry);
2269        ZVAL_COPY(&resultentry->res, result);
2270        resultentry->data = entry;
2271        resultentry->ber = NULL;
2272    }
2273}
2274/* }}} */
2275
2276/* {{{ proto resource ldap_next_reference(resource link, resource reference_entry)
2277   Get next reference */
2278PHP_FUNCTION(ldap_next_reference)
2279{
2280    zval *link, *result_entry;
2281    ldap_linkdata *ld;
2282    ldap_resultentry *resultentry, *resultentry_next;
2283    LDAPMessage *entry_next;
2284
2285    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &link, &result_entry) != SUCCESS) {
2286        return;
2287    }
2288
2289    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2290    ZEND_FETCH_RESOURCE(resultentry, ldap_resultentry *, result_entry, -1, "ldap result entry", le_result_entry);
2291
2292    if ((entry_next = ldap_next_reference(ld->link, resultentry->data)) == NULL) {
2293        RETVAL_FALSE;
2294    } else {
2295        resultentry_next = emalloc(sizeof(ldap_resultentry));
2296        ZEND_REGISTER_RESOURCE(return_value, resultentry_next, le_result_entry);
2297        ZVAL_COPY(&resultentry_next->res, &resultentry->res);
2298        resultentry_next->data = entry_next;
2299        resultentry_next->ber = NULL;
2300    }
2301}
2302/* }}} */
2303
2304#ifdef HAVE_LDAP_PARSE_REFERENCE
2305/* {{{ proto bool ldap_parse_reference(resource link, resource reference_entry, array referrals)
2306   Extract information from reference entry */
2307PHP_FUNCTION(ldap_parse_reference)
2308{
2309    zval *link, *result_entry, *referrals;
2310    ldap_linkdata *ld;
2311    ldap_resultentry *resultentry;
2312    char **lreferrals, **refp;
2313
2314    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrz/", &link, &result_entry, &referrals) != SUCCESS) {
2315        return;
2316    }
2317
2318    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2319    ZEND_FETCH_RESOURCE(resultentry, ldap_resultentry *, result_entry, -1, "ldap result entry", le_result_entry);
2320
2321    if (ldap_parse_reference(ld->link, resultentry->data, &lreferrals, NULL /* &serverctrls */, 0) != LDAP_SUCCESS) {
2322        RETURN_FALSE;
2323    }
2324
2325    zval_ptr_dtor(referrals);
2326    array_init(referrals);
2327    if (lreferrals != NULL) {
2328        refp = lreferrals;
2329        while (*refp) {
2330            add_next_index_string(referrals, *refp);
2331            refp++;
2332        }
2333        ldap_value_free(lreferrals);
2334    }
2335    RETURN_TRUE;
2336}
2337/* }}} */
2338#endif
2339
2340/* {{{ proto bool ldap_rename(resource link, string dn, string newrdn, string newparent, bool deleteoldrdn);
2341   Modify the name of an entry */
2342PHP_FUNCTION(ldap_rename)
2343{
2344    zval *link;
2345    ldap_linkdata *ld;
2346    int rc;
2347    char *dn, *newrdn, *newparent;
2348    size_t dn_len, newrdn_len, newparent_len;
2349    zend_bool deleteoldrdn;
2350
2351    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsssb", &link, &dn, &dn_len, &newrdn, &newrdn_len, &newparent, &newparent_len, &deleteoldrdn) != SUCCESS) {
2352        return;
2353    }
2354
2355    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2356
2357    if (newparent_len == 0) {
2358        newparent = NULL;
2359    }
2360
2361#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
2362    rc = ldap_rename_s(ld->link, dn, newrdn, newparent, deleteoldrdn, NULL, NULL);
2363#else
2364    if (newparent_len != 0) {
2365        php_error_docref(NULL TSRMLS_CC, E_WARNING, "You are using old LDAP API, newparent must be the empty string, can only modify RDN");
2366        RETURN_FALSE;
2367    }
2368/* could support old APIs but need check for ldap_modrdn2()/ldap_modrdn() */
2369    rc = ldap_modrdn2_s(ld->link, dn, newrdn, deleteoldrdn);
2370#endif
2371
2372    if (rc == LDAP_SUCCESS) {
2373        RETURN_TRUE;
2374    }
2375    RETURN_FALSE;
2376}
2377/* }}} */
2378
2379#ifdef HAVE_LDAP_START_TLS_S
2380/* {{{ proto bool ldap_start_tls(resource link)
2381   Start TLS */
2382PHP_FUNCTION(ldap_start_tls)
2383{
2384    zval *link;
2385    ldap_linkdata *ld;
2386    int rc, protocol = LDAP_VERSION3;
2387
2388    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &link) != SUCCESS) {
2389        return;
2390    }
2391
2392    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2393
2394    if (((rc = ldap_set_option(ld->link, LDAP_OPT_PROTOCOL_VERSION, &protocol)) != LDAP_SUCCESS) ||
2395        ((rc = ldap_start_tls_s(ld->link, NULL, NULL)) != LDAP_SUCCESS)
2396    ) {
2397        php_error_docref(NULL TSRMLS_CC, E_WARNING,"Unable to start TLS: %s", ldap_err2string(rc));
2398        RETURN_FALSE;
2399    } else {
2400        RETURN_TRUE;
2401    }
2402}
2403/* }}} */
2404#endif
2405#endif /* (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP */
2406
2407#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
2408/* {{{ _ldap_rebind_proc()
2409*/
2410int _ldap_rebind_proc(LDAP *ldap, const char *url, ber_tag_t req, ber_int_t msgid, void *params)
2411{
2412    ldap_linkdata *ld;
2413    int retval;
2414    zval cb_args[2];
2415    zval cb_retval;
2416    zval *cb_link = (zval *) params;
2417    TSRMLS_FETCH();
2418
2419    ld = (ldap_linkdata *) zend_fetch_resource(cb_link TSRMLS_CC, -1, "ldap link", NULL, 1, le_link);
2420
2421    /* link exists and callback set? */
2422    if (ld == NULL || Z_ISUNDEF(ld->rebindproc)) {
2423        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Link not found or no callback set");
2424        return LDAP_OTHER;
2425    }
2426
2427    /* callback */
2428    ZVAL_COPY_VALUE(&cb_args[0], cb_link);
2429    ZVAL_STRING(&cb_args[1], url);
2430    if (call_user_function_ex(EG(function_table), NULL, &ld->rebindproc, &cb_retval, 2, cb_args, 0, NULL TSRMLS_CC) == SUCCESS && !Z_ISUNDEF(cb_retval)) {
2431        convert_to_long_ex(&cb_retval);
2432        retval = Z_LVAL(cb_retval);
2433        zval_ptr_dtor(&cb_retval);
2434    } else {
2435        php_error_docref(NULL TSRMLS_CC, E_WARNING, "rebind_proc PHP callback failed");
2436        retval = LDAP_OTHER;
2437    }
2438    zval_ptr_dtor(&cb_args[1]);
2439    return retval;
2440}
2441/* }}} */
2442
2443/* {{{ proto bool ldap_set_rebind_proc(resource link, string callback)
2444   Set a callback function to do re-binds on referral chasing. */
2445PHP_FUNCTION(ldap_set_rebind_proc)
2446{
2447    zval *link, *callback;
2448    ldap_linkdata *ld;
2449    zend_string *callback_name;
2450
2451    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rz", &link, &callback) != SUCCESS) {
2452        RETURN_FALSE;
2453    }
2454
2455    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2456
2457    if (Z_TYPE_P(callback) == IS_STRING && Z_STRLEN_P(callback) == 0) {
2458        /* unregister rebind procedure */
2459        if (!Z_ISUNDEF(ld->rebindproc)) {
2460            zval_ptr_dtor(&ld->rebindproc);
2461            ZVAL_UNDEF(&ld->rebindproc);
2462            ldap_set_rebind_proc(ld->link, NULL, NULL);
2463        }
2464        RETURN_TRUE;
2465    }
2466
2467    /* callable? */
2468    if (!zend_is_callable(callback, 0, &callback_name TSRMLS_CC)) {
2469        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Two arguments expected for '%s' to be a valid callback", callback_name->val);
2470        zend_string_release(callback_name);
2471        RETURN_FALSE;
2472    }
2473    zend_string_release(callback_name);
2474
2475    /* register rebind procedure */
2476    if (Z_ISUNDEF(ld->rebindproc)) {
2477        ldap_set_rebind_proc(ld->link, _ldap_rebind_proc, (void *) link);
2478    } else {
2479        zval_ptr_dtor(&ld->rebindproc);
2480    }
2481
2482    ZVAL_COPY(&ld->rebindproc, callback);
2483    RETURN_TRUE;
2484}
2485/* }}} */
2486#endif
2487
2488static void php_ldap_do_escape(const zend_bool *map, const char *value, size_t valuelen, char **result, size_t *resultlen)
2489{
2490    char hex[] = "0123456789abcdef";
2491    int i, p = 0;
2492    size_t len = 0;
2493
2494    for (i = 0; i < valuelen; i++) {
2495        len += (map[(unsigned char) value[i]]) ? 3 : 1;
2496    }
2497
2498    (*result) = (char *) safe_emalloc(1, len, 1);
2499    (*resultlen) = len;
2500
2501    for (i = 0; i < valuelen; i++) {
2502        unsigned char v = (unsigned char) value[i];
2503
2504        if (map[v]) {
2505            (*result)[p++] = '\\';
2506            (*result)[p++] = hex[v >> 4];
2507            (*result)[p++] = hex[v & 0x0f];
2508        } else {
2509            (*result)[p++] = v;
2510        }
2511    }
2512
2513    (*result)[p++] = '\0';
2514}
2515
2516static void php_ldap_escape_map_set_chars(zend_bool *map, const char *chars, const int charslen, char escape)
2517{
2518    int i = 0;
2519    while (i < charslen) {
2520        map[(unsigned char) chars[i++]] = escape;
2521    }
2522}
2523
2524PHP_FUNCTION(ldap_escape)
2525{
2526    char *value, *ignores, *result;
2527    size_t valuelen = 0, ignoreslen = 0;
2528    int i;
2529    size_t resultlen;
2530    zend_long flags = 0;
2531    zend_bool map[256] = {0}, havecharlist = 0;
2532
2533    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sl", &value, &valuelen, &ignores, &ignoreslen, &flags) != SUCCESS) {
2534        return;
2535    }
2536
2537    if (!valuelen) {
2538        RETURN_EMPTY_STRING();
2539    }
2540
2541    if (flags & PHP_LDAP_ESCAPE_FILTER) {
2542        havecharlist = 1;
2543        php_ldap_escape_map_set_chars(map, "\\*()\0", sizeof("\\*()\0") - 1, 1);
2544    }
2545
2546    if (flags & PHP_LDAP_ESCAPE_DN) {
2547        havecharlist = 1;
2548        php_ldap_escape_map_set_chars(map, "\\,=+<>;\"#", sizeof("\\,=+<>;\"#") - 1, 1);
2549    }
2550
2551    if (!havecharlist) {
2552        for (i = 0; i < 256; i++) {
2553            map[i] = 1;
2554        }
2555    }
2556
2557    if (ignoreslen) {
2558        php_ldap_escape_map_set_chars(map, ignores, ignoreslen, 0);
2559    }
2560
2561    php_ldap_do_escape(map, value, valuelen, &result, &resultlen);
2562
2563    RETVAL_STRINGL(result, resultlen);
2564    efree(result);
2565}
2566
2567#ifdef STR_TRANSLATION
2568/* {{{ php_ldap_do_translate
2569 */
2570static void php_ldap_do_translate(INTERNAL_FUNCTION_PARAMETERS, int way)
2571{
2572    char *value;
2573    int result, ldap_len;
2574
2575    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &value, &value_len) != SUCCESS) {
2576        return;
2577    }
2578
2579    if (value_len == 0) {
2580        RETURN_FALSE;
2581    }
2582
2583    if (way == 1) {
2584        result = ldap_8859_to_t61(&value, &value_len, 0);
2585    } else {
2586        result = ldap_t61_to_8859(&value, &value_len, 0);
2587    }
2588
2589    if (result == LDAP_SUCCESS) {
2590        RETVAL_STRINGL(value, value_len);
2591        free(value);
2592    } else {
2593        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Conversion from iso-8859-1 to t61 failed: %s", ldap_err2string(result));
2594        RETVAL_FALSE;
2595    }
2596}
2597/* }}} */
2598
2599/* {{{ proto string ldap_t61_to_8859(string value)
2600   Translate t61 characters to 8859 characters */
2601PHP_FUNCTION(ldap_t61_to_8859)
2602{
2603    php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2604}
2605/* }}} */
2606
2607/* {{{ proto string ldap_8859_to_t61(string value)
2608   Translate 8859 characters to t61 characters */
2609PHP_FUNCTION(ldap_8859_to_t61)
2610{
2611    php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2612}
2613/* }}} */
2614#endif
2615
2616#ifdef LDAP_CONTROL_PAGEDRESULTS
2617/* {{{ proto mixed ldap_control_paged_result(resource link, int pagesize [, bool iscritical [, string cookie]])
2618   Inject paged results control*/
2619PHP_FUNCTION(ldap_control_paged_result)
2620{
2621    zend_long pagesize;
2622    zend_bool iscritical;
2623    zval *link;
2624    char *cookie = NULL;
2625    size_t cookie_len = 0;
2626    struct berval lcookie = { 0, NULL };
2627    ldap_linkdata *ld;
2628    LDAP *ldap;
2629    BerElement *ber = NULL;
2630    LDAPControl ctrl, *ctrlsp[2];
2631    int rc, myargcount = ZEND_NUM_ARGS();
2632
2633    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|bs", &link, &pagesize, &iscritical, &cookie, &cookie_len) != SUCCESS) {
2634        return;
2635    }
2636
2637    if (Z_TYPE_P(link) == IS_NULL) {
2638        ldap = NULL;
2639    } else {
2640        ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2641        ldap = ld->link;
2642    }
2643
2644    ber = ber_alloc_t(LBER_USE_DER);
2645    if (ber == NULL) {
2646        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to alloc BER encoding resources for paged results control");
2647        RETURN_FALSE;
2648    }
2649
2650    ctrl.ldctl_iscritical = 0;
2651
2652    switch (myargcount) {
2653        case 4:
2654            lcookie.bv_val = cookie;
2655            lcookie.bv_len = cookie_len;
2656            /* fallthru */
2657        case 3:
2658            ctrl.ldctl_iscritical = (int)iscritical;
2659            /* fallthru */
2660    }
2661
2662    if (ber_printf(ber, "{iO}", (int)pagesize, &lcookie) == LBER_ERROR) {
2663        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to BER printf paged results control");
2664        RETVAL_FALSE;
2665        goto lcpr_error_out;
2666    }
2667    rc = ber_flatten2(ber, &ctrl.ldctl_value, 0);
2668    if (rc == LBER_ERROR) {
2669        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to BER encode paged results control");
2670        RETVAL_FALSE;
2671        goto lcpr_error_out;
2672    }
2673
2674    ctrl.ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
2675
2676    if (ldap) {
2677        /* directly set the option */
2678        ctrlsp[0] = &ctrl;
2679        ctrlsp[1] = NULL;
2680
2681        rc = ldap_set_option(ldap, LDAP_OPT_SERVER_CONTROLS, ctrlsp);
2682        if (rc != LDAP_SUCCESS) {
2683            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to set paged results control: %s (%d)", ldap_err2string(rc), rc);
2684            RETVAL_FALSE;
2685            goto lcpr_error_out;
2686        }
2687        RETVAL_TRUE;
2688    } else {
2689        /* return a PHP control object */
2690        array_init(return_value);
2691
2692        add_assoc_string(return_value, "oid", ctrl.ldctl_oid);
2693        if (ctrl.ldctl_value.bv_len) {
2694            add_assoc_stringl(return_value, "value", ctrl.ldctl_value.bv_val, ctrl.ldctl_value.bv_len);
2695        }
2696        if (ctrl.ldctl_iscritical) {
2697            add_assoc_bool(return_value, "iscritical", ctrl.ldctl_iscritical);
2698        }
2699    }
2700
2701lcpr_error_out:
2702    if (ber != NULL) {
2703        ber_free(ber, 1);
2704    }
2705    return;
2706}
2707/* }}} */
2708
2709/* {{{ proto bool ldap_control_paged_result_response(resource link, resource result [, string &cookie [, int &estimated]])
2710   Extract paged results control response */
2711PHP_FUNCTION(ldap_control_paged_result_response)
2712{
2713    zval *link, *result, *cookie, *estimated;
2714    struct berval lcookie;
2715    int lestimated;
2716    ldap_linkdata *ld;
2717    LDAPMessage *ldap_result;
2718    LDAPControl **lserverctrls, *lctrl;
2719    BerElement *ber;
2720    ber_tag_t tag;
2721    int rc, lerrcode, myargcount = ZEND_NUM_ARGS();
2722
2723    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr|z/z/", &link, &result, &cookie, &estimated) != SUCCESS) {
2724        return;
2725    }
2726
2727    ZEND_FETCH_RESOURCE(ld, ldap_linkdata *, link, -1, "ldap link", le_link);
2728    ZEND_FETCH_RESOURCE(ldap_result, LDAPMessage *, result, -1, "ldap result", le_result);
2729
2730    rc = ldap_parse_result(ld->link,
2731                ldap_result,
2732                &lerrcode,
2733                NULL,       /* matcheddn */
2734                NULL,       /* errmsg */
2735                NULL,       /* referrals */
2736                &lserverctrls,
2737                0);
2738
2739    if (rc != LDAP_SUCCESS) {
2740        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to parse result: %s (%d)", ldap_err2string(rc), rc);
2741        RETURN_FALSE;
2742    }
2743
2744    if (lerrcode != LDAP_SUCCESS) {
2745        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Result is: %s (%d)", ldap_err2string(lerrcode), lerrcode);
2746        RETURN_FALSE;
2747    }
2748
2749    if (lserverctrls == NULL) {
2750        php_error_docref(NULL TSRMLS_CC, E_WARNING, "No server controls in result");
2751        RETURN_FALSE;
2752    }
2753
2754    lctrl = ldap_find_control(LDAP_CONTROL_PAGEDRESULTS, lserverctrls);
2755    if (lctrl == NULL) {
2756        ldap_controls_free(lserverctrls);
2757        php_error_docref(NULL TSRMLS_CC, E_WARNING, "No paged results control response in result");
2758        RETURN_FALSE;
2759    }
2760
2761    ber = ber_init(&lctrl->ldctl_value);
2762    if (ber == NULL) {
2763        ldap_controls_free(lserverctrls);
2764        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to alloc BER decoding resources for paged results control response");
2765        RETURN_FALSE;
2766    }
2767
2768    tag = ber_scanf(ber, "{io}", &lestimated, &lcookie);
2769    (void)ber_free(ber, 1);
2770
2771    if (tag == LBER_ERROR) {
2772        ldap_controls_free(lserverctrls);
2773        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to decode paged results control response");
2774        RETURN_FALSE;
2775    }
2776
2777    if (lestimated < 0) {
2778        ldap_controls_free(lserverctrls);
2779        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid paged results control response value");
2780        RETURN_FALSE;
2781    }
2782
2783    ldap_controls_free(lserverctrls);
2784    if (myargcount == 4) {
2785        zval_dtor(estimated);
2786        ZVAL_LONG(estimated, lestimated);
2787    }
2788
2789    zval_ptr_dtor(cookie);
2790    if (lcookie.bv_len == 0) {
2791        ZVAL_EMPTY_STRING(cookie);
2792    } else {
2793        ZVAL_STRINGL(cookie, lcookie.bv_val, lcookie.bv_len);
2794    }
2795    ldap_memfree(lcookie.bv_val);
2796
2797    RETURN_TRUE;
2798}
2799/* }}} */
2800#endif
2801
2802/* {{{ arginfo */
2803ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_connect, 0, 0, 0)
2804    ZEND_ARG_INFO(0, hostname)
2805    ZEND_ARG_INFO(0, port)
2806#ifdef HAVE_ORALDAP
2807    ZEND_ARG_INFO(0, wallet)
2808    ZEND_ARG_INFO(0, wallet_passwd)
2809    ZEND_ARG_INFO(0, authmode)
2810#endif
2811ZEND_END_ARG_INFO()
2812
2813ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_resource, 0, 0, 1)
2814    ZEND_ARG_INFO(0, link_identifier)
2815ZEND_END_ARG_INFO()
2816
2817ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_bind, 0, 0, 1)
2818    ZEND_ARG_INFO(0, link_identifier)
2819    ZEND_ARG_INFO(0, bind_rdn)
2820    ZEND_ARG_INFO(0, bind_password)
2821ZEND_END_ARG_INFO()
2822
2823#ifdef HAVE_LDAP_SASL
2824ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_sasl_bind, 0, 0, 1)
2825    ZEND_ARG_INFO(0, link)
2826    ZEND_ARG_INFO(0, binddn)
2827    ZEND_ARG_INFO(0, password)
2828    ZEND_ARG_INFO(0, sasl_mech)
2829    ZEND_ARG_INFO(0, sasl_realm)
2830    ZEND_ARG_INFO(0, sasl_authz_id)
2831    ZEND_ARG_INFO(0, props)
2832ZEND_END_ARG_INFO()
2833#endif
2834
2835ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_read, 0, 0, 3)
2836    ZEND_ARG_INFO(0, link_identifier)
2837    ZEND_ARG_INFO(0, base_dn)
2838    ZEND_ARG_INFO(0, filter)
2839    ZEND_ARG_INFO(0, attributes)
2840    ZEND_ARG_INFO(0, attrsonly)
2841    ZEND_ARG_INFO(0, sizelimit)
2842    ZEND_ARG_INFO(0, timelimit)
2843    ZEND_ARG_INFO(0, deref)
2844ZEND_END_ARG_INFO()
2845
2846ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_list, 0, 0, 3)
2847    ZEND_ARG_INFO(0, link_identifier)
2848    ZEND_ARG_INFO(0, base_dn)
2849    ZEND_ARG_INFO(0, filter)
2850    ZEND_ARG_INFO(0, attributes)
2851    ZEND_ARG_INFO(0, attrsonly)
2852    ZEND_ARG_INFO(0, sizelimit)
2853    ZEND_ARG_INFO(0, timelimit)
2854    ZEND_ARG_INFO(0, deref)
2855ZEND_END_ARG_INFO()
2856
2857ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_search, 0, 0, 3)
2858    ZEND_ARG_INFO(0, link_identifier)
2859    ZEND_ARG_INFO(0, base_dn)
2860    ZEND_ARG_INFO(0, filter)
2861    ZEND_ARG_INFO(0, attributes)
2862    ZEND_ARG_INFO(0, attrsonly)
2863    ZEND_ARG_INFO(0, sizelimit)
2864    ZEND_ARG_INFO(0, timelimit)
2865    ZEND_ARG_INFO(0, deref)
2866ZEND_END_ARG_INFO()
2867
2868ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_count_entries, 0, 0, 2)
2869    ZEND_ARG_INFO(0, link_identifier)
2870    ZEND_ARG_INFO(0, result_identifier)
2871ZEND_END_ARG_INFO()
2872
2873ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_entry, 0, 0, 2)
2874    ZEND_ARG_INFO(0, link_identifier)
2875    ZEND_ARG_INFO(0, result_identifier)
2876ZEND_END_ARG_INFO()
2877
2878ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_entry, 0, 0, 2)
2879    ZEND_ARG_INFO(0, link_identifier)
2880    ZEND_ARG_INFO(0, result_identifier)
2881ZEND_END_ARG_INFO()
2882
2883ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_entries, 0, 0, 2)
2884    ZEND_ARG_INFO(0, link_identifier)
2885    ZEND_ARG_INFO(0, result_identifier)
2886ZEND_END_ARG_INFO()
2887
2888ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_attribute, 0, 0, 2)
2889    ZEND_ARG_INFO(0, link_identifier)
2890    ZEND_ARG_INFO(0, result_entry_identifier)
2891ZEND_END_ARG_INFO()
2892
2893ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_attribute, 0, 0, 2)
2894    ZEND_ARG_INFO(0, link_identifier)
2895    ZEND_ARG_INFO(0, result_entry_identifier)
2896ZEND_END_ARG_INFO()
2897
2898ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_attributes, 0, 0, 2)
2899    ZEND_ARG_INFO(0, link_identifier)
2900    ZEND_ARG_INFO(0, result_entry_identifier)
2901ZEND_END_ARG_INFO()
2902
2903ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_values, 0, 0, 3)
2904    ZEND_ARG_INFO(0, link_identifier)
2905    ZEND_ARG_INFO(0, result_entry_identifier)
2906    ZEND_ARG_INFO(0, attribute)
2907ZEND_END_ARG_INFO()
2908
2909ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_values_len, 0, 0, 3)
2910    ZEND_ARG_INFO(0, link_identifier)
2911    ZEND_ARG_INFO(0, result_entry_identifier)
2912    ZEND_ARG_INFO(0, attribute)
2913ZEND_END_ARG_INFO()
2914
2915ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_dn, 0, 0, 2)
2916    ZEND_ARG_INFO(0, link_identifier)
2917    ZEND_ARG_INFO(0, result_entry_identifier)
2918ZEND_END_ARG_INFO()
2919
2920ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_explode_dn, 0, 0, 2)
2921    ZEND_ARG_INFO(0, dn)
2922    ZEND_ARG_INFO(0, with_attrib)
2923ZEND_END_ARG_INFO()
2924
2925ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_dn2ufn, 0, 0, 1)
2926    ZEND_ARG_INFO(0, dn)
2927ZEND_END_ARG_INFO()
2928
2929ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_add, 0, 0, 3)
2930    ZEND_ARG_INFO(0, link_identifier)
2931    ZEND_ARG_INFO(0, dn)
2932    ZEND_ARG_INFO(0, entry)
2933ZEND_END_ARG_INFO()
2934
2935ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_delete, 0, 0, 2)
2936    ZEND_ARG_INFO(0, link_identifier)
2937    ZEND_ARG_INFO(0, dn)
2938ZEND_END_ARG_INFO()
2939
2940ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_modify, 0, 0, 3)
2941    ZEND_ARG_INFO(0, link_identifier)
2942    ZEND_ARG_INFO(0, dn)
2943    ZEND_ARG_INFO(0, entry)
2944ZEND_END_ARG_INFO()
2945
2946ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_modify_batch, 0, 0, 3)
2947    ZEND_ARG_INFO(0, link_identifier)
2948    ZEND_ARG_INFO(0, dn)
2949    ZEND_ARG_ARRAY_INFO(0, modifications_info, 0)
2950ZEND_END_ARG_INFO()
2951
2952ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_add, 0, 0, 3)
2953    ZEND_ARG_INFO(0, link_identifier)
2954    ZEND_ARG_INFO(0, dn)
2955    ZEND_ARG_INFO(0, entry)
2956ZEND_END_ARG_INFO()
2957
2958ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_replace, 0, 0, 3)
2959    ZEND_ARG_INFO(0, link_identifier)
2960    ZEND_ARG_INFO(0, dn)
2961    ZEND_ARG_INFO(0, entry)
2962ZEND_END_ARG_INFO()
2963
2964ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_del, 0, 0, 3)
2965    ZEND_ARG_INFO(0, link_identifier)
2966    ZEND_ARG_INFO(0, dn)
2967    ZEND_ARG_INFO(0, entry)
2968ZEND_END_ARG_INFO()
2969
2970ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_err2str, 0, 0, 1)
2971    ZEND_ARG_INFO(0, errno)
2972ZEND_END_ARG_INFO()
2973
2974ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_compare, 0, 0, 4)
2975    ZEND_ARG_INFO(0, link_identifier)
2976    ZEND_ARG_INFO(0, dn)
2977    ZEND_ARG_INFO(0, attribute)
2978    ZEND_ARG_INFO(0, value)
2979ZEND_END_ARG_INFO()
2980
2981ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_sort, 0, 0, 3)
2982    ZEND_ARG_INFO(0, link)
2983    ZEND_ARG_INFO(0, result)
2984    ZEND_ARG_INFO(0, sortfilter)
2985ZEND_END_ARG_INFO()
2986
2987#ifdef LDAP_CONTROL_PAGEDRESULTS
2988ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_control_paged_result, 0, 0, 2)
2989    ZEND_ARG_INFO(0, link)
2990    ZEND_ARG_INFO(0, pagesize)
2991    ZEND_ARG_INFO(0, iscritical)
2992    ZEND_ARG_INFO(0, cookie)
2993ZEND_END_ARG_INFO();
2994
2995ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_control_paged_result_response, 0, 0, 2)
2996    ZEND_ARG_INFO(0, link)
2997    ZEND_ARG_INFO(0, result)
2998    ZEND_ARG_INFO(1, cookie)
2999    ZEND_ARG_INFO(1, estimated)
3000ZEND_END_ARG_INFO();
3001#endif
3002
3003#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
3004ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_rename, 0, 0, 5)
3005    ZEND_ARG_INFO(0, link_identifier)
3006    ZEND_ARG_INFO(0, dn)
3007    ZEND_ARG_INFO(0, newrdn)
3008    ZEND_ARG_INFO(0, newparent)
3009    ZEND_ARG_INFO(0, deleteoldrdn)
3010ZEND_END_ARG_INFO()
3011
3012ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_option, 0, 0, 3)
3013    ZEND_ARG_INFO(0, link_identifier)
3014    ZEND_ARG_INFO(0, option)
3015    ZEND_ARG_INFO(1, retval)
3016ZEND_END_ARG_INFO()
3017
3018ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_set_option, 0, 0, 3)
3019    ZEND_ARG_INFO(0, link_identifier)
3020    ZEND_ARG_INFO(0, option)
3021    ZEND_ARG_INFO(0, newval)
3022ZEND_END_ARG_INFO()
3023
3024ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_reference, 0, 0, 2)
3025    ZEND_ARG_INFO(0, link)
3026    ZEND_ARG_INFO(0, result)
3027ZEND_END_ARG_INFO()
3028
3029ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_reference, 0, 0, 2)
3030    ZEND_ARG_INFO(0, link)
3031    ZEND_ARG_INFO(0, entry)
3032ZEND_END_ARG_INFO()
3033
3034#ifdef HAVE_LDAP_PARSE_REFERENCE
3035ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_parse_reference, 0, 0, 3)
3036    ZEND_ARG_INFO(0, link)
3037    ZEND_ARG_INFO(0, entry)
3038    ZEND_ARG_INFO(1, referrals)
3039ZEND_END_ARG_INFO()
3040#endif
3041
3042
3043#ifdef HAVE_LDAP_PARSE_RESULT
3044ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_parse_result, 0, 0, 3)
3045    ZEND_ARG_INFO(0, link)
3046    ZEND_ARG_INFO(0, result)
3047    ZEND_ARG_INFO(1, errcode)
3048    ZEND_ARG_INFO(1, matcheddn)
3049    ZEND_ARG_INFO(1, errmsg)
3050    ZEND_ARG_INFO(1, referrals)
3051ZEND_END_ARG_INFO()
3052#endif
3053#endif
3054
3055#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
3056ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_set_rebind_proc, 0, 0, 2)
3057    ZEND_ARG_INFO(0, link)
3058    ZEND_ARG_INFO(0, callback)
3059ZEND_END_ARG_INFO()
3060#endif
3061
3062ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_escape, 0, 0, 1)
3063    ZEND_ARG_INFO(0, value)
3064    ZEND_ARG_INFO(0, ignore)
3065    ZEND_ARG_INFO(0, flags)
3066ZEND_END_ARG_INFO()
3067
3068#ifdef STR_TRANSLATION
3069ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_t61_to_8859, 0, 0, 1)
3070    ZEND_ARG_INFO(0, value)
3071ZEND_END_ARG_INFO()
3072
3073ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_8859_to_t61, 0, 0, 1)
3074    ZEND_ARG_INFO(0, value)
3075ZEND_END_ARG_INFO()
3076#endif
3077/* }}} */
3078
3079/*
3080    This is just a small subset of the functionality provided by the LDAP library. All the
3081    operations are synchronous. Referrals are not handled automatically.
3082*/
3083/* {{{ ldap_functions[]
3084 */
3085const zend_function_entry ldap_functions[] = {
3086    PHP_FE(ldap_connect,                                arginfo_ldap_connect)
3087    PHP_FALIAS(ldap_close,      ldap_unbind,            arginfo_ldap_resource)
3088    PHP_FE(ldap_bind,                                   arginfo_ldap_bind)
3089#ifdef HAVE_LDAP_SASL
3090    PHP_FE(ldap_sasl_bind,                              arginfo_ldap_sasl_bind)
3091#endif
3092    PHP_FE(ldap_unbind,                                 arginfo_ldap_resource)
3093    PHP_FE(ldap_read,                                   arginfo_ldap_read)
3094    PHP_FE(ldap_list,                                   arginfo_ldap_list)
3095    PHP_FE(ldap_search,                                 arginfo_ldap_search)
3096    PHP_FE(ldap_free_result,                            arginfo_ldap_resource)
3097    PHP_FE(ldap_count_entries,                          arginfo_ldap_count_entries)
3098    PHP_FE(ldap_first_entry,                            arginfo_ldap_first_entry)
3099    PHP_FE(ldap_next_entry,                             arginfo_ldap_next_entry)
3100    PHP_FE(ldap_get_entries,                            arginfo_ldap_get_entries)
3101    PHP_FE(ldap_first_attribute,                        arginfo_ldap_first_attribute)
3102    PHP_FE(ldap_next_attribute,                         arginfo_ldap_next_attribute)
3103    PHP_FE(ldap_get_attributes,                         arginfo_ldap_get_attributes)
3104    PHP_FALIAS(ldap_get_values, ldap_get_values_len,    arginfo_ldap_get_values)
3105    PHP_FE(ldap_get_values_len,                         arginfo_ldap_get_values_len)
3106    PHP_FE(ldap_get_dn,                                 arginfo_ldap_get_dn)
3107    PHP_FE(ldap_explode_dn,                             arginfo_ldap_explode_dn)
3108    PHP_FE(ldap_dn2ufn,                                 arginfo_ldap_dn2ufn)
3109    PHP_FE(ldap_add,                                    arginfo_ldap_add)
3110    PHP_FE(ldap_delete,                                 arginfo_ldap_delete)
3111    PHP_FE(ldap_modify_batch,                           arginfo_ldap_modify_batch)
3112    PHP_FALIAS(ldap_modify,     ldap_mod_replace,       arginfo_ldap_modify)
3113
3114/* additional functions for attribute based modifications, Gerrit Thomson */
3115    PHP_FE(ldap_mod_add,                                arginfo_ldap_mod_add)
3116    PHP_FE(ldap_mod_replace,                            arginfo_ldap_mod_replace)
3117    PHP_FE(ldap_mod_del,                                arginfo_ldap_mod_del)
3118/* end gjt mod */
3119
3120    PHP_FE(ldap_errno,                                  arginfo_ldap_resource)
3121    PHP_FE(ldap_err2str,                                arginfo_ldap_err2str)
3122    PHP_FE(ldap_error,                                  arginfo_ldap_resource)
3123    PHP_FE(ldap_compare,                                arginfo_ldap_compare)
3124    PHP_FE(ldap_sort,                                   arginfo_ldap_sort)
3125
3126#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
3127    PHP_FE(ldap_rename,                                 arginfo_ldap_rename)
3128    PHP_FE(ldap_get_option,                             arginfo_ldap_get_option)
3129    PHP_FE(ldap_set_option,                             arginfo_ldap_set_option)
3130    PHP_FE(ldap_first_reference,                        arginfo_ldap_first_reference)
3131    PHP_FE(ldap_next_reference,                         arginfo_ldap_next_reference)
3132#ifdef HAVE_LDAP_PARSE_REFERENCE
3133    PHP_FE(ldap_parse_reference,                        arginfo_ldap_parse_reference)
3134#endif
3135#ifdef HAVE_LDAP_PARSE_RESULT
3136    PHP_FE(ldap_parse_result,                           arginfo_ldap_parse_result)
3137#endif
3138#ifdef HAVE_LDAP_START_TLS_S
3139    PHP_FE(ldap_start_tls,                              arginfo_ldap_resource)
3140#endif
3141#endif
3142
3143#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
3144    PHP_FE(ldap_set_rebind_proc,                        arginfo_ldap_set_rebind_proc)
3145#endif
3146
3147    PHP_FE(ldap_escape,                                 arginfo_ldap_escape)
3148
3149#ifdef STR_TRANSLATION
3150    PHP_FE(ldap_t61_to_8859,                            arginfo_ldap_t61_to_8859)
3151    PHP_FE(ldap_8859_to_t61,                            arginfo_ldap_8859_to_t61)
3152#endif
3153
3154#ifdef LDAP_CONTROL_PAGEDRESULTS
3155    PHP_FE(ldap_control_paged_result,                           arginfo_ldap_control_paged_result)
3156    PHP_FE(ldap_control_paged_result_response,      arginfo_ldap_control_paged_result_response)
3157#endif
3158    PHP_FE_END
3159};
3160/* }}} */
3161
3162zend_module_entry ldap_module_entry = { /* {{{ */
3163    STANDARD_MODULE_HEADER,
3164    "ldap",
3165    ldap_functions,
3166    PHP_MINIT(ldap),
3167    PHP_MSHUTDOWN(ldap),
3168    NULL,
3169    NULL,
3170    PHP_MINFO(ldap),
3171    NO_VERSION_YET,
3172    PHP_MODULE_GLOBALS(ldap),
3173    PHP_GINIT(ldap),
3174    NULL,
3175    NULL,
3176    STANDARD_MODULE_PROPERTIES_EX
3177};
3178/* }}} */
3179
3180/*
3181 * Local variables:
3182 * tab-width: 4
3183 * c-basic-offset: 4
3184 * End:
3185 * vim600: sw=4 ts=4 fdm=marker
3186 * vim<600: sw=4 ts=4
3187 */
3188