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