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