1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 5                                                        |
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: Christian Stocker <chregu@php.net>                          |
16   |          Rob Richards <rrichards@php.net>                            |
17   +----------------------------------------------------------------------+
18*/
19
20/* $Id$ */
21
22#ifdef HAVE_CONFIG_H
23#include "config.h"
24#endif
25
26#include "php.h"
27#if HAVE_LIBXML && HAVE_DOM
28#include "php_dom.h"
29
30#define PHP_DOM_XPATH_QUERY 0
31#define PHP_DOM_XPATH_EVALUATE 1
32
33/*
34* class DOMXPath
35*/
36
37#if defined(LIBXML_XPATH_ENABLED)
38
39/* {{{ arginfo */
40ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_xpath_construct, 0, 0, 1)
41    ZEND_ARG_OBJ_INFO(0, doc, DOMDocument, 0)
42ZEND_END_ARG_INFO();
43
44ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_xpath_register_ns, 0, 0, 2)
45    ZEND_ARG_INFO(0, prefix)
46    ZEND_ARG_INFO(0, uri)
47ZEND_END_ARG_INFO();
48
49ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_xpath_query, 0, 0, 1)
50    ZEND_ARG_INFO(0, expr)
51    ZEND_ARG_OBJ_INFO(0, context, DOMNode, 1)
52    ZEND_ARG_INFO(0, registerNodeNS)
53ZEND_END_ARG_INFO();
54
55ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_xpath_evaluate, 0, 0, 1)
56    ZEND_ARG_INFO(0, expr)
57    ZEND_ARG_OBJ_INFO(0, context, DOMNode, 1)
58    ZEND_ARG_INFO(0, registerNodeNS)
59ZEND_END_ARG_INFO();
60
61ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_xpath_register_php_functions, 0, 0, 0)
62ZEND_END_ARG_INFO();
63/* }}} */
64
65const zend_function_entry php_dom_xpath_class_functions[] = {
66    PHP_ME(domxpath, __construct, arginfo_dom_xpath_construct, ZEND_ACC_PUBLIC)
67    PHP_FALIAS(registerNamespace, dom_xpath_register_ns, arginfo_dom_xpath_register_ns)
68    PHP_FALIAS(query, dom_xpath_query, arginfo_dom_xpath_query)
69    PHP_FALIAS(evaluate, dom_xpath_evaluate, arginfo_dom_xpath_evaluate)
70    PHP_FALIAS(registerPhpFunctions, dom_xpath_register_php_functions, arginfo_dom_xpath_register_php_functions)
71    PHP_FE_END
72};
73
74
75static void dom_xpath_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */
76{
77    zval retval;
78    int result, i;
79    int error = 0;
80    zend_fcall_info fci;
81    xmlXPathObjectPtr obj;
82    char *str;
83    zend_string *callable = NULL;
84    dom_xpath_object *intern;
85
86    TSRMLS_FETCH();
87
88    if (! zend_is_executing(TSRMLS_C)) {
89        xmlGenericError(xmlGenericErrorContext,
90        "xmlExtFunctionTest: Function called from outside of PHP\n");
91        error = 1;
92    } else {
93        intern = (dom_xpath_object *) ctxt->context->userData;
94        if (intern == NULL) {
95            xmlGenericError(xmlGenericErrorContext,
96            "xmlExtFunctionTest: failed to get the internal object\n");
97            error = 1;
98        }
99        else if (intern->registerPhpFunctions == 0) {
100            xmlGenericError(xmlGenericErrorContext,
101            "xmlExtFunctionTest: PHP Object did not register PHP functions\n");
102            error = 1;
103        }
104    }
105
106    if (error == 1) {
107        for (i = nargs - 1; i >= 0; i--) {
108            obj = valuePop(ctxt);
109            xmlXPathFreeObject(obj);
110        }
111        return;
112    }
113
114    fci.param_count = nargs - 1;
115    if (fci.param_count > 0) {
116        fci.params = safe_emalloc(fci.param_count, sizeof(zval), 0);
117    }
118    /* Reverse order to pop values off ctxt stack */
119    for (i = nargs - 2; i >= 0; i--) {
120        obj = valuePop(ctxt);
121        switch (obj->type) {
122            case XPATH_STRING:
123                ZVAL_STRING(&fci.params[i],  (char *)obj->stringval);
124                break;
125            case XPATH_BOOLEAN:
126                ZVAL_BOOL(&fci.params[i],  obj->boolval);
127                break;
128            case XPATH_NUMBER:
129                ZVAL_DOUBLE(&fci.params[i], obj->floatval);
130                break;
131            case XPATH_NODESET:
132                if (type == 1) {
133                    str = (char *)xmlXPathCastToString(obj);
134                    ZVAL_STRING(&fci.params[i], str);
135                    xmlFree(str);
136                } else if (type == 2) {
137                    int j;
138                    array_init(&fci.params[i]);
139                    if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
140                        for (j = 0; j < obj->nodesetval->nodeNr; j++) {
141                            xmlNodePtr node = obj->nodesetval->nodeTab[j];
142                            zval child;
143                            /* not sure, if we need this... it's copied from xpath.c */
144                            if (node->type == XML_NAMESPACE_DECL) {
145                                xmlNsPtr curns;
146                                xmlNodePtr nsparent;
147
148                                nsparent = node->_private;
149                                curns = xmlNewNs(NULL, node->name, NULL);
150                                if (node->children) {
151                                    curns->prefix = xmlStrdup((xmlChar *) node->children);
152                                }
153                                if (node->children) {
154                                    node = xmlNewDocNode(node->doc, NULL, (xmlChar *) node->children, node->name);
155                                } else {
156                                    node = xmlNewDocNode(node->doc, NULL, (xmlChar *) "xmlns", node->name);
157                                }
158                                node->type = XML_NAMESPACE_DECL;
159                                node->parent = nsparent;
160                                node->ns = curns;
161                            }
162                            php_dom_create_object(node, &child, &intern->dom TSRMLS_CC);
163                            add_next_index_zval(&fci.params[i], &child);
164                        }
165                    }
166                }
167                break;
168            default:
169            ZVAL_STRING(&fci.params[i], (char *)xmlXPathCastToString(obj));
170        }
171        xmlXPathFreeObject(obj);
172    }
173
174    fci.size = sizeof(fci);
175    fci.function_table = EG(function_table);
176
177    obj = valuePop(ctxt);
178    if (obj->stringval == NULL) {
179        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Handler name must be a string");
180        xmlXPathFreeObject(obj);
181        if (fci.param_count > 0) {
182            for (i = 0; i < nargs - 1; i++) {
183                zval_ptr_dtor(&fci.params[i]);
184            }
185            efree(fci.params);
186        }
187        return;
188    }
189    ZVAL_STRING(&fci.function_name, obj->stringval);
190    xmlXPathFreeObject(obj);
191
192    fci.symbol_table = NULL;
193    fci.object = NULL;
194    fci.retval = &retval;
195    fci.no_separation = 0;
196
197    if (!zend_make_callable(&fci.function_name, &callable TSRMLS_CC)) {
198        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", callable->val);
199    } else if (intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable) == 0) {
200        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not allowed to call handler '%s()'.", callable->val);
201        /* Push an empty string, so that we at least have an xslt result... */
202        valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
203    } else {
204        result = zend_call_function(&fci, NULL TSRMLS_CC);
205        if (result == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
206            if (Z_TYPE(retval) == IS_OBJECT && instanceof_function(Z_OBJCE(retval), dom_node_class_entry TSRMLS_CC)) {
207                xmlNode *nodep;
208                dom_object *obj;
209                if (intern->node_list == NULL) {
210                    ALLOC_HASHTABLE(intern->node_list);
211                    zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0);
212                }
213                GC_REFCOUNT(&retval)++;
214                zend_hash_next_index_insert(intern->node_list, &retval);
215                obj = Z_DOMOBJ_P(&retval);
216                nodep = dom_object_get_node(obj);
217                valuePush(ctxt, xmlXPathNewNodeSet(nodep));
218            } else if (Z_TYPE(retval) == IS_FALSE || Z_TYPE(retval) == IS_TRUE) {
219                valuePush(ctxt, xmlXPathNewBoolean(Z_TYPE(retval) == IS_TRUE));
220            } else if (Z_TYPE(retval) == IS_OBJECT) {
221                php_error_docref(NULL TSRMLS_CC, E_WARNING, "A PHP Object cannot be converted to a XPath-string");
222                valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
223            } else {
224                zend_string *str = zval_get_string(&retval);
225                valuePush(ctxt, xmlXPathNewString(str->val));
226                zend_string_release(str);
227            }
228            zval_ptr_dtor(&retval);
229        }
230    }
231    zend_string_release(callable);
232    zval_dtor(&fci.function_name);
233    if (fci.param_count > 0) {
234        for (i = 0; i < nargs - 1; i++) {
235            zval_ptr_dtor(&fci.params[i]);
236        }
237        efree(fci.params);
238    }
239}
240/* }}} */
241
242static void dom_xpath_ext_function_string_php(xmlXPathParserContextPtr ctxt, int nargs) /* {{{ */
243{
244    dom_xpath_ext_function_php(ctxt, nargs, 1);
245}
246/* }}} */
247
248static void dom_xpath_ext_function_object_php(xmlXPathParserContextPtr ctxt, int nargs) /* {{{ */
249{
250    dom_xpath_ext_function_php(ctxt, nargs, 2);
251}
252/* }}} */
253
254/* {{{ proto void DOMXPath::__construct(DOMDocument doc) U */
255PHP_METHOD(domxpath, __construct)
256{
257    zval *id, *doc;
258    xmlDocPtr docp = NULL;
259    dom_object *docobj;
260    dom_xpath_object *intern;
261    xmlXPathContextPtr ctx, oldctx;
262    zend_error_handling error_handling;
263
264    zend_replace_error_handling(EH_THROW, dom_domexception_class_entry, &error_handling TSRMLS_CC);
265    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &id, dom_xpath_class_entry, &doc, dom_document_class_entry) == FAILURE) {
266        zend_restore_error_handling(&error_handling TSRMLS_CC);
267        return;
268    }
269
270    zend_restore_error_handling(&error_handling TSRMLS_CC);
271    DOM_GET_OBJ(docp, doc, xmlDocPtr, docobj);
272
273    ctx = xmlXPathNewContext(docp);
274    if (ctx == NULL) {
275        php_dom_throw_error(INVALID_STATE_ERR, 1 TSRMLS_CC);
276        RETURN_FALSE;
277    }
278
279    intern = Z_XPATHOBJ_P(id);
280    if (intern != NULL) {
281        oldctx = (xmlXPathContextPtr)intern->dom.ptr;
282        if (oldctx != NULL) {
283            php_libxml_decrement_doc_ref((php_libxml_node_object *) &intern->dom TSRMLS_CC);
284            xmlXPathFreeContext(oldctx);
285        }
286
287        xmlXPathRegisterFuncNS (ctx, (const xmlChar *) "functionString",
288                       (const xmlChar *) "http://php.net/xpath",
289                       dom_xpath_ext_function_string_php);
290        xmlXPathRegisterFuncNS (ctx, (const xmlChar *) "function",
291                       (const xmlChar *) "http://php.net/xpath",
292                       dom_xpath_ext_function_object_php);
293
294        intern->dom.ptr = ctx;
295        ctx->userData = (void *)intern;
296        intern->dom.document = docobj->document;
297        php_libxml_increment_doc_ref((php_libxml_node_object *) &intern->dom, docp TSRMLS_CC);
298    }
299}
300/* }}} end DOMXPath::__construct */
301
302/* {{{ document DOMDocument*/
303int dom_xpath_document_read(dom_object *obj, zval *retval TSRMLS_DC)
304{
305    xmlDoc *docp = NULL;
306    xmlXPathContextPtr ctx = (xmlXPathContextPtr) obj->ptr;
307
308    if (ctx) {
309        docp = (xmlDocPtr) ctx->doc;
310    }
311
312    php_dom_create_object((xmlNodePtr) docp, retval, obj TSRMLS_CC);
313    return SUCCESS;
314}
315/* }}} */
316
317/* {{{ proto boolean dom_xpath_register_ns(string prefix, string uri); */
318PHP_FUNCTION(dom_xpath_register_ns)
319{
320    zval *id;
321    xmlXPathContextPtr ctxp;
322    size_t prefix_len, ns_uri_len;
323    dom_xpath_object *intern;
324    unsigned char *prefix, *ns_uri;
325
326    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &id, dom_xpath_class_entry, &prefix, &prefix_len, &ns_uri, &ns_uri_len) == FAILURE) {
327        return;
328    }
329
330    intern = Z_XPATHOBJ_P(id);
331
332    ctxp = (xmlXPathContextPtr) intern->dom.ptr;
333    if (ctxp == NULL) {
334        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid XPath Context");
335        RETURN_FALSE;
336    }
337
338    if (xmlXPathRegisterNs(ctxp, prefix, ns_uri) != 0) {
339        RETURN_FALSE
340    }
341    RETURN_TRUE;
342}
343/* }}} */
344
345static void dom_xpath_iter(zval *baseobj, dom_object *intern) /* {{{ */
346{
347    dom_nnodemap_object *mapptr = (dom_nnodemap_object *) intern->ptr;
348
349    ZVAL_COPY_VALUE(&mapptr->baseobj_zv, baseobj);
350    mapptr->nodetype = DOM_NODESET;
351}
352/* }}} */
353
354static void php_xpath_eval(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
355{
356    zval *id, retval, *context = NULL;
357    xmlXPathContextPtr ctxp;
358    xmlNodePtr nodep = NULL;
359    xmlXPathObjectPtr xpathobjp;
360    size_t expr_len, nsnbr = 0, xpath_type;
361    dom_xpath_object *intern;
362    dom_object *nodeobj;
363    char *expr;
364    xmlDoc *docp = NULL;
365    xmlNsPtr *ns = NULL;
366    zend_bool register_node_ns = 1;
367
368    if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|O!b", &id, dom_xpath_class_entry, &expr, &expr_len, &context, dom_node_class_entry, &register_node_ns) == FAILURE) {
369        return;
370    }
371
372    intern = Z_XPATHOBJ_P(id);
373
374    ctxp = (xmlXPathContextPtr) intern->dom.ptr;
375    if (ctxp == NULL) {
376        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid XPath Context");
377        RETURN_FALSE;
378    }
379
380    docp = (xmlDocPtr) ctxp->doc;
381    if (docp == NULL) {
382        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid XPath Document Pointer");
383        RETURN_FALSE;
384    }
385
386    if (context != NULL) {
387        DOM_GET_OBJ(nodep, context, xmlNodePtr, nodeobj);
388    }
389
390    if (!nodep) {
391        nodep = xmlDocGetRootElement(docp);
392    }
393
394    if (nodep && docp != nodep->doc) {
395        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Node From Wrong Document");
396        RETURN_FALSE;
397    }
398
399    ctxp->node = nodep;
400
401    if (register_node_ns) {
402        /* Register namespaces in the node */
403        ns = xmlGetNsList(docp, nodep);
404
405        if (ns != NULL) {
406            while (ns[nsnbr] != NULL)
407            nsnbr++;
408        }
409    }
410
411
412    ctxp->namespaces = ns;
413    ctxp->nsNr = nsnbr;
414
415    xpathobjp = xmlXPathEvalExpression(expr, ctxp);
416    ctxp->node = NULL;
417
418    if (ns != NULL) {
419        xmlFree(ns);
420        ctxp->namespaces = NULL;
421        ctxp->nsNr = 0;
422    }
423
424    if (! xpathobjp) {
425        RETURN_FALSE;
426    }
427
428    if (type == PHP_DOM_XPATH_QUERY) {
429        xpath_type = XPATH_NODESET;
430    } else {
431        xpath_type = xpathobjp->type;
432    }
433
434    switch (xpath_type) {
435
436        case  XPATH_NODESET:
437        {
438            int i;
439            xmlNodeSetPtr nodesetp;
440
441            array_init(&retval);
442
443            if (xpathobjp->type == XPATH_NODESET && NULL != (nodesetp = xpathobjp->nodesetval)) {
444
445                for (i = 0; i < nodesetp->nodeNr; i++) {
446                    xmlNodePtr node = nodesetp->nodeTab[i];
447                    zval child;
448
449                    if (node->type == XML_NAMESPACE_DECL) {
450                        xmlNsPtr curns;
451                        xmlNodePtr nsparent;
452
453                        nsparent = node->_private;
454                        curns = xmlNewNs(NULL, node->name, NULL);
455                        if (node->children) {
456                            curns->prefix = xmlStrdup((char *) node->children);
457                        }
458                        if (node->children) {
459                            node = xmlNewDocNode(docp, NULL, (char *) node->children, node->name);
460                        } else {
461                            node = xmlNewDocNode(docp, NULL, "xmlns", node->name);
462                        }
463                        node->type = XML_NAMESPACE_DECL;
464                        node->parent = nsparent;
465                        node->ns = curns;
466                    }
467                    php_dom_create_object(node, &child, &intern->dom TSRMLS_CC);
468                    add_next_index_zval(&retval, &child);
469                }
470            }
471            php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC);
472            nodeobj = Z_DOMOBJ_P(return_value);
473            dom_xpath_iter(&retval, nodeobj);
474            break;
475        }
476
477        case XPATH_BOOLEAN:
478            RETVAL_BOOL(xpathobjp->boolval);
479            break;
480
481        case XPATH_NUMBER:
482            RETVAL_DOUBLE(xpathobjp->floatval)
483            break;
484
485        case XPATH_STRING:
486            RETVAL_STRING(xpathobjp->stringval);
487            break;
488
489        default:
490            RETVAL_NULL();
491            break;
492    }
493
494    xmlXPathFreeObject(xpathobjp);
495}
496/* }}} */
497
498/* {{{ proto DOMNodeList dom_xpath_query(string expr [,DOMNode context [, boolean registerNodeNS]]); */
499PHP_FUNCTION(dom_xpath_query)
500{
501    php_xpath_eval(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_DOM_XPATH_QUERY);
502}
503/* }}} end dom_xpath_query */
504
505/* {{{ proto mixed dom_xpath_evaluate(string expr [,DOMNode context [, boolean registerNodeNS]]); */
506PHP_FUNCTION(dom_xpath_evaluate)
507{
508    php_xpath_eval(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_DOM_XPATH_EVALUATE);
509}
510/* }}} end dom_xpath_evaluate */
511
512/* {{{ proto void dom_xpath_register_php_functions() */
513PHP_FUNCTION(dom_xpath_register_php_functions)
514{
515    zval *id;
516    dom_xpath_object *intern;
517    zval *array_value, *entry, new_string;
518    zend_string *name;
519
520    DOM_GET_THIS(id);
521
522    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "a",  &array_value) == SUCCESS) {
523        intern = Z_XPATHOBJ_P(id);
524        zend_hash_internal_pointer_reset(Z_ARRVAL_P(array_value));
525        while ((entry = zend_hash_get_current_data(Z_ARRVAL_P(array_value)))) {
526            zend_string *str = zval_get_string(entry);
527            ZVAL_LONG(&new_string,1);
528            zend_hash_update(intern->registered_phpfunctions, str, &new_string);
529            zend_hash_move_forward(Z_ARRVAL_P(array_value));
530            zend_string_release(str);
531        }
532        intern->registerPhpFunctions = 2;
533        RETURN_TRUE;
534
535    } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "S",  &name) == SUCCESS) {
536        intern = Z_XPATHOBJ_P(id);
537
538        ZVAL_LONG(&new_string, 1);
539        zend_hash_update(intern->registered_phpfunctions, name, &new_string);
540        intern->registerPhpFunctions = 2;
541    } else {
542        intern = Z_XPATHOBJ_P(id);
543        intern->registerPhpFunctions = 1;
544    }
545
546}
547/* }}} end dom_xpath_register_php_functions */
548
549#endif /* LIBXML_XPATH_ENABLED */
550
551#endif
552
553/*
554 * Local variables:
555 * tab-width: 4
556 * c-basic-offset: 4
557 * End:
558 * vim600: noet sw=4 ts=4 fdm=marker
559 * vim<600: noet sw=4 ts=4
560 */
561