Exemplo n.º 1
0
/*
 * call-seq:
 *    XML.default_tree_indent_string = "string"
 *
 * Set the default string used by parsers to indent the XML tree
 * for output.
 */
static VALUE rxml_default_tree_indent_string_set(VALUE klass, VALUE string)
{
  Check_Type(string, T_STRING);
  xmlTreeIndentString = (const char *)xmlStrdup((xmlChar *)StringValuePtr(string));
  return (string);
}
Exemplo n.º 2
0
static xmlChar
*
pgxmlNodeSetToText(xmlNodeSetPtr nodeset,
				   xmlChar * toptagname,
				   xmlChar * septagname,
				   xmlChar * plainsep)
{
	/* Function translates a nodeset into a text representation */

	/*
	 * iterates over each node in the set and calls xmlNodeDump to write it to
	 * an xmlBuffer -from which an xmlChar * string is returned.
	 */

	/* each representation is surrounded by <tagname> ... </tagname> */

	/*
	 * plainsep is an ordinary (not tag) seperator - if used, then nodes are
	 * cast to string as output method
	 */


	xmlBufferPtr buf;
	xmlChar    *result;
	int			i;

	buf = xmlBufferCreate();

	if ((toptagname != NULL) && (xmlStrlen(toptagname) > 0))
	{
		xmlBufferWriteChar(buf, "<");
		xmlBufferWriteCHAR(buf, toptagname);
		xmlBufferWriteChar(buf, ">");
	}
	if (nodeset != NULL)
	{
		for (i = 0; i < nodeset->nodeNr; i++)
		{

			if (plainsep != NULL)
			{
				xmlBufferWriteCHAR(buf,
							  xmlXPathCastNodeToString(nodeset->nodeTab[i]));

				/* If this isn't the last entry, write the plain sep. */
				if (i < (nodeset->nodeNr) - 1)
					xmlBufferWriteChar(buf, plainsep);
			}
			else
			{


				if ((septagname != NULL) && (xmlStrlen(septagname) > 0))
				{
					xmlBufferWriteChar(buf, "<");
					xmlBufferWriteCHAR(buf, septagname);
					xmlBufferWriteChar(buf, ">");
				}
				xmlNodeDump(buf,
							nodeset->nodeTab[i]->doc,
							nodeset->nodeTab[i],
							1, 0);

				if ((septagname != NULL) && (xmlStrlen(septagname) > 0))
				{
					xmlBufferWriteChar(buf, "</");
					xmlBufferWriteCHAR(buf, septagname);
					xmlBufferWriteChar(buf, ">");
				}
			}
		}
	}

	if ((toptagname != NULL) && (xmlStrlen(toptagname) > 0))
	{
		xmlBufferWriteChar(buf, "</");
		xmlBufferWriteCHAR(buf, toptagname);
		xmlBufferWriteChar(buf, ">");
	}
	result = xmlStrdup(buf->content);
	xmlBufferFree(buf);
	return result;
}
Exemplo n.º 3
0
/* This snippet is borrowed from the xsltproc source
 * and adapted to help the xsl transform find our temporary
 * files in $HOME/.gnc-migration-tmp/
 */
static xmlParserInputPtr
xsltprocExternalEntityLoader(const char *URL, const char *ID,
                             xmlParserCtxtPtr ctxt)
{
    xmlParserInputPtr ret;
    warningSAXFunc warning = NULL;
    xmlChar *newURL;
    gchar *tmpdir = g_build_filename (g_get_home_dir (), ".gnc-migration-tmp", NULL);

    const char *lastsegment = URL;
    const char *iter = URL;

    while (*iter != 0)
    {
        if (*iter == '/')
            lastsegment = iter + 1;
        iter++;
    }

    if ((ctxt != NULL) && (ctxt->sax != NULL))
    {
        warning = ctxt->sax->warning;
        ctxt->sax->warning = NULL;
    }

    if (defaultEntityLoader != NULL)
    {
        ret = defaultEntityLoader(URL, ID, ctxt);
        if (ret != NULL)
        {
            if (warning != NULL)
                ctxt->sax->warning = warning;
            return(ret);
        }
    }

    newURL = xmlStrdup((const xmlChar *) tmpdir);
    newURL = xmlStrcat(newURL, (const xmlChar *) "/");
    newURL = xmlStrcat(newURL, (const xmlChar *) lastsegment);
    g_free (tmpdir);
    if (newURL != NULL)
    {
        ret = defaultEntityLoader((const char *)newURL, ID, ctxt);
        if (ret != NULL)
        {
            if (warning != NULL)
                ctxt->sax->warning = warning;
            xmlFree(newURL);
            return(ret);
        }
        xmlFree(newURL);
    }
    if (warning != NULL)
    {
        ctxt->sax->warning = warning;
        if (URL != NULL)
            DEBUG ("External entity \"%s\" not loaded", URL);
        else if (ID != NULL)
            DEBUG ("External entity \"%s\" not loaded", ID);
    }
    return(NULL);
}
Exemplo n.º 4
0
static void dom_xpath_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */
{
	zval retval;
	int result, i;
	int error = 0;
	zend_fcall_info fci;
	xmlXPathObjectPtr obj;
	char *str;
	zend_string *callable = NULL;
	dom_xpath_object *intern;


	if (! zend_is_executing()) {
		xmlGenericError(xmlGenericErrorContext,
		"xmlExtFunctionTest: Function called from outside of PHP\n");
		error = 1;
	} else {
		intern = (dom_xpath_object *) ctxt->context->userData;
		if (intern == NULL) {
			xmlGenericError(xmlGenericErrorContext,
			"xmlExtFunctionTest: failed to get the internal object\n");
			error = 1;
		}
		else if (intern->registerPhpFunctions == 0) {
			xmlGenericError(xmlGenericErrorContext,
			"xmlExtFunctionTest: PHP Object did not register PHP functions\n");
			error = 1;
		}
	}

	if (error == 1) {
		for (i = nargs - 1; i >= 0; i--) {
			obj = valuePop(ctxt);
			xmlXPathFreeObject(obj);
		}
		return;
	}

	fci.param_count = nargs - 1;
	if (fci.param_count > 0) {
		fci.params = safe_emalloc(fci.param_count, sizeof(zval), 0);
	}
	/* Reverse order to pop values off ctxt stack */
	for (i = nargs - 2; i >= 0; i--) {
		obj = valuePop(ctxt);
		switch (obj->type) {
			case XPATH_STRING:
				ZVAL_STRING(&fci.params[i],  (char *)obj->stringval);
				break;
			case XPATH_BOOLEAN:
				ZVAL_BOOL(&fci.params[i],  obj->boolval);
				break;
			case XPATH_NUMBER:
				ZVAL_DOUBLE(&fci.params[i], obj->floatval);
				break;
			case XPATH_NODESET:
				if (type == 1) {
					str = (char *)xmlXPathCastToString(obj);
					ZVAL_STRING(&fci.params[i], str);
					xmlFree(str);
				} else if (type == 2) {
					int j;
					array_init(&fci.params[i]);
					if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
						for (j = 0; j < obj->nodesetval->nodeNr; j++) {
							xmlNodePtr node = obj->nodesetval->nodeTab[j];
							zval child;
							/* not sure, if we need this... it's copied from xpath.c */
							if (node->type == XML_NAMESPACE_DECL) {
								xmlNsPtr curns;
								xmlNodePtr nsparent;

								nsparent = node->_private;
								curns = xmlNewNs(NULL, node->name, NULL);
								if (node->children) {
									curns->prefix = xmlStrdup((xmlChar *) node->children);
								}
								if (node->children) {
									node = xmlNewDocNode(node->doc, NULL, (xmlChar *) node->children, node->name);
								} else {
									node = xmlNewDocNode(node->doc, NULL, (xmlChar *) "xmlns", node->name);
								}
								node->type = XML_NAMESPACE_DECL;
								node->parent = nsparent;
								node->ns = curns;
							}
							php_dom_create_object(node, &child, &intern->dom);
							add_next_index_zval(&fci.params[i], &child);
						}
					}
				}
				break;
			default:
			ZVAL_STRING(&fci.params[i], (char *)xmlXPathCastToString(obj));
		}
		xmlXPathFreeObject(obj);
	}

	fci.size = sizeof(fci);

	obj = valuePop(ctxt);
	if (obj->stringval == NULL) {
		php_error_docref(NULL, E_WARNING, "Handler name must be a string");
		xmlXPathFreeObject(obj);
		if (fci.param_count > 0) {
			for (i = 0; i < nargs - 1; i++) {
				zval_ptr_dtor(&fci.params[i]);
			}
			efree(fci.params);
		}
		return;
	}
	ZVAL_STRING(&fci.function_name, (char *) obj->stringval);
	xmlXPathFreeObject(obj);

	fci.object = NULL;
	fci.retval = &retval;
	fci.no_separation = 0;

	if (!zend_make_callable(&fci.function_name, &callable)) {
		php_error_docref(NULL, E_WARNING, "Unable to call handler %s()", ZSTR_VAL(callable));
	} else if (intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable) == 0) {
		php_error_docref(NULL, E_WARNING, "Not allowed to call handler '%s()'.", ZSTR_VAL(callable));
		/* Push an empty string, so that we at least have an xslt result... */
		valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
	} else {
		result = zend_call_function(&fci, NULL);
		if (result == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
			if (Z_TYPE(retval) == IS_OBJECT && instanceof_function(Z_OBJCE(retval), dom_node_class_entry)) {
				xmlNode *nodep;
				dom_object *obj;
				if (intern->node_list == NULL) {
					ALLOC_HASHTABLE(intern->node_list);
					zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0);
				}
				Z_ADDREF(retval);
				zend_hash_next_index_insert(intern->node_list, &retval);
				obj = Z_DOMOBJ_P(&retval);
				nodep = dom_object_get_node(obj);
				valuePush(ctxt, xmlXPathNewNodeSet(nodep));
			} else if (Z_TYPE(retval) == IS_FALSE || Z_TYPE(retval) == IS_TRUE) {
				valuePush(ctxt, xmlXPathNewBoolean(Z_TYPE(retval) == IS_TRUE));
			} else if (Z_TYPE(retval) == IS_OBJECT) {
				php_error_docref(NULL, E_WARNING, "A PHP Object cannot be converted to a XPath-string");
				valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
			} else {
				zend_string *str = zval_get_string(&retval);
				valuePush(ctxt, xmlXPathNewString((xmlChar *) ZSTR_VAL(str)));
				zend_string_release(str);
			}
			zval_ptr_dtor(&retval);
		}
	}
	zend_string_release(callable);
	zval_dtor(&fci.function_name);
	if (fci.param_count > 0) {
		for (i = 0; i < nargs - 1; i++) {
			zval_ptr_dtor(&fci.params[i]);
		}
		efree(fci.params);
	}
}
Exemplo n.º 5
0
/**
 * xmlEncodeEntitiesReentrant:
 * @doc:  the document containing the string
 * @input:  A string to convert to XML.
 *
 * Do a global encoding of a string, replacing the predefined entities
 * and non ASCII values with their entities and CharRef counterparts.
 * Contrary to xmlEncodeEntities, this routine is reentrant, and result
 * must be deallocated.
 *
 * Returns A newly allocated string with the substitution done.
 *
 * OOM: possible --> returns NULL (for input!=NULL), sets OOM flag
 */
