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