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