c6f3da91e20290148fe42889fbd4c6e942a8363d
[idzebra-moved-to-github.git] / util / zebramap.c
1 /* This file is part of the Zebra server.
2    Copyright (C) 1995-2008 Index Data
3
4 Zebra is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 #include <assert.h>
21 #include <stdlib.h>
22 #include <ctype.h>
23
24 #include <charmap.h>
25 #include <attrfind.h>
26 #include <yaz/yaz-util.h>
27
28 #if YAZ_HAVE_ICU
29 #include <yaz/icu.h>
30 #endif
31 #include <zebramap.h>
32
33 #define ZEBRA_MAP_TYPE_SORT  1
34 #define ZEBRA_MAP_TYPE_INDEX 2
35 #define ZEBRA_MAP_TYPE_STATICRANK 3
36
37 #define ZEBRA_REPLACE_ANY  300
38
39 struct zebra_map {
40     const char *id;
41     int completeness;
42     int positioned;
43     int alwaysmatches;
44     int first_in_field;
45     int type;
46     int use_chain;
47     int debug;
48     union {
49         struct {
50             int entry_size;
51         } sort;
52     } u;
53     chrmaptab maptab;
54     const char *maptab_name;
55     zebra_maps_t zebra_maps;
56 #if YAZ_HAVE_XML2
57     xmlDocPtr doc;
58 #endif
59 #if YAZ_HAVE_ICU
60     struct icu_chain *icu_chain;
61 #endif
62     WRBUF input_str;
63     WRBUF print_str;
64     size_t simple_off;
65     struct zebra_map *next;
66 };
67
68 struct zebra_maps_s {
69     char *tabpath;
70     char *tabroot;
71     NMEM nmem;
72     char temp_map_str[2];
73     const char *temp_map_ptr[2];
74     WRBUF wrbuf_1;
75     int no_files_read;
76     zebra_map_t map_list;
77     zebra_map_t last_map;
78 };
79
80 void zebra_maps_close(zebra_maps_t zms)
81 {
82     struct zebra_map *zm = zms->map_list;
83     while (zm)
84     {
85         if (zm->maptab)
86             chrmaptab_destroy(zm->maptab);
87 #if YAZ_HAVE_ICU
88         if (zm->icu_chain)
89             icu_chain_destroy(zm->icu_chain);
90 #endif
91 #if YAZ_HAVE_XML2
92         xmlFreeDoc(zm->doc);
93 #endif
94         wrbuf_destroy(zm->input_str);
95         wrbuf_destroy(zm->print_str);
96         zm = zm->next;
97     }
98     wrbuf_destroy(zms->wrbuf_1);
99     nmem_destroy(zms->nmem);
100     xfree(zms);
101 }
102
103 zebra_map_t zebra_add_map(zebra_maps_t zms, const char *index_type,
104                           int map_type)
105 {
106     zebra_map_t zm = (zebra_map_t) nmem_malloc(zms->nmem, sizeof(*zm));
107
108     zm->zebra_maps = zms;
109     zm->id = nmem_strdup(zms->nmem, index_type);
110     zm->maptab_name = 0;
111     zm->use_chain = 0;
112     zm->debug = 0;
113     zm->maptab = 0;
114     zm->type = map_type;
115     zm->completeness = 0;
116     zm->positioned = 0;
117     zm->alwaysmatches = 0;
118     zm->first_in_field = 0;
119
120     if (zms->last_map)
121         zms->last_map->next = zm;
122     else
123         zms->map_list = zm;
124     zms->last_map = zm;
125     zm->next = 0;
126 #if YAZ_HAVE_ICU
127     zm->icu_chain = 0;
128 #endif
129 #if YAZ_HAVE_XML2
130     zm->doc = 0;
131 #endif
132     zm->input_str = wrbuf_alloc();
133     zm->print_str = wrbuf_alloc();
134     return zm;
135 }
136
137 static int parse_command(zebra_maps_t zms, int argc, char **argv,
138                          const char *fname, int lineno)
139 {
140     zebra_map_t zm = zms->last_map;
141     if (argc == 1)
142     {
143         yaz_log(YLOG_WARN, "%s:%d: Missing arguments for '%s'",
144                 fname, lineno, argv[0]);
145         return -1;
146     }
147     if (argc > 2)
148     {
149         yaz_log(YLOG_WARN, "%s:%d: Too many arguments for '%s'",
150                 fname, lineno, argv[0]);
151         return -1;
152     }
153     if (!yaz_matchstr(argv[0], "index"))
154     {
155         zm = zebra_add_map(zms, argv[1], ZEBRA_MAP_TYPE_INDEX);
156         zm->positioned = 1;
157     }
158     else if (!yaz_matchstr(argv[0], "sort"))
159     {
160         zm = zebra_add_map(zms, argv[1], ZEBRA_MAP_TYPE_SORT);
161         zm->u.sort.entry_size = 80;
162     }
163     else if (!yaz_matchstr(argv[0], "staticrank"))
164     {
165         zm = zebra_add_map(zms, argv[1], ZEBRA_MAP_TYPE_STATICRANK);
166         zm->completeness = 1;
167     }
168     else if (!zm)
169     {
170         yaz_log(YLOG_WARN, "%s:%d: Missing sort/index before '%s'",  
171                 fname, lineno, argv[0]);
172         return -1;
173     }
174     else if (!yaz_matchstr(argv[0], "charmap") && argc == 2)
175     {
176         if (zm->type != ZEBRA_MAP_TYPE_STATICRANK)
177             zm->maptab_name = nmem_strdup(zms->nmem, argv[1]);
178         else
179         {
180             yaz_log(YLOG_WARN|YLOG_FATAL, "%s:%d: charmap for "
181                     "staticrank is invalid", fname, lineno);
182             yaz_log(YLOG_LOG, "Type is %d", zm->type);
183             return -1;
184         }
185     }
186     else if (!yaz_matchstr(argv[0], "completeness") && argc == 2)
187     {
188         zm->completeness = atoi(argv[1]);
189     }
190     else if (!yaz_matchstr(argv[0], "position") && argc == 2)
191     {
192         zm->positioned = atoi(argv[1]);
193     }
194     else if (!yaz_matchstr(argv[0], "alwaysmatches") && argc == 2)
195     {
196         if (zm->type != ZEBRA_MAP_TYPE_STATICRANK)
197             zm->alwaysmatches = atoi(argv[1]);
198         else
199         {
200             yaz_log(YLOG_WARN|YLOG_FATAL, "%s:%d: alwaysmatches for "
201                     "staticrank is invalid", fname, lineno);
202             return -1;
203         }
204     }
205     else if (!yaz_matchstr(argv[0], "firstinfield") && argc == 2)
206     {
207         zm->first_in_field = atoi(argv[1]);
208     }
209     else if (!yaz_matchstr(argv[0], "entrysize") && argc == 2)
210     {
211         if (zm->type == ZEBRA_MAP_TYPE_SORT)
212             zm->u.sort.entry_size = atoi(argv[1]);
213         else
214         {
215             yaz_log(YLOG_WARN, 
216                     "%s:%d: entrysize only valid in sort section",  
217                     fname, lineno);
218             return -1;
219         }
220     }
221     else if (!yaz_matchstr(argv[0], "simplechain"))
222     {
223         zm->use_chain = 1;
224 #if YAZ_HAVE_ICU
225         zm->icu_chain = 0;
226 #endif
227     }
228     else if (!yaz_matchstr(argv[0], "icuchain"))
229     {
230         char full_path[1024];
231         if (!yaz_filepath_resolve(argv[1], zms->tabpath, zms->tabroot,
232                                   full_path))
233         {
234             yaz_log(YLOG_WARN, "%s:%d: Could not locate icuchain config '%s'",
235                     fname, lineno, argv[1]);
236             return -1;
237         }
238 #if YAZ_HAVE_XML2
239         zm->doc = xmlParseFile(full_path);
240         if (!zm->doc)
241         {
242             yaz_log(YLOG_WARN, "%s:%d: Could not load icuchain config '%s'",
243                     fname, lineno, argv[1]);
244             return -1;
245         }
246         else
247         {
248 #if YAZ_HAVE_ICU
249             UErrorCode status;
250             xmlNode *xml_node = xmlDocGetRootElement(zm->doc);
251             zm->icu_chain = 
252                 icu_chain_xml_config(xml_node,
253 /* not sure about sort for this function yet.. */
254 #if 1
255                                      1,
256 #else
257                                      zm->type == ZEBRA_MAP_TYPE_SORT,
258 #endif                                    
259                                      &status);
260             if (!zm->icu_chain)
261             {
262                 yaz_log(YLOG_WARN, "%s:%d: Failed to load ICU chain %s",
263                         fname, lineno, argv[1]);
264             }
265             zm->use_chain = 1;
266 #else
267             yaz_log(YLOG_WARN, "%s:%d: ICU support unavailable",
268                     fname, lineno);
269             return -1;
270 #endif
271         }
272 #else
273         yaz_log(YLOG_WARN, "%s:%d: XML support unavailable",
274                 fname, lineno);
275         return -1;
276 #endif
277     }
278     else if (!yaz_matchstr(argv[0], "debug") && argc == 2)
279     {
280         zm->debug = atoi(argv[1]);
281     }
282     else
283     {
284         yaz_log(YLOG_WARN, "%s:%d: Unrecognized directive '%s'",  
285                 fname, lineno, argv[0]);
286         return -1;
287     }
288     return 0;
289 }
290
291 ZEBRA_RES zebra_maps_read_file(zebra_maps_t zms, const char *fname)
292 {
293     FILE *f;
294     char line[512];
295     char *argv[10];
296     int argc;
297     int lineno = 0;
298     int failures = 0;
299
300     if (!(f = yaz_fopen(zms->tabpath, fname, "r", zms->tabroot)))
301     {
302         yaz_log(YLOG_ERRNO|YLOG_FATAL, "%s", fname);
303         return ZEBRA_FAIL;
304     }
305     while ((argc = readconf_line(f, &lineno, line, 512, argv, 10)))
306     {
307         int r = parse_command(zms, argc, argv, fname, lineno);
308         if (r)
309             failures++;
310     }
311     yaz_fclose(f);
312
313     if (failures)
314         return ZEBRA_FAIL;
315
316     (zms->no_files_read)++;
317     return ZEBRA_OK;
318 }
319
320 zebra_maps_t zebra_maps_open(Res res, const char *base_path,
321                              const char *profile_path)
322 {
323     zebra_maps_t zms = (zebra_maps_t) xmalloc(sizeof(*zms));
324
325     zms->nmem = nmem_create();
326     zms->tabpath = profile_path ? nmem_strdup(zms->nmem, profile_path) : 0;
327     zms->tabroot = 0;
328     if (base_path)
329         zms->tabroot = nmem_strdup(zms->nmem, base_path);
330     zms->map_list = 0;
331     zms->last_map = 0;
332
333     zms->temp_map_str[0] = '\0';
334     zms->temp_map_str[1] = '\0';
335
336     zms->temp_map_ptr[0] = zms->temp_map_str;
337     zms->temp_map_ptr[1] = NULL;
338
339     zms->wrbuf_1 = wrbuf_alloc();
340
341     zms->no_files_read = 0;
342     return zms;
343 }
344
345 zebra_map_t zebra_map_get(zebra_maps_t zms, const char *id)
346 {
347     zebra_map_t zm;
348     for (zm = zms->map_list; zm; zm = zm->next)
349         if (!strcmp(zm->id, id))
350             break;
351     return zm;
352 }
353
354 zebra_map_t zebra_map_get_or_add(zebra_maps_t zms, const char *id)
355 {
356     struct zebra_map *zm = zebra_map_get(zms, id);
357     if (!zm)
358     {
359         zm = zebra_add_map(zms, id, ZEBRA_MAP_TYPE_INDEX);
360         
361         /* no reason to warn if no maps are read from file */
362         if (zms->no_files_read)
363             yaz_log(YLOG_WARN, "Unknown register type: %s", id);
364
365         zm->maptab_name = nmem_strdup(zms->nmem, "@");
366         zm->completeness = 0;
367         zm->positioned = 1;
368     }
369     return zm;
370 }
371
372 chrmaptab zebra_charmap_get(zebra_map_t zm)
373 {
374     if (!zm->maptab)
375     {
376         if (!zm->maptab_name || !yaz_matchstr(zm->maptab_name, "@"))
377             return NULL;
378         if (!(zm->maptab = chrmaptab_create(zm->zebra_maps->tabpath,
379                                             zm->maptab_name,
380                                             zm->zebra_maps->tabroot)))
381             yaz_log(YLOG_WARN, "Failed to read character table %s",
382                     zm->maptab_name);
383         else
384             yaz_log(YLOG_DEBUG, "Read character table %s", zm->maptab_name);
385     }
386     return zm->maptab;
387 }
388
389 const char **zebra_maps_input(zebra_map_t zm,
390                               const char **from, int len, int first)
391 {
392     chrmaptab maptab = zebra_charmap_get(zm);
393     if (maptab)
394         return chr_map_input(maptab, from, len, first);
395     
396     zm->zebra_maps->temp_map_str[0] = **from;
397
398     (*from)++;
399     return zm->zebra_maps->temp_map_ptr;
400 }
401
402 const char **zebra_maps_search(zebra_map_t zm,
403                                const char **from, int len,  int *q_map_match)
404 {
405     chrmaptab maptab;
406     
407     *q_map_match = 0;
408     maptab = zebra_charmap_get(zm);
409     if (maptab)
410     {
411         const char **map;
412         map = chr_map_q_input(maptab, from, len, 0);
413         if (map && map[0])
414         {
415             *q_map_match = 1;
416             return map;
417         }
418         map = chr_map_input(maptab, from, len, 0);
419         if (map)
420             return map;
421     }
422     zm->zebra_maps->temp_map_str[0] = **from;
423
424     (*from)++;
425     return zm->zebra_maps->temp_map_ptr;
426 }
427
428 const char *zebra_maps_output(zebra_map_t zm,
429                               const char **from)
430 {
431     chrmaptab maptab = zebra_charmap_get(zm);
432     if (!maptab)
433         return 0;
434     return chr_map_output(maptab, from, 1);
435 }
436
437
438 /* ------------------------------------ */
439
440 int zebra_maps_is_complete(zebra_map_t zm)
441
442     if (zm)
443         return zm->completeness;
444     return 0;
445 }
446
447 int zebra_maps_is_positioned(zebra_map_t zm)
448 {
449     if (zm)
450         return zm->positioned;
451     return 0;
452 }
453
454 int zebra_maps_is_index(zebra_map_t zm)
455 {
456     if (zm)
457         return zm->type == ZEBRA_MAP_TYPE_INDEX;
458     return 0;
459 }
460
461 int zebra_maps_is_staticrank(zebra_map_t zm)
462 {
463     if (zm)
464         return zm->type == ZEBRA_MAP_TYPE_STATICRANK;
465     return 0;
466 }
467     
468 int zebra_maps_is_sort(zebra_map_t zm)
469 {
470     if (zm)
471         return zm->type == ZEBRA_MAP_TYPE_SORT;
472     return 0;
473 }
474
475 int zebra_maps_is_alwaysmatches(zebra_map_t zm)
476 {
477     if (zm)
478         return zm->alwaysmatches;
479     return 0;
480 }
481
482 int zebra_maps_is_first_in_field(zebra_map_t zm)
483 {
484     if (zm)
485         return zm->first_in_field;
486     return 0;
487 }
488
489 int zebra_maps_sort(zebra_maps_t zms, Z_SortAttributes *sortAttributes,
490                     int *numerical)
491 {
492     AttrType use;
493     AttrType structure;
494     int structure_value;
495     attr_init_AttrList(&use, sortAttributes->list, 1);
496     attr_init_AttrList(&structure, sortAttributes->list, 4);
497
498     *numerical = 0;
499     structure_value = attr_find(&structure, 0);
500     if (structure_value == 109)
501         *numerical = 1;
502     return attr_find(&use, NULL);
503 }
504
505 int zebra_maps_attr(zebra_maps_t zms, Z_AttributesPlusTerm *zapt,
506                     const char **index_type, char **search_type, char *rank_type,
507                     int *complete_flag, int *sort_flag)
508 {
509     AttrType completeness;
510     AttrType structure;
511     AttrType relation;
512     AttrType sort_relation;
513     AttrType weight;
514     AttrType use;
515     int completeness_value;
516     int structure_value;
517     const char *structure_str = 0;
518     int relation_value;
519     int sort_relation_value;
520     int weight_value;
521     int use_value;
522
523     attr_init_APT(&structure, zapt, 4);
524     attr_init_APT(&completeness, zapt, 6);
525     attr_init_APT(&relation, zapt, 2);
526     attr_init_APT(&sort_relation, zapt, 7);
527     attr_init_APT(&weight, zapt, 9);
528     attr_init_APT(&use, zapt, 1);
529
530     completeness_value = attr_find(&completeness, NULL);
531     structure_value = attr_find_ex(&structure, NULL, &structure_str);
532     relation_value = attr_find(&relation, NULL);
533     sort_relation_value = attr_find(&sort_relation, NULL);
534     weight_value = attr_find(&weight, NULL);
535     use_value = attr_find(&use, NULL);
536
537     if (completeness_value == 2 || completeness_value == 3)
538         *complete_flag = 1;
539     else
540         *complete_flag = 0;
541     *index_type = 0;
542
543     *sort_flag =(sort_relation_value > 0) ? 1 : 0;
544     *search_type = "phrase";
545     strcpy(rank_type, "void");
546     if (relation_value == 102)
547     {
548         if (weight_value == -1)
549             weight_value = 34;
550         sprintf(rank_type, "rank,w=%d,u=%d", weight_value, use_value);
551     }
552     if (*complete_flag)
553         *index_type = "p";
554     else
555         *index_type = "w";
556     switch (structure_value)
557     {
558     case 6:   /* word list */
559         *search_type = "and-list";
560         break;
561     case 105: /* free-form-text */
562         *search_type = "or-list";
563         break;
564     case 106: /* document-text */
565         *search_type = "or-list";
566         break;  
567     case -1:
568     case 1:   /* phrase */
569     case 2:   /* word */
570     case 108: /* string */ 
571         *search_type = "phrase";
572         break;
573     case 107: /* local-number */
574         *search_type = "local";
575         *index_type = 0;
576         break;
577     case 109: /* numeric string */
578         *index_type = "n";
579         *search_type = "numeric";
580         break;
581     case 104: /* urx */
582         *index_type = "u";
583         *search_type = "phrase";
584         break;
585     case 3:   /* key */
586         *index_type = "0";
587         *search_type = "phrase";
588         break;
589     case 4:  /* year */
590         *index_type = "y";
591         *search_type = "phrase";
592         break;
593     case 5:  /* date */
594         *index_type = "d";
595         *search_type = "phrase";
596         break;
597     case -2:
598         if (structure_str && *structure_str)
599             *index_type = structure_str;
600         else
601             return -1;
602         break;
603     default:
604         return -1;
605     }
606     return 0;
607 }
608
609 WRBUF zebra_replace(zebra_map_t zm, const char *ex_list,
610                     const char *input_str, int input_len)
611 {
612     wrbuf_rewind(zm->zebra_maps->wrbuf_1);
613     wrbuf_write(zm->zebra_maps->wrbuf_1, input_str, input_len);
614     return zm->zebra_maps->wrbuf_1;
615 }
616
617 #define SE_CHARS ";,.()-/?<> \r\n\t"
618
619 static int tokenize_simple(zebra_map_t zm,
620                            const char **result_buf, size_t *result_len)
621 {
622     char *buf = wrbuf_buf(zm->input_str);
623     size_t len = wrbuf_len(zm->input_str);
624     size_t i = zm->simple_off;
625     size_t start;
626
627     while (i < len && strchr(SE_CHARS, buf[i]))
628         i++;
629     start = i;
630     while (i < len && !strchr(SE_CHARS, buf[i]))
631     {
632         if (buf[i] > 32 && buf[i] < 127)
633             buf[i] = tolower(buf[i]);
634         i++;
635     }
636
637     zm->simple_off = i;
638     if (start != i)
639     {
640         *result_buf = buf + start;
641         *result_len = i - start;
642         return 1;
643     }
644     return 0;
645  }
646
647
648 int zebra_map_tokenize_next(zebra_map_t zm,
649                             const char **result_buf, size_t *result_len,
650                             const char **display_buf, size_t *display_len)
651 {
652     assert(zm->use_chain);
653
654 #if YAZ_HAVE_ICU
655     if (!zm->icu_chain)
656         return tokenize_simple(zm, result_buf, result_len);
657     else
658     {
659         UErrorCode status;
660         while (icu_chain_next_token(zm->icu_chain, &status))
661         {
662             if (!U_SUCCESS(status))
663                 return 0;
664             *result_buf = icu_chain_token_sortkey(zm->icu_chain);
665             assert(*result_buf);
666
667             *result_len = strlen(*result_buf);
668
669             if (display_buf)
670             {
671                 *display_buf = icu_chain_token_display(zm->icu_chain);
672                 if (display_len)
673                     *display_len = strlen(*display_buf);
674             }
675             if (zm->debug)
676             {
677                 wrbuf_rewind(zm->print_str);
678                 wrbuf_write_escaped(zm->print_str, *result_buf, *result_len);
679                 yaz_log(YLOG_LOG, "output %s", wrbuf_cstr(zm->print_str));
680             }
681
682             if (**result_buf != '\0')
683                 return 1;
684         }
685     }
686     return 0;
687 #else
688     return tokenize_simple(zm, result_buf, result_len);
689 #endif
690 }
691
692 int zebra_map_tokenize_start(zebra_map_t zm,
693                              const char *buf, size_t len)
694 {
695     assert(zm->use_chain);
696
697     wrbuf_rewind(zm->input_str);
698     wrbuf_write(zm->input_str, buf, len);
699     zm->simple_off = 0;
700 #if YAZ_HAVE_ICU
701     if (zm->icu_chain)
702     {
703         UErrorCode status;
704         if (zm->debug)
705         {
706             wrbuf_rewind(zm->print_str);
707             wrbuf_write_escaped(zm->print_str, wrbuf_buf(zm->input_str),
708                                 wrbuf_len(zm->input_str));
709             
710             yaz_log(YLOG_LOG, "input %s", 
711                     wrbuf_cstr(zm->print_str)); 
712         }
713         icu_chain_assign_cstr(zm->icu_chain,
714                               wrbuf_cstr(zm->input_str),
715                               &status);
716         if (!U_SUCCESS(status))
717         {
718             if (zm->debug)
719             {
720                 yaz_log(YLOG_WARN, "bad encoding for input");
721             }
722             return -1;
723         }
724     }
725 #endif
726     return 0;
727 }
728
729 int zebra_maps_is_icu(zebra_map_t zm)
730 {
731     assert(zm);
732 #if YAZ_HAVE_ICU
733     return zm->use_chain;
734 #else
735     return 0;
736 #endif
737 }
738
739
740 /*
741  * Local variables:
742  * c-basic-offset: 4
743  * indent-tabs-mode: nil
744  * End:
745  * vim: shiftwidth=4 tabstop=8 expandtab
746  */
747