+#if YAZ_HAVE_XML2
+static int replace_node(NMEM nmem, xmlNode *ptr,
+ const char *type_spec, char *record_buf)
+{
+ int ret = -1;
+ const char *res;
+ int len;
+ int m_len;
+ WRBUF wrbuf = wrbuf_alloc();
+ ODR odr = odr_createmem(ODR_ENCODE);
+ Z_NamePlusRecord *npr = odr_malloc(odr, sizeof(*npr));
+ npr->which = Z_NamePlusRecord_databaseRecord;
+
+ if (atoi_n_check(record_buf, 5, &m_len))
+ npr->u.databaseRecord =
+ z_ext_record_usmarc(odr, record_buf, strlen(record_buf));
+ else
+ npr->u.databaseRecord =
+ z_ext_record_xml(odr, record_buf, strlen(record_buf));
+ res = yaz_record_render(npr, 0, wrbuf, type_spec, &len);
+ if (res)
+ {
+ xmlDoc *doc = xmlParseMemory(res, strlen(res));
+ if (doc)
+ {
+ xmlNode *nptr = xmlCopyNode(xmlDocGetRootElement(doc), 1);
+ xmlReplaceNode(ptr, nptr);
+ xmlFreeDoc(doc);
+ }
+ else
+ {
+ xmlNode *nptr = xmlNewText(BAD_CAST res);
+ xmlReplaceNode(ptr, nptr);
+ }
+ ret = 0;
+ }
+ wrbuf_destroy(wrbuf);
+ odr_destroy(odr);
+ return ret;
+}
+#endif
+
+static const char *base64_render(NMEM nmem, WRBUF wrbuf,
+ const char *buf, int *len,
+ const char *expr, const char *type_spec)
+{
+#if YAZ_HAVE_XML2
+ xmlDocPtr doc = xmlParseMemory(buf, *len);
+ if (doc)
+ {
+ xmlChar *buf_out;
+ int len_out;
+ xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
+ if (xpathCtx)
+ {
+ xmlXPathObjectPtr xpathObj =
+ xmlXPathEvalExpression((const xmlChar *) expr, xpathCtx);
+ if (xpathObj)
+ {
+ xmlNodeSetPtr nodes = xpathObj->nodesetval;
+ if (nodes)
+ {
+ int i;
+ for (i = 0; i < nodes->nodeNr; i++)
+ {
+ xmlNode *ptr = nodes->nodeTab[i];
+ if (ptr->type == XML_TEXT_NODE)
+ {
+ const char *input =
+ nmem_text_node_cdata(ptr, nmem);
+ char *output = nmem_malloc(
+ nmem, strlen(input) + 1);
+ if (yaz_base64decode(input, output) == 0)
+ {
+ if (!replace_node(nmem, ptr, type_spec, output))
+ {
+ /* replacement OK */
+ xmlFreeNode(ptr);
+ /* unset below to avoid a bad reference in
+ xmlXPathFreeObject below */
+ nodes->nodeTab[i] = 0;
+ }
+ }
+ }
+ }
+ }
+ xmlXPathFreeObject(xpathObj);
+ }
+ xmlXPathFreeContext(xpathCtx);
+ }
+ xmlDocDumpMemory(doc, &buf_out, &len_out);
+ if (buf_out)
+ {
+ wrbuf_rewind(wrbuf);
+ wrbuf_write(wrbuf, (const char *) buf_out, len_out);
+ buf = wrbuf_cstr(wrbuf);
+ *len = len_out;
+ }
+ xmlFreeDoc(doc);
+ xmlFree(buf_out);
+ }
+#endif
+ return buf;
+}
+