xmlChar*
xmlEncodeEntitiesReentrant(xmlDocPtr doc, const xmlChar *input) {
    const xmlChar* cur = input;
    xmlChar* buffer = NULL;
    xmlChar* out = NULL;
    int buffer_size;
    int html;

    if (input == NULL)
        return(NULL);

    html = doc && (doc->type == XML_HTML_DOCUMENT_NODE);
    /*
     * allocate an translation buffer.
     */
    // TODO: "Magic number" for buffer size - make a controlled parameter
    // TODO: OPTIMIZE: Select most appropriate buffer size by default / reuse some preallocated buffer
    buffer_size = 1000;
    buffer = (xmlChar *) xmlMalloc(buffer_size * sizeof(xmlChar));
    if (buffer == NULL) {
        SET_OOM_FLAG;
        xmlGenericError(xmlGenericErrorContext, EMBED_ERRTXT("malloc failed\n"));
        return(NULL);
    }
    out = buffer;

    while (*cur != '\0') {
        // TODO: Another "magic" number -- select optimal for current buffer_size
        if (out - buffer > buffer_size - 100) {
            xmlChar* newbuf;
            int indx = out - buffer;

            newbuf = (xmlChar*)xmlGrowBufferReentrant(&buffer_size, buffer); // on OOM returns NULL (buffer is not freed)
            if(!buffer)
                {
                xmlFree(buffer);
                return NULL;
                }
            buffer = newbuf;
            out = &buffer[indx];
        }

    /*
     * By default one have to encode at least '<', '>', '"' and '&' !
     */
    // TODO: OPTIMIZE: Rearrange IFs according expectations of conditions
    //                 Obviously, the default case is the most expected
    if (*cur == '<') {
        *out++ = '&';
        *out++ = 'l';
        *out++ = 't';
        *out++ = ';';
    } else if (*cur == '>') {
        *out++ = '&';
        *out++ = 'g';
        *out++ = 't';
        *out++ = ';';
    } else if (*cur == '&') {
        *out++ = '&';
        *out++ = 'a';
        *out++ = 'm';
        *out++ = 'p';
        *out++ = ';';
    } else if (((*cur >= 0x20) && (*cur < 0x80)) ||
        (*cur == '\n') || (*cur == '\t') || ((html) && (*cur == '\r'))) {
        /*
         * default case, just copy !
         */
        *out++ = *cur;
    } else if (*cur >= 0x80) {
        if (((doc != NULL) && (doc->encoding != NULL)) || (html)) {
        /*
         * Bj?rn Reese <*****@*****.**> provided the patch
            xmlChar xc;
            xc = (*cur & 0x3F) << 6;
            if (cur[1] != 0) {
            xc += *(++cur) & 0x3F;
            *out++ = xc;
            } else
         */
            *out++ = *cur;
        } else {
        /*
         * We assume we have UTF-8 input.
         */
        char buf[11], *ptr;
        // TODO: rename 'l' variable -- hard to understand and error-prone otherwise (looks like '1')
        int val = 0, l = 1;

        if (*cur < 0xC0) {
            xmlGenericError(xmlGenericErrorContext, EMBED_ERRTXT("xmlEncodeEntitiesReentrant : input not UTF-8\n"));
            if (doc != NULL){
                doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1");
                if(OOM_FLAG)
                    goto OOM;
            }
            // TODO: Detect OOM..
            // TODO: these several lines repeat four times in WHILE loop -- try to combine and use GOTO
            snprintf(buf, sizeof(buf), "&#%d;", *cur);
            buf[sizeof(buf) - 1] = 0;
            ptr = buf;
            while (*ptr != 0)
            {
                *out++ = *ptr++;
            }
            cur++;
            continue;
            // ENDTODO:
        } else if (*cur < 0xE0) {
                val = (cur[0]) & 0x1F;
                val <<= 6;
                val |= (cur[1]) & 0x3F;
                l = 2;
        } else if (*cur < 0xF0) {
                val = (cur[0]) & 0x0F;
                val <<= 6;
                val |= (cur[1]) & 0x3F;
                val <<= 6;
                val |= (cur[2]) & 0x3F;
                l = 3;
        } else if (*cur < 0xF8) {
                val = (cur[0]) & 0x07;
                val <<= 6;
                val |= (cur[1]) & 0x3F;
                val <<= 6;
                val |= (cur[2]) & 0x3F;
                val <<= 6;
                val |= (cur[3]) & 0x3F;
                l = 4;
        }
        if ((l == 1) || (!IS_CHAR(val))) {
            xmlGenericError(xmlGenericErrorContext, EMBED_ERRTXT("xmlEncodeEntitiesReentrant : char out of range\n"));
            if (doc != NULL){
                doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1");
                if(OOM_FLAG)
                    goto OOM;
            }
            // 2-->
            snprintf(buf, sizeof(buf), "&#%d;", *cur);
            buf[sizeof(buf) - 1] = 0;
            ptr = buf;
            while (*ptr != 0)
            {
                *out++ = *ptr++;
            }
            cur++;
            continue;
            // <--2
        }
        /*
         * We could do multiple things here. Just save as a char ref
         */
        // 3-->
        if (html)
            snprintf(buf, sizeof(buf), "&#%d;", val);
        else
            snprintf(buf, sizeof(buf), "&#x%X;", val);
        buf[sizeof(buf) - 1] = 0;
        ptr = buf;
        while (*ptr != 0)
        {
            *out++ = *ptr++;
        }
        cur += l;
        continue;
        // <--3
        }
    } else if (IS_BYTE_CHAR(*cur)) {
        char buf[11], *ptr;
        // 4-->
        snprintf(buf, sizeof(buf), "&#%d;", *cur);
        buf[sizeof(buf) - 1] = 0;
        ptr = buf;
        while (*ptr != 0)
        {
            *out++ = *ptr++;
        }
    }
    cur++;
    // continue; is implied here
    // <--4
    } // while (*cur != '\0')
    *out++ = 0;
    return(buffer);
OOM:
    xmlFree(buffer);
    return NULL;
}
Exemplo n.º 6
0
/**
 * xsltAttrListTemplateProcess:
 * @ctxt:  the XSLT transformation context
 * @target:  the element where the attributes will be grafted
 * @attrs:  the first attribute
 *
 * Processes all attributes of a Literal Result Element.
 * Attribute references are applied via xsl:use-attribute-set
 * attributes.
 * Copies all non XSLT-attributes over to the @target element
 * and evaluates Attribute Value Templates.
 *
 * Called by xsltApplySequenceConstructor() (transform.c).
 *
 * Returns a new list of attribute nodes, or NULL in case of error.
 *         (Don't assign the result to @target->properties; if
 *         the result is NULL, you'll get memory leaks, since the
 *         attributes will be disattached.)
 */
xmlAttrPtr
xsltAttrListTemplateProcess(xsltTransformContextPtr ctxt, 
	                    xmlNodePtr target, xmlAttrPtr attrs)
{
    xmlAttrPtr attr, copy, last;
    xmlNodePtr oldInsert, text;
    xmlNsPtr origNs = NULL, copyNs = NULL;
    const xmlChar *value;
    xmlChar *valueAVT;

    if ((ctxt == NULL) || (target == NULL) || (attrs == NULL))
	return(NULL);

    oldInsert = ctxt->insert;
    ctxt->insert = target;        

    /*
    * Instantiate LRE-attributes.
    */
    if (target->properties) {
	last = target->properties;
	while (last->next != NULL)
	    last = last->next;
    } else {
	last = NULL;
    }
    attr = attrs;
    do {
	/*
	* Skip XSLT attributes.
	*/
#ifdef XSLT_REFACTORED
	if (attr->psvi == xsltXSLTAttrMarker) {
	    goto next_attribute;
	}
#else
	if ((attr->ns != NULL) &&
	    xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
	{
	    goto next_attribute;
	}
#endif
	/*
	* Get the value.
	*/
	if (attr->children != NULL) {
	    if ((attr->children->type != XML_TEXT_NODE) ||
		(attr->children->next != NULL))
	    {
		xsltTransformError(ctxt, NULL, attr->parent,
		    "Internal error: The children of an attribute node of a "
		    "literal result element are not in the expected form.\n");
		goto error;
	    }
	    value = attr->children->content;
	    if (value == NULL)
		value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
	} else
	    value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);

	/*
	* Create a new attribute.
	*/
	copy = xmlNewDocProp(target->doc, attr->name, NULL);
	if (copy == NULL) {
	    if (attr->ns) {
		xsltTransformError(ctxt, NULL, attr->parent,
		    "Internal error: Failed to create attribute '{%s}%s'.\n",
		    attr->ns->href, attr->name);
	    } else {
		xsltTransformError(ctxt, NULL, attr->parent,
		    "Internal error: Failed to create attribute '%s'.\n",
		    attr->name);
	    }
	    goto error;
	}
	/*
	* Attach it to the target element.
	*/
	copy->parent = target;
	if (last == NULL) {
	    target->properties = copy;
	    last = copy;
	} else {
	    last->next = copy;
	    copy->prev = last;
	    last = copy;
	}
	/*
	* Set the namespace. Avoid lookups of same namespaces.
	*/
	if (attr->ns != origNs) {
	    origNs = attr->ns;
	    if (attr->ns != NULL) {
#ifdef XSLT_REFACTORED
		copyNs = xsltGetSpecialNamespace(ctxt, attr->parent,
		    attr->ns->href, attr->ns->prefix, target);
#else
		copyNs = xsltGetNamespace(ctxt, attr->parent,
		    attr->ns, target);
#endif
		if (copyNs == NULL)
		    goto error;
	    } else
		copyNs = NULL;
	}
	copy->ns = copyNs;

	/*
	* Set the value.
	*/
	text = xmlNewText(NULL);
	if (text != NULL) {
	    copy->last = copy->children = text;
	    text->parent = (xmlNodePtr) copy;
	    text->doc = copy->doc;

	    if (attr->psvi != NULL) {
		/*
		* Evaluate the Attribute Value Template.
		*/
		valueAVT = xsltEvalAVT(ctxt, attr->psvi, attr->parent);
		if (valueAVT == NULL) {
		    /*
		    * TODO: Damn, we need an easy mechanism to report
		    * qualified names!
		    */
		    if (attr->ns) {
			xsltTransformError(ctxt, NULL, attr->parent,
			    "Internal error: Failed to evaluate the AVT "
			    "of attribute '{%s}%s'.\n",
			    attr->ns->href, attr->name);
		    } else {
			xsltTransformError(ctxt, NULL, attr->parent,
			    "Internal error: Failed to evaluate the AVT "
			    "of attribute '%s'.\n",
			    attr->name);
		    }
		    text->content = xmlStrdup(BAD_CAST "");
		    goto error;
		} else {
		    text->content = valueAVT;
		}
	    } else if ((ctxt->internalized) &&
		(target->doc != NULL) &&
		(target->doc->dict == ctxt->dict))
	    {
		text->content = (xmlChar *) value;
	    } else {
		text->content = xmlStrdup(value);
	    }
            if ((copy != NULL) && (text != NULL) &&
                (xmlIsID(copy->doc, copy->parent, copy)))
                xmlAddID(NULL, copy->doc, text->content, copy);
	}

next_attribute:
	attr = attr->next;
    } while (attr != NULL);

    /*
    * Apply attribute-sets.
    * The creation of such attributes will not overwrite any existing
    * attribute.
    */
    attr = attrs;
    do {
#ifdef XSLT_REFACTORED
	if ((attr->psvi == xsltXSLTAttrMarker) &&
	    xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets"))
	{
	    xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);
	}
#else
	if ((attr->ns != NULL) &&
	    xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets") &&
	    xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
	{
	    xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);
	}
#endif
	attr = attr->next;
    } while (attr != NULL);

    ctxt->insert = oldInsert;
    return(target->properties);

error:
    ctxt->insert = oldInsert;
    return(NULL);
}
Exemplo n.º 7
0
/* dept -1 causes depth to be ignored */
static xmlChar* get_xml_element (
    xmlTextReaderPtr reader
    )
{
    int rc;
    while((rc = xmlTextReaderRead(reader)) == 1){
        int type;
        xmlChar *name;
        type = xmlTextReaderNodeType(reader);
        if (type == XML_READER_TYPE_TEXT){
            xmlChar *value;
            value = xmlTextReaderValue(reader);
            rrd_set_error("line %d: expected element but found text '%s'",
                          xmlTextReaderGetParserLineNumber(reader),value);
            xmlFree(value);
            return NULL;
        }
        /* skip all other non-elements */
        if (type != XML_READER_TYPE_ELEMENT && type != XML_READER_TYPE_END_ELEMENT)
            continue;

        name = xmlTextReaderName(reader);
        if (type == XML_READER_TYPE_END_ELEMENT){
            xmlChar *temp;
            xmlChar *temp2;            
            temp = (xmlChar*)sprintf_alloc("/%s",name);
            temp2 = xmlStrdup(temp);
            free(temp);
            xmlFree(name);            
            return temp2;            
        }
        /* all seems well, return the happy news */
        return name;
    }
    if (rc == 0) {
	rrd_set_error("the xml ended while we were looking for an element");
    } else {
	xmlErrorPtr err = xmlGetLastError();
	/* argh: err->message often contains \n at the end. This is not 
	   what we want: Bite the bullet by copying the message, replacing any 
	   \n, constructing the rrd error message and freeing the temp. buffer.
	*/
	char *msgcpy = NULL, *c;
	if (err != NULL && err->message != NULL) {
	    msgcpy = strdup(err->message);
	    if (msgcpy != NULL) {
		for (c = msgcpy ; *c ; c++) {
		    if (*c == '\n') *c = ' ';
		}
		/* strip whitespace from end of message */
		for (c-- ; c != msgcpy ; c--) {
		    if (!isprint(*c)) {
			*c = 0;
		    }
		}
	    } else {
		/* out of memory during error handling, hmmmm */
	    }
	}

	rrd_set_error("error reading/parsing XML: %s", 
		      msgcpy != NULL ? msgcpy : "?");
	if (msgcpy) free(msgcpy);
    }
    return NULL;
} /* get_xml_element */
/**
 * xsltAttrTemplateProcess:
 * @ctxt:  the XSLT transformation context
 * @target:  the result node
 * @cur:  the attribute template node
 *
 * Process the given attribute and return the new processed copy.
 *
 * Returns the attribute replacement.
 */
