2ae747b9bf140a9da393d370d274a9c8edf639e8
[idzebra-moved-to-github.git] / util / zebramap.c
1 /* This file is part of the Zebra server.
2    Copyright (C) 1994-2009 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 void zebra_maps_define_default_sort(zebra_maps_t zms)
346 {
347     zebra_map_t zm = zebra_add_map(zms, "s", ZEBRA_MAP_TYPE_SORT);
348     zm->u.sort.entry_size = 80;
349 }
350
351 zebra_map_t zebra_map_get(zebra_maps_t zms, const char *id)
352 {
353     zebra_map_t zm;
354     for (zm = zms->map_list; zm; zm = zm->next)
355         if (!strcmp(zm->id, id))
356             break;
357     return zm;
358 }
359
360 zebra_map_t zebra_map_get_or_add(zebra_maps_t zms, const char *id)
361 {
362     struct zebra_map *zm = zebra_map_get(zms, id);
363     if (!zm)
364     {
365         zm = zebra_add_map(zms, id, ZEBRA_MAP_TYPE_INDEX);
366         
367         /* no reason to warn if no maps are read from file */
368         if (zms->no_files_read)
369             yaz_log(YLOG_WARN, "Unknown register type: %s", id);
370
371         zm->maptab_name = nmem_strdup(zms->nmem, "@");
372         zm->completeness = 0;
373         zm->positioned = 1;
374     }
375     return zm;
376 }
377
378 chrmaptab zebra_charmap_get(zebra_map_t zm)
379 {
380     if (!zm->maptab)
381     {
382         if (!zm->maptab_name || !yaz_matchstr(zm->maptab_name, "@"))
383             return NULL;
384         if (!(zm->maptab = chrmaptab_create(zm->zebra_maps->tabpath,
385                                             zm->maptab_name,
386                                             zm->zebra_maps->tabroot)))
387             yaz_log(YLOG_WARN, "Failed to read character table %s",
388                     zm->maptab_name);
389         else
390             yaz_log(YLOG_DEBUG, "Read character table %s", zm->maptab_name);
391     }
392     return zm->maptab;
393 }
394
395 const char **zebra_maps_input(zebra_map_t zm,
396                               const char **from, int len, int first)
397 {
398     chrmaptab maptab = zebra_charmap_get(zm);
399     if (maptab)
400         return chr_map_input(maptab, from, len, first);
401     
402     zm->zebra_maps->temp_map_str[0] = **from;
403
404     (*from)++;
405     return zm->zebra_maps->temp_map_ptr;
406 }
407
408 const char **zebra_maps_search(zebra_map_t zm,
409                                const char **from, int len,  int *q_map_match)
410 {
411     chrmaptab maptab;
412     
413     *q_map_match = 0;
414     maptab = zebra_charmap_get(zm);
415     if (maptab)
416     {
417         const char **map;
418         map = chr_map_q_input(maptab, from, len, 0);
419         if (map && map[0])
420         {
421             *q_map_match = 1;
422             return map;
423         }
424         map = chr_map_input(maptab, from, len, 0);
425         if (map)
426             return map;
427     }
428     zm->zebra_maps->temp_map_str[0] = **from;
429
430     (*from)++;
431     return zm->zebra_maps->temp_map_ptr;
432 }
433
434 const char *zebra_maps_output(zebra_map_t zm,
435                               const char **from)
436 {
437     chrmaptab maptab = zebra_charmap_get(zm);
438     if (!maptab)
439         return 0;
440     return chr_map_output(maptab, from, 1);
441 }
442
443
444 /* ------------------------------------ */
445
446 int zebra_maps_is_complete(zebra_map_t zm)
447
448     if (zm)
449         return zm->completeness;
450     return 0;
451 }
452
453 int zebra_maps_is_positioned(zebra_map_t zm)
454 {
455     if (zm)
456         return zm->positioned;
457     return 0;
458 }
459
460 int zebra_maps_is_index(zebra_map_t zm)
461 {
462     if (zm)
463         return zm->type == ZEBRA_MAP_TYPE_INDEX;
464     return 0;
465 }
466
467 int zebra_maps_is_staticrank(zebra_map_t zm)
468 {
469     if (zm)
470         return zm->type == ZEBRA_MAP_TYPE_STATICRANK;
471     return 0;
472 }
473     
474 int zebra_maps_is_sort(zebra_map_t zm)
475 {
476     if (zm)
477         return zm->type == ZEBRA_MAP_TYPE_SORT;
478     return 0;
479 }
480
481 int zebra_maps_is_alwaysmatches(zebra_map_t zm)
482 {
483     if (zm)
484         return zm->alwaysmatches;
485     return 0;
486 }
487
488 int zebra_maps_is_first_in_field(zebra_map_t zm)
489 {
490     if (zm)
491         return zm->first_in_field;
492     return 0;
493 }
494
495 int zebra_maps_sort(zebra_maps_t zms, Z_SortAttributes *sortAttributes,
496                     int *numerical)
497 {
498     AttrType use;
499     AttrType structure;
500     int structure_value;
501     attr_init_AttrList(&use, sortAttributes->list, 1);
502     attr_init_AttrList(&structure, sortAttributes->list, 4);
503
504     *numerical = 0;
505     structure_value = attr_find(&structure, 0);
506     if (structure_value == 109)
507         *numerical = 1;
508     return attr_find(&use, NULL);
509 }
510
511 int zebra_maps_attr(zebra_maps_t zms, Z_AttributesPlusTerm *zapt,
512                     const char **index_type, char **search_type, char *rank_type,
513                     int *complete_flag, int *sort_flag)
514 {
515     AttrType completeness;
516     AttrType structure;
517     AttrType relation;
518     AttrType sort_relation;
519     AttrType weight;
520     AttrType use;
521     int completeness_value;
522     int structure_value;
523     const char *structure_str = 0;
524     int relation_value;
525     int sort_relation_value;
526     int weight_value;
527     int use_value;
528
529     attr_init_APT(&structure, zapt, 4);
530     attr_init_APT(&completeness, zapt, 6);
531     attr_init_APT(&relation, zapt, 2);
532     attr_init_APT(&sort_relation, zapt, 7);
533     attr_init_APT(&weight, zapt, 9);
534     attr_init_APT(&use, zapt, 1);
535
536     completeness_value = attr_find(&completeness, NULL);
537     structure_value = attr_find_ex(&structure, NULL, &structure_str);
538     relation_value = attr_find(&relation, NULL);
539     sort_relation_value = attr_find(&sort_relation, NULL);
540     weight_value = attr_find(&weight, NULL);
541     use_value = attr_find(&use, NULL);
542
543     if (completeness_value == 2 || completeness_value == 3)
544         *complete_flag = 1;
545     else
546         *complete_flag = 0;
547     *index_type = 0;
548
549     *sort_flag =(sort_relation_value > 0) ? 1 : 0;
550     *search_type = "phrase";
551     strcpy(rank_type, "void");
552     if (relation_value == 102)
553     {
554         if (weight_value == -1)
555             weight_value = 34;
556         sprintf(rank_type, "rank,w=%d,u=%d", weight_value, use_value);
557     }
558     if (*complete_flag)
559         *index_type = "p";
560     else
561         *index_type = "w";
562     switch (structure_value)
563     {
564     case 6:   /* word list */
565         *search_type = "and-list";
566         break;
567     case 105: /* free-form-text */
568         *search_type = "or-list";
569         break;
570     case 106: /* document-text */
571         *search_type = "or-list";
572         break;  
573     case -1:
574     case 1:   /* phrase */
575     case 2:   /* word */
576     case 108: /* string */ 
577         *search_type = "phrase";
578         break;
579     case 107: /* local-number */
580         *search_type = "local";
581         *index_type = 0;
582         break;
583     case 109: /* numeric string */
584         *index_type = "n";
585         *search_type = "numeric";
586         break;
587     case 104: /* urx */
588         *index_type = "u";
589         *search_type = "phrase";
590         break;
591     case 3:   /* key */
592         *index_type = "0";
593         *search_type = "phrase";
594         break;
595     case 4:  /* year */
596         *index_type = "y";
597         *search_type = "phrase";
598         break;
599     case 5:  /* date */
600         *index_type = "d";
601         *search_type = "phrase";
602         break;
603     case -2:
604         if (structure_str && *structure_str)
605             *index_type = structure_str;
606         else
607             return -1;
608         break;
609     default:
610         return -1;
611     }
612     return 0;
613 }
614
615 WRBUF zebra_replace(zebra_map_t zm, const char *ex_list,
616                     const char *input_str, int input_len)
617 {
618     wrbuf_rewind(zm->zebra_maps->wrbuf_1);
619     wrbuf_write(zm->zebra_maps->wrbuf_1, input_str, input_len);
620     return zm->zebra_maps->wrbuf_1;
621 }
622
623 #define SE_CHARS ";,.()-/?<> \r\n\t"
624
625 static int tokenize_simple(zebra_map_t zm,
626                            const char **result_buf, size_t *result_len)
627 {
628     char *buf = wrbuf_buf(zm->input_str);
629     size_t len = wrbuf_len(zm->input_str);
630     size_t i = zm->simple_off;
631     size_t start;
632
633     while (i < len && strchr(SE_CHARS, buf[i]))
634         i++;
635     start = i;
636     while (i < len && !strchr(SE_CHARS, buf[i]))
637     {
638         if (buf[i] > 32 && buf[i] < 127)
639             buf[i] = tolower(buf[i]);
640         i++;
641     }
642
643     zm->simple_off = i;
644     if (start != i)
645     {
646         *result_buf = buf + start;
647         *result_len = i - start;
648         return 1;
649     }
650     return 0;
651  }
652
653
654 int zebra_map_tokenize_next(zebra_map_t zm,
655                             const char **result_buf, size_t *result_len,
656                             const char **display_buf, size_t *display_len)
657 {
658     assert(zm->use_chain);
659
660 #if YAZ_HAVE_ICU
661     if (!zm->icu_chain)
662         return tokenize_simple(zm, result_buf, result_len);
663     else
664     {
665         UErrorCode status;
666         while (icu_chain_next_token(zm->icu_chain, &status))
667         {
668             if (!U_SUCCESS(status))
669                 return 0;
670             *result_buf = icu_chain_token_sortkey(zm->icu_chain);
671             assert(*result_buf);
672
673             *result_len = strlen(*result_buf);
674
675             if (display_buf)
676             {
677                 *display_buf = icu_chain_token_display(zm->icu_chain);
678                 if (display_len)
679                     *display_len = strlen(*display_buf);
680             }
681             if (zm->debug)
682             {
683                 wrbuf_rewind(zm->print_str);
684                 wrbuf_write_escaped(zm->print_str, *result_buf, *result_len);
685                 yaz_log(YLOG_LOG, "output %s", wrbuf_cstr(zm->print_str));
686             }
687
688             if (**result_buf != '\0')
689                 return 1;
690         }
691     }
692     return 0;
693 #else
694     return tokenize_simple(zm, result_buf, result_len);
695 #endif
696 }
697
698 int zebra_map_tokenize_start(zebra_map_t zm,
699                              const char *buf, size_t len)
700 {
701     assert(zm->use_chain);
702
703     wrbuf_rewind(zm->input_str);
704     wrbuf_write(zm->input_str, buf, len);
705     zm->simple_off = 0;
706 #if YAZ_HAVE_ICU
707     if (zm->icu_chain)
708     {
709         UErrorCode status;
710         if (zm->debug)
711         {
712             wrbuf_rewind(zm->print_str);
713             wrbuf_write_escaped(zm->print_str, wrbuf_buf(zm->input_str),
714                                 wrbuf_len(zm->input_str));
715             
716             yaz_log(YLOG_LOG, "input %s", 
717                     wrbuf_cstr(zm->print_str)); 
718         }
719         icu_chain_assign_cstr(zm->icu_chain,
720                               wrbuf_cstr(zm->input_str),
721                               &status);
722         if (!U_SUCCESS(status))
723         {
724             if (zm->debug)
725             {
726                 yaz_log(YLOG_WARN, "bad encoding for input");
727             }
728             return -1;
729         }
730     }
731 #endif
732     return 0;
733 }
734
735 int zebra_maps_is_icu(zebra_map_t zm)
736 {
737     assert(zm);
738 #if YAZ_HAVE_ICU
739     return zm->use_chain;
740 #else
741     return 0;
742 #endif
743 }
744
745
746 /*
747  * Local variables:
748  * c-basic-offset: 4
749  * indent-tabs-mode: nil
750  * End:
751  * vim: shiftwidth=4 tabstop=8 expandtab
752  */
753