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