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