xmlAttrPtr
xsltAttrTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target,
	                xmlAttrPtr cur) {
    const xmlChar *value;
    xmlNsPtr ns;
    xmlAttrPtr ret;
    if ((ctxt == NULL) || (cur == NULL) || (target == NULL))
	return(NULL);
    
    if (cur->type != XML_ATTRIBUTE_NODE)
	return(NULL);

    if ((cur->children == NULL) || (cur->children->type != XML_TEXT_NODE) ||
        (cur->children->next != NULL)) {
	xsltTransformError(ctxt, NULL, cur->parent,
		"attribute %s content problem\n", cur->name);
        return(NULL);
    }
    value = cur->children->content;
    if (value == NULL)
        value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
    if ((cur->ns != NULL) &&
	(xmlStrEqual(cur->ns->href, XSLT_NAMESPACE))) {
	if (xmlStrEqual(cur->name, (const xmlChar *)"use-attribute-sets")) {
	    xsltApplyAttributeSet(ctxt, ctxt->node, NULL, value);
	}
	return(NULL);
    }

    ret = target->properties;
    while (ret != NULL) {
        if (xmlStrEqual(ret->name, cur->name)) {
	    if (cur->ns == NULL) {
	        if (ret->ns == NULL)
		    break;
	    } else {
	        if ((ret->ns != NULL) &&
		    (xmlStrEqual(ret->ns->href, cur->ns->href)))
		    break;
	    }
	}
        ret = ret->next;
    }
    if (ret != NULL) {
        /* free the existing value */
	xmlFreeNodeList(ret->children);
	ret->children = ret->last = NULL;
    } else {
        /* create a new attribute */
	if (cur->ns != NULL)
	    ns = xsltGetPlainNamespace(ctxt, cur->parent, cur->ns, target);
	else
	    ns = NULL;
	ret = xmlNewNsProp(target, ns, cur->name, NULL);
    }
    if (ret != NULL) {
        xmlNodePtr text;

        text = xmlNewText(NULL);
	if (text != NULL) {
	    ret->last = ret->children = text;
	    text->parent = (xmlNodePtr) ret;
	    text->doc = ret->doc;
	    if (cur->psvi != NULL) {
		xmlChar *val;
		val = xsltEvalAVT(ctxt, cur->psvi, cur->parent);
		if (val == NULL) {
		    text->content = xmlStrdup(BAD_CAST "runtime error");
		} else {
		    text->content = val;
		}
	    } else if ((ctxt->internalized) && (target != NULL) &&
	               (target->doc != NULL) &&
		       (target->doc->dict == ctxt->dict)) {
		text->content = (xmlChar *) value;
	    } else {
		text->content = xmlStrdup(value);
	    }
	}
    } else {
	xsltTransformError(ctxt, NULL, cur->parent,
		"Failed to create attribute %s\n", cur->name);
    }
    return(ret);
}
Exemplo n.º 9
0
/* Note: this function is called for both item and feed context */
static gchar *
atom10_parse_link (xmlNodePtr cur, feedParserCtxtPtr ctxt, struct atom10ParserState *state)
{
	gchar *href, *alternate = NULL;
	
	href = xml_get_ns_attribute (cur, "href", NULL);
	if (href) {
		xmlChar *baseURL = xmlNodeGetBase (cur->doc, cur);
		gchar *url, *relation, *type, *escTitle = NULL, *title;
		const gchar *feedURL = subscription_get_homepage (ctxt->subscription);
		
		if (!baseURL && feedURL && feedURL[0] != '|' && strstr (feedURL, "://"))
			baseURL = xmlStrdup (BAD_CAST (feedURL));
		url = (gchar *)common_build_url (href, (gchar *)baseURL);

		type = xml_get_ns_attribute (cur, "type", NULL);
		relation = xml_get_ns_attribute (cur, "rel", NULL);
		title = xml_get_ns_attribute (cur, "title", NULL);
		if (title)
			escTitle = g_markup_escape_text (title, -1);
		
		if (!xmlHasNsProp (cur, BAD_CAST"rel", NULL) || !relation || g_str_equal (relation, BAD_CAST"alternate"))
			alternate = g_strdup (url);
		else if (g_str_equal (relation, "replies")) {
			if (!type || g_str_equal (type, BAD_CAST"application/atom+xml")) {
				gchar *commentUri = (gchar *)common_build_url ((gchar *)url, subscription_get_homepage (ctxt->subscription));
				if (ctxt->item)
					metadata_list_set (&ctxt->item->metadata, "commentFeedUri", commentUri);
				g_free (commentUri);
			}
		} else if (g_str_equal (relation, "enclosure")) {
			if (ctxt->item) {
				gsize length = 0;
				gchar *lengthStr = xml_get_ns_attribute (cur, "length", NULL);
				if (lengthStr)
					length = atol (lengthStr);
				g_free (lengthStr);
				
				gchar *encStr = enclosure_values_to_string (url, type, length, FALSE /* not yet downloaded */);
				ctxt->item->metadata = metadata_list_append (ctxt->item->metadata, "enclosure", encStr);
				ctxt->item->hasEnclosure = TRUE;
				g_free (encStr);
			}
		} else if (g_str_equal (relation, "related") || g_str_equal (relation, "via")) {	
			if (ctxt->item)
				ctxt->item->metadata = metadata_list_append (ctxt->item->metadata, relation, url);
		} else {
			/* g_warning ("Unhandled Atom link with unexpected relation \"%s\"\n", relation); */
		}
		xmlFree (title);
		xmlFree (baseURL);
		g_free (escTitle);
		g_free (url);
		g_free(relation);
		g_free(type);
		g_free(href);
	} else {
		/* FIXME: @href is required, this document is not valid Atom */;
	}
	
	return alternate;
}
Exemplo n.º 10
0
/*
 * Function translates a nodeset into a text representation
 *
 * iterates over each node in the set and calls xmlNodeDump to write it to
 * an xmlBuffer -from which an xmlChar * string is returned.
 *
 * each representation is surrounded by <tagname> ... </tagname>
 *
 * plainsep is an ordinary (not tag) separator - if used, then nodes are
 * cast to string as output method
 */
static xmlChar *
pgxmlNodeSetToText(xmlNodeSetPtr nodeset,
				   xmlChar *toptagname,
				   xmlChar *septagname,
				   xmlChar *plainsep)
{
	xmlBufferPtr buf;
	xmlChar    *result;
	int			i;

	buf = xmlBufferCreate();

	if ((toptagname != NULL) && (xmlStrlen(toptagname) > 0))
	{
		xmlBufferWriteChar(buf, "<");
		xmlBufferWriteCHAR(buf, toptagname);
		xmlBufferWriteChar(buf, ">");
	}
	if (nodeset != NULL)
	{
		for (i = 0; i < nodeset->nodeNr; i++)
		{
			if (plainsep != NULL)
			{
				xmlBufferWriteCHAR(buf,
							  xmlXPathCastNodeToString(nodeset->nodeTab[i]));

				/* If this isn't the last entry, write the plain sep. */
				if (i < (nodeset->nodeNr) - 1)
					xmlBufferWriteChar(buf, (char *) plainsep);
			}
			else
			{
				if ((septagname != NULL) && (xmlStrlen(septagname) > 0))
				{
					xmlBufferWriteChar(buf, "<");
					xmlBufferWriteCHAR(buf, septagname);
					xmlBufferWriteChar(buf, ">");
				}
				xmlNodeDump(buf,
							nodeset->nodeTab[i]->doc,
							nodeset->nodeTab[i],
							1, 0);

				if ((septagname != NULL) && (xmlStrlen(septagname) > 0))
				{
					xmlBufferWriteChar(buf, "</");
					xmlBufferWriteCHAR(buf, septagname);
					xmlBufferWriteChar(buf, ">");
				}
			}
		}
	}

	if ((toptagname != NULL) && (xmlStrlen(toptagname) > 0))
	{
		xmlBufferWriteChar(buf, "</");
		xmlBufferWriteCHAR(buf, toptagname);
		xmlBufferWriteChar(buf, ">");
	}
	result = xmlStrdup(buf->content);
	xmlBufferFree(buf);
	return result;
}
Exemplo n.º 11
0
static void dom_xpath_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */
{
	zval **args = NULL;
	zval *retval;
	int result, i, ret;
	int error = 0;
	zend_fcall_info fci;
	zval handler;
	xmlXPathObjectPtr obj;
	char *str;
	char *callable = NULL;
	dom_xpath_object *intern;
	
	TSRMLS_FETCH();

	if (! zend_is_executing(TSRMLS_C)) {
		xmlGenericError(xmlGenericErrorContext,
		"xmlExtFunctionTest: Function called from outside of PHP\n");
		error = 1;
	} else {
		intern = (dom_xpath_object *) ctxt->context->userData;
		if (intern == NULL) {
			xmlGenericError(xmlGenericErrorContext,
			"xmlExtFunctionTest: failed to get the internal object\n");
			error = 1;
		}
		else if (intern->registerPhpFunctions == 0) {
			xmlGenericError(xmlGenericErrorContext,
			"xmlExtFunctionTest: PHP Object did not register PHP functions\n");
			error = 1;
		}
	}
	
	if (error == 1) {
		for (i = nargs - 1; i >= 0; i--) {
			obj = valuePop(ctxt);
			xmlXPathFreeObject(obj);
		}
		return;
	}
		
	fci.param_count = nargs - 1;
	if (fci.param_count > 0) {
		fci.params = safe_emalloc(fci.param_count, sizeof(zval**), 0);
		args = safe_emalloc(fci.param_count, sizeof(zval *), 0);
	}
	/* Reverse order to pop values off ctxt stack */
	for (i = nargs - 2; i >= 0; i--) {
		obj = valuePop(ctxt);
		MAKE_STD_ZVAL(args[i]);
		switch (obj->type) {
			case XPATH_STRING:
				ZVAL_STRING(args[i],  (char *)obj->stringval, 1);
				break;
			case XPATH_BOOLEAN:
				ZVAL_BOOL(args[i],  obj->boolval);
				break;
			case XPATH_NUMBER:
				ZVAL_DOUBLE(args[i], obj->floatval);
				break;
			case XPATH_NODESET:
				if (type == 1) {
					str = (char *)xmlXPathCastToString(obj);
					ZVAL_STRING(args[i], str, 1);
					xmlFree(str);
				} else if (type == 2) {
					int j;
					array_init(args[i]);
					if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
						for (j = 0; j < obj->nodesetval->nodeNr; j++) {
							xmlNodePtr node = obj->nodesetval->nodeTab[j];
							zval *child;
							MAKE_STD_ZVAL(child);
							/* not sure, if we need this... it's copied from xpath.c */
							if (node->type == XML_NAMESPACE_DECL) {
								xmlNsPtr curns;
								xmlNodePtr nsparent;
								
								nsparent = node->_private;
								curns = xmlNewNs(NULL, node->name, NULL);
								if (node->children) {
									curns->prefix = xmlStrdup((xmlChar *) node->children);
								}
								if (node->children) {
									node = xmlNewDocNode(node->doc, NULL, (xmlChar *) node->children, node->name);
								} else {
									node = xmlNewDocNode(node->doc, NULL, (xmlChar *) "xmlns", node->name);
								}
								node->type = XML_NAMESPACE_DECL;
								node->parent = nsparent;
								node->ns = curns;
							}
							child = php_dom_create_object(node, &ret, child, (dom_object *)intern TSRMLS_CC);
							add_next_index_zval(args[i], child);
						}
					}
				}
				break;
			default:
			ZVAL_STRING(args[i], (char *)xmlXPathCastToString(obj), 1);
		}
		xmlXPathFreeObject(obj);
		fci.params[i] = &args[i];
	}
	
	fci.size = sizeof(fci);
	fci.function_table = EG(function_table);
	
	obj = valuePop(ctxt);
	if (obj->stringval == NULL) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Handler name must be a string");
		xmlXPathFreeObject(obj);
		if (fci.param_count > 0) {
			for (i = 0; i < nargs - 1; i++) {
				zval_ptr_dtor(&args[i]);
			}
			efree(args);
			efree(fci.params);
		}
		return; 
	}
	INIT_PZVAL(&handler);
	ZVAL_STRING(&handler, obj->stringval, 1);
	xmlXPathFreeObject(obj);

	fci.function_name = &handler;
	fci.symbol_table = NULL;
	fci.object_ptr = NULL;
	fci.retval_ptr_ptr = &retval;
	fci.no_separation = 0;

	if (!zend_make_callable(&handler, &callable TSRMLS_CC)) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", callable);
		
	} else if ( intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable, strlen(callable) + 1) == 0) { 
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not allowed to call handler '%s()'.", callable);
		/* Push an empty string, so that we at least have an xslt result... */
		valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
	} else {
		result = zend_call_function(&fci, NULL TSRMLS_CC);
		if (result == FAILURE) {
			if (Z_TYPE(handler) == IS_STRING) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(&handler));
			}
		/* retval is == NULL, when an exception occurred, don't report anything, because PHP itself will handle that */
		} else if (retval == NULL) {
		} else {
			if (retval->type == IS_OBJECT && instanceof_function( Z_OBJCE_P(retval), dom_node_class_entry TSRMLS_CC)) {
				xmlNode *nodep;
				dom_object *obj;
				if (intern->node_list == NULL) {
					ALLOC_HASHTABLE(intern->node_list);
					zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0);
				}
				zval_add_ref(&retval);
				zend_hash_next_index_insert(intern->node_list, &retval, sizeof(zval *), NULL);
				obj = (dom_object *)zend_object_store_get_object(retval TSRMLS_CC);
				nodep = dom_object_get_node(obj);
				valuePush(ctxt, xmlXPathNewNodeSet(nodep));
			} else if (retval->type == IS_BOOL) {
				valuePush(ctxt, xmlXPathNewBoolean(retval->value.lval));
			} else if (retval->type == IS_OBJECT) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "A PHP Object cannot be converted to a XPath-string");
				valuePush(ctxt, xmlXPathNewString((xmlChar *)""));
			} else {
				convert_to_string_ex(&retval);
				valuePush(ctxt, xmlXPathNewString( Z_STRVAL_P(retval)));
			}
			zval_ptr_dtor(&retval);
		}
	}
	efree(callable);
	zval_dtor(&handler);
	if (fci.param_count > 0) {
		for (i = 0; i < nargs - 1; i++) {
			zval_ptr_dtor(&args[i]);
		}
		efree(args);
		efree(fci.params);
	}
}
Exemplo n.º 12
0
static void method_caller(xmlXPathParserContextPtr ctxt, int nargs)
{
    const xmlChar * function;
    const xmlChar * functionURI;
    int i;
    size_t count;

    xsltTransformContextPtr transform;
    xmlXPathObjectPtr xpath;
    VALUE obj;
    VALUE *args;

    transform = xsltXPathGetTransformContext(ctxt);

    function = ctxt->context->function;
    functionURI = ctxt->context->functionURI;
    obj = (VALUE)xsltGetExtData(transform, functionURI);

    count = (size_t)ctxt->valueNr;
    args = calloc(count, sizeof(VALUE *));

    for(i = 0; i < count; i++) {
	VALUE thing;

	xpath = valuePop(ctxt);
	switch(xpath->type) {
	    case XPATH_STRING:
		thing = NOKOGIRI_STR_NEW2(xpath->stringval);
		break;
	    case XPATH_NODESET:
		if(NULL == xpath->nodesetval) {
		    thing = Nokogiri_wrap_xml_node_set(
			    xmlXPathNodeSetCreate(NULL),
			    DOC_RUBY_OBJECT(ctxt->context->doc));
		} else {
		    thing = Nokogiri_wrap_xml_node_set(xpath->nodesetval,
			    DOC_RUBY_OBJECT(ctxt->context->doc));
		}
		break;
	    default:
		rb_raise(rb_eRuntimeError, "do not handle type: %d", xpath->type);
	}
	args[i] = thing;
    }
    VALUE result = rb_funcall3(obj, rb_intern((const char *)function), (int)count, args);
    switch(TYPE(result)) {
	case T_FLOAT:
	case T_BIGNUM:
	case T_FIXNUM:
	    xmlXPathReturnNumber(ctxt, NUM2DBL(result));
	    break;
	case T_STRING:
	    xmlXPathReturnString(
		    ctxt,
		    xmlStrdup((xmlChar *)StringValuePtr(result))
		    );
	    break;
	case T_TRUE:
	    xmlXPathReturnTrue(ctxt);
	    break;
	case T_FALSE:
	    xmlXPathReturnFalse(ctxt);
	    break;
	case T_NIL:
	    break;
	default:
	    rb_raise(rb_eRuntimeError, "Invalid return type");
    }
}
Exemplo n.º 13
0
Arquivo: svg2.c Projeto: anj1/cdac
/* if p is NULL, just returns n */
int parse_outline2(xmlAttr *data, point2d32f *p, int *n, int nmax)
{
	char *str;
	char *tok;
	float x,y;
	float initx,inity;	/* beginning of sub-path */
	float curx,cury;	/* cursor */
	int i;
	int absolute;		/* absolute or relative coordinates */
	int mode;			/* 0:moveto 1:lineto */
	
	mode=-1;
	
	/* first, copy string */
	str = (char *)xmlStrdup(data->children->content);
	
	/* now, tokenize it */
	/* to avoid a lot of headaches, we make the assumption that the
	 * input will be "m blablablabala z" */
	
	absolute=0;
	/* initialize strtok */
	tok = strtok(str," ");

	curx = 0;
	cury = 0;
	
	/* just a guess (also stops gcc's whining) */
	initx = curx;
	inity = cury;
	
	i=0;
	while(tok!=NULL){
		if(strlen(tok)==1){	/* command */
			
			absolute = tok[0] > 'Z' ? 0 : 1;
			
			switch(tok[0]){
				case 'm':
				case 'M':
					mode=0;
					break;
					
				case 'l':
				case 'L':
					mode=1;
					break;
					
				case 'z':
				case 'Z':
					curx = initx;
					cury = inity;
					*n = i;
					return 0;
				
				default:
					printf("Error: command '%c' not supported.\n", tok[0]);
					printf("Cell outlines must be polygons (not curves)\n");
					return -3;
			}
		} else {	/* coordinates */
		
			sscanf(tok,"%f,%f",&x,&y);
		
			if(mode==-1){
				printf("Error: first token in path data must be command.\n");
				return -1;
			}
			
			if(mode==0){
				if(i>0){
					printf("Error: Cell outlines must be contiguous.\n");
					return -2;
				}
			}
			
			if(!absolute){x += curx; y += cury;}
			
			if(i==0){
				initx = x;	/* needed for closepath, */
				inity = y;	/* as it must move cursor to beginning */
			}
			
			if(p){
				p[i].x = x;
				p[i].y = y;
			}
			i++;
			
			curx = x;
			cury = y;
			
			if(mode==0) /* moveto can only be for first pair */
				mode=1;
		}
		
		tok = strtok(NULL," ");
	}

	printf("Error: Cell path must be closed. Continuing anyway...\n");
	*n = i;
	return 0;
}
Exemplo n.º 14
0
static void
filter_option_xml_create (EFilterElement *element,
                          xmlNodePtr node)
{
	EFilterOption *option = E_FILTER_OPTION (element);
	xmlNodePtr n, work;

	/* Chain up to parent's xml_create() method. */
	E_FILTER_ELEMENT_CLASS (e_filter_option_parent_class)->
		xml_create (element, node);

	n = node->children;
	while (n) {
		if (!strcmp ((gchar *) n->name, "option")) {
			gchar *tmp, *value, *title = NULL, *code = NULL, *code_gen_func = NULL;

			value = (gchar *) xmlGetProp (n, (xmlChar *)"value");
			work = n->children;
			while (work) {
				if (!strcmp ((gchar *) work->name, "title") ||
					!strcmp ((gchar *) work->name, "_title")) {
					if (!title) {
						if (!(tmp = (gchar *) xmlNodeGetContent (work)))
							tmp = (gchar *) xmlStrdup ((xmlChar *)"");

						title = g_strdup (tmp);
						xmlFree (tmp);
					}
				} else if (!strcmp ((gchar *) work->name, "code")) {
					if (code || code_gen_func) {
						g_warning (
							"Element 'code' defined twice in '%s'",
							element->name);
					} else {
						xmlChar *fn;

						/* if element 'code' has attribute 'func', then
						 * the content of the element is ignored and only
						 * the 'func' is used to generate actual rule code;
						 * The function prototype is:
						 * void code_gen_func (EFilterElement *element, GString *out, EFilterPart *part);
						 * where @element is the one on which was called,
						 * @out is GString where to add the code, and
						 * @part is part which contains @element and other options of it.
						*/
						fn = xmlGetProp (work, (xmlChar *)"func");
						if (fn && *fn) {
							code_gen_func = g_strdup ((const gchar *) fn);
						} else {
							if (!(tmp = (gchar *) xmlNodeGetContent (work)))
								tmp = (gchar *) xmlStrdup ((xmlChar *)"");

							code = g_strdup (tmp);
							xmlFree (tmp);
						}

						xmlFree (fn);
					}
				}
				work = work->next;
			}

			e_filter_option_add (option, value, title, code, code_gen_func, FALSE);
			xmlFree (value);
			g_free (title);
			g_free (code);
			g_free (code_gen_func);
		} else if (g_str_equal ((gchar *) n->name, "dynamic")) {
			if (option->dynamic_func) {
				g_warning (
					"Only one 'dynamic' node is "
					"acceptable in the optionlist '%s'",
					element->name);
			} else {
				/* Expecting only one <dynamic func="cb" />
				 * in the option list,
				 * The 'cb' should be of this prototype:
				 * GSList *cb (void);
				 * returning GSList of struct _filter_option,
				 * all newly allocated, because it'll be
				 * freed with g_free and g_slist_free.
				 * 'is_dynamic' member is ignored here.
				 */
				xmlChar *fn;

				fn = xmlGetProp (n, (xmlChar *)"func");
				if (fn && *fn) {
					GSList *items, *i;
					struct _filter_option *op;

					option->dynamic_func = g_strdup ((const gchar *) fn);

					/* Get options now, to have them
					 * available when reading saved
					 * rules. */
					items = filter_option_get_dynamic_options (option);
					for (i = items; i; i = i->next) {
						op = i->data;

						if (op) {
							e_filter_option_add (
								option,
								op->value,
								op->title,
								op->code,
								op->code_gen_func,
								TRUE);
							free_option (op);
						}
					}

					g_slist_free (items);
				} else {
					g_warning (
						"Missing 'func' attribute within "
						"'%s' node in optionlist '%s'",
						n->name, element->name);
				}

				xmlFree (fn);
			}
		} else if (n->type == XML_ELEMENT_NODE) {
			g_warning ("Unknown xml node within optionlist: %s\n", n->name);
		}
		n = n->next;
	}
}
Exemplo n.º 15
0
/**
 *  Parse command line for XSLT parameters
 */
