Added some type casts to avoid warnings produced by GCC 4.
[idzebra-moved-to-github.git] / recctrl / xslt.c
1 /* $Id: xslt.c,v 1.14 2005-08-19 21:41:37 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     const char *include_snippet;
45     xsltStylesheetPtr stylesheet_xsp;
46 };
47
48 struct filter_info {
49     xmlDocPtr doc;
50     char *fname;
51     const char *split_level;
52     const char *split_path;
53     ODR odr;
54     struct filter_schema *schemas;
55     xmlTextReaderPtr reader;
56 };
57
58 #define ZEBRA_SCHEMA_XSLT_NS "http://indexdata.dk/zebra/xslt/1"
59
60 #define XML_STRCMP(a,b)   strcmp((char*)a, b)
61 #define XML_STRLEN(a) strlen((char*)a)
62
63 static const char *zebra_xslt_ns = ZEBRA_SCHEMA_XSLT_NS;
64
65 static void set_param_xml(const char **params, const char *name,
66                           const char *value, ODR odr)
67 {
68     while (*params)
69         params++;
70     params[0] = name;
71     params[1] = value;
72     params[2] = 0;
73 }
74
75 static void set_param_str(const char **params, const char *name,
76                           const char *value, ODR odr)
77 {
78     char *quoted = odr_malloc(odr, 3 + strlen(value));
79     sprintf(quoted, "'%s'", value);
80     while (*params)
81         params++;
82     params[0] = name;
83     params[1] = quoted;
84     params[2] = 0;
85 }
86
87 static void set_param_int(const char **params, const char *name,
88                           zint value, ODR odr)
89 {
90     char *quoted = odr_malloc(odr, 30); /* 25 digits enough for 2^64 */
91     while (*params)
92         params++;
93     sprintf(quoted, "'" ZINT_FORMAT "'", value);
94     params[0] = name;
95     params[1] = quoted;
96     params[2] = 0;
97 }
98
99 static int zebra_xmlInputMatchCallback (char const *filename)
100 {
101     yaz_log(YLOG_LOG, "match %s", filename);
102     return 0;
103 }
104
105 static void * zebra_xmlInputOpenCallback (char const *filename)
106 {
107     return 0;
108 }
109
110 static int zebra_xmlInputReadCallback (void * context, char * buffer, int len)
111 {
112     return 0;
113 }
114
115 static int zebra_xmlInputCloseCallback (void * context)
116 {
117     return 0;
118 }
119
120 static void *filter_init_xslt(Res res, RecType recType)
121 {
122     struct filter_info *tinfo = (struct filter_info *) xmalloc(sizeof(*tinfo));
123     tinfo->reader = 0;
124     tinfo->fname = 0;
125     tinfo->split_level = 0;
126     tinfo->split_path = 0;
127     tinfo->odr = odr_createmem(ODR_ENCODE);
128     tinfo->doc = 0;
129     tinfo->schemas = 0;
130
131 #if 0
132     xmlRegisterDefaultInputCallbacks();
133     xmlRegisterInputCallbacks(zebra_xmlInputMatchCallback,
134                               zebra_xmlInputOpenCallback,
135                               zebra_xmlInputReadCallback,
136                               zebra_xmlInputCloseCallback);
137 #endif
138     return tinfo;
139 }
140
141 static int attr_content(struct _xmlAttr *attr, const char *name,
142                         const char **dst_content)
143 {
144     if (!XML_STRCMP(attr->name, name) && attr->children &&
145         attr->children->type == XML_TEXT_NODE)
146     {
147         *dst_content = (const char *)(attr->children->content);
148         return 1;
149     }
150     return 0;
151 }
152
153 static void destroy_schemas(struct filter_info *tinfo)
154 {
155     struct filter_schema *schema = tinfo->schemas;
156     while (schema)
157     {
158         struct filter_schema *schema_next = schema->next;
159         if (schema->stylesheet_xsp)
160             xsltFreeStylesheet(schema->stylesheet_xsp);
161         xfree(schema);
162         schema = schema_next;
163     }
164     tinfo->schemas = 0;
165     xfree(tinfo->fname);
166     if (tinfo->doc)
167         xmlFreeDoc(tinfo->doc);    
168     tinfo->doc = 0;
169 }
170
171 static ZEBRA_RES create_schemas(struct filter_info *tinfo, const char *fname)
172 {
173     xmlNodePtr ptr;
174     tinfo->fname = xstrdup(fname);
175     tinfo->doc = xmlParseFile(tinfo->fname);
176     if (!tinfo->doc)
177         return ZEBRA_FAIL;
178     ptr = xmlDocGetRootElement(tinfo->doc);
179     if (!ptr || ptr->type != XML_ELEMENT_NODE ||
180         XML_STRCMP(ptr->name, "schemaInfo"))
181         return ZEBRA_FAIL;
182     for (ptr = ptr->children; ptr; ptr = ptr->next)
183     {
184         if (ptr->type != XML_ELEMENT_NODE)
185             continue;
186         if (!XML_STRCMP(ptr->name, "schema"))
187         {
188             struct _xmlAttr *attr;
189             struct filter_schema *schema = xmalloc(sizeof(*schema));
190             schema->name = 0;
191             schema->identifier = 0;
192             schema->stylesheet = 0;
193             schema->default_schema = 0;
194             schema->next = tinfo->schemas;
195             schema->stylesheet_xsp = 0;
196             schema->include_snippet = 0;
197             tinfo->schemas = schema;
198             for (attr = ptr->properties; attr; attr = attr->next)
199             {
200                 attr_content(attr, "identifier", &schema->identifier);
201                 attr_content(attr, "name", &schema->name);
202                 attr_content(attr, "stylesheet", &schema->stylesheet);
203                 attr_content(attr, "default", &schema->default_schema);
204                 attr_content(attr, "snippet", &schema->include_snippet);
205             }
206             if (schema->stylesheet)
207                 schema->stylesheet_xsp =
208                     xsltParseStylesheetFile(
209                         (const xmlChar*) schema->stylesheet);
210         }
211         else if (!XML_STRCMP(ptr->name, "split"))
212         {
213             struct _xmlAttr *attr;
214             for (attr = ptr->properties; attr; attr = attr->next)
215             {
216                 attr_content(attr, "level", &tinfo->split_level);
217                 attr_content(attr, "path", &tinfo->split_path);
218             }
219         }
220         else
221         {
222             yaz_log(YLOG_WARN, "Bad element %s in %s", ptr->name, fname);
223             return ZEBRA_FAIL;
224         }
225     }
226     return ZEBRA_OK;
227 }
228
229 static struct filter_schema *lookup_schema(struct filter_info *tinfo,
230                                            const char *est)
231 {
232     struct filter_schema *schema;
233     for (schema = tinfo->schemas; schema; schema = schema->next)
234     {
235         if (est)
236         {
237             if (schema->identifier && !strcmp(schema->identifier, est))
238                 return schema;
239             if (schema->name && !strcmp(schema->name, est))
240                 return schema;
241         }
242         if (schema->default_schema)
243             return schema;
244     }
245     return 0;
246 }
247
248 static void filter_config(void *clientData, Res res, const char *args)
249 {
250     struct filter_info *tinfo = clientData;
251     if (!args || !*args)
252         args = "xsltfilter.xml";
253     if (tinfo->fname && !strcmp(args, tinfo->fname))
254         return;
255     destroy_schemas(tinfo);
256     create_schemas(tinfo, args);
257 }
258
259 static void filter_destroy(void *clientData)
260 {
261     struct filter_info *tinfo = clientData;
262     destroy_schemas(tinfo);
263     if (tinfo->reader)
264         xmlFreeTextReader(tinfo->reader);
265     odr_destroy(tinfo->odr);
266     xfree(tinfo);
267 }
268
269 static int ioread_ex(void *context, char *buffer, int len)
270 {
271     struct recExtractCtrl *p = context;
272     return (*p->readf)(p->fh, buffer, len);
273 }
274
275 static int ioclose_ex(void *context)
276 {
277     return 0;
278 }
279
280 static void index_cdata(struct filter_info *tinfo, struct recExtractCtrl *ctrl,
281                         xmlNodePtr ptr, RecWord *recWord)
282 {
283     for(; ptr; ptr = ptr->next)
284     {
285         index_cdata(tinfo, ctrl, ptr->children, recWord);
286         if (ptr->type != XML_TEXT_NODE)
287             continue;
288         recWord->term_buf = (const char *)ptr->content;
289         recWord->term_len = XML_STRLEN(ptr->content);
290         (*ctrl->tokenAdd)(recWord);
291     }
292 }
293
294 static void index_node(struct filter_info *tinfo,  struct recExtractCtrl *ctrl,
295                        xmlNodePtr ptr, RecWord *recWord)
296 {
297     for(; ptr; ptr = ptr->next)
298     {
299         index_node(tinfo, ctrl, ptr->children, recWord);
300         if (ptr->type != XML_ELEMENT_NODE || !ptr->ns ||
301             XML_STRCMP(ptr->ns->href, zebra_xslt_ns))
302             continue;
303         if (!XML_STRCMP(ptr->name, "index"))
304         {
305             const char *name_str = 0;
306             const char *type_str = 0;
307             const char *xpath_str = 0;
308             struct _xmlAttr *attr;
309             for (attr = ptr->properties; attr; attr = attr->next)
310             {
311                 attr_content(attr, "name", &name_str);
312                 attr_content(attr, "xpath", &xpath_str);
313                 attr_content(attr, "type", &type_str);
314             }
315             if (name_str)
316             {
317                 int prev_type = recWord->index_type; /* save default type */
318
319                 if (type_str && *type_str)
320                     recWord->index_type = *type_str; /* type was given */
321                 recWord->index_name = name_str;
322                 index_cdata(tinfo, ctrl, ptr->children, recWord);
323
324                 recWord->index_type = prev_type;     /* restore it again */
325             }
326         }
327     }
328 }
329
330 static void index_record(struct filter_info *tinfo,struct recExtractCtrl *ctrl,
331                          xmlNodePtr ptr, RecWord *recWord)
332 {
333     if (ptr && ptr->type == XML_ELEMENT_NODE && ptr->ns &&
334         !XML_STRCMP(ptr->ns->href, zebra_xslt_ns)
335         && !XML_STRCMP(ptr->name, "record"))
336     {
337         const char *type_str = "update";
338         const char *id_str = 0;
339         const char *rank_str = 0;
340         struct _xmlAttr *attr;
341         for (attr = ptr->properties; attr; attr = attr->next)
342         {
343             attr_content(attr, "type", &type_str);
344             attr_content(attr, "id", &id_str);
345             attr_content(attr, "rank", &rank_str);
346         }
347         if (id_str)
348             sscanf(id_str, "%255s", ctrl->match_criteria);
349         if (rank_str)
350         {
351             ctrl->staticrank = atoi(rank_str);
352             yaz_log(YLOG_LOG, "rank=%d",ctrl->staticrank);
353         }
354         else
355             yaz_log(YLOG_LOG, "no rank");
356         
357         ptr = ptr->children;
358     }
359     index_node(tinfo, ctrl, ptr, recWord);
360 }
361     
362 static int extract_doc(struct filter_info *tinfo, struct recExtractCtrl *p,
363                        xmlDocPtr doc)
364 {
365     RecWord recWord;
366     const char *params[10];
367     xmlChar *buf_out;
368     int len_out;
369
370     struct filter_schema *schema = lookup_schema(tinfo, zebra_xslt_ns);
371
372     params[0] = 0;
373     set_param_str(params, "schema", zebra_xslt_ns, tinfo->odr);
374
375     (*p->init)(p, &recWord);
376
377     if (schema && schema->stylesheet_xsp)
378     {
379         xmlNodePtr root_ptr;
380         xmlDocPtr resDoc = 
381             xsltApplyStylesheet(schema->stylesheet_xsp,
382                                 doc, params);
383         if (p->flagShowRecords)
384         {
385             xmlDocDumpMemory(resDoc, &buf_out, &len_out);
386             fwrite(buf_out, len_out, 1, stdout);
387             xmlFree(buf_out);
388         }
389         root_ptr = xmlDocGetRootElement(resDoc);
390         if (root_ptr)
391             index_record(tinfo, p, root_ptr, &recWord);
392         else
393         {
394             yaz_log(YLOG_WARN, "No root for index XML record."
395                     " split_level=%s stylesheet=%s",
396                     tinfo->split_level, schema->stylesheet);
397         }
398         xmlFreeDoc(resDoc);
399     }
400     xmlDocDumpMemory(doc, &buf_out, &len_out);
401     if (p->flagShowRecords)
402         fwrite(buf_out, len_out, 1, stdout);
403     (*p->setStoreData)(p, buf_out, len_out);
404     xmlFree(buf_out);
405     
406     xmlFreeDoc(doc);
407     return RECCTRL_EXTRACT_OK;
408 }
409
410 static int extract_split(struct filter_info *tinfo, struct recExtractCtrl *p)
411 {
412     int ret;
413     int split_depth = 0;
414     if (p->first_record)
415     {
416         if (tinfo->reader)
417             xmlFreeTextReader(tinfo->reader);
418         tinfo->reader = xmlReaderForIO(ioread_ex, ioclose_ex,
419                                        p /* I/O handler */,
420                                        0 /* URL */, 
421                                        0 /* encoding */,
422                                        XML_PARSE_XINCLUDE);
423     }
424     if (!tinfo->reader)
425         return RECCTRL_EXTRACT_ERROR_GENERIC;
426
427     if (tinfo->split_level)
428         split_depth = atoi(tinfo->split_level);
429     ret = xmlTextReaderRead(tinfo->reader);
430     while (ret == 1) {
431         int type = xmlTextReaderNodeType(tinfo->reader);
432         int depth = xmlTextReaderDepth(tinfo->reader);
433         if (split_depth == 0 ||
434             (split_depth > 0 &&
435              type == XML_READER_TYPE_ELEMENT && split_depth == depth))
436         {
437             xmlNodePtr ptr = xmlTextReaderExpand(tinfo->reader);
438             xmlNodePtr ptr2 = xmlCopyNode(ptr, 1);
439             xmlDocPtr doc = xmlNewDoc((const xmlChar*) "1.0");
440
441             xmlDocSetRootElement(doc, ptr2);
442
443             return extract_doc(tinfo, p, doc);      
444         }
445         ret = xmlTextReaderRead(tinfo->reader);
446     }
447     xmlFreeTextReader(tinfo->reader);
448     tinfo->reader = 0;
449     return RECCTRL_EXTRACT_EOF;
450 }
451
452 static int extract_full(struct filter_info *tinfo, struct recExtractCtrl *p)
453 {
454     if (p->first_record) /* only one record per stream */
455     {
456         xmlDocPtr doc = xmlReadIO(ioread_ex, ioclose_ex, p /* I/O handler */,
457                                   0 /* URL */,
458                                   0 /* encoding */,
459                                   XML_PARSE_XINCLUDE);
460         if (!doc)
461         {
462             return RECCTRL_EXTRACT_ERROR_GENERIC;
463         }
464         return extract_doc(tinfo, p, doc);
465     }
466     else
467         return RECCTRL_EXTRACT_EOF;
468 }
469
470 static int filter_extract(void *clientData, struct recExtractCtrl *p)
471 {
472     struct filter_info *tinfo = clientData;
473
474     odr_reset(tinfo->odr);
475
476     if (tinfo->split_level == 0 && tinfo->split_path == 0)
477         return extract_full(tinfo, p);
478     else
479     {
480         return extract_split(tinfo, p);
481     }
482 }
483
484 static int ioread_ret(void *context, char *buffer, int len)
485 {
486     struct recRetrieveCtrl *p = context;
487     return (*p->readf)(p->fh, buffer, len);
488 }
489
490 static int ioclose_ret(void *context)
491 {
492     return 0;
493 }
494
495
496 static const char *snippet_doc(struct recRetrieveCtrl *p, int text_mode,
497                                int window_size)
498 {
499     const char *xml_doc_str;
500     int ord = 0;
501     WRBUF wrbuf = wrbuf_alloc();
502     zebra_snippets *res = 
503         zebra_snippets_window(p->doc_snippet, p->hit_snippet, window_size);
504     zebra_snippet_word *w = zebra_snippets_list(res);
505
506     if (text_mode)
507         wrbuf_printf(wrbuf, "\'");
508     else
509         wrbuf_printf(wrbuf, "<snippet xmlns='%s'>\n", zebra_xslt_ns);
510     for (; w; w = w->next)
511     {
512         if (ord == 0)
513             ord = w->ord;
514         else if (ord != w->ord)
515
516             break;
517         if (text_mode)
518             wrbuf_printf(wrbuf, "%s%s%s ", 
519                          w->match ? "*" : "",
520                          w->term,
521                          w->match ? "*" : "");
522         else
523         {
524             wrbuf_printf(wrbuf, " <term ord='%d' seqno='" ZINT_FORMAT "' %s>", 
525                          w->ord, w->seqno,
526                          (w->match ? "match='1'" : ""));
527             wrbuf_xmlputs(wrbuf, w->term);
528             wrbuf_printf(wrbuf, "</term>\n");
529         }
530     }
531     if (text_mode)
532         wrbuf_printf(wrbuf, "\'");
533     else
534         wrbuf_printf(wrbuf, "</snippet>\n");
535
536     xml_doc_str = odr_strdup(p->odr, wrbuf_buf(wrbuf));
537
538     zebra_snippets_destroy(res);
539     wrbuf_free(wrbuf, 1);
540     return xml_doc_str;
541 }
542
543 static int filter_retrieve (void *clientData, struct recRetrieveCtrl *p)
544 {
545     const char *esn = zebra_xslt_ns;
546     const char *params[10];
547     struct filter_info *tinfo = clientData;
548     xmlDocPtr resDoc;
549     xmlDocPtr doc;
550     struct filter_schema *schema;
551     int window_size = -1;
552
553     if (p->comp)
554     {
555         if (p->comp->which != Z_RecordComp_simple
556             || p->comp->u.simple->which != Z_ElementSetNames_generic)
557         {
558             p->diagnostic = YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP;
559             return 0;
560         }
561         esn = p->comp->u.simple->u.generic;
562     }
563     schema = lookup_schema(tinfo, esn);
564     if (!schema)
565     {
566         p->diagnostic =
567             YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
568         return 0;
569     }
570
571     if (schema->include_snippet)
572         window_size = atoi(schema->include_snippet);
573
574     params[0] = 0;
575     set_param_str(params, "schema", esn, p->odr);
576     if (p->fname)
577         set_param_str(params, "filename", p->fname, p->odr);
578     if (p->score >= 0)
579         set_param_int(params, "score", p->score, p->odr);
580     set_param_int(params, "size", p->recordSize, p->odr);
581     set_param_int(params, "id", p->localno, p->odr);
582
583     if (window_size >= 0)
584         set_param_xml(params, "snippet", snippet_doc(p, 1, window_size),
585                       p->odr);
586     doc = xmlReadIO(ioread_ret, ioclose_ret, p /* I/O handler */,
587                     0 /* URL */,
588                     0 /* encoding */,
589                     XML_PARSE_XINCLUDE);
590     if (!doc)
591     {
592         p->diagnostic = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
593         return 0;
594     }
595
596     if (window_size >= 0)
597     {
598         xmlNodePtr node = xmlDocGetRootElement(doc);
599         const char *snippet_str = snippet_doc(p, 0, window_size);
600         xmlDocPtr snippet_doc = xmlParseMemory(snippet_str, strlen(snippet_str));
601         xmlAddChild(node, xmlDocGetRootElement(snippet_doc));
602     }
603     if (!schema->stylesheet_xsp)
604         resDoc = doc;
605     else
606     {
607         resDoc = xsltApplyStylesheet(schema->stylesheet_xsp,
608                                      doc, params);
609         xmlFreeDoc(doc);
610     }
611     if (!resDoc)
612     {
613         p->diagnostic = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
614     }
615     else if (p->input_format == VAL_NONE || p->input_format == VAL_TEXT_XML)
616     {
617         xmlChar *buf_out;
618         int len_out;
619         xmlDocDumpMemory(resDoc, &buf_out, &len_out);
620
621         p->output_format = VAL_TEXT_XML;
622         p->rec_len = len_out;
623         p->rec_buf = odr_malloc(p->odr, p->rec_len);
624         memcpy(p->rec_buf, buf_out, p->rec_len);
625         
626         xmlFree(buf_out);
627     }
628     else if (p->output_format == VAL_SUTRS)
629     {
630         xmlChar *buf_out;
631         int len_out;
632         xmlDocDumpMemory(resDoc, &buf_out, &len_out);
633
634         p->output_format = VAL_SUTRS;
635         p->rec_len = len_out;
636         p->rec_buf = odr_malloc(p->odr, p->rec_len);
637         memcpy(p->rec_buf, buf_out, p->rec_len);
638         
639         xmlFree(buf_out);
640     }
641     else
642     {
643         p->diagnostic = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
644     }
645     xmlFreeDoc(resDoc);
646     return 0;
647 }
648
649 static struct recType filter_type_xslt = {
650     0,
651     "xslt",
652     filter_init_xslt,
653     filter_config,
654     filter_destroy,
655     filter_extract,
656     filter_retrieve
657 };
658
659 RecType
660 #ifdef IDZEBRA_STATIC_XSLT
661 idzebra_filter_xslt
662 #else
663 idzebra_filter
664 #endif
665
666 [] = {
667     &filter_type_xslt,
668     0,
669 };