closing bug #928 by dropping DOM document to xmlbuffer and re-reading into DOM each...
[idzebra-moved-to-github.git] / index / mod_dom.c
1 /* $Id: mod_dom.c,v 1.23 2007-02-28 14:46:41 marc Exp $
2    Copyright (C) 1995-2007
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 this program; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
21 */
22
23 #include <stdio.h>
24 #include <assert.h>
25 #include <ctype.h>
26 #include <stdarg.h>
27
28 #include <yaz/diagbib1.h>
29 #include <yaz/tpath.h>
30 #include <yaz/snprintf.h>
31
32 #include <libxml/xmlversion.h>
33 #include <libxml/parser.h>
34 #include <libxml/tree.h>
35 #include <libxml/xmlIO.h>
36 #include <libxml/xmlreader.h>
37 #include <libxslt/transform.h>
38 #include <libxslt/xsltutils.h>
39
40 #if YAZ_HAVE_EXSLT
41 #include <libexslt/exslt.h>
42 #endif
43
44 #include <idzebra/util.h>
45 #include <idzebra/recctrl.h>
46
47 /* DOM filter style indexing */
48 #define ZEBRA_DOM_NS "http://indexdata.com/zebra-2.0"
49 static const char *zebra_dom_ns = ZEBRA_DOM_NS;
50
51 /* DOM filter style indexing */
52 #define ZEBRA_PI_NAME "zebra-2.0"
53 static const char *zebra_pi_name = ZEBRA_PI_NAME;
54
55
56
57 struct convert_s {
58     const char *stylesheet;
59     xsltStylesheetPtr stylesheet_xsp;
60     struct convert_s *next;
61 };
62
63 struct filter_extract {
64     const char *name;
65     struct convert_s *convert;
66 };
67
68 struct filter_store {
69     struct convert_s *convert;
70 };
71
72 struct filter_retrieve {
73     const char *name;
74     const char *identifier;
75     struct convert_s *convert;
76     struct filter_retrieve *next;
77 };
78
79 #define DOM_INPUT_XMLREADER 1
80 #define DOM_INPUT_MARC 2
81 struct filter_input {
82     const char *syntax;
83     const char *name;
84     struct convert_s *convert;
85     int type;
86     union {
87         struct {
88             const char *input_charset;
89             yaz_marc_t handle;
90             yaz_iconv_t iconv;
91         } marc;
92         struct {
93             xmlTextReaderPtr reader;
94             int split_level;
95         } xmlreader;
96     } u;
97     struct filter_input *next;
98 };
99   
100 struct filter_info {
101     char *fname;
102     char *full_name;
103     const char *profile_path;
104     ODR odr_record;
105     ODR odr_config;
106     xmlDocPtr doc_config;
107     struct filter_extract *extract;
108     struct filter_retrieve *retrieve_list;
109     struct filter_input *input_list;
110     struct filter_store *store;
111 };
112
113
114
115 #define XML_STRCMP(a,b)   strcmp((char*)a, b)
116 #define XML_STRLEN(a) strlen((char*)a)
117
118
119 #define FOR_EACH_ELEMENT(ptr) for (; ptr; ptr = ptr->next) if (ptr->type == XML_ELEMENT_NODE)
120
121 static void dom_log(int level, struct filter_info *tinfo, xmlNodePtr ptr,
122                     const char *fmt, ...)
123 #ifdef __GNUC__
124     __attribute__ ((format (printf, 4, 5)))
125 #endif
126     ;
127
128 static void dom_log(int level, struct filter_info *tinfo, xmlNodePtr ptr,
129                     const char *fmt, ...)
130 {
131     va_list ap;
132     char buf[4096];
133
134     va_start(ap, fmt);
135     yaz_vsnprintf(buf, sizeof(buf)-1, fmt, ap);
136     if (ptr)
137     {
138         yaz_log(level, "%s:%ld: %s", tinfo->fname ? tinfo->fname : "none", 
139                 xmlGetLineNo(ptr), buf);
140     }
141     else
142     {
143         yaz_log(level, "%s: %s", tinfo->fname ? tinfo->fname : "none", buf);
144     }
145     va_end(ap);
146 }
147
148
149 static void set_param_str(const char **params, const char *name,
150                           const char *value, ODR odr)
151 {
152     char *quoted = odr_malloc(odr, 3 + strlen(value));
153     sprintf(quoted, "'%s'", value);
154     while (*params)
155         params++;
156     params[0] = name;
157     params[1] = quoted;
158     params[2] = 0;
159 }
160
161 static void set_param_int(const char **params, const char *name,
162                           zint value, ODR odr)
163 {
164     char *quoted = odr_malloc(odr, 30); /* 25 digits enough for 2^64 */
165     while (*params)
166         params++;
167     sprintf(quoted, "'" ZINT_FORMAT "'", value);
168     params[0] = name;
169     params[1] = quoted;
170     params[2] = 0;
171 }
172
173 static void *filter_init(Res res, RecType recType)
174 {
175     struct filter_info *tinfo = (struct filter_info *) xmalloc(sizeof(*tinfo));
176     tinfo->fname = 0;
177     tinfo->full_name = 0;
178     tinfo->profile_path = 0;
179     tinfo->odr_record = odr_createmem(ODR_ENCODE);
180     tinfo->odr_config = odr_createmem(ODR_ENCODE);
181     tinfo->extract = 0;
182     tinfo->retrieve_list = 0;
183     tinfo->input_list = 0;
184     tinfo->store = 0;
185     tinfo->doc_config = 0;
186
187 #if YAZ_HAVE_EXSLT
188     exsltRegisterAll(); 
189 #endif
190
191     return tinfo;
192 }
193
194 static int attr_content(struct _xmlAttr *attr, const char *name,
195                         const char **dst_content)
196 {
197     if (!XML_STRCMP(attr->name, name) && attr->children 
198         && attr->children->type == XML_TEXT_NODE)
199     {
200         *dst_content = (const char *)(attr->children->content);
201         return 1;
202     }
203     return 0;
204 }
205
206 static void destroy_xsp(struct convert_s *c)
207 {
208     while(c)
209     {
210         if (c->stylesheet_xsp)
211             xsltFreeStylesheet(c->stylesheet_xsp);
212         c = c->next;
213     }
214 }
215
216 static void destroy_dom(struct filter_info *tinfo)
217 {
218     if (tinfo->extract)
219     {
220         destroy_xsp(tinfo->extract->convert);
221         tinfo->extract = 0;
222     }
223     if (tinfo->store)
224     {
225         destroy_xsp(tinfo->store->convert);
226         tinfo->store = 0;
227     }
228     if (tinfo->input_list)
229     {
230         struct filter_input *i_ptr;
231         for (i_ptr = tinfo->input_list; i_ptr; i_ptr = i_ptr->next)
232         {
233             switch(i_ptr->type)
234             {
235             case DOM_INPUT_XMLREADER:
236                 if (i_ptr->u.xmlreader.reader)
237                     xmlFreeTextReader(i_ptr->u.xmlreader.reader);
238                 break;
239             case DOM_INPUT_MARC:
240                 yaz_iconv_close(i_ptr->u.marc.iconv);
241                 yaz_marc_destroy(i_ptr->u.marc.handle);
242                 break;
243             }
244             destroy_xsp(i_ptr->convert);
245         }
246         tinfo->input_list = 0;
247     }
248     if (tinfo->retrieve_list)
249     {
250         struct filter_retrieve *r_ptr;
251         for (r_ptr = tinfo->retrieve_list; r_ptr; r_ptr = r_ptr->next)
252             destroy_xsp(r_ptr->convert);
253         tinfo->retrieve_list = 0;
254     }
255
256     if (tinfo->doc_config)
257     {
258         xmlFreeDoc(tinfo->doc_config);
259         tinfo->doc_config = 0;
260     }
261     odr_reset(tinfo->odr_config);
262 }
263
264 static ZEBRA_RES parse_convert(struct filter_info *tinfo, xmlNodePtr ptr,
265                                struct convert_s **l)
266 {
267     *l = 0;
268     FOR_EACH_ELEMENT(ptr) {
269         if (!XML_STRCMP(ptr->name, "xslt"))
270         {
271             struct _xmlAttr *attr;
272             struct convert_s *p 
273                 = odr_malloc(tinfo->odr_config, sizeof(*p));
274             
275             p->next = 0;
276             p->stylesheet = 0;
277             p->stylesheet_xsp = 0;
278             
279             for (attr = ptr->properties; attr; attr = attr->next)
280                 if (attr_content(attr, "stylesheet", &p->stylesheet))
281                     ;
282                 else
283                 {
284                     dom_log(YLOG_WARN, tinfo, ptr,
285                             "bad attribute @%s", attr->name);
286                 }
287             if (p->stylesheet)
288             {
289                 char tmp_xslt_full_name[1024];
290                 if (!yaz_filepath_resolve(p->stylesheet, 
291                                           tinfo->profile_path,
292                                           NULL, 
293                                           tmp_xslt_full_name))
294                 {
295                     dom_log(YLOG_WARN, tinfo, 0,
296                             "stylesheet %s not found in "
297                             "path %s",
298                             p->stylesheet, 
299                             tinfo->profile_path);
300                     return ZEBRA_FAIL;
301                 }
302                 
303                 p->stylesheet_xsp
304                     = xsltParseStylesheetFile((const xmlChar*) 
305                                               tmp_xslt_full_name);
306                 if (!p->stylesheet_xsp)
307                 {
308                     dom_log(YLOG_WARN, tinfo, 0,
309                             "could not parse xslt stylesheet %s",
310                             tmp_xslt_full_name);
311                     return ZEBRA_FAIL;
312                 }
313                 }
314                 else
315                 {
316                     dom_log(YLOG_WARN, tinfo, ptr,
317                             "missing attribute 'stylesheet' ");
318                     return ZEBRA_FAIL;
319                 }
320                 *l = p;
321                 l = &p->next;
322         }
323         else
324         {
325             dom_log(YLOG_WARN, tinfo, ptr,
326                     "bad element '%s', expected <xslt>", ptr->name);
327             return ZEBRA_FAIL;
328         }
329     }
330     return ZEBRA_OK;
331 }
332
333 static ZEBRA_RES perform_convert(struct filter_info *tinfo, 
334                                  struct convert_s *convert,
335                                  const char **params,
336                                  xmlDocPtr *doc,
337                                  xsltStylesheetPtr *last_xsp)
338 {
339     for (; convert; convert = convert->next)
340     {
341         xmlChar *buf_out = 0;
342         int len_out = 0;
343         xmlDocPtr res_doc = xsltApplyStylesheet(convert->stylesheet_xsp,
344                                                 *doc, params);
345         if (last_xsp)
346             *last_xsp = convert->stylesheet_xsp;
347         
348         xmlFreeDoc(*doc);
349         /* *doc = res_doc; */
350
351         /* now saving into buffer and re-reading into DOM to avoid annoing
352            XSLT problem with thrown-out indentation text nodes */
353         if (res_doc){
354             xsltSaveResultToString(&buf_out, &len_out, res_doc,
355                                    convert->stylesheet_xsp); 
356             xmlFreeDoc(res_doc);
357         }
358
359
360         *doc =  xmlParseDoc(buf_out);
361
362          yaz_log(YLOG_DEBUG, "%s: %s \n %s", 
363                  tinfo->fname ? tinfo->fname : "none ", 
364                  convert->stylesheet,
365                  buf_out);
366
367         xmlFree(buf_out);
368     }
369     return ZEBRA_OK;
370 }
371
372 static struct filter_input *new_input(struct filter_info *tinfo, int type)
373 {
374     struct filter_input *p;
375     struct filter_input **np = &tinfo->input_list;
376     for (;*np; np = &(*np)->next)
377         ;
378     p = *np = odr_malloc(tinfo->odr_config, sizeof(*p));
379     p->next = 0;
380     p->syntax = 0;
381     p->name = 0;
382     p->convert = 0;
383     p->type = type;
384     return p;
385 }
386
387 static ZEBRA_RES parse_input(struct filter_info *tinfo, xmlNodePtr ptr,
388                              const char *syntax, const char *name)
389 {
390     FOR_EACH_ELEMENT(ptr) {
391         if (!XML_STRCMP(ptr->name, "marc"))
392         {
393             yaz_iconv_t iconv = 0;
394             const char *input_charset = "marc-8";
395             struct _xmlAttr *attr;
396             
397             for (attr = ptr->properties; attr; attr = attr->next)
398             {
399                 if (attr_content(attr, "inputcharset", &input_charset))
400                     ;
401                 else
402                 {
403                     dom_log(YLOG_WARN, tinfo, ptr,
404                             "bad attribute @%s, expected @inputcharset",
405                             attr->name);
406                 }
407             }
408             iconv = yaz_iconv_open("utf-8", input_charset);
409             if (!iconv)
410             {
411                 dom_log(YLOG_WARN, tinfo, ptr, 
412                         "unsupported @charset '%s'", input_charset);
413                 return ZEBRA_FAIL;
414             }
415             else
416             {
417                 struct filter_input *p 
418                     = new_input(tinfo, DOM_INPUT_MARC);
419                 p->u.marc.handle = yaz_marc_create();
420                 p->u.marc.iconv = iconv;
421                 
422                 yaz_marc_iconv(p->u.marc.handle, p->u.marc.iconv);
423                 
424                 ptr = ptr->next;
425                 
426                 parse_convert(tinfo, ptr, &p->convert);
427             }
428             break;
429
430         }
431         else if (!XML_STRCMP(ptr->name, "xmlreader"))
432         {
433             struct filter_input *p 
434                 = new_input(tinfo, DOM_INPUT_XMLREADER);
435             struct _xmlAttr *attr;
436             const char *level_str = 0;
437
438             p->u.xmlreader.split_level = 0;
439             p->u.xmlreader.reader = 0;
440
441             for (attr = ptr->properties; attr; attr = attr->next)
442             {
443                 if (attr_content(attr, "level", &level_str))
444                     ;
445                 else
446                 {
447                     dom_log(YLOG_WARN, tinfo, ptr,
448                             "bad attribute @%s, expected @level",
449                             attr->name);
450                 }
451             }
452             if (level_str)
453                 p->u.xmlreader.split_level = atoi(level_str);
454                 
455             ptr = ptr->next;
456
457             parse_convert(tinfo, ptr, &p->convert);
458             break;
459         }
460         else
461         {
462             dom_log(YLOG_WARN, tinfo, ptr,
463                     "bad element <%s>, expected <marc>|<xmlreader>",
464                     ptr->name);
465             return ZEBRA_FAIL;
466         }
467     }
468     return ZEBRA_OK;
469 }
470
471 static ZEBRA_RES parse_dom(struct filter_info *tinfo, const char *fname)
472 {
473     char tmp_full_name[1024];
474     xmlNodePtr ptr;
475     xmlDocPtr doc;
476
477     tinfo->fname = odr_strdup(tinfo->odr_config, fname);
478     
479     if (yaz_filepath_resolve(tinfo->fname, tinfo->profile_path, 
480                              NULL, tmp_full_name))
481         tinfo->full_name = odr_strdup(tinfo->odr_config, tmp_full_name);
482     else
483         tinfo->full_name = odr_strdup(tinfo->odr_config, tinfo->fname);
484     
485     yaz_log(YLOG_LOG, "%s dom filter: "
486             "loading config file %s", tinfo->fname, tinfo->full_name);
487
488     doc = xmlParseFile(tinfo->full_name);
489     if (!doc)
490     {
491         yaz_log(YLOG_WARN, "%s: dom filter: "
492                 "failed to parse config file %s",
493                 tinfo->fname, tinfo->full_name);
494         return ZEBRA_FAIL;
495     }
496     /* save because we store ptrs to the content */ 
497     tinfo->doc_config = doc;
498     
499     ptr = xmlDocGetRootElement(doc);
500     if (!ptr || ptr->type != XML_ELEMENT_NODE 
501         || XML_STRCMP(ptr->name, "dom"))
502     {
503         dom_log(YLOG_WARN, tinfo, ptr,
504                 "bad root element <%s>, expected root element <dom>", 
505                 ptr->name);  
506         return ZEBRA_FAIL;
507     }
508
509     ptr = ptr->children;
510     FOR_EACH_ELEMENT(ptr) {
511         if (!XML_STRCMP(ptr->name, "extract"))
512         {
513             /*
514               <extract name="index">
515               <xslt stylesheet="first.xsl"/>
516               <xslt stylesheet="second.xsl"/>
517               </extract>
518             */
519             struct _xmlAttr *attr;
520             struct filter_extract *f =
521                 odr_malloc(tinfo->odr_config, sizeof(*f));
522             
523             tinfo->extract = f;
524             f->name = 0;
525             f->convert = 0;
526             for (attr = ptr->properties; attr; attr = attr->next)
527             {
528                 if (attr_content(attr, "name", &f->name))
529                     ;
530                 else
531                 {
532                     dom_log(YLOG_WARN, tinfo, ptr,
533                             "bad attribute @%s, expected @name",
534                             attr->name);
535                 }
536             }
537             parse_convert(tinfo, ptr->children, &f->convert);
538         }
539         else if (!XML_STRCMP(ptr->name, "retrieve"))
540         {  
541             /* 
542                <retrieve name="F">
543                <xslt stylesheet="some.xsl"/>
544                <xslt stylesheet="some.xsl"/>
545                </retrieve>
546             */
547             struct _xmlAttr *attr;
548             struct filter_retrieve **fp = &tinfo->retrieve_list;
549             struct filter_retrieve *f =
550                 odr_malloc(tinfo->odr_config, sizeof(*f));
551             
552             while (*fp)
553                 fp = &(*fp)->next;
554
555             *fp = f;
556             f->name = 0;
557             f->identifier = 0;
558             f->convert = 0;
559             f->next = 0;
560
561             for (attr = ptr->properties; attr; attr = attr->next)
562             {
563                 if (attr_content(attr, "identifier", 
564                                  &f->identifier))
565                     ;
566                 else if (attr_content(attr, "name", &f->name))
567                     ;
568                 else
569                 {
570                     dom_log(YLOG_WARN, tinfo, ptr,
571                             "bad attribute @%s,  expected @identifier|@name",
572                             attr->name);
573                 }
574             }
575             parse_convert(tinfo, ptr->children, &f->convert);
576         }
577         else if (!XML_STRCMP(ptr->name, "store"))
578         {
579             /*
580               <store name="F">
581               <xslt stylesheet="some.xsl"/>
582               <xslt stylesheet="some.xsl"/>
583               </retrieve>
584             */
585             struct filter_store *f =
586                 odr_malloc(tinfo->odr_config, sizeof(*f));
587             
588             tinfo->store = f;
589             f->convert = 0;
590             parse_convert(tinfo, ptr->children, &f->convert);
591         }
592         else if (!XML_STRCMP(ptr->name, "input"))
593         {
594             /*
595               <input syntax="xml">
596               <xmlreader level="1"/>
597               </input>
598               <input syntax="usmarc">
599               <marc inputcharset="marc-8"/>
600               </input>
601             */
602             struct _xmlAttr *attr;
603             const char  *syntax = 0;
604             const char *name = 0;
605             for (attr = ptr->properties; attr; attr = attr->next)
606             {
607                 if (attr_content(attr, "syntax", &syntax))
608                     ;
609                 else if (attr_content(attr, "name", &name))
610                     ;
611                 else
612                 {
613                     dom_log(YLOG_WARN, tinfo, ptr,
614                             "bad attribute @%s,  expected @syntax|@name",
615                             attr->name);
616                 }
617             }
618             parse_input(tinfo, ptr->children, syntax, name);
619         }
620         else
621         {
622             dom_log(YLOG_WARN, tinfo, ptr,
623                     "bad element <%s>, "
624                     "expected <extract>|<input>|<retrieve>|<store>",
625                     ptr->name);
626             return ZEBRA_FAIL;
627         }
628     }
629     return ZEBRA_OK;
630 }
631
632 static struct filter_retrieve *lookup_retrieve(struct filter_info *tinfo,
633                                                const char *est)
634 {
635     struct filter_retrieve *f = tinfo->retrieve_list;
636
637     /* return first schema if no est is provided */
638     if (!est)
639         return f;
640     for (; f; f = f->next)
641     { 
642         /* find requested schema */
643         if (est) 
644         {    
645             if (f->identifier && !strcmp(f->identifier, est))
646                 return f;
647             if (f->name && !strcmp(f->name, est))
648                 return f;
649         } 
650     }
651     return 0;
652 }
653
654 static ZEBRA_RES filter_config(void *clientData, Res res, const char *args)
655 {
656     struct filter_info *tinfo = clientData;
657     if (!args || !*args)
658     {
659         yaz_log(YLOG_WARN, "dom filter: need config file");
660         return ZEBRA_FAIL;
661     }
662
663     if (tinfo->fname && !strcmp(args, tinfo->fname))
664         return ZEBRA_OK;
665     
666     tinfo->profile_path = res_get(res, "profilePath");
667
668     destroy_dom(tinfo);
669     return parse_dom(tinfo, args);
670 }
671
672 static void filter_destroy(void *clientData)
673 {
674     struct filter_info *tinfo = clientData;
675     destroy_dom(tinfo);
676     odr_destroy(tinfo->odr_config);
677     odr_destroy(tinfo->odr_record);
678     xfree(tinfo);
679 }
680
681 static int ioread_ex(void *context, char *buffer, int len)
682 {
683     struct recExtractCtrl *p = context;
684     return p->stream->readf(p->stream, buffer, len);
685 }
686
687 static int ioclose_ex(void *context)
688 {
689     return 0;
690 }
691
692
693 /* DOM filter style indexing */
694 static int attr_content_xml(struct _xmlAttr *attr, const char *name,
695                             xmlChar **dst_content)
696 {
697     if (0 == XML_STRCMP(attr->name, name) && attr->children 
698         && attr->children->type == XML_TEXT_NODE)
699     {
700         *dst_content = (attr->children->content);
701         return 1;
702     }
703     return 0;
704 }
705
706
707 /* DOM filter style indexing */
708 static void index_value_of(struct filter_info *tinfo, 
709                            struct recExtractCtrl *extctr,
710                            RecWord* recword, 
711                            xmlNodePtr node, 
712                            xmlChar * index_p)
713 {
714     xmlChar *text = xmlNodeGetContent(node);
715     size_t text_len = strlen((const char *)text);
716
717     /*dom_log(YLOG_DEBUG, tinfo, node, "Indexing: '%s' '%s'", index_p, text);*/
718
719     /* if there is no text, we do not need to proceed */
720     if (text_len)
721     {            
722         xmlChar *look = index_p;
723         xmlChar *bval;
724         xmlChar *eval;
725
726         xmlChar index[256];
727         xmlChar type[256];
728
729         /* assingning text to be indexed */
730         recword->term_buf = (const char *)text;
731         recword->term_len = text_len;
732
733         /* parsing all index name/type pairs */
734         /* may not start with ' ' or ':' */
735         while (*look && ' ' != *look && ':' != *look)
736         {
737             /* setting name and type to zero */
738             *index = '\0';
739             *type = '\0';
740     
741             /* parsing one index name */
742             bval = look;
743             while (*look && ':' != *look && ' ' != *look)
744             {
745                 look++;
746             }
747             eval = look;
748             strncpy((char *)index, (const char *)bval, eval - bval);
749             index[eval - bval] = '\0';
750     
751     
752             /* parsing one index type, if existing */
753             if (':' == *look)
754             {
755                 look++;
756       
757                 bval = look;
758                 while (*look && ' ' != *look)
759                 {
760                     look++;
761                 }
762                 eval = look;
763                 strncpy((char *)type, (const char *)bval, eval - bval);
764                 type[eval - bval] = '\0';
765             }
766
767             /* actually indexing the text given */
768             dom_log(YLOG_DEBUG, tinfo, 0, 
769                     "INDEX '%s:%s' '%s'", 
770                     index ? (const char *) index : "null",
771                     type ? (const char *) type : "null", 
772                     text ? (const char *) text : "null");
773
774             recword->index_name = (const char *)index;
775             if (type && *type)
776                 recword->index_type = *type;
777             (extctr->tokenAdd)(recword);
778
779             /* eat whitespaces */
780             if (*look && ' ' == *look && *(look+1))
781             {
782                 look++;
783             } 
784         }
785     }
786     
787     xmlFree(text); 
788 }
789
790
791 /* DOM filter style indexing */
792 static void set_record_info(struct filter_info *tinfo, 
793                             struct recExtractCtrl *extctr, 
794                             xmlChar * id_p, 
795                             xmlChar * rank_p, 
796                             xmlChar * type_p)
797 {
798     dom_log(YLOG_DEBUG, tinfo, 0,
799             "RECORD id=%s rank=%s type=%s", 
800             id_p ? (const char *) id_p : "null",
801             rank_p ? (const char *) rank_p : "null",
802             type_p ? (const char *) type_p : "null");
803     
804     if (id_p)
805         sscanf((const char *)id_p, "%255s", extctr->match_criteria);
806
807     if (rank_p)
808         extctr->staticrank = atozint((const char *)rank_p);
809
810     /*     if (!strcmp("update", type_str)) */
811     /*         index_node(tinfo, ctrl, ptr, recword); */
812     /*     else if (!strcmp("delete", type_str)) */
813     /*         dom_log(YLOG_WARN, tinfo, ptr, "dom filter delete: to be implemented"); */
814     /*     else */
815     /*         dom_log(YLOG_WARN, tinfo, ptr, "dom filter: unknown record type '%s'",  */
816     /*                 type_str); */
817
818 }
819
820
821 /* DOM filter style indexing */
822 static void process_xml_element_zebra_node(struct filter_info *tinfo, 
823                                            struct recExtractCtrl *extctr, 
824                                            RecWord* recword, 
825                                            xmlNodePtr node)
826 {
827     if (node->type == XML_ELEMENT_NODE && node->ns && node->ns->href
828         && 0 == XML_STRCMP(node->ns->href, zebra_dom_ns))
829     {
830          if (0 == XML_STRCMP(node->name, "index"))
831          {
832             xmlChar *index_p = 0;
833
834             struct _xmlAttr *attr;      
835             for (attr = node->properties; attr; attr = attr->next)
836             {
837                 if (attr_content_xml(attr, "name", &index_p))
838                 {
839                     index_value_of(tinfo, extctr, recword,node, index_p);
840                 }  
841                 else
842                 {
843                     dom_log(YLOG_WARN, tinfo, node,
844                             "bad attribute @%s, expected @name",
845                             attr->name);
846                 }
847             }
848         }
849         else if (0 == XML_STRCMP(node->name, "record"))
850         {
851             xmlChar *id_p = 0;
852             xmlChar *rank_p = 0;
853             xmlChar *type_p = 0;
854
855             struct _xmlAttr *attr;
856             for (attr = node->properties; attr; attr = attr->next)
857             {
858                 if (attr_content_xml(attr, "id", &id_p))
859                     ;
860                 else if (attr_content_xml(attr, "rank", &rank_p))
861                     ;
862                 else if (attr_content_xml(attr, "type", &type_p))
863                     ;
864                 else
865                 {
866                     dom_log(YLOG_WARN, tinfo, node,
867                             "bad attribute @%s, expected @id|@rank|@type",
868                             attr->name);
869                 }
870
871                 if (type_p && 0 != strcmp("update", (const char *)type_p))
872                 {
873                     dom_log(YLOG_WARN, tinfo, node,
874                             "attribute @%s, only implemented '@type='update'",
875                             attr->name);
876                 }
877             }
878             set_record_info(tinfo, extctr, id_p, rank_p, type_p);
879         } 
880         else
881         {
882             dom_log(YLOG_WARN, tinfo, node,
883                     "bad element <%s>,"
884                     " expected <record>|<index> in namespace '%s'",
885                     node->name, zebra_dom_ns);
886         }
887     }
888 }
889
890
891 /* DOM filter style indexing */
892 static void process_xml_pi_node(struct filter_info *tinfo, 
893                                 struct recExtractCtrl *extctr, 
894                                 xmlNodePtr node,
895                                 xmlChar **index_pp)
896 {
897     /* if right PI name, continue parsing PI */
898     if (0 == strcmp(zebra_pi_name, (const char *)node->name))
899     {
900         xmlChar *pi_p =  node->content;
901         xmlChar *look = pi_p;
902     
903         xmlChar *bval;
904         xmlChar *eval;
905
906         /* parsing PI record instructions */
907         if (0 == strncmp((const char *)look, "record", 6))
908         {
909             xmlChar id[256];
910             xmlChar rank[256];
911             xmlChar type[256];
912
913             *id = '\0';
914             *rank = '\0';
915             *type = '\0';
916       
917             look += 6;
918       
919             /* eat whitespace */
920             while (*look && ' ' == *look && *(look+1))
921                 look++;
922
923             /* parse possible id */
924             if (*look && 0 == strncmp((const char *)look, "id=", 3))
925             {
926                 look += 3;
927                 bval = look;
928                 while (*look && ' ' != *look)
929                     look++;
930                 eval = look;
931                 strncpy((char *)id, (const char *)bval, eval - bval);
932                 id[eval - bval] = '\0';
933             }
934       
935             /* eat whitespace */
936             while (*look && ' ' == *look && *(look+1))
937                 look++;
938       
939             /* parse possible rank */
940             if (*look && 0 == strncmp((const char *)look, "rank=", 5))
941             {
942                 look += 6;
943                 bval = look;
944                 while (*look && ' ' != *look)
945                     look++;
946                 eval = look;
947                 strncpy((char *)rank, (const char *)bval, eval - bval);
948                 rank[eval - bval] = '\0';
949             }
950
951             /* eat whitespace */
952             while (*look && ' ' == *look && *(look+1))
953                 look++;
954
955             if (look && '\0' != *look)
956             {
957                 dom_log(YLOG_WARN, tinfo, node,
958                         "content '%s', can not parse '%s'",
959                         pi_p, look);
960             }
961             else 
962                 set_record_info(tinfo, extctr, id, rank, 0);
963
964         } 
965         /* parsing index instruction */
966         else if (0 == strncmp((const char *)look, "index", 5))
967         {
968             look += 5;
969       
970             /* eat whitespace */
971             while (*look && ' ' == *look && *(look+1))
972                 look++;
973
974             /* export index instructions to outside */
975             *index_pp = look;
976         } 
977         else 
978         {
979             dom_log(YLOG_WARN, tinfo, node,
980                     "content '%s', can not parse '%s'",
981                     pi_p, look);
982         }
983     }
984 }
985
986 /* DOM filter style indexing */
987 static void process_xml_element_node(struct filter_info *tinfo, 
988                                      struct recExtractCtrl *extctr, 
989                                      RecWord* recword, 
990                                      xmlNodePtr node)
991 {
992     /* remember indexing instruction from PI to next element node */
993     xmlChar *index_p = 0;
994
995     /* check if we are an element node in the special zebra namespace 
996        and either set record data or index value-of node content*/
997     process_xml_element_zebra_node(tinfo, extctr, recword, node);
998   
999     /* loop through kid nodes */
1000     for (node = node->children; node; node = node->next)
1001     {
1002         /* check and set PI record and index index instructions */
1003         if (node->type == XML_PI_NODE)
1004         {
1005             process_xml_pi_node(tinfo, extctr, node, &index_p);
1006         }
1007         else if (node->type == XML_ELEMENT_NODE)
1008         {
1009             /* if there was a PI index instruction before this element */
1010             if (index_p)
1011             {
1012                 index_value_of(tinfo, extctr, recword, node, index_p);
1013                 index_p = 0;
1014             }
1015             process_xml_element_node(tinfo, extctr, recword,node);
1016         }
1017         else
1018             continue;
1019     }
1020 }
1021
1022
1023 /* DOM filter style indexing */
1024 static void extract_dom_doc_node(struct filter_info *tinfo, 
1025                                  struct recExtractCtrl *extctr, 
1026                                  xmlDocPtr doc)
1027 {
1028     xmlChar *buf_out;
1029     int len_out;
1030
1031     /* only need to do the initialization once, reuse recword for all terms */
1032     RecWord recword;
1033     (*extctr->init)(extctr, &recword);
1034
1035     if (extctr->flagShowRecords)
1036     {
1037         xmlDocDumpMemory(doc, &buf_out, &len_out);
1038         fwrite(buf_out, len_out, 1, stdout);
1039         xmlFree(buf_out);
1040     }
1041
1042     process_xml_element_node(tinfo, extctr, &recword, (xmlNodePtr)doc);
1043 }
1044
1045
1046
1047
1048 static int convert_extract_doc(struct filter_info *tinfo, 
1049                                struct filter_input *input,
1050                                struct recExtractCtrl *p, 
1051                                xmlDocPtr doc)
1052
1053 {
1054     xmlChar *buf_out;
1055     int len_out;
1056     const char *params[10];
1057     xsltStylesheetPtr last_xsp = 0;
1058     xmlDocPtr store_doc = 0;
1059
1060     params[0] = 0;
1061     set_param_str(params, "schema", zebra_dom_ns, tinfo->odr_record);
1062
1063     /* input conversion */
1064     perform_convert(tinfo, input->convert, params, &doc, 0);
1065
1066     if (tinfo->store)
1067     {
1068         /* store conversion */
1069         store_doc = xmlCopyDoc(doc, 1);
1070         perform_convert(tinfo, tinfo->store->convert,
1071                         params, &store_doc, &last_xsp);
1072     }
1073     
1074     if (last_xsp)
1075         xsltSaveResultToString(&buf_out, &len_out, 
1076                                store_doc ? store_doc : doc, last_xsp);
1077     else
1078         xmlDocDumpMemory(store_doc ? store_doc : doc, &buf_out, &len_out);
1079     if (p->flagShowRecords)
1080         fwrite(buf_out, len_out, 1, stdout);
1081     (*p->setStoreData)(p, buf_out, len_out);
1082     xmlFree(buf_out);
1083
1084     if (store_doc)
1085         xmlFreeDoc(store_doc);
1086
1087     /* extract conversion */
1088     perform_convert(tinfo, tinfo->extract->convert, params, &doc, 0);
1089
1090     /* finally, do the indexing */
1091     if (doc)
1092         extract_dom_doc_node(tinfo, p, doc);
1093
1094     if (doc)
1095         xmlFreeDoc(doc);
1096
1097     return RECCTRL_EXTRACT_OK;
1098 }
1099
1100 static int extract_xml_split(struct filter_info *tinfo,
1101                              struct filter_input *input,
1102                              struct recExtractCtrl *p)
1103 {
1104     int ret;
1105
1106     if (p->first_record)
1107     {
1108         if (input->u.xmlreader.reader)
1109             xmlFreeTextReader(input->u.xmlreader.reader);
1110         input->u.xmlreader.reader = xmlReaderForIO(ioread_ex, ioclose_ex,
1111                                                    p /* I/O handler */,
1112                                                    0 /* URL */, 
1113                                                    0 /* encoding */,
1114                                                    XML_PARSE_XINCLUDE|
1115                                                    XML_PARSE_NOENT);
1116     }
1117     if (!input->u.xmlreader.reader)
1118         return RECCTRL_EXTRACT_ERROR_GENERIC;
1119
1120     ret = xmlTextReaderRead(input->u.xmlreader.reader);
1121     while (ret == 1)
1122     {
1123         int type = xmlTextReaderNodeType(input->u.xmlreader.reader);
1124         int depth = xmlTextReaderDepth(input->u.xmlreader.reader);
1125         if (type == XML_READER_TYPE_ELEMENT && 
1126             input->u.xmlreader.split_level == depth)
1127         {
1128             xmlNodePtr ptr
1129                 = xmlTextReaderExpand(input->u.xmlreader.reader);
1130             if (ptr)
1131             {
1132                 xmlNodePtr ptr2 = xmlCopyNode(ptr, 1);
1133                 xmlDocPtr doc = xmlNewDoc((const xmlChar*) "1.0");
1134                 
1135                 xmlDocSetRootElement(doc, ptr2);
1136                 
1137                 return convert_extract_doc(tinfo, input, p, doc);
1138             }
1139             else
1140             {
1141                 xmlFreeTextReader(input->u.xmlreader.reader);
1142                 input->u.xmlreader.reader = 0;
1143                 return RECCTRL_EXTRACT_ERROR_GENERIC;
1144             }
1145         }
1146         ret = xmlTextReaderRead(input->u.xmlreader.reader);
1147     }
1148     xmlFreeTextReader(input->u.xmlreader.reader);
1149     input->u.xmlreader.reader = 0;
1150     return RECCTRL_EXTRACT_EOF;
1151 }
1152
1153 static int extract_xml_full(struct filter_info *tinfo, 
1154                             struct filter_input *input,
1155                             struct recExtractCtrl *p)
1156 {
1157     if (p->first_record) /* only one record per stream */
1158     {
1159         xmlDocPtr doc = xmlReadIO(ioread_ex, ioclose_ex, 
1160                                   p /* I/O handler */,
1161                                   0 /* URL */,
1162                                   0 /* encoding */,
1163                                   XML_PARSE_XINCLUDE|XML_PARSE_NOENT);
1164         if (!doc)
1165         {
1166             return RECCTRL_EXTRACT_ERROR_GENERIC;
1167         }
1168         return convert_extract_doc(tinfo, input, p, doc);
1169     }
1170     else
1171         return RECCTRL_EXTRACT_EOF;
1172 }
1173
1174 static int extract_iso2709(struct filter_info *tinfo,
1175                            struct filter_input *input,
1176                            struct recExtractCtrl *p)
1177 {
1178     char buf[100000];
1179     int record_length;
1180     int read_bytes, r;
1181
1182     if (p->stream->readf(p->stream, buf, 5) != 5)
1183         return RECCTRL_EXTRACT_EOF;
1184     while (*buf < '0' || *buf > '9')
1185     {
1186         int i;
1187
1188         dom_log(YLOG_WARN, tinfo, 0,
1189                 "MARC: Skipping bad byte %d (0x%02X)",
1190                 *buf & 0xff, *buf & 0xff);
1191         for (i = 0; i<4; i++)
1192             buf[i] = buf[i+1];
1193
1194         if (p->stream->readf(p->stream, buf+4, 1) != 1)
1195             return RECCTRL_EXTRACT_EOF;
1196     }
1197     record_length = atoi_n (buf, 5);
1198     if (record_length < 25)
1199     {
1200         dom_log(YLOG_WARN, tinfo, 0,
1201                 "MARC record length < 25, is %d",  record_length);
1202         return RECCTRL_EXTRACT_ERROR_GENERIC;
1203     }
1204     read_bytes = p->stream->readf(p->stream, buf+5, record_length-5);
1205     if (read_bytes < record_length-5)
1206     {
1207         dom_log(YLOG_WARN, tinfo, 0,
1208                 "couldn't read whole MARC record");
1209         return RECCTRL_EXTRACT_ERROR_GENERIC;
1210     }
1211     r = yaz_marc_read_iso2709(input->u.marc.handle,  buf, record_length);
1212     if (r < record_length)
1213     {
1214         dom_log (YLOG_WARN, tinfo, 0,
1215                  "parsing of MARC record failed r=%d length=%d",
1216                  r, record_length);
1217         return RECCTRL_EXTRACT_ERROR_GENERIC;
1218     }
1219     else
1220     {
1221         xmlDocPtr rdoc;
1222         xmlNode *root_ptr;
1223         yaz_marc_write_xml(input->u.marc.handle, &root_ptr, 0, 0, 0);
1224         rdoc = xmlNewDoc((const xmlChar*) "1.0");
1225         xmlDocSetRootElement(rdoc, root_ptr);
1226         return convert_extract_doc(tinfo, input, p, rdoc);        
1227     }
1228     return RECCTRL_EXTRACT_OK;
1229 }
1230
1231 static int filter_extract(void *clientData, struct recExtractCtrl *p)
1232 {
1233     struct filter_info *tinfo = clientData;
1234     struct filter_input *input = tinfo->input_list;
1235
1236     if (!input)
1237         return RECCTRL_EXTRACT_ERROR_GENERIC;
1238
1239     odr_reset(tinfo->odr_record);
1240     switch(input->type)
1241     {
1242     case DOM_INPUT_XMLREADER:
1243         if (input->u.xmlreader.split_level == 0)
1244             return extract_xml_full(tinfo, input, p);
1245         else
1246             return extract_xml_split(tinfo, input, p);
1247         break;
1248     case DOM_INPUT_MARC:
1249         return extract_iso2709(tinfo, input, p);
1250     }
1251     return RECCTRL_EXTRACT_ERROR_GENERIC;
1252 }
1253
1254 static int ioread_ret(void *context, char *buffer, int len)
1255 {
1256     struct recRetrieveCtrl *p = context;
1257     return p->stream->readf(p->stream, buffer, len);
1258 }
1259
1260 static int ioclose_ret(void *context)
1261 {
1262     return 0;
1263 }
1264
1265 static int filter_retrieve (void *clientData, struct recRetrieveCtrl *p)
1266 {
1267     /* const char *esn = zebra_dom_ns; */
1268     const char *esn = 0;
1269     const char *params[32];
1270     struct filter_info *tinfo = clientData;
1271     xmlDocPtr doc;
1272     struct filter_retrieve *retrieve;
1273     xsltStylesheetPtr last_xsp = 0;
1274
1275     if (p->comp)
1276     {
1277         if (p->comp->which == Z_RecordComp_simple
1278             && p->comp->u.simple->which == Z_ElementSetNames_generic)
1279         {
1280             esn = p->comp->u.simple->u.generic;
1281         }
1282         else if (p->comp->which == Z_RecordComp_complex 
1283                  && p->comp->u.complex->generic->elementSpec
1284                  && p->comp->u.complex->generic->elementSpec->which ==
1285                  Z_ElementSpec_elementSetName)
1286         {
1287             esn = p->comp->u.complex->generic->elementSpec->u.elementSetName;
1288         }
1289     }
1290     retrieve = lookup_retrieve(tinfo, esn);
1291     if (!retrieve)
1292     {
1293         p->diagnostic =
1294             YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
1295         return 0;
1296     }
1297
1298     params[0] = 0;
1299     set_param_int(params, "id", p->localno, p->odr);
1300     if (p->fname)
1301         set_param_str(params, "filename", p->fname, p->odr);
1302     if (p->staticrank >= 0)
1303         set_param_int(params, "rank", p->staticrank, p->odr);
1304
1305     if (esn)
1306         set_param_str(params, "schema", esn, p->odr);
1307     else
1308         if (retrieve->name)
1309             set_param_str(params, "schema", retrieve->name, p->odr);
1310         else if (retrieve->identifier)
1311             set_param_str(params, "schema", retrieve->identifier, p->odr);
1312         else
1313             set_param_str(params, "schema", "", p->odr);
1314
1315     if (p->score >= 0)
1316         set_param_int(params, "score", p->score, p->odr);
1317     set_param_int(params, "size", p->recordSize, p->odr);
1318
1319     doc = xmlReadIO(ioread_ret, ioclose_ret, p /* I/O handler */,
1320                     0 /* URL */,
1321                     0 /* encoding */,
1322                     XML_PARSE_XINCLUDE|XML_PARSE_NOENT);
1323     if (!doc)
1324     {
1325         p->diagnostic = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1326         return 0;
1327     }
1328
1329     /* retrieve conversion */
1330     perform_convert(tinfo, retrieve->convert, params, &doc, &last_xsp);
1331     if (!doc)
1332     {
1333         p->diagnostic = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1334     }
1335     else if (p->input_format == VAL_NONE || p->input_format == VAL_TEXT_XML)
1336     {
1337         xmlChar *buf_out;
1338         int len_out;
1339
1340         if (last_xsp)
1341             xsltSaveResultToString(&buf_out, &len_out, doc, last_xsp);
1342         else
1343             xmlDocDumpMemory(doc, &buf_out, &len_out);            
1344
1345         p->output_format = VAL_TEXT_XML;
1346         p->rec_len = len_out;
1347         p->rec_buf = odr_malloc(p->odr, p->rec_len);
1348         memcpy(p->rec_buf, buf_out, p->rec_len);
1349         xmlFree(buf_out);
1350     }
1351     else if (p->output_format == VAL_SUTRS)
1352     {
1353         xmlChar *buf_out;
1354         int len_out;
1355
1356         if (last_xsp)
1357             xsltSaveResultToString(&buf_out, &len_out, doc, last_xsp);
1358         else
1359             xmlDocDumpMemory(doc, &buf_out, &len_out);            
1360         
1361         p->output_format = VAL_SUTRS;
1362         p->rec_len = len_out;
1363         p->rec_buf = odr_malloc(p->odr, p->rec_len);
1364         memcpy(p->rec_buf, buf_out, p->rec_len);
1365         
1366         xmlFree(buf_out);
1367     }
1368     else
1369     {
1370         p->diagnostic = YAZ_BIB1_RECORD_SYNTAX_UNSUPP;
1371     }
1372     xmlFreeDoc(doc);
1373     return 0;
1374 }
1375
1376 static struct recType filter_type = {
1377     0,
1378     "dom",
1379     filter_init,
1380     filter_config,
1381     filter_destroy,
1382     filter_extract,
1383     filter_retrieve
1384 };
1385
1386 RecType
1387 #ifdef IDZEBRA_STATIC_DOM
1388 idzebra_filter_dom
1389 #else
1390 idzebra_filter
1391 #endif
1392
1393 [] = {
1394     &filter_type,
1395     0,
1396 };
1397 /*
1398  * Local variables:
1399  * c-basic-offset: 4
1400  * indent-tabs-mode: nil
1401  * End:
1402  * vim: shiftwidth=4 tabstop=8 expandtab
1403  */
1404