int
trParseParams(const char** params, int* plen,
              int count, char **argv)
{
    int i;
    *plen = 0;
    params[0] = 0;

    for (i=0; i<count; i++)
    {
        if (argv[i][0] == '-')
        {
            if (!strcmp(argv[i], "-p"))
            {
                int j;
                xmlChar *name, *value;
                
                i++;
                if (i >= count) trUsage(argv[0], EXIT_BAD_ARGS);

                for(j=0; argv[i][j] && (argv[i][j] != '='); j++);
                if (argv[i][j] != '=') trUsage(argv[0], EXIT_BAD_ARGS);
                
                name = xmlStrndup((const xmlChar *) argv[i], j);
                value = xmlStrdup((const xmlChar *) argv[i]+j+1);

                if (*plen >= MAX_PARAMETERS)
                {
                    fprintf(stderr, "too many params increase MAX_PARAMETERS\n");
                    exit(EXIT_INTERNAL_ERROR);
                }

                params[*plen] = (char *)name;
                (*plen)++;
                params[*plen] = (char *)value;
                (*plen)++;                
                params[*plen] = 0;
            }
            else if (!strcmp(argv[i], "-s"))
            {
                int j;
                const xmlChar *string;
                xmlChar *name, *value;

                i++;
                if (i >= count) trUsage(argv[0], EXIT_BAD_ARGS);

                for(j=0; argv[i][j] && (argv[i][j] != '='); j++);
                if (argv[i][j] != '=') trUsage(argv[0], EXIT_BAD_ARGS);

                name = xmlStrndup((const xmlChar *)argv[i], j);
                string = (const xmlChar *)(argv[i]+j+1);

                if (xmlStrchr(string, '"'))
                {
                    if (xmlStrchr(string, '\''))
                    {
                        fprintf(stderr,
                            "string parameter contains both quote and double-quotes\n");
                        exit(EXIT_INTERNAL_ERROR);
                    }
                    value = xmlStrdup((const xmlChar *)"'");
                    value = xmlStrcat(value, string);
                    value = xmlStrcat(value, (const xmlChar *)"'");
                }
                else
                {
                    value = xmlStrdup((const xmlChar *)"\"");
                    value = xmlStrcat(value, string);
                    value = xmlStrcat(value, (const xmlChar *)"\"");
                }

                if (*plen >= MAX_PARAMETERS)
                {
                    fprintf(stderr, "too many params increase MAX_PARAMETERS\n");
                    exit(EXIT_INTERNAL_ERROR);
                }

                params[*plen] = (char *)name;
                (*plen)++;
                params[*plen] = (char *)value;
                (*plen)++;
                params[*plen] = 0;
            }
        }
        else
            break;
    }

    return i;    
}
static void
parse_style (ParserState *parser_state)
{
	gchar *id;
	xmlChar *name, *map_to;
	xmlChar *tmp;
	gchar *lang_id = NULL;

	g_return_if_fail (parser_state->error == NULL);

	tmp = xmlTextReaderGetAttribute (parser_state->reader,
					 BAD_CAST "id");

	if (id_is_decorated ((gchar*) tmp, NULL))
		id = g_strdup ((gchar*) tmp);
	else
		id = decorate_id (parser_state, (gchar*) tmp);

	xmlFree (tmp);

	name = xmlTextReaderGetAttribute (parser_state->reader,
					  BAD_CAST "_name");

	if (name != NULL)
	{
		gchar *tmp2 = _gtk_source_language_translate_string (parser_state->language,
								     (gchar*) name);
		tmp = xmlStrdup (BAD_CAST tmp2);
		xmlFree (name);
		name = tmp;
		g_free (tmp2);
	}
	else
	{
		name = xmlTextReaderGetAttribute (parser_state->reader,
						  BAD_CAST "name");
	}

	map_to = xmlTextReaderGetAttribute (parser_state->reader,
					    BAD_CAST "map-to");

	if (map_to != NULL && !id_is_decorated ((gchar*) map_to, &lang_id))
	{
		g_set_error (&parser_state->error,
			     PARSER_ERROR,
			     PARSER_ERROR_MALFORMED_MAP_TO,
			     "the map-to attribute '%s' for the style '%s' lacks the prefix",
			     map_to, id);
	}

	if (parser_state->error == NULL && lang_id != NULL && lang_id[0] == 0)
	{
		g_free (lang_id);
		lang_id = NULL;
	}

	if (parser_state->error == NULL && lang_id != NULL &&
	    !lang_id_is_already_loaded (parser_state, lang_id))
	{
		parse_language_with_id (parser_state, lang_id);
	}

	DEBUG (g_message ("style %s (%s) to be mapped to '%s'",
			  name, id, map_to ? (char*) map_to : "(null)"));

	if (map_to != NULL &&
	    g_hash_table_lookup (parser_state->styles_mapping, map_to) == NULL)
	{
		g_warning ("in file %s: style '%s' not defined", parser_state->filename, map_to);
	}

	if (parser_state->error == NULL)
	{

		GtkSourceStyleInfo *info;

		/* Remember the style name only if the style has been defined in
		 * the lang file we are parsing */
		if (g_str_has_prefix (id, parser_state->language_decoration))
			info = _gtk_source_style_info_new ((gchar *) name,
							   (gchar *) map_to);
		else
			info = _gtk_source_style_info_new (NULL,
							   (gchar *) map_to);

		g_hash_table_insert (parser_state->styles_mapping, g_strdup (id), info);
	}

	g_free (lang_id);
	g_free (id);
	xmlFree (name);
	xmlFree (map_to);
}
Exemplo n.º 17
0
/**
 * xsltAttrTemplateProcess:
 * @ctxt:  the XSLT transformation context
 * @target:  the element where the attribute will be grafted
 * @attr:  the attribute node of a literal result element
 *
 * Process one attribute of a Literal Result Element (in the stylesheet).
 * Evaluates Attribute Value Templates and copies the attribute over to
 * the result element.
 * This does *not* process attribute sets (xsl:use-attribute-set).
 * 
 *
 * Returns the generated attribute node.
 */
