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