added support for default retrieval schema other than indexing schema
[idzebra-moved-to-github.git] / recctrl / alvis.c
1 /* $Id: alvis.c,v 1.12 2006-05-23 15:21:58 marc 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             if (schema->stylesheet)
212                 schema->stylesheet_xsp =
213                     xsltParseStylesheetFile(
214                         (const xmlChar*) schema->stylesheet);
215
216                 
217         }
218         else if (!XML_STRCMP(ptr->name, "split"))
219         {
220             struct _xmlAttr *attr;
221             for (attr = ptr->properties; attr; attr = attr->next)
222             {
223                 attr_content(attr, "level", &tinfo->split_level);
224                 attr_content(attr, "path", &tinfo->split_path);
225             }
226         }
227         else
228         {
229             yaz_log(YLOG_WARN, "Bad element %s in %s", ptr->name, fname);
230             return ZEBRA_FAIL;
231         }
232     }
233     return ZEBRA_OK;
234 }
235
236 static struct filter_schema *lookup_schema(struct filter_info *tinfo,
237                                            const char *est)
238 {
239     struct filter_schema *schema;
240     for (schema = tinfo->schemas; schema; schema = schema->next)
241     {
242         /* find requested schema */
243         if (est) 
244         {
245             if (schema->identifier && !strcmp(schema->identifier, est))
246                 return schema;
247             if (schema->name && !strcmp(schema->name, est))
248                 return schema;
249         }
250
251         /* or return default schema if defined */
252         if (schema->default_schema)
253             return schema;
254     }
255
256     /* return first schema if no default schema defined */
257     if (tinfo->schemas)
258         return tinfo->schemas;
259     
260     return 0;
261 }
262
263 static ZEBRA_RES filter_config(void *clientData, Res res, const char *args)
264 {
265     struct filter_info *tinfo = clientData;
266     if (!args || !*args)
267         return ZEBRA_FAIL;
268     if (tinfo->fname && !strcmp(args, tinfo->fname))
269         return ZEBRA_OK;
270     destroy_schemas(tinfo);
271     create_schemas(tinfo, args);
272     return ZEBRA_OK;
273 }
274
275 static void filter_destroy(void *clientData)
276 {
277     struct filter_info *tinfo = clientData;
278     destroy_schemas(tinfo);
279     if (tinfo->reader)
280         xmlFreeTextReader(tinfo->reader);
281     odr_destroy(tinfo->odr);
282     xfree(tinfo);
283 }
284
285 static int ioread_ex(void *context, char *buffer, int len)
286 {
287     struct recExtractCtrl *p = context;
288     return (*p->readf)(p->fh, buffer, len);
289 }
290
291 static int ioclose_ex(void *context)
292 {
293     return 0;
294 }
295
296 static void index_cdata(struct filter_info *tinfo, struct recExtractCtrl *ctrl,
297                         xmlNodePtr ptr, RecWord *recWord)
298 {
299     for(; ptr; ptr = ptr->next)
300     {
301         index_cdata(tinfo, ctrl, ptr->children, recWord);
302         if (ptr->type != XML_TEXT_NODE)
303             continue;
304         recWord->term_buf = (const char *)ptr->content;
305         recWord->term_len = XML_STRLEN(ptr->content);
306         (*ctrl->tokenAdd)(recWord);
307     }
308 }
309
310 static void index_node(struct filter_info *tinfo,  struct recExtractCtrl *ctrl,
311                        xmlNodePtr ptr, RecWord *recWord)
312 {
313     for(; ptr; ptr = ptr->next)
314     {
315         index_node(tinfo, ctrl, ptr->children, recWord);
316         if (ptr->type != XML_ELEMENT_NODE || !ptr->ns ||
317             XML_STRCMP(ptr->ns->href, zebra_xslt_ns))
318             continue;
319         if (!XML_STRCMP(ptr->name, "index"))
320         {
321             const char *name_str = 0;
322             const char *type_str = 0;
323             const char *xpath_str = 0;
324             struct _xmlAttr *attr;
325             for (attr = ptr->properties; attr; attr = attr->next)
326             {
327                 attr_content(attr, "name", &name_str);
328                 attr_content(attr, "xpath", &xpath_str);
329                 attr_content(attr, "type", &type_str);
330             }
331             if (name_str)
332             {
333                 int prev_type = recWord->index_type; /* save default type */
334
335                 if (type_str && *type_str)
336                     recWord->index_type = *type_str; /* type was given */
337                 recWord->index_name = name_str;
338                 index_cdata(tinfo, ctrl, ptr->children, recWord);
339
340                 recWord->index_type = prev_type;     /* restore it again */
341             }
342         }
343     }
344 }
345
346 static void index_record(struct filter_info *tinfo,struct recExtractCtrl *ctrl,
347                          xmlNodePtr ptr, RecWord *recWord)
348 {
349     if (ptr && ptr->type == XML_ELEMENT_NODE && ptr->ns &&
350         !XML_STRCMP(ptr->ns->href, zebra_xslt_ns)
351         && !XML_STRCMP(ptr->name, "record"))
352     {
353         const char *type_str = "update";
354         const char *id_str = 0;
355         const char *rank_str = 0;
356         struct _xmlAttr *attr;
357         for (attr = ptr->properties; attr; attr = attr->next)
358         {
359             attr_content(attr, "type", &type_str);
360             attr_content(attr, "id", &id_str);
361             attr_content(attr, "rank", &rank_str);
362         }
363         if (id_str)
364             sscanf(id_str, "%255s", ctrl->match_criteria);
365         if (rank_str)
366         {
367             ctrl->staticrank = atoi(rank_str);
368             yaz_log(YLOG_LOG, "rank=%d",ctrl->staticrank);
369         }
370         else
371             yaz_log(YLOG_LOG, "no rank");
372         
373         ptr = ptr->children;
374     }
375     index_node(tinfo, ctrl, ptr, recWord);
376 }
377     
378 static int extract_doc(struct filter_info *tinfo, struct recExtractCtrl *p,
379                        xmlDocPtr doc)
380 {
381     RecWord recWord;
382     const char *params[10];
383     xmlChar *buf_out;
384     int len_out;
385
386     struct filter_schema *schema = lookup_schema(tinfo, zebra_xslt_ns);
387
388     params[0] = 0;
389     set_param_str(params, "schema", zebra_xslt_ns, tinfo->odr);
390
391     (*p->init)(p, &recWord);
392
393     if (schema && schema->stylesheet_xsp)
394     {
395         xmlNodePtr root_ptr;
396         xmlDocPtr resDoc = 
397             xsltApplyStylesheet(schema->stylesheet_xsp,
398                                 doc, params);
399         if (p->flagShowRecords)
400         {
401             xmlDocDumpMemory(resDoc, &buf_out, &len_out);
402             fwrite(buf_out, len_out, 1, stdout);
403             xmlFree(buf_out);
404         }
405         root_ptr = xmlDocGetRootElement(resDoc);
406         if (root_ptr)
407             index_record(tinfo, p, root_ptr, &recWord);
408         else
409         {
410             yaz_log(YLOG_WARN, "No root for index XML record."
411                     " split_level=%s stylesheet=%s",
412                     tinfo->split_level, schema->stylesheet);
413         }
414         xmlFreeDoc(resDoc);
415     }
416     xmlDocDumpMemory(doc, &buf_out, &len_out);
417     if (p->flagShowRecords)
418         fwrite(buf_out, len_out, 1, stdout);
419     (*p->setStoreData)(p, buf_out, len_out);
420     xmlFree(buf_out);
421     
422     xmlFreeDoc(doc);
423     return RECCTRL_EXTRACT_OK;
424 }
425
426 static int extract_split(struct filter_info *tinfo, struct recExtractCtrl *p)
427 {
428     int ret;
429     int split_depth = 0;
430     if (p->first_record)
431     {
432         if (tinfo->reader)
433             xmlFreeTextReader(tinfo->reader);
434         tinfo->reader = xmlReaderForIO(ioread_ex, ioclose_ex,
435                                        p /* I/O handler */,
436                                        0 /* URL */, 
437                                        0 /* encoding */,
438                                        XML_PARSE_XINCLUDE);
439     }
440     if (!tinfo->reader)
441         return RECCTRL_EXTRACT_ERROR_GENERIC;
442
443     if (tinfo->split_level)
444         split_depth = atoi(tinfo->split_level);
445     ret = xmlTextReaderRead(tinfo->reader);
446     while (ret == 1) {
447         int type = xmlTextReaderNodeType(tinfo->reader);
448         int depth = xmlTextReaderDepth(tinfo->reader);
449         if (split_depth == 0 ||
450             (split_depth > 0 &&
451              type == XML_READER_TYPE_ELEMENT && split_depth == depth))
452         {
453             xmlNodePtr ptr = xmlTextReaderExpand(tinfo->reader);
454             xmlNodePtr ptr2 = xmlCopyNode(ptr, 1);
455             xmlDocPtr doc = xmlNewDoc((const xmlChar*) "1.0");
456
457             xmlDocSetRootElement(doc, ptr2);
458
459             return extract_doc(tinfo, p, doc);   
460         }
461         ret = xmlTextReaderRead(tinfo->reader);
462     }
463     xmlFreeTextReader(tinfo->reader);
464     tinfo->reader = 0;
465     return RECCTRL_EXTRACT_EOF;
466 }
467
468 static int extract_full(struct filter_info *tinfo, struct recExtractCtrl *p)
469 {
470     if (p->first_record) /* only one record per stream */
471     {
472         xmlDocPtr doc = xmlReadIO(ioread_ex, ioclose_ex, p /* I/O handler */,
473                                   0 /* URL */,
474                                   0 /* encoding */,
475                                   XML_PARSE_XINCLUDE);
476         if (!doc)
477         {
478             return RECCTRL_EXTRACT_ERROR_GENERIC;
479         }
480         return extract_doc(tinfo, p, doc);
481     }
482     else
483         return RECCTRL_EXTRACT_EOF;
484 }
485
486 static int filter_extract(void *clientData, struct recExtractCtrl *p)
487 {
488     struct filter_info *tinfo = clientData;
489
490     odr_reset(tinfo->odr);
491
492     if (tinfo->split_level == 0 && tinfo->split_path == 0)
493         return extract_full(tinfo, p);
494     else
495     {
496         return extract_split(tinfo, p);
497     }
498 }
499
500 static int ioread_ret(void *context, char *buffer, int len)
501 {
502     struct recRetrieveCtrl *p = context;
503     return (*p->readf)(p->fh, buffer, len);
504 }
505
506 static int ioclose_ret(void *context)
507 {
508     return 0;
509 }
510
511
512 static const char *snippet_doc(struct recRetrieveCtrl *p, int text_mode,
513                                int window_size)
514 {
515     const char *xml_doc_str;
516     int ord = 0;
517     WRBUF wrbuf = wrbuf_alloc();
518     zebra_snippets *res = 
519         zebra_snippets_window(p->doc_snippet, p->hit_snippet, window_size);
520     zebra_snippet_word *w = zebra_snippets_list(res);
521
522     if (text_mode)
523         wrbuf_printf(wrbuf, "\'");
524     else
525         wrbuf_printf(wrbuf, "<snippet xmlns='%s'>\n", zebra_xslt_ns);
526     for (; w; w = w->next)
527     {
528         if (ord == 0)
529             ord = w->ord;
530         else if (ord != w->ord)
531
532             break;
533         if (text_mode)
534             wrbuf_printf(wrbuf, "%s%s%s ", 
535                          w->match ? "*" : "",
536                          w->term,
537                          w->match ? "*" : "");
538         else
539         {
540             wrbuf_printf(wrbuf, " <term ord='%d' seqno='" ZINT_FORMAT "' %s>", 
541                          w->ord, w->seqno,
542                          (w->match ? "match='1'" : ""));
543             wrbuf_xmlputs(wrbuf, w->term);
544             wrbuf_printf(wrbuf, "</term>\n");
545         }
546     }
547     if (text_mode)
548         wrbuf_printf(wrbuf, "\'");
549     else
550         wrbuf_printf(wrbuf, "</snippet>\n");
551
552     xml_doc_str = odr_strdup(p->odr, wrbuf_buf(wrbuf));
553
554     zebra_snippets_destroy(res);
555     wrbuf_free(wrbuf, 1);
556     return xml_doc_str;
557 }
558
559 static int filter_retrieve (void *clientData, struct recRetrieveCtrl *p)
560 {
561     /* const char *esn = zebra_xslt_ns; */
562     const char *esn = 0;
563     const char *params[32];
564     struct filter_info *tinfo = clientData;
565     xmlDocPtr resDoc;
566     xmlDocPtr doc;
567     struct filter_schema *schema;
568     int window_size = -1;
569
570     if (p->comp)
571     {
572         if (p->comp->which == Z_RecordComp_simple
573             && p->comp->u.simple->which == Z_ElementSetNames_generic)
574         {
575             esn = p->comp->u.simple->u.generic;
576         }
577         else if (p->comp->which == Z_RecordComp_complex 
578                  && p->comp->u.complex->generic->elementSpec
579                  && p->comp->u.complex->generic->elementSpec->which ==
580                  Z_ElementSpec_elementSetName)
581         {
582             esn = p->comp->u.complex->generic->elementSpec->u.elementSetName;
583         }
584     }
585     schema = lookup_schema(tinfo, esn);
586     if (!schema)
587     {
588         p->diagnostic =
589             YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
590         return 0;
591     }
592
593     if (schema->include_snippet)
594         window_size = atoi(schema->include_snippet);
595
596     params[0] = 0;
597     set_param_int(params, "id", p->localno, p->odr);
598     if (p->fname)
599         set_param_str(params, "filename", p->fname, p->odr);
600     if (p->staticrank >= 0)
601         set_param_int(params, "rank", p->staticrank, p->odr);
602     if (esn)
603         set_param_str(params, "schema", esn, p->odr);
604     else
605         set_param_str(params, "schema", "", p->odr);
606     /* should use default elem set here .. */
607     if (p->score >= 0)
608         set_param_int(params, "score", p->score, p->odr);
609     set_param_int(params, "size", p->recordSize, p->odr);
610
611     if (window_size >= 0)
612         set_param_xml(params, "snippet", snippet_doc(p, 1, window_size),
613                       p->odr);
614     doc = xmlReadIO(ioread_ret, ioclose_ret, p /* I/O handler */,
615                     0 /* URL */,
616                     0 /* encoding */,
617                     XML_PARSE_XINCLUDE);
618     if (!doc)
619     {
620         p->diagnostic = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
621         return 0;
622     }
623
624     if (window_size >= 0)
625     {
626         xmlNodePtr node = xmlDocGetRootElement(doc);
627         const char *snippet_str = snippet_doc(p, 0, window_size);
628         xmlDocPtr snippet_doc = xmlParseMemory(snippet_str, strlen(snippet_str));
629         xmlAddChild(node, xmlDocGetRootElement(snippet_doc));
630     }
631     if (!schema->stylesheet_xsp)
632         resDoc = doc;
633     else
634     {
635         resDoc = xsltApplyStylesheet(schema->stylesheet_xsp,
636                                      doc, params);
637         xmlFreeDoc(doc);
638     }
639     if (!resDoc)
640     {
641         p->diagnostic = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
642     }
643     else if (p->input_format == VAL_NONE || p->input_format == VAL_TEXT_XML)
644     {
645         xmlChar *buf_out;
646         int len_out;
647         xmlDocDumpMemory(resDoc, &buf_out, &len_out);
648
649         p->output_format = VAL_TEXT_XML;
650         p->rec_len = len_out;
651         p->rec_buf = odr_malloc(p->odr, p->rec_len);
652         memcpy(p->rec_buf, buf_out, p->rec_len);
653         
654         xmlFree(buf_out);
655     }
656     else if (p->output_format == VAL_SUTRS)
657     {
658         xmlChar *buf_out;
659         int len_out;
660         xmlDocDumpMemory(resDoc, &buf_out, &len_out);
661
662         p->output_format = VAL_SUTRS;
663         p->rec_len = len_out;
664         p->rec_buf = odr_malloc(p->odr, p->rec_len);
665         memcpy(p->rec_buf, buf_out, p->rec_len);
666         
667         xmlFree(buf_out);
668     }
669     else
670     {
671         p->diagnostic = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
672     }
673     xmlFreeDoc(resDoc);
674     return 0;
675 }
676
677 static struct recType filter_type = {
678     0,
679     "alvis",
680     filter_init,
681     filter_config,
682     filter_destroy,
683     filter_extract,
684     filter_retrieve
685 };
686
687 RecType
688 #ifdef IDZEBRA_STATIC_ALVIS
689 idzebra_filter_alvis
690 #else
691 idzebra_filter
692 #endif
693
694 [] = {
695     &filter_type,
696     0,
697 };
698 /*
699  * Local variables:
700  * c-basic-offset: 4
701  * indent-tabs-mode: nil
702  * End:
703  * vim: shiftwidth=4 tabstop=8 expandtab
704  */
705