xmlAttrPtr
xsltAttrTemplateProcess(xsltTransformContextPtr ctxt, xmlNodePtr target,
	                xmlAttrPtr attr)
{
    const xmlChar *value;
    xmlAttrPtr ret;

    if ((ctxt == NULL) || (attr == NULL) || (target == NULL))
	return(NULL);
    
    if (attr->type != XML_ATTRIBUTE_NODE)
	return(NULL);

    /*
    * Skip all XSLT attributes.
    */
#ifdef XSLT_REFACTORED    
    if (attr->psvi == xsltXSLTAttrMarker)
	return(NULL);
#else
    if ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
	return(NULL);
#endif
    /*
    * Get the value.
    */
    if (attr->children != NULL) {
	if ((attr->children->type != XML_TEXT_NODE) ||
	    (attr->children->next != NULL))
	{
	    xsltTransformError(ctxt, NULL, attr->parent,
		"Internal error: The children of an attribute node of a "
		"literal result element are not in the expected form.\n");
	    return(NULL);
	}
	value = attr->children->content;
	if (value == NULL)
	    value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
    } else
	value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
    /*
    * Overwrite duplicates.
    */
    ret = target->properties;
    while (ret != NULL) {
        if (((attr->ns != NULL) == (ret->ns != NULL)) &&
	    xmlStrEqual(ret->name, attr->name) &&
	    ((attr->ns == NULL) || xmlStrEqual(ret->ns->href, attr->ns->href)))
	{
	    break;
	}
        ret = ret->next;
    }
    if (ret != NULL) {	
        /* free the existing value */
	xmlFreeNodeList(ret->children);
	ret->children = ret->last = NULL;
	/*
	* Adjust ns-prefix if needed.
	*/
	if ((ret->ns != NULL) &&
	    (! xmlStrEqual(ret->ns->prefix, attr->ns->prefix)))
	{
	    ret->ns = xsltGetNamespace(ctxt, attr->parent, attr->ns, target);
	}
    } else {
        /* create a new attribute */
	if (attr->ns != NULL)
	    ret = xmlNewNsProp(target,
		xsltGetNamespace(ctxt, attr->parent, attr->ns, target),
		    attr->name, NULL);
	else
	    ret = xmlNewNsProp(target, NULL, attr->name, NULL);	
    }
    /*
    * Set the value.
    */
    if (ret != NULL) {
        xmlNodePtr text;

        text = xmlNewText(NULL);
	if (text != NULL) {
	    ret->last = ret->children = text;
	    text->parent = (xmlNodePtr) ret;
	    text->doc = ret->doc;

	    if (attr->psvi != NULL) {
		/*
		* Evaluate the Attribute Value Template.
		*/
		xmlChar *val;
		val = xsltEvalAVT(ctxt, attr->psvi, attr->parent);
		if (val == NULL) {
		    /*
		    * TODO: Damn, we need an easy mechanism to report
		    * qualified names!
		    */
		    if (attr->ns) {
			xsltTransformError(ctxt, NULL, attr->parent,
			    "Internal error: Failed to evaluate the AVT "
			    "of attribute '{%s}%s'.\n",
			    attr->ns->href, attr->name);
		    } else {
			xsltTransformError(ctxt, NULL, attr->parent,
			    "Internal error: Failed to evaluate the AVT "
			    "of attribute '%s'.\n",
			    attr->name);
		    }
		    text->content = xmlStrdup(BAD_CAST "");
		} else {
		    text->content = val;
		}
	    } else if ((ctxt->internalized) && (target != NULL) &&
	               (target->doc != NULL) &&
		       (target->doc->dict == ctxt->dict)) {
		text->content = (xmlChar *) value;
	    } else {
		text->content = xmlStrdup(value);
	    }
	}
    } else {
	if (attr->ns) {
	    xsltTransformError(ctxt, NULL, attr->parent,
	    	"Internal error: Failed to create attribute '{%s}%s'.\n",
		attr->ns->href, attr->name);
	} else {
	    xsltTransformError(ctxt, NULL, attr->parent,
	    	"Internal error: Failed to create attribute '%s'.\n",
		attr->name);
	}
    }
    return(ret);
}
static void
handle_context_element (ParserState *parser_state)
{
	gchar *id, *parent_id, *style_ref;
	xmlChar *ref, *sub_pattern, *tmp;
	int is_empty;
	gboolean success;
	gboolean ignore_style = FALSE;
	GtkSourceContextRefOptions options = 0;
	GSList *context_classes;

	GError *tmp_error = NULL;

	g_return_if_fail (parser_state->error == NULL);

	ref = xmlTextReaderGetAttribute (parser_state->reader, BAD_CAST "ref");
	sub_pattern = xmlTextReaderGetAttribute (parser_state->reader,
						 BAD_CAST "sub-pattern");

	tmp = xmlTextReaderGetAttribute (parser_state->reader, BAD_CAST "ignore-style");
	if (tmp != NULL && str_to_bool (tmp))
		ignore_style = TRUE;
	xmlFree (tmp);

	tmp = xmlTextReaderGetAttribute (parser_state->reader, BAD_CAST "style-ref");
	if (tmp == NULL || id_is_decorated ((gchar*) tmp, NULL))
		style_ref = g_strdup ((gchar*) tmp);
	else
		style_ref = decorate_id (parser_state, (gchar*) tmp);
	xmlFree (tmp);

	if (ignore_style && ref == NULL)
	{
		g_set_error (&parser_state->error,
			     PARSER_ERROR,
			     PARSER_ERROR_WRONG_STYLE,
			     "ignore-style used not in a reference to context");

		xmlFree (ref);
		g_free (style_ref);

		return;
	}

	if (ignore_style)
	{
		options |= GTK_SOURCE_CONTEXT_IGNORE_STYLE;

		if (style_ref != NULL)
			g_warning ("in file %s: style-ref and ignore-style used simultaneously",
				   parser_state->filename);
	}

	/* XXX */
	if (!ignore_style && style_ref != NULL &&
	    g_hash_table_lookup (parser_state->styles_mapping, style_ref) == NULL)
	{
		g_warning ("in file %s: style '%s' not defined", parser_state->filename, style_ref);
	}

	context_classes = parse_classes (parser_state);

	if (ref != NULL)
	{
		tmp = xmlTextReaderGetAttribute (parser_state->reader, BAD_CAST "original");
		if (tmp != NULL && str_to_bool (tmp))
			options |= GTK_SOURCE_CONTEXT_REF_ORIGINAL;
		xmlFree (tmp);

		if (style_ref != NULL)
			options |= GTK_SOURCE_CONTEXT_OVERRIDE_STYLE;

		add_ref (parser_state,
		         (gchar*) ref,
		         options,
		         style_ref,
		         &tmp_error);
	}
	else
	{
		char *freeme = NULL;

		tmp = xmlTextReaderGetAttribute (parser_state->reader, BAD_CAST "id");
		if (tmp == NULL)
		{
			freeme = generate_new_id (parser_state);
			tmp = xmlStrdup (BAD_CAST freeme);
		}

		if (id_is_decorated ((gchar*) tmp, NULL))
			id = g_strdup ((gchar*) tmp);
		else
			id = decorate_id (parser_state, (gchar*) tmp);

		g_free (freeme);
		xmlFree (tmp);

		if (parser_state->ctx_data != NULL)
		{
			if (sub_pattern != NULL)
			{
				create_sub_pattern (parser_state,
				                    id,
				                    (gchar *)sub_pattern,
				                    style_ref,
				                    context_classes,
				                    &tmp_error);
			}
			else
			{
				parent_id = g_queue_peek_head (
						parser_state->curr_parents);

				is_empty = xmlTextReaderIsEmptyElement (
						parser_state->reader);

				if (is_empty)
					success = _gtk_source_context_data_define_context (parser_state->ctx_data,
											   id,
											   parent_id,
											   "$^",
											   NULL,
											   NULL,
											   NULL,
											   NULL,
											   0,
											   &tmp_error);
				else
					success = create_definition (parser_state,
					                             id,
					                             parent_id,
					                             style_ref,
					                             context_classes,
					                             &tmp_error);

				if (success && !is_empty)
				{
					/* Push the new context in the curr_parents
					 * stack only if other contexts can be
					 * defined inside it */
					g_queue_push_head (parser_state->curr_parents,
							   g_strdup (id));
				}
			}
		}

		g_free (id);
	}

	g_slist_free_full (context_classes, (GDestroyNotify)gtk_source_context_class_free);

	g_free (style_ref);
	xmlFree (sub_pattern);
	xmlFree (ref);

	if (tmp_error != NULL)
		g_propagate_error (&parser_state->error, tmp_error);
}
Exemplo n.º 19
0
void
loadBook(const char * file)
{
	LIBXML_TEST_VERSION

	int i = 0, j;
	char* token, *string, *tmp;
	xmlDocPtr doc = NULL;
	xmlNodePtr node = NULL;
	xmlNodePtr node_child = NULL;
	xmlAttrPtr prop = NULL;

	if ((doc = xmlReadFile (file, NULL, 0)) == NULL)
	{
		fprintf (stderr, "Error: couldn't parse file %s\n", file);
		exit(1);
	}

	node = xmlDocGetRootElement (doc);

	if (xmlStrcmp (node->name, (xmlChar *) "story"))
	{
		fprintf (stderr, "Error when loading configuration\n");
		exit(1);
	}

	node = ((xmlNodePtr)node->children);

	while (node)
	{
		if (node->type == XML_ELEMENT_NODE && node->children->type == XML_TEXT_NODE)
		{
			#ifdef _DEBUG
				printf("%s -> \n", xmlStrdup(node->name) );
			#endif

			if(!gamebook.action)
				gamebook.action = malloc( sizeof(struct gbook_act) * CH_BLOCK );

			if(gamebook.n_action % CH_BLOCK)
				gamebook.action = realloc( gamebook.action, (gamebook.n_action + CH_BLOCK) * sizeof(struct gbook_act) );

			gamebook.action[gamebook.n_action].id = gamebook.n_action + 1;
			gamebook.action[gamebook.n_action].choices = NULL;
			gamebook.action[gamebook.n_action].n_choice = 0;

			node_child = ((xmlNodePtr)node->children);

			while(node_child)
			{
				if (node_child->type == XML_ELEMENT_NODE && node_child->children->type == XML_TEXT_NODE)
				{
					if( !strcmp(xmlStrdup(node_child->name), "text") )
					{
						gamebook.action[gamebook.n_action].text = strreplace(xmlStrdup( node_child->children->content ) , "$user", user_cfg.name );
					} else {
						if(!gamebook.action[gamebook.n_action].choices)
							gamebook.action[gamebook.n_action].choices = malloc( sizeof(struct gbook_choice) * CH_BLOCK );

						if(gamebook.action[gamebook.n_action].n_choice % CH_BLOCK)
							gamebook.action[gamebook.n_action].choices = realloc( gamebook.action[gamebook.n_action].choices, 
									( CH_BLOCK + gamebook.action[gamebook.n_action].n_choice ) * sizeof(struct gbook_choice) );

						gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].text = strreplace( xmlStrdup( node_child->children->content ), "$user", user_cfg.name );

						gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].require = \
						gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].gain = NULL;
						gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].life = \
						gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].money = 0;

						prop = node_child->properties;

						while( prop )
						{
							if( !strcmp( xmlStrdup( prop->name) , "link" ) )
							{
								gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].link = _atoi(xmlStrdup( prop->children->content ));
							} else if (!strcmp( xmlStrdup( prop->name ), "require" ))
							{
								gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].require = xmlStrdup( prop->children->content );
							} else if (!strcmp( xmlStrdup( prop->name ), "gain" ))
							{
								gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].gain = xmlStrdup( prop->children->content );
							} else if (!strcmp( xmlStrdup( prop->name ), "life" ))
							{
								gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].life = _atoi(xmlStrdup( prop->children->content ));
							} else if (!strcmp( xmlStrdup( prop->name ), "money" ))
							{
								gamebook.action[gamebook.n_action].choices[gamebook.action[gamebook.n_action].n_choice].money = _atoi(xmlStrdup( prop->children->content ));
							}

							prop = prop->next;
						}

						#ifdef _DEBUG
							printf("%s -> \"%s\"\n", xmlStrdup(node_child->name), xmlStrdup(node_child->children->content) );

							if ( node_child->properties )
								printf("( %s = %s )\n", xmlStrdup( node_child->properties->name ), xmlStrdup( node_child->properties->children->content ) );
						#endif

						gamebook.action[gamebook.n_action].n_choice++;
					}
				}

				node_child = node_child->next;
			}

			gamebook.n_action++;
		}

		node = node->next;
	}
}
Exemplo n.º 20
0
static void _parse_relay(xmlDocPtr doc, xmlNodePtr node,
        ice_config_t *configuration)
{
    char *tmp;
    relay_server *relay = acalloc(1, sizeof(relay_server));
    relay_server *current = configuration->relay;
    relay_server *last=NULL;

    while(current) {
        last = current;
        current = current->next;
    }

    if(last)
        last->next = relay;
    else
        configuration->relay = relay;

    relay->next = NULL;
    relay->mp3metadata = 1;
    relay->on_demand = configuration->on_demand;
    relay->server = (char *)xmlCharStrdup ("127.0.0.1");
    relay->mount = (char *)xmlCharStrdup ("/");

    do {
        if (node == NULL) break;
        if (xmlIsBlankNode(node)) continue;

        if (xmlStrcmp (node->name, XMLSTR("server")) == 0) {
            if (relay->server) xmlFree (relay->server);
            relay->server = (char *)xmlNodeListGetString(
                    doc, node->xmlChildrenNode, 1);
        }
        else if (xmlStrcmp (node->name, XMLSTR("port")) == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            relay->port = atoi(tmp);
            if(tmp) xmlFree(tmp);
        }
        else if (xmlStrcmp (node->name, XMLSTR("mount")) == 0) {
            if (relay->mount) xmlFree (relay->mount);
            relay->mount = (char *)xmlNodeListGetString(
                    doc, node->xmlChildrenNode, 1);
        }
        else if (xmlStrcmp (node->name, XMLSTR("local-mount")) == 0) {
            if (relay->localmount) xmlFree (relay->localmount);
            relay->localmount = (char *)xmlNodeListGetString(
                    doc, node->xmlChildrenNode, 1);
        }
        else if (xmlStrcmp (node->name, XMLSTR("relay-shoutcast-metadata")) == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            relay->mp3metadata = atoi(tmp);
            if(tmp) xmlFree(tmp);
        }
        else if (xmlStrcmp (node->name, XMLSTR("username")) == 0) {
            if (relay->username) xmlFree (relay->username);
            relay->username = (char *)xmlNodeListGetString(doc,
                    node->xmlChildrenNode, 1);
        }
        else if (xmlStrcmp (node->name, XMLSTR("password")) == 0) {
            if (relay->password) xmlFree (relay->password);
            relay->password = (char *)xmlNodeListGetString(doc,
                    node->xmlChildrenNode, 1);
        }
        else if (xmlStrcmp (node->name, XMLSTR("on-demand")) == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            relay->on_demand = atoi(tmp);
            if (tmp) xmlFree(tmp);
        }
        else if (xmlStrcmp (node->name, XMLSTR("bind")) == 0) {
            if (relay->bind) xmlFree (relay->bind);
            relay->bind = (char *)xmlNodeListGetString (doc, node->xmlChildrenNode, 1);
        }
    } while ((node = node->next));
    if (relay->localmount == NULL)
        relay->localmount = (char *)xmlStrdup (XMLSTR(relay->mount));
}
Exemplo n.º 21
0
static void php_xpath_eval(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
	zval *id, retval, *context = NULL;
	xmlXPathContextPtr ctxp;
	xmlNodePtr nodep = NULL;
	xmlXPathObjectPtr xpathobjp;
	size_t expr_len, nsnbr = 0, xpath_type;
	dom_xpath_object *intern;
	dom_object *nodeobj;
	char *expr;
	xmlDoc *docp = NULL;
	xmlNsPtr *ns = NULL;
	zend_bool register_node_ns = 1;

	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) {
		return;
	}

	intern = Z_XPATHOBJ_P(id);

	ctxp = (xmlXPathContextPtr) intern->dom.ptr;
	if (ctxp == NULL) {
		php_error_docref(NULL, E_WARNING, "Invalid XPath Context");
		RETURN_FALSE;
	}

	docp = (xmlDocPtr) ctxp->doc;
	if (docp == NULL) {
		php_error_docref(NULL, E_WARNING, "Invalid XPath Document Pointer");
		RETURN_FALSE;
	}

	if (context != NULL) {
		DOM_GET_OBJ(nodep, context, xmlNodePtr, nodeobj);
	}

	if (!nodep) {
		nodep = xmlDocGetRootElement(docp);
	}

	if (nodep && docp != nodep->doc) {
		php_error_docref(NULL, E_WARNING, "Node From Wrong Document");
		RETURN_FALSE;
	}

	ctxp->node = nodep;

	if (register_node_ns) {
		/* Register namespaces in the node */
		ns = xmlGetNsList(docp, nodep);

		if (ns != NULL) {
			while (ns[nsnbr] != NULL)
			nsnbr++;
		}
	}


    ctxp->namespaces = ns;
    ctxp->nsNr = nsnbr;

	xpathobjp = xmlXPathEvalExpression((xmlChar *) expr, ctxp);
	ctxp->node = NULL;

	if (ns != NULL) {
		xmlFree(ns);
		ctxp->namespaces = NULL;
		ctxp->nsNr = 0;
	}

	if (! xpathobjp) {
		RETURN_FALSE;
	}

	if (type == PHP_DOM_XPATH_QUERY) {
		xpath_type = XPATH_NODESET;
	} else {
		xpath_type = xpathobjp->type;
	}

	switch (xpath_type) {

		case  XPATH_NODESET:
		{
			int i;
			xmlNodeSetPtr nodesetp;

			array_init(&retval);

			if (xpathobjp->type == XPATH_NODESET && NULL != (nodesetp = xpathobjp->nodesetval)) {

				for (i = 0; i < nodesetp->nodeNr; i++) {
					xmlNodePtr node = nodesetp->nodeTab[i];
					zval child;

					if (node->type == XML_NAMESPACE_DECL) {
						xmlNsPtr curns;
						xmlNodePtr nsparent;

						nsparent = node->_private;
						curns = xmlNewNs(NULL, node->name, NULL);
						if (node->children) {
							curns->prefix = xmlStrdup((xmlChar *) node->children);
						}
						if (node->children) {
							node = xmlNewDocNode(docp, NULL, (xmlChar *) node->children, node->name);
						} else {
							node = xmlNewDocNode(docp, NULL, (xmlChar *) "xmlns", node->name);
						}
						node->type = XML_NAMESPACE_DECL;
						node->parent = nsparent;
						node->ns = curns;
					}
					php_dom_create_object(node, &child, &intern->dom);
					add_next_index_zval(&retval, &child);
				}
			}
			php_dom_create_interator(return_value, DOM_NODELIST);
			nodeobj = Z_DOMOBJ_P(return_value);
			dom_xpath_iter(&retval, nodeobj);
			break;
		}

		case XPATH_BOOLEAN:
			RETVAL_BOOL(xpathobjp->boolval);
			break;

		case XPATH_NUMBER:
			RETVAL_DOUBLE(xpathobjp->floatval);
			break;

		case XPATH_STRING:
			RETVAL_STRING((char *) xpathobjp->stringval);
			break;

		default:
			RETVAL_NULL();
			break;
	}

	xmlXPathFreeObject(xpathobjp);
}
Exemplo n.º 22
0
static void _parse_listen_socket(xmlDocPtr doc, xmlNodePtr node,
        ice_config_t *configuration)
{
    char *tmp;
    listener_t *listener = acalloc (1, sizeof(listener_t));

    if (listener == NULL)
        return;
    listener->port = 8000;

    do {
        if (node == NULL) break;
        if (xmlIsBlankNode(node)) continue;

        if (xmlStrcmp (node->name, XMLSTR("port")) == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            if(configuration->port == 0)
                configuration->port = atoi(tmp);
            listener->port = atoi(tmp);
            if(tmp) xmlFree(tmp);
        }
        else if (xmlStrcmp (node->name, XMLSTR("ssl")) == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            listener->ssl = atoi(tmp);
            if(tmp) xmlFree(tmp);
        }
        else if (xmlStrcmp (node->name, XMLSTR("shoutcast-compat")) == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            listener->shoutcast_compat = atoi(tmp);
            if(tmp) xmlFree(tmp);
        }
        else if (xmlStrcmp (node->name, XMLSTR("shoutcast-mount")) == 0) {
            if (listener->shoutcast_mount) xmlFree (listener->shoutcast_mount);
            listener->shoutcast_mount = (char *)xmlNodeListGetString(doc, 
                    node->xmlChildrenNode, 1);
        }
        else if (xmlStrcmp (node->name, XMLSTR("bind-address")) == 0) {
            if (listener->bind_address) xmlFree (listener->bind_address);
            listener->bind_address = (char *)xmlNodeListGetString(doc, 
                    node->xmlChildrenNode, 1);
        }
        else if (xmlStrcmp (node->name, XMLSTR("so-sndbuf")) == 0) {
            tmp = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
            listener->so_sndbuf = atoi(tmp);
            if(tmp) xmlFree(tmp);
        }
    } while ((node = node->next));

    /* we know there's at least one of these, so add this new one after the first
     * that way it can be removed easily later on */
    listener->next = configuration->listen_sock->next;
    configuration->listen_sock->next = listener;
    configuration->listen_sock_count++;
    if (listener->shoutcast_mount)
    {
        listener_t *sc_port = acalloc (1, sizeof (listener_t));
        sc_port->port = listener->port+1;
        sc_port->shoutcast_compat = 1;
        sc_port->shoutcast_mount = (char*)xmlStrdup (XMLSTR(listener->shoutcast_mount));
        if (listener->bind_address)
            sc_port->bind_address = (char*)xmlStrdup (XMLSTR(listener->bind_address));

        sc_port->next = listener->next;
        listener->next = sc_port;
        configuration->listen_sock_count++;
    }
}
Exemplo n.º 23
0
/**
 * xmlEncodeEntitiesReentrant:
 * @doc:  the document containing the string
 * @input:  A string to convert to XML.
 *
 * Do a global encoding of a string, replacing the predefined entities
 * and non ASCII values with their entities and CharRef counterparts.
 * Contrary to xmlEncodeEntities, this routine is reentrant, and result
 * must be deallocated.
 *
 * Returns A newly allocated string with the substitution done.
 */
