Fixed bug #594: Zebra pollutes XSLT output? For alvis and xslt
[idzebra-moved-to-github.git] / recctrl / alvis.c
1 /* $Id: alvis.c,v 1.15 2006-05-24 18:31:33 adam Exp $
2    Copyright (C) 1995-2005
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23 #include <stdio.h>
24 #include <assert.h>
25 #include <ctype.h>
26
27 #include <yaz/diagbib1.h>
28 #include <libxml/xmlversion.h>
29 #include <libxml/parser.h>
30 #include <libxml/tree.h>
31 #include <libxml/xmlIO.h>
32 #include <libxml/xmlreader.h>
33 #include <libxslt/transform.h>
34
35 #include <idzebra/util.h>
36 #include <idzebra/recctrl.h>
37
38 struct filter_schema {
39     const char *name;
40     const char *identifier;
41     const char *stylesheet;
42     struct filter_schema *next;
43     const char *default_schema;
44     /* char default_schema; */
45     const char *include_snippet;
46     xsltStylesheetPtr stylesheet_xsp;
47 };
48
49 struct filter_info {
50     xmlDocPtr doc;
51     char *fname;
52     const char *split_level;
53     const char *split_path;
54     ODR odr;
55     struct filter_schema *schemas;
56     xmlTextReaderPtr reader;
57 };
58
59 #define ZEBRA_SCHEMA_XSLT_NS "http://indexdata.dk/zebra/xslt/1"
60
61 #define XML_STRCMP(a,b)   strcmp((char*)a, b)
62 #define XML_STRLEN(a) strlen((char*)a)
63
64 static const char *zebra_xslt_ns = ZEBRA_SCHEMA_XSLT_NS;
65
66 static void set_param_xml(const char **params, const char *name,
67                           const char *value, ODR odr)
68 {
69     while (*params)
70         params++;
71     params[0] = name;
72     params[1] = value;
73     params[2] = 0;
74 }
75
76 static void set_param_str(const char **params, const char *name,
77                           const char *value, ODR odr)
78 {
79     char *quoted = odr_malloc(odr, 3 + strlen(value));
80     sprintf(quoted, "'%s'", value);
81     while (*params)
82         params++;
83     params[0] = name;
84     params[1] = quoted;
85     params[2] = 0;
86 }
87
88 static void set_param_int(const char **params, const char *name,
89                           zint value, ODR odr)
90 {
91     char *quoted = odr_malloc(odr, 30); /* 25 digits enough for 2^64 */
92     while (*params)
93         params++;
94     sprintf(quoted, "'" ZINT_FORMAT "'", value);
95     params[0] = name;
96     params[1] = quoted;
97     params[2] = 0;
98 }
99
100 #define ENABLE_INPUT_CALLBACK 0
101
102 #if ENABLE_INPUT_CALLBACK
103 static int zebra_xmlInputMatchCallback (char const *filename)
104 {
105     yaz_log(YLOG_LOG, "match %s", filename);
106     return 0;
107 }
108
109 static void * zebra_xmlInputOpenCallback (char const *filename)
110 {
111     return 0;
112 }
113
114 static int zebra_xmlInputReadCallback (void * context, char * buffer, int len)
115 {
116     return 0;
117 }
118
119 static int zebra_xmlInputCloseCallback (void * context)
120 {
121     return 0;
122 }
123 #endif
124
125 static void *filter_init(Res res, RecType recType)
126 {
127     struct filter_info *tinfo = (struct filter_info *) xmalloc(sizeof(*tinfo));
128     tinfo->reader = 0;
129     tinfo->fname = 0;
130     tinfo->split_level = 0;
131     tinfo->split_path = 0;
132     tinfo->odr = odr_createmem(ODR_ENCODE);
133     tinfo->doc = 0;
134     tinfo->schemas = 0;
135
136 #if ENABLE_INPUT_CALLBACK
137     xmlRegisterDefaultInputCallbacks();
138     xmlRegisterInputCallbacks(zebra_xmlInputMatchCallback,
139                               zebra_xmlInputOpenCallback,
140                               zebra_xmlInputReadCallback,
141                               zebra_xmlInputCloseCallback);
142 #endif
143     return tinfo;
144 }
145
146 static int attr_content(struct _xmlAttr *attr, const char *name,
147                         const char **dst_content)
148 {
149     if (!XML_STRCMP(attr->name, name) && attr->children &&
150         attr->children->type == XML_TEXT_NODE)
151     {
152         *dst_content = (const char *)(attr->children->content);
153         return 1;
154     }
155     return 0;
156 }
157
158 static void destroy_schemas(struct filter_info *tinfo)
159 {
160     struct filter_schema *schema = tinfo->schemas;
161     while (schema)
162     {
163         struct filter_schema *schema_next = schema->next;
164         if (schema->stylesheet_xsp)
165             xsltFreeStylesheet(schema->stylesheet_xsp);
166         xfree(schema);
167         schema = schema_next;
168     }
169     tinfo->schemas = 0;
170     xfree(tinfo->fname);
171     if (tinfo->doc)
172         xmlFreeDoc(tinfo->doc);    
173     tinfo->doc = 0;
174 }
175
176 static ZEBRA_RES create_schemas(struct filter_info *tinfo, const char *fname)
177 {
178     xmlNodePtr ptr;
179     tinfo->fname = xstrdup(fname);
180     tinfo->doc = xmlParseFile(tinfo->fname);
181     if (!tinfo->doc)
182         return ZEBRA_FAIL;
183     ptr = xmlDocGetRootElement(tinfo->doc);
184     if (!ptr || ptr->type != XML_ELEMENT_NODE ||
185         XML_STRCMP(ptr->name, "schemaInfo"))
186         return ZEBRA_FAIL;
187     for (ptr = ptr->children; ptr; ptr = ptr->next)
188     {
189         if (ptr->type != XML_ELEMENT_NODE)
190             continue;
191         if (!XML_STRCMP(ptr->name, "schema"))
192         {
193             struct _xmlAttr *attr;
194             struct filter_schema *schema = xmalloc(sizeof(*schema));
195             schema->name = 0;
196             schema->identifier = 0;
197             schema->stylesheet = 0;
198             schema->default_schema = 0;
199             schema->next = tinfo->schemas;
200             schema->stylesheet_xsp = 0;
201             schema->include_snippet = 0;
202             tinfo->schemas = schema;
203             for (attr = ptr->properties; attr; attr = attr->next)
204             {
205                 attr_content(attr, "identifier", &schema->identifier);
206                 attr_content(attr, "name", &schema->name);
207                 attr_content(attr, "stylesheet", &schema->stylesheet);
208                 attr_content(attr, "default", &schema->default_schema);
209                 attr_content(attr, "snippet", &schema->include_snippet);
210             }
211             /*yaz_log(YLOG_LOG, "XSLT add %s %s %s", 
212               schema->name, schema->identifier, schema->stylesheet); */
213
214             /* find requested schema */
215
216             if (schema->stylesheet)
217                 schema->stylesheet_xsp =
218                     xsltParseStylesheetFile(
219                         (const xmlChar*) schema->stylesheet);
220
221                 
222         }
223         else if (!XML_STRCMP(ptr->name, "split"))
224         {
225             struct _xmlAttr *attr;
226             for (attr = ptr->properties; attr; attr = attr->next)
227             {
228                 attr_content(attr, "level", &tinfo->split_level);
229                 attr_content(attr, "path", &tinfo->split_path);
230             }
231         }
232         else
233         {
234             yaz_log(YLOG_WARN, "Bad element %s in %s", ptr->name, fname);
235             return ZEBRA_FAIL;
236         }
237     }
238     return ZEBRA_OK;
239 }
240
241 static struct filter_schema *lookup_schema(struct filter_info *tinfo,
242                                            const char *est)
243 {
244     struct filter_schema *schema;
245
246     for (schema = tinfo->schemas; schema; schema = schema->next)
247     { 
248         /* find requested schema */
249         if (est) 
250         {    
251             if (schema->identifier && !strcmp(schema->identifier, est))
252                 return schema;
253             
254             if (schema->name && !strcmp(schema->name, est))
255                 return schema;
256         } 
257         /* or return default schema if defined */
258         else if (schema->default_schema)
259             return schema;
260     }
261
262     /* return first schema if no default schema defined */
263     if (tinfo->schemas)
264         return tinfo->schemas;
265     
266     return 0;
267 }
268
269 static ZEBRA_RES filter_config(void *clientData, Res res, const char *args)
270 {
271     struct filter_info *tinfo = clientData;
272     if (!args || !*args)
273         return ZEBRA_FAIL;
274     if (tinfo->fname && !strcmp(args, tinfo->fname))
275         return ZEBRA_OK;
276     destroy_schemas(tinfo);
277     create_schemas(tinfo, args);
278     return ZEBRA_OK;
279 }
280
281 static void filter_destroy(void *clientData)
282 {
283     struct filter_info *tinfo = clientData;
284     destroy_schemas(tinfo);
285     if (tinfo->reader)
286         xmlFreeTextReader(tinfo->reader);
287     odr_destroy(tinfo->odr);
288     xfree(tinfo);
289 }
290
291 static int ioread_ex(void *context, char *buffer, int len)
292 {
293     struct recExtractCtrl *p = context;
294     return (*p->readf)(p->fh, buffer, len);
295 }
296
297 static int ioclose_ex(void *context)
298 {
299     return 0;
300 }
301
302 static void index_cdata(struct filter_info *tinfo, struct recExtractCtrl *ctrl,
303                         xmlNodePtr ptr, RecWord *recWord)
304 {
305     for(; ptr; ptr = ptr->next)
306     {
307         index_cdata(tinfo, ctrl, ptr->children, recWord);
308         if (ptr->type != XML_TEXT_NODE)
309             continue;
310         recWord->term_buf = (const char *)ptr->content;
311         recWord->term_len = XML_STRLEN(ptr->content);
312         (*ctrl->tokenAdd)(recWord);
313     }
314 }
315
316 static void index_node(struct filter_info *tinfo,  struct recExtractCtrl *ctrl,
317                        xmlNodePtr ptr, RecWord *recWord)
318 {
319     for(; ptr; ptr = ptr->next)
320     {
321         index_node(tinfo, ctrl, ptr->children, recWord);
322         if (ptr->type != XML_ELEMENT_NODE || !ptr->ns ||
323             XML_STRCMP(ptr->ns->href, zebra_xslt_ns))
324             continue;
325         if (!XML_STRCMP(ptr->name, "index"))
326         {
327             const char *name_str = 0;
328             const char *type_str = 0;
329             const char *xpath_str = 0;
330             struct _xmlAttr *attr;
331             for (attr = ptr->properties; attr; attr = attr->next)
332             {
333                 attr_content(attr, "name", &name_str);
334                 attr_content(attr, "xpath", &xpath_str);
335                 attr_content(attr, "type", &type_str);
336             }
337             if (name_str)
338             {
339                 int prev_type = recWord->index_type; /* save default type */
340
341                 if (type_str && *type_str)
342                     recWord->index_type = *type_str; /* type was given */
343                 recWord->index_name = name_str;
344                 index_cdata(tinfo, ctrl, ptr->children, recWord);
345
346                 recWord->index_type = prev_type;     /* restore it again */
347             }
348         }
349     }
350 }
351
352 static void index_record(struct filter_info *tinfo,struct recExtractCtrl *ctrl,
353                          xmlNodePtr ptr, RecWord *recWord)
354 {
355     if (ptr && ptr->type == XML_ELEMENT_NODE && ptr->ns &&
356         !XML_STRCMP(ptr->ns->href, zebra_xslt_ns)
357         && !XML_STRCMP(ptr->name, "record"))
358     {
359         const char *type_str = "update";
360         const char *id_str = 0;
361         const char *rank_str = 0;
362         struct _xmlAttr *attr;
363         for (attr = ptr->properties; attr; attr = attr->next)
364         {
365             attr_content(attr, "type", &type_str);
366             attr_content(attr, "id", &id_str);
367             attr_content(attr, "rank", &rank_str);
368         }
369         if (id_str)
370             sscanf(id_str, "%255s", ctrl->match_criteria);
371         if (rank_str)
372         {
373             ctrl->staticrank = atoi(rank_str);
374             yaz_log(YLOG_LOG, "rank=%d",ctrl->staticrank);
375         }
376         else
377             yaz_log(YLOG_LOG, "no rank");
378         
379         ptr = ptr->children;
380     }
381     index_node(tinfo, ctrl, ptr, recWord);
382 }
383     
384 static int extract_doc(struct filter_info *tinfo, struct recExtractCtrl *p,
385                        xmlDocPtr doc)
386 {
387     RecWord recWord;
388     const char *params[10];
389     xmlChar *buf_out;
390     int len_out;
391
392     struct filter_schema *schema = lookup_schema(tinfo, zebra_xslt_ns);
393
394     params[0] = 0;
395     set_param_str(params, "schema", zebra_xslt_ns, tinfo->odr);
396
397     (*p->init)(p, &recWord);
398
399     if (schema && schema->stylesheet_xsp)
400     {
401         xmlNodePtr root_ptr;
402         xmlDocPtr resDoc = 
403             xsltApplyStylesheet(schema->stylesheet_xsp,
404                                 doc, params);
405         if (p->flagShowRecords)
406         {
407             xmlDocDumpMemory(resDoc, &buf_out, &len_out);
408             fwrite(buf_out, len_out, 1, stdout);
409             xmlFree(buf_out);
410         }
411         root_ptr = xmlDocGetRootElement(resDoc);
412         if (root_ptr)
413             index_record(tinfo, p, root_ptr, &recWord);
414         else
415         {
416             yaz_log(YLOG_WARN, "No root for index XML record."
417                     " split_level=%s stylesheet=%s",
418                     tinfo->split_level, schema->stylesheet);
419         }
420         xmlFreeDoc(resDoc);
421     }
422     xmlDocDumpMemory(doc, &buf_out, &len_out);
423     if (p->flagShowRecords)
424         fwrite(buf_out, len_out, 1, stdout);
425     (*p->setStoreData)(p, buf_out, len_out);
426     xmlFree(buf_out);
427     
428     xmlFreeDoc(doc);
429     return RECCTRL_EXTRACT_OK;
430 }
431
432 static int extract_split(struct filter_info *tinfo, struct recExtractCtrl *p)
433 {
434     int ret;
435     int split_depth = 0;
436     if (p->first_record)
437     {
438         if (tinfo->reader)
439             xmlFreeTextReader(tinfo->reader);
440         tinfo->reader = xmlReaderForIO(ioread_ex, ioclose_ex,
441                                        p /* I/O handler */,
442                                        0 /* URL */, 
443                                        0 /* encoding */,
444                                        XML_PARSE_XINCLUDE);
445     }
446     if (!tinfo->reader)
447         return RECCTRL_EXTRACT_ERROR_GENERIC;
448
449     if (tinfo->split_level)
450         split_depth = atoi(tinfo->split_level);
451     ret = xmlTextReaderRead(tinfo->reader);
452     while (ret == 1) {
453         int type = xmlTextReaderNodeType(tinfo->reader);
454         int depth = xmlTextReaderDepth(tinfo->reader);
455         if (split_depth == 0 ||
456             (split_depth > 0 &&
457              type == XML_READER_TYPE_ELEMENT && split_depth == depth))
458         {
459             xmlNodePtr ptr = xmlTextReaderExpand(tinfo->reader);
460             xmlNodePtr ptr2 = xmlCopyNode(ptr, 1);
461             xmlDocPtr doc = xmlNewDoc((const xmlChar*) "1.0");
462
463             xmlDocSetRootElement(doc, ptr2);
464
465             return extract_doc(tinfo, p, doc);   
466         }
467         ret = xmlTextReaderRead(tinfo->reader);
468     }
469     xmlFreeTextReader(tinfo->reader);
470     tinfo->reader = 0;
471     return RECCTRL_EXTRACT_EOF;
472 }
473
474 static int extract_full(struct filter_info *tinfo, struct recExtractCtrl *p)
475 {
476     if (p->first_record) /* only one record per stream */
477     {
478         xmlDocPtr doc = xmlReadIO(ioread_ex, ioclose_ex, p /* I/O handler */,
479                                   0 /* URL */,
480                                   0 /* encoding */,
481                                   XML_PARSE_XINCLUDE);
482         if (!doc)
483         {
484             return RECCTRL_EXTRACT_ERROR_GENERIC;
485         }
486         return extract_doc(tinfo, p, doc);
487     }
488     else
489         return RECCTRL_EXTRACT_EOF;
490 }
491
492 static int filter_extract(void *clientData, struct recExtractCtrl *p)
493 {
494     struct filter_info *tinfo = clientData;
495
496     odr_reset(tinfo->odr);
497
498     if (tinfo->split_level == 0 && tinfo->split_path == 0)
499         return extract_full(tinfo, p);
500     else
501     {
502         return extract_split(tinfo, p);
503     }
504 }
505
506 static int ioread_ret(void *context, char *buffer, int len)
507 {
508     struct recRetrieveCtrl *p = context;
509     return (*p->readf)(p->fh, buffer, len);
510 }
511
512 static int ioclose_ret(void *context)
513 {
514     return 0;
515 }
516
517
518 static const char *snippet_doc(struct recRetrieveCtrl *p, int text_mode,
519                                int window_size)
520 {
521     const char *xml_doc_str;
522     int ord = 0;
523     WRBUF wrbuf = wrbuf_alloc();
524     zebra_snippets *res = 
525         zebra_snippets_window(p->doc_snippet, p->hit_snippet, window_size);
526     zebra_snippet_word *w = zebra_snippets_list(res);
527
528     if (text_mode)
529         wrbuf_printf(wrbuf, "\'");
530     else
531         wrbuf_printf(wrbuf, "<snippet xmlns='%s'>\n", zebra_xslt_ns);
532     for (; w; w = w->next)
533     {
534         if (ord == 0)
535             ord = w->ord;
536         else if (ord != w->ord)
537
538             break;
539         if (text_mode)
540             wrbuf_printf(wrbuf, "%s%s%s ", 
541                          w->match ? "*" : "",
542                          w->term,
543                          w->match ? "*" : "");
544         else
545         {
546             wrbuf_printf(wrbuf, " <term ord='%d' seqno='" ZINT_FORMAT "' %s>", 
547                          w->ord, w->seqno,
548                          (w->match ? "match='1'" : ""));
549             wrbuf_xmlputs(wrbuf, w->term);
550             wrbuf_printf(wrbuf, "</term>\n");
551         }
552     }
553     if (text_mode)
554         wrbuf_printf(wrbuf, "\'");
555     else
556         wrbuf_printf(wrbuf, "</snippet>\n");
557
558     xml_doc_str = odr_strdup(p->odr, wrbuf_buf(wrbuf));
559
560     zebra_snippets_destroy(res);
561     wrbuf_free(wrbuf, 1);
562     return xml_doc_str;
563 }
564
565 static int filter_retrieve (void *clientData, struct recRetrieveCtrl *p)
566 {
567     /* const char *esn = zebra_xslt_ns; */
568     const char *esn = 0;
569     const char *params[32];
570     struct filter_info *tinfo = clientData;
571     xmlDocPtr resDoc;
572     xmlDocPtr doc;
573     struct filter_schema *schema;
574     int window_size = -1;
575
576     if (p->comp)
577     {
578         if (p->comp->which == Z_RecordComp_simple
579             && p->comp->u.simple->which == Z_ElementSetNames_generic)
580         {
581             esn = p->comp->u.simple->u.generic;
582         }
583         else if (p->comp->which == Z_RecordComp_complex 
584                  && p->comp->u.complex->generic->elementSpec
585                  && p->comp->u.complex->generic->elementSpec->which ==
586                  Z_ElementSpec_elementSetName)
587         {
588             esn = p->comp->u.complex->generic->elementSpec->u.elementSetName;
589         }
590     }
591     schema = lookup_schema(tinfo, esn);
592     if (!schema)
593     {
594         p->diagnostic =
595             YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
596         return 0;
597     }
598
599     if (schema->include_snippet)
600         window_size = atoi(schema->include_snippet);
601
602     params[0] = 0;
603     set_param_int(params, "id", p->localno, p->odr);
604     if (p->fname)
605         set_param_str(params, "filename", p->fname, p->odr);
606     if (p->staticrank >= 0)
607         set_param_int(params, "rank", p->staticrank, p->odr);
608
609     if (esn)
610         set_param_str(params, "schema", esn, p->odr);
611     else
612         if (schema->name)
613             set_param_str(params, "schema", schema->name, p->odr);
614         else if (schema->identifier)
615             set_param_str(params, "schema", schema->identifier, p->odr);
616         else
617             set_param_str(params, "schema", "", p->odr);
618
619     if (p->score >= 0)
620         set_param_int(params, "score", p->score, p->odr);
621     set_param_int(params, "size", p->recordSize, p->odr);
622
623     if (window_size >= 0)
624         set_param_xml(params, "snippet", snippet_doc(p, 1, window_size),
625                       p->odr);
626     doc = xmlReadIO(ioread_ret, ioclose_ret, p /* I/O handler */,
627                     0 /* URL */,
628                     0 /* encoding */,
629                     XML_PARSE_XINCLUDE);
630     if (!doc)
631     {
632         p->diagnostic = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
633         return 0;
634     }
635
636     if (window_size >= 0)
637     {
638         xmlNodePtr node = xmlDocGetRootElement(doc);
639         const char *snippet_str = snippet_doc(p, 0, window_size);
640         xmlDocPtr snippet_doc = xmlParseMemory(snippet_str, strlen(snippet_str));
641         xmlAddChild(node, xmlDocGetRootElement(snippet_doc));
642     }
643     if (!schema->stylesheet_xsp)
644         resDoc = doc;
645     else
646     {
647         resDoc = xsltApplyStylesheet(schema->stylesheet_xsp,
648                                      doc, params);
649         xmlFreeDoc(doc);
650     }
651     if (!resDoc)
652     {
653         p->diagnostic = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
654     }
655     else if (p->input_format == VAL_NONE || p->input_format == VAL_TEXT_XML)
656     {
657         xmlChar *buf_out;
658         int len_out;
659
660         xsltSaveResultToString(&buf_out, &len_out, resDoc,
661                                schema->stylesheet_xsp); 
662
663         p->output_format = VAL_TEXT_XML;
664         p->rec_len = len_out;
665         p->rec_buf = odr_malloc(p->odr, p->rec_len);
666         memcpy(p->rec_buf, buf_out, p->rec_len);
667         xmlFree(buf_out);
668     }
669     else if (p->output_format == VAL_SUTRS)
670     {
671         xmlChar *buf_out;
672         int len_out;
673
674         xsltSaveResultToString(&buf_out, &len_out, resDoc,
675                                schema->stylesheet_xsp); 
676
677         p->output_format = VAL_SUTRS;
678         p->rec_len = len_out;
679         p->rec_buf = odr_malloc(p->odr, p->rec_len);
680         memcpy(p->rec_buf, buf_out, p->rec_len);
681         
682         xmlFree(buf_out);
683     }
684     else
685     {
686         p->diagnostic = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
687     }
688     xmlFreeDoc(resDoc);
689     return 0;
690 }
691
692 static struct recType filter_type = {
693     0,
694     "alvis",
695     filter_init,
696     filter_config,
697     filter_destroy,
698     filter_extract,
699     filter_retrieve
700 };
701
702 RecType
703 #ifdef IDZEBRA_STATIC_ALVIS
704 idzebra_filter_alvis
705 #else
706 idzebra_filter
707 #endif
708
709 [] = {
710     &filter_type,
711     0,
712 };
713 /*
714  * Local variables:
715  * c-basic-offset: 4
716  * indent-tabs-mode: nil
717  * End:
718  * vim: shiftwidth=4 tabstop=8 expandtab
719  */
720