xmlChar *
xmlEncodeEntitiesReentrant(xmlDocPtr doc, const xmlChar *input) {
    const xmlChar *cur = input;
    xmlChar *buffer = NULL;
    xmlChar *out = NULL;
    int buffer_size = 0;
    int html = 0;

    if (input == NULL) return(NULL);
    if (doc != NULL)
        html = (doc->type == XML_HTML_DOCUMENT_NODE);

    /*
     * allocate an translation buffer.
     */
    buffer_size = 1000;
    buffer = (xmlChar *) xmlMalloc(buffer_size * sizeof(xmlChar));
    if (buffer == NULL) {
	perror("malloc failed");
	return(NULL);
    }
    out = buffer;

    while (*cur != '\0') {
        if (out - buffer > buffer_size - 100) {
	    int indx = out - buffer;

	    growBufferReentrant();
	    out = &buffer[indx];
	}

	/*
	 * By default one have to encode at least '<', '>', '"' and '&' !
	 */
	if (*cur == '<') {
	    *out++ = '&';
	    *out++ = 'l';
	    *out++ = 't';
	    *out++ = ';';
	} else if (*cur == '>') {
	    *out++ = '&';
	    *out++ = 'g';
	    *out++ = 't';
	    *out++ = ';';
	} else if (*cur == '&') {
	    *out++ = '&';
	    *out++ = 'a';
	    *out++ = 'm';
	    *out++ = 'p';
	    *out++ = ';';
	} else if (*cur == '"') {
	    *out++ = '&';
	    *out++ = 'q';
	    *out++ = 'u';
	    *out++ = 'o';
	    *out++ = 't';
	    *out++ = ';';
#if 0
	} else if ((*cur == '\'') && (!html)) {
	    *out++ = '&';
	    *out++ = 'a';
	    *out++ = 'p';
	    *out++ = 'o';
	    *out++ = 's';
	    *out++ = ';';
#endif
	} else if (((*cur >= 0x20) && (*cur < 0x80)) ||
	    (*cur == '\n') || (*cur == '\r') || (*cur == '\t')) {
	    /*
	     * default case, just copy !
	     */
	    *out++ = *cur;
	} else if (*cur >= 0x80) {
	    if (((doc != NULL) && (doc->encoding != NULL)) || (html)) {
		/*
		 * Bjørn Reese <*****@*****.**> provided the patch
	        xmlChar xc;
	        xc = (*cur & 0x3F) << 6;
	        if (cur[1] != 0) {
		    xc += *(++cur) & 0x3F;
		    *out++ = xc;
	        } else
		 */
		    *out++ = *cur;
	    } else {
		/*
		 * We assume we have UTF-8 input.
		 */
		char buf[10], *ptr;
		int val = 0, l = 1;

		if (*cur < 0xC0) {
		    xmlGenericError(xmlGenericErrorContext,
			    "xmlEncodeEntitiesReentrant : input not UTF-8\n");
		    if (doc != NULL)
			doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1");
		    snprintf(buf, sizeof(buf), "&#%d;", *cur);
		    buf[sizeof(buf) - 1] = 0;
		    ptr = buf;
		    while (*ptr != 0) *out++ = *ptr++;
		    cur++;
		    continue;
		} else if (*cur < 0xE0) {
                    val = (cur[0]) & 0x1F;
		    val <<= 6;
		    val |= (cur[1]) & 0x3F;
		    l = 2;
		} else if (*cur < 0xF0) {
                    val = (cur[0]) & 0x0F;
		    val <<= 6;
		    val |= (cur[1]) & 0x3F;
		    val <<= 6;
		    val |= (cur[2]) & 0x3F;
		    l = 3;
		} else if (*cur < 0xF8) {
                    val = (cur[0]) & 0x07;
		    val <<= 6;
		    val |= (cur[1]) & 0x3F;
		    val <<= 6;
		    val |= (cur[2]) & 0x3F;
		    val <<= 6;
		    val |= (cur[3]) & 0x3F;
		    l = 4;
		}
		if ((l == 1) || (!IS_CHAR(val))) {
		    xmlGenericError(xmlGenericErrorContext,
			"xmlEncodeEntitiesReentrant : char out of range\n");
		    if (doc != NULL)
			doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1");
		    snprintf(buf, sizeof(buf), "&#%d;", *cur);
		    buf[sizeof(buf) - 1] = 0;
		    ptr = buf;
		    while (*ptr != 0) *out++ = *ptr++;
		    cur++;
		    continue;
		}
		/*
		 * We could do multiple things here. Just save as a char ref
		 */
		if (html)
		    snprintf(buf, sizeof(buf), "&#%d;", val);
		else
		    snprintf(buf, sizeof(buf), "&#x%X;", val);
		buf[sizeof(buf) - 1] = 0;
		ptr = buf;
		while (*ptr != 0) *out++ = *ptr++;
		cur += l;
		continue;
	    }
	} else if (IS_CHAR(*cur)) {
	    char buf[10], *ptr;

	    snprintf(buf, sizeof(buf), "&#%d;", *cur);
	    buf[sizeof(buf) - 1] = 0;
            ptr = buf;
	    while (*ptr != 0) *out++ = *ptr++;
	}
#if 0
	else {
	    /*
	     * default case, this is not a valid char !
	     * Skip it...
	     */
	    xmlGenericError(xmlGenericErrorContext,
		    "xmlEncodeEntities: invalid char %d\n", (int) *cur);
	}
#endif
	cur++;
    }
    *out++ = 0;
    return(buffer);
}
Exemplo n.º 24
0
static void
_start_element_handler_ns(void *user, const xmlChar *name, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar ** namespaces, int nb_attributes, int nb_defaulted, const xmlChar ** attributes)
{
	XML_Parser  parser = (XML_Parser) user;
	xmlChar    *qualified_name = NULL;
	xmlChar **attrs = NULL;
	int i;
	int z = 0;
	int y = 0;

	if (nb_namespaces > 0 && parser->h_start_ns != NULL) {
		for (i = 0; i < nb_namespaces; i += 1) {
			parser->h_start_ns(parser->user, (const XML_Char *) namespaces[y], (const XML_Char *) namespaces[y+1]);
			y += 2;
		}
		y = 0;
	}

	if (parser->h_start_element == NULL) {
	 	if (parser->h_default) {

			if (prefix) {
				qualified_name = xmlStrncatNew((xmlChar *)"<", prefix, xmlStrlen(prefix));
				qualified_name = xmlStrncat(qualified_name, (xmlChar *)":", 1);
				qualified_name = xmlStrncat(qualified_name, name, xmlStrlen(name));
			} else {
				qualified_name = xmlStrncatNew((xmlChar *)"<", name, xmlStrlen(name));
			}

			if (namespaces) {
				int i, j;
				for (i = 0,j = 0;j < nb_namespaces;j++) {
					int ns_len;
					char *ns_string, *ns_prefix, *ns_url;

					ns_prefix = (char *) namespaces[i++];
					ns_url = (char *) namespaces[i++];

					if (ns_prefix) {
						ns_len = spprintf(&ns_string, 0, " xmlns:%s=\"%s\"", ns_prefix, ns_url);
					} else {
						ns_len = spprintf(&ns_string, 0, " xmlns=\"%s\"", ns_url);
					}
					qualified_name = xmlStrncat(qualified_name, (xmlChar *)ns_string, ns_len);

					efree(ns_string);
				}
			}

			if (attributes) {
				for (i = 0; i < nb_attributes; i += 1) {
					int att_len;
					char *att_string, *att_name, *att_value, *att_prefix, *att_valueend;

					att_name = (char *) attributes[y++];
					att_prefix = (char *)attributes[y++];
					y++;
					att_value = (char *)attributes[y++];
					att_valueend = (char *)attributes[y++];

					if (att_prefix) {
						att_len = spprintf(&att_string, 0, " %s:%s=\"", att_prefix, att_name);
					} else {
						att_len = spprintf(&att_string, 0, " %s=\"", att_name);
					}

					qualified_name = xmlStrncat(qualified_name, (xmlChar *)att_string, att_len);
					qualified_name = xmlStrncat(qualified_name, (xmlChar *)att_value, att_valueend - att_value);
					qualified_name = xmlStrncat(qualified_name, (xmlChar *)"\"", 1);

					efree(att_string);
				}

			}
			qualified_name = xmlStrncat(qualified_name, (xmlChar *)">", 1);
			parser->h_default(parser->user, (const XML_Char *) qualified_name, xmlStrlen(qualified_name));
			xmlFree(qualified_name);
		}
		return;
	}
	_qualify_namespace(parser, name, URI, &qualified_name);

	if (attributes != NULL) {
		xmlChar    *qualified_name_attr = NULL;
		attrs = safe_emalloc((nb_attributes  * 2) + 1, sizeof(int *), 0);

		for (i = 0; i < nb_attributes; i += 1) {

			if (attributes[y+1] != NULL) {
				_qualify_namespace(parser, attributes[y] , attributes[y + 2], &qualified_name_attr);
			} else {
				qualified_name_attr = xmlStrdup(attributes[y]);
			}
			attrs[z] = qualified_name_attr;
			attrs[z + 1] = xmlStrndup(attributes[y + 3] , (int) (attributes[y + 4] - attributes[y + 3]));
			z += 2;
			y += 5;
		}

		attrs[z] = NULL;
	}
	parser->h_start_element(parser->user, (const XML_Char *) qualified_name, (const XML_Char **) attrs);
	if (attrs) {
		for (i = 0; i < z; i++) {
			xmlFree(attrs[i]);
		}
		efree(attrs);
	}
	xmlFree(qualified_name);
}
Exemplo n.º 25
0
/*
 * xmlAddEntity : register a new entity for an entities table.
 */
static xmlEntityPtr
xmlAddEntity(xmlDtdPtr dtd, const xmlChar *name, int type,
      const xmlChar *ExternalID, const xmlChar *SystemID,
      const xmlChar *content) {
    xmlEntitiesTablePtr table = NULL;
    xmlEntityPtr ret;

    if (name == NULL)
    return(NULL);
    switch (type) {
        case XML_INTERNAL_GENERAL_ENTITY:
        case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
        case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
            if (dtd->entities == NULL)
            dtd->entities = xmlHashCreate(0);
            table = (xmlEntitiesTablePtr)dtd->entities;
            break;
        case XML_INTERNAL_PARAMETER_ENTITY:
        case XML_EXTERNAL_PARAMETER_ENTITY:
            if (dtd->pentities == NULL)
            dtd->pentities = xmlHashCreate(0);
            table = (xmlEntitiesTablePtr)dtd->pentities;
            break;
        case XML_INTERNAL_PREDEFINED_ENTITY:
            return(NULL);
    }
    if (table == NULL)
        return(NULL);

    ret = (xmlEntityPtr) xmlMalloc(sizeof(xmlEntity));
    if (ret == NULL) {
        xmlGenericError(xmlGenericErrorContext, EMBED_ERRTXT("xmlAddEntity: out of memory\n"));
        // TODO: Handle OOM - cannot be distinguished from NULL result of function
        return(NULL);
    }
    memset(ret, 0, sizeof(xmlEntity));
    ret->type = XML_ENTITY_DECL;

    /*
     * fill the structure.
     */
    // TODO: Multiple xmlStrdup() calls! Avoid memory leaks in OOM!!!
    ret->name = xmlStrdup(name);
    ret->etype = (xmlEntityType) type;
    if (ExternalID != NULL)
        ret->ExternalID = xmlStrdup(ExternalID);
    if (SystemID != NULL)
        ret->SystemID = xmlStrdup(SystemID);
    if (content != NULL) {
        ret->length = xmlStrlen(content);
        ret->content = xmlStrndup(content, ret->length);
     } else {
        ret->length = 0;
        ret->content = NULL;
    }
    ret->URI = NULL; /* to be computed by the layer knowing the defining entity */
    ret->orig = NULL;
    ret->owner = 0;

    if (xmlHashAddEntry(table, name, ret)) {
        /*
        * entity was already defined at another level.
        */
        xmlFreeEntity(ret);
        return(NULL);
    }
    return(ret);
}
Exemplo n.º 26
0
static void
exsltRegexpReplaceFunction (xmlXPathParserContextPtr ctxt, int nargs)
{
    xmlChar *haystack, *regexp, *flagstr, *replace, *tmp;
    xmlChar *result = NULL, *working, *end;
    int rc, x, flags, global, ovector[3];

    if ((nargs < 1) || (nargs > 4)) {
        xmlXPathSetArityError(ctxt);
        return;
    }

    replace = xmlXPathPopString(ctxt);
    if (xmlXPathCheckError(ctxt) || (replace == NULL)) {
        return;
    }

    flagstr = xmlXPathPopString(ctxt);
    if (xmlXPathCheckError(ctxt) || (flagstr == NULL)) {
        xmlFree(replace);
        return;
    }

    regexp = xmlXPathPopString(ctxt);
    if (xmlXPathCheckError(ctxt) || (regexp == NULL)) {
        xmlFree(flagstr);
        xmlFree(replace);
        return;
    }

    haystack = xmlXPathPopString(ctxt);
    if (xmlXPathCheckError(ctxt) || (haystack == NULL)) {
        xmlFree(regexp);
        xmlFree(flagstr);
        xmlFree(replace);
        return;
    }

    exsltRegexpFlagsFromString(flagstr, &global, &flags);

    working = haystack;
    rc = exsltRegexpExecute(ctxt, working, regexp, flags, 
                            ovector, sizeof(ovector)/sizeof(int));

    while (rc > 0 ) {
      if (0==ovector[0]) {
        if (NULL==result) result = xmlStrdup(replace);
        else result = xmlStrcat(result, replace);
      }
      else {
        tmp = xmlStrsub(working, 0, ovector[0]);
        if (NULL==result) result = tmp;
        else {
          result = xmlStrcat(result, tmp);
          xmlFree(tmp);
        }
        result = xmlStrcat(result, replace);
      }
      
      working = working + ovector[1];

      if (!global) break;
      rc = exsltRegexpExecute(ctxt, working, regexp, flags, 
                              ovector, sizeof(ovector)/sizeof(int));
    }

    end = haystack + xmlUTF8Strlen(haystack);
    if (working < end ) {
        if (NULL==result) result = xmlStrdup(working);
        else {
          result = xmlStrcat(result, working);
        }
    }

fail:
    if (replace != NULL)
            xmlFree(replace);
    if (flagstr != NULL)
            xmlFree(flagstr);
    if (regexp != NULL)
            xmlFree(regexp);
    if (haystack != NULL)
            xmlFree(haystack);

    xmlXPathReturnString(ctxt, result);
}
Exemplo n.º 27
0
Datum
xpath_table(PG_FUNCTION_ARGS)
{
/* SPI (input tuple) support */
	SPITupleTable *tuptable;
	HeapTuple	spi_tuple;
	TupleDesc	spi_tupdesc;

/* Output tuple (tuplestore) support */
	Tuplestorestate *tupstore = NULL;
	TupleDesc	ret_tupdesc;
	HeapTuple	ret_tuple;

	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
	AttInMetadata *attinmeta;
	MemoryContext per_query_ctx;
	MemoryContext oldcontext;

/* Function parameters */
	char	   *pkeyfield = GET_STR(PG_GETARG_TEXT_P(0));
	char	   *xmlfield = GET_STR(PG_GETARG_TEXT_P(1));
	char	   *relname = GET_STR(PG_GETARG_TEXT_P(2));
	char	   *xpathset = GET_STR(PG_GETARG_TEXT_P(3));
	char	   *condition = GET_STR(PG_GETARG_TEXT_P(4));

	char	  **values;
	xmlChar   **xpaths;
	xmlChar    *pos;
	xmlChar    *pathsep = "|";

	int			numpaths;
	int			ret;
	int			proc;
	int			i;
	int			j;
	int			rownr;			/* For issuing multiple rows from one original
								 * document */
	int			had_values;		/* To determine end of nodeset results */

	StringInfo	querysql;

	/* We only have a valid tuple description in table function mode */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context that cannot accept a set")));
	if (rsinfo->expectedDesc == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("xpath_table must be called as a table function")));

	/*
	 * We want to materialise because it means that we don't have to carry
	 * libxml2 parser state between invocations of this function
	 */
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
			   errmsg("xpath_table requires Materialize mode, but it is not "
					  "allowed in this context")));

	/*
	 * The tuplestore must exist in a higher context than this function call
	 * (per_query_ctx is used)
	 */

	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	/*
	 * Create the tuplestore - work_mem is the max in-memory size before a
	 * file is created on disk to hold it.
	 */
	tupstore = tuplestore_begin_heap(true, false, work_mem);

	MemoryContextSwitchTo(oldcontext);

	/* get the requested return tuple description */
	ret_tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);

	/*
	 * At the moment we assume that the returned attributes make sense for the
	 * XPath specififed (i.e. we trust the caller). It's not fatal if they get
	 * it wrong - the input function for the column type will raise an error
	 * if the path result can't be converted into the correct binary
	 * representation.
	 */

	attinmeta = TupleDescGetAttInMetadata(ret_tupdesc);

	/* Set return mode and allocate value space. */
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setDesc = ret_tupdesc;

	values = (char **) palloc(ret_tupdesc->natts * sizeof(char *));

	xpaths = (xmlChar **) palloc(ret_tupdesc->natts * sizeof(xmlChar *));

	/* Split XPaths. xpathset is a writable CString. */

	/* Note that we stop splitting once we've done all needed for tupdesc */

	numpaths = 0;
	pos = xpathset;
	do
	{
		xpaths[numpaths] = pos;
		pos = strstr(pos, pathsep);
		if (pos != NULL)
		{
			*pos = '\0';
			pos++;
		}
		numpaths++;
	} while ((pos != NULL) && (numpaths < (ret_tupdesc->natts - 1)));

	/* Now build query */

	querysql = makeStringInfo();

	/* Build initial sql statement */
	appendStringInfo(querysql, "SELECT %s, %s FROM %s WHERE %s",
					 pkeyfield,
					 xmlfield,
					 relname,
					 condition
		);


	if ((ret = SPI_connect()) < 0)
		elog(ERROR, "xpath_table: SPI_connect returned %d", ret);

	if ((ret = SPI_exec(querysql->data, 0)) != SPI_OK_SELECT)
		elog(ERROR, "xpath_table: SPI execution failed for query %s", querysql->data);

	proc = SPI_processed;
	/* elog(DEBUG1,"xpath_table: SPI returned %d rows",proc); */
	tuptable = SPI_tuptable;
	spi_tupdesc = tuptable->tupdesc;

/* Switch out of SPI context */
	MemoryContextSwitchTo(oldcontext);


/* Check that SPI returned correct result. If you put a comma into one of
 * the function parameters, this will catch it when the SPI query returns
 * e.g. 3 columns.
 */

	if (spi_tupdesc->natts != 2)
	{
		ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						errmsg("Expression returning multiple columns is not valid in parameter list"),
						errdetail("Expected two columns in SPI result, got %d", spi_tupdesc->natts)));
	}

/* Setup the parser. Beware that this must happen in the same context as the
 * cleanup - which means that any error from here on must do cleanup to
 * ensure that the entity table doesn't get freed by being out of context.
 */
	pgxml_parser_init();

	/* For each row i.e. document returned from SPI */
	for (i = 0; i < proc; i++)
	{
		char	   *pkey;
		char	   *xmldoc;

		xmlDocPtr	doctree;
		xmlXPathContextPtr ctxt;
		xmlXPathObjectPtr res;
		xmlChar    *resstr;


		xmlXPathCompExprPtr comppath;

		/* Extract the row data as C Strings */

		spi_tuple = tuptable->vals[i];
		pkey = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
		xmldoc = SPI_getvalue(spi_tuple, spi_tupdesc, 2);


		/*
		 * Clear the values array, so that not-well-formed documents return
		 * NULL in all columns.
		 */

		/* Note that this also means that spare columns will be NULL. */
		for (j = 0; j < ret_tupdesc->natts; j++)
			values[j] = NULL;

		/* Insert primary key */
		values[0] = pkey;

		/* Parse the document */
		doctree = xmlParseMemory(xmldoc, strlen(xmldoc));

		if (doctree == NULL)
		{						/* not well-formed, so output all-NULL tuple */

			ret_tuple = BuildTupleFromCStrings(attinmeta, values);
			oldcontext = MemoryContextSwitchTo(per_query_ctx);
			tuplestore_puttuple(tupstore, ret_tuple);
			MemoryContextSwitchTo(oldcontext);
			heap_freetuple(ret_tuple);
		}
		else
		{
			/* New loop here - we have to deal with nodeset results */
			rownr = 0;

			do
			{
				/* Now evaluate the set of xpaths. */
				had_values = 0;
				for (j = 0; j < numpaths; j++)
				{

					ctxt = xmlXPathNewContext(doctree);
					ctxt->node = xmlDocGetRootElement(doctree);
					xmlSetGenericErrorFunc(ctxt, pgxml_errorHandler);

					/* compile the path */
					comppath = xmlXPathCompile(xpaths[j]);
					if (comppath == NULL)
					{
						xmlCleanupParser();
						xmlFreeDoc(doctree);

						elog_error(ERROR, "XPath Syntax Error", 1);

						PG_RETURN_NULL();		/* Keep compiler happy */
					}

					/* Now evaluate the path expression. */
					res = xmlXPathCompiledEval(comppath, ctxt);
					xmlXPathFreeCompExpr(comppath);

					if (res != NULL)
					{
						switch (res->type)
						{
							case XPATH_NODESET:
								/* We see if this nodeset has enough nodes */
								if ((res->nodesetval != NULL) && (rownr < res->nodesetval->nodeNr))
								{
									resstr =
										xmlXPathCastNodeToString(res->nodesetval->nodeTab[rownr]);
									had_values = 1;
								}
								else
									resstr = NULL;

								break;

							case XPATH_STRING:
								resstr = xmlStrdup(res->stringval);
								break;

							default:
								elog(NOTICE, "Unsupported XQuery result: %d", res->type);
								resstr = xmlStrdup("<unsupported/>");
						}


						/*
						 * Insert this into the appropriate column in the
						 * result tuple.
						 */
						values[j + 1] = resstr;
					}
					xmlXPathFreeContext(ctxt);
				}
				/* Now add the tuple to the output, if there is one. */
				if (had_values)
				{
					ret_tuple = BuildTupleFromCStrings(attinmeta, values);
					oldcontext = MemoryContextSwitchTo(per_query_ctx);
					tuplestore_puttuple(tupstore, ret_tuple);
					MemoryContextSwitchTo(oldcontext);
					heap_freetuple(ret_tuple);
				}

				rownr++;

			} while (had_values);

		}

		xmlFreeDoc(doctree);

		pfree(pkey);
		pfree(xmldoc);
	}

	xmlCleanupParser();
/* Needed to flag completeness in 7.3.1. 7.4 defines it as a no-op. */
	tuplestore_donestoring(tupstore);

	SPI_finish();

	rsinfo->setResult = tupstore;

	/*
	 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
	 * tuples are in our tuplestore and passed back through rsinfo->setResult.
	 * rsinfo->setDesc is set to the tuple description that we actually used
	 * to build our tuples with, so the caller can verify we did what it was
	 * expecting.
	 */
	return (Datum) 0;

}
Exemplo n.º 28
0
static void
exsltRegexpMatchFunction (xmlXPathParserContextPtr ctxt, int nargs)
{
    xsltTransformContextPtr tctxt;
    xmlNodePtr node;
    xmlDocPtr container;
    xmlXPathObjectPtr ret = NULL;
    xmlChar *haystack, *regexp, *flagstr, *working, *match;
    int rc, x, flags, global, ovector[30];

    if ((nargs < 1) || (nargs > 3)) {
        xmlXPathSetArityError(ctxt);
        return;
    }


    if (nargs > 2) {
      flagstr = xmlXPathPopString(ctxt);
      if (xmlXPathCheckError(ctxt) || (flagstr == NULL)) {
          return;
      }
    } else {
     flagstr = xmlStrdup("");
    }
    
    regexp = xmlXPathPopString(ctxt);
    if (xmlXPathCheckError(ctxt) || (regexp == NULL)) {
        xmlFree(flagstr);
        return;
    }

    haystack = xmlXPathPopString(ctxt);
    if (xmlXPathCheckError(ctxt) || (haystack == NULL)) {
        xmlFree(regexp);
        xmlFree(flagstr);
        return;
    }

    /* Return a result tree fragment */
    tctxt = xsltXPathGetTransformContext(ctxt);
    if (tctxt == NULL) {
      xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
                         "exslt:regexp : internal error tctxt == NULL\n");
      goto fail;
    }

    container = xsltCreateRVT(tctxt);
    if (container != NULL) {
      xsltRegisterTmpRVT(tctxt, container);
      ret = xmlXPathNewNodeSet(NULL);
      if (ret != NULL) {
        ret->boolval = 0; 

        exsltRegexpFlagsFromString(flagstr, &global, &flags);
        working = haystack;
        rc = exsltRegexpExecute(ctxt, working, regexp, flags, 
                                ovector, sizeof(ovector)/sizeof(int));

        while (rc > 0) {
          for(int group = 0; group < rc; group++) {
            match = xmlStrsub(working, ovector[group*2], ovector[group*2+1]-ovector[group*2]);
            if (NULL == match) goto fail;

            node = xmlNewDocRawNode(container, NULL, "match", match);
            xmlFree(match);

            xmlAddChild((xmlNodePtr) container, node);
            xmlXPathNodeSetAddUnique(ret->nodesetval, node);
          }
          if (!global) break;

          working = working + ovector[1];
          rc = exsltRegexpExecute(ctxt, working, regexp, flags, 
                                  ovector, sizeof(ovector)/sizeof(int));
        }
      }
    }
    
 fail:
    if (flagstr != NULL)
      xmlFree(flagstr);
    if (regexp != NULL)
      xmlFree(regexp);
    if (haystack != NULL)
      xmlFree(haystack);

    if (ret != NULL)
      valuePush(ctxt, ret);
    else
      valuePush(ctxt, xmlXPathNewNodeSet(NULL));
}
static void
handle_define_regex_element (ParserState *parser_state)
{
	gchar *id;
	xmlChar *regex;
	xmlChar *tmp;
	gchar *expanded_regex;
	int i;
	const gchar *regex_options[] = {"extended", "case-sensitive", "dupnames", NULL};
	GRegexCompileFlags flags;
	GError *tmp_error = NULL;

	int type;

	g_return_if_fail (parser_state->error == NULL);

	if (parser_state->ctx_data == NULL)
		return;

	tmp = xmlTextReaderGetAttribute (parser_state->reader, BAD_CAST "id");

	/* If the file is validated <define-regex> must have an id
	 * attribute */
	g_assert (tmp != NULL);

	if (id_is_decorated ((gchar *)tmp, NULL))
		id = g_strdup ((gchar *)tmp);
	else
		id = decorate_id (parser_state, (gchar *)tmp);
	xmlFree (tmp);

	flags = parser_state->regex_compile_flags;

	for (i=0; regex_options[i] != NULL; i++)
	{
		tmp = xmlTextReaderGetAttribute (parser_state->reader,
						 BAD_CAST regex_options[i]);
		if (tmp != NULL)
		{
			flags = update_regex_flags (flags,
						    BAD_CAST regex_options[i],
						    tmp);
		}
		xmlFree (tmp);
	}

	xmlTextReaderRead (parser_state->reader);

	type = xmlTextReaderNodeType (parser_state->reader);

	if (type == XML_READER_TYPE_TEXT || type == XML_READER_TYPE_CDATA)
		regex = xmlTextReaderValue (parser_state->reader);
	else
		regex = xmlStrdup (BAD_CAST "");

	expanded_regex = expand_regex (parser_state, (gchar*) regex, flags,
				       TRUE, TRUE, &tmp_error);

	if (tmp_error == NULL)
	{
		DEBUG (g_message ("defined regex %s: \"%s\"", id, (gchar *)regex));
		g_hash_table_insert (parser_state->defined_regexes, id, expanded_regex);
	}
	else
	{
		g_propagate_error (&parser_state->error, tmp_error);
		g_free (id);
	}

	xmlFree (regex);
}
Exemplo n.º 30
0
/**
 * xmlSchematronReportSuccess:
 * @ctxt:  the validation context
 * @test: the compiled test
 * @cur: the current node tested
 * @success: boolean value for the result
 *
 * called from the validation engine when an assert or report test have
 * been done.
 */
static void
xmlSchematronReportSuccess(xmlSchematronValidCtxtPtr ctxt, 
		   xmlSchematronTestPtr test, xmlNodePtr cur, xmlSchematronPatternPtr pattern, int success) {
    if ((ctxt == NULL) || (cur == NULL) || (test == NULL))
        return;
    /* if quiet and not SVRL report only failures */
    if ((ctxt->flags & XML_SCHEMATRON_OUT_QUIET) &&
        ((ctxt->flags & XML_SCHEMATRON_OUT_XML) == 0) &&
	(test->type == XML_SCHEMATRON_REPORT))
        return;
    if (ctxt->flags & XML_SCHEMATRON_OUT_XML) {
        TODO
    } else {
        xmlChar *path;
	char msg[1000];
	long line;
	const xmlChar *report = NULL;

        if (((test->type == XML_SCHEMATRON_REPORT) & (!success)) ||
	    ((test->type == XML_SCHEMATRON_ASSERT) & (success)))
	    return;
	line = xmlGetLineNo(cur);
	path = xmlGetNodePath(cur);
	if (path == NULL)
	    path = (xmlChar *) cur->name;
#if 0
	if ((test->report != NULL) && (test->report[0] != 0))
	    report = test->report;
#endif
	if (test->node != NULL)
            report = xmlSchematronFormatReport(ctxt, test->node, cur);
	if (report == NULL) {
	    if (test->type == XML_SCHEMATRON_ASSERT) {
            report = xmlStrdup((const xmlChar *) "node failed assert");
	    } else {
            report = xmlStrdup((const xmlChar *) "node failed report");
	    }
	    }
	    snprintf(msg, 999, "%s line %ld: %s\n", (const char *) path,
		     line, (const char *) report);

    if (ctxt->flags & XML_SCHEMATRON_OUT_ERROR) {
        xmlStructuredErrorFunc schannel = NULL;
        xmlGenericErrorFunc channel = NULL;
        void *data = NULL;

        if (ctxt != NULL) {
            if (ctxt->serror != NULL)
                schannel = ctxt->serror;
            else
                channel = ctxt->error;
            data = ctxt->userData;
	}

        __xmlRaiseError(schannel, channel, data,
                        NULL, cur, XML_FROM_SCHEMATRONV,
                        (test->type == XML_SCHEMATRON_ASSERT)?XML_SCHEMATRONV_ASSERT:XML_SCHEMATRONV_REPORT,
                        XML_ERR_ERROR, NULL, line,
                        (pattern == NULL)?NULL:((const char *) pattern->name),
                        (const char *) path,
                        (const char *) report, 0, 0,
                        msg);
    } else {
	xmlSchematronReportOutput(ctxt, cur, &msg[0]);
    }

    xmlFree((char *) report);

	if ((path != NULL) && (path != (xmlChar *) cur->name))
	    xmlFree(path);
    }
}