5b602ed19f532cb2353341994978c09651fcd517
[idzebra-moved-to-github.git] / index / retrieve.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 <stdio.h>
21 #include <assert.h>
22
23 #include <fcntl.h>
24 #ifdef WIN32
25 #include <io.h>
26 #include <process.h>
27 #endif
28 #if HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31
32 #include "index.h"
33 #include <yaz/diagbib1.h>
34 #include <yaz/snprintf.h>
35 #include <direntz.h>
36 #include <yaz/oid_db.h>
37 #include <zebra_strmap.h>
38
39 #define MAX_SYSNOS_PER_RECORD 40
40
41 #define ZEBRA_XML_HEADER_STR "<record xmlns=\"http://www.indexdata.com/zebra/\""
42
43 struct special_fetch_s {
44     ZebraHandle zh;
45     const char *setname;
46     zint sysno;
47     int score;
48     NMEM nmem;
49 };
50
51 static int zebra_create_record_stream(ZebraHandle zh, 
52                                       Record *rec,
53                                       struct ZebraRecStream *stream)
54 {
55     RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, *rec);
56
57     if ((*rec)->size[recInfo_storeData] > 0 
58         || (*rec)->info[recInfo_filename] == 0)
59         zebra_create_stream_mem(stream, (*rec)->info[recInfo_storeData],
60                                 (*rec)->size[recInfo_storeData]);
61     else
62     {
63         char full_rep[1024];
64         int fd;
65             
66         if (zh->path_reg && !yaz_is_abspath((*rec)->info[recInfo_filename])){
67             strcpy(full_rep, zh->path_reg);
68             strcat(full_rep, "/");
69             strcat(full_rep, (*rec)->info[recInfo_filename]);
70         }
71         else
72             strcpy(full_rep, (*rec)->info[recInfo_filename]);
73             
74         if ((fd = open(full_rep, O_BINARY|O_RDONLY)) == -1){
75             yaz_log(YLOG_WARN|YLOG_ERRNO, "Retrieve fail; missing file: %s",
76                      full_rep);
77             rec_free(rec);
78             return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
79         }
80         zebra_create_stream_fd(stream, fd, recordAttr->recordOffset);
81     }
82     return 0;
83 }
84    
85
86 struct index_spec {
87     const char *index_name;
88     const char *index_type;
89     const char *extra;
90     struct index_spec *next;
91 };
92
93
94 struct index_spec *parse_index_spec(const char *elem, NMEM nmem,
95                                     int *error)
96 {
97     struct index_spec *first = 0;
98     struct index_spec **last = &first;
99     const char *cp = elem;
100
101     *error = 0;
102     if (cp[0] == ':' && cp[1] == ':')
103     {
104
105         cp++; /* skip first ':' */
106
107         for (;;)
108         {
109             const char *cp0;
110             struct index_spec *spec = nmem_malloc(nmem, sizeof(*spec));
111             spec->index_type = 0;
112             spec->next = 0;
113             spec->extra = 0;
114
115             if (!first)
116                 first = spec;
117             *last = spec;
118             last = &spec->next;
119
120             cp++; /* skip ',' or second ':' */
121             cp0 = cp;
122             while (*cp != ':' && *cp != '\0' && *cp != ',')
123                 cp++;
124             spec->index_name = nmem_strdupn(nmem, cp0, cp - cp0);
125             if (*cp == ':') /* type as well */
126             {
127                 cp++;
128                 cp0 = cp;
129                 
130                 while (*cp != '\0' && *cp != ',' && *cp != ':')
131                     cp++;
132                 spec->index_type = nmem_strdupn(nmem, cp0, cp - cp0);
133             }
134             if (*cp == ':') /* extra arguments */
135             {
136                 cp++;
137                 cp0 = cp;
138                 
139                 while (*cp != '\0' && *cp != ',' && *cp != ':')
140                     cp++;
141                 spec->extra = nmem_strdupn(nmem, cp0, cp - cp0);
142             }
143             if (*cp != ',')
144                 break;
145         }
146     }
147     if (*cp != '\0')
148         *error = 1;
149     return first;
150 }
151                             
152 static int parse_zebra_elem(const char *elem,
153                             const char **index, size_t *index_len,
154                             const char **type, size_t *type_len)
155 {
156     *index = 0;
157     *index_len = 0;
158
159     *type = 0;
160     *type_len = 0;
161
162     if (elem && *elem)
163     {
164         char *cp;
165         /* verify that '::' is in the beginning of *elem 
166            and something more follows */
167         if (':' != *elem
168             || !(elem +1) || ':' != *(elem +1)
169             || !(elem +2) || '\0' == *(elem +2))
170             return 0;
171  
172         /* pick out info from string after '::' */
173         elem = elem + 2;
174         cp = strchr(elem, ':');
175
176         if (!cp) /* index, no colon, no type */
177         {
178             *index = elem;
179             *index_len = strlen(elem);
180         }
181         else if (cp[1] == '\0') /* colon, but no following type */
182         {
183             return 0;
184         }
185         else  /* index, colon and type */
186         {
187             *index = elem;
188             *index_len = cp - elem;
189             *type = cp+1;
190             *type_len = strlen(cp+1);
191         }
192     }
193     return 1;
194 }
195
196
197 int zebra_special_sort_fetch(
198     struct special_fetch_s *fi, const char *elemsetname,
199     const Odr_oid *input_format,
200     const Odr_oid **output_format,
201     WRBUF result, WRBUF addinfo)
202 {
203     const char *retrieval_index;
204     size_t retrieval_index_len; 
205     const char *retrieval_type;
206     size_t retrieval_type_len;
207     char retrieval_index_cstr[256];
208     char retrieval_type_cstr[256];
209     int ord;
210     ZebraHandle zh = fi->zh;
211
212     /* only accept XML and SUTRS requests */
213     if (oid_oidcmp(input_format, yaz_oid_recsyn_xml) 
214         && oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
215     {
216         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
217                 elemsetname);
218         *output_format = 0;
219         return YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
220     }
221     
222     if (!parse_zebra_elem(elemsetname,
223                           &retrieval_index, &retrieval_index_len,
224                           &retrieval_type,  &retrieval_type_len))
225     {
226         return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
227     }
228     
229     if (retrieval_type_len == 0)
230         return -1;   /* must have a register type specified */
231     if (!retrieval_index_len ||
232         retrieval_index_len >= sizeof(retrieval_index_cstr)-1)
233     {
234         return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
235     }
236         
237     memcpy(retrieval_index_cstr, retrieval_index, retrieval_index_len);
238     retrieval_index_cstr[retrieval_index_len] = '\0';
239
240     memcpy(retrieval_type_cstr, retrieval_type, retrieval_type_len);
241     retrieval_type_cstr[retrieval_type_len] = '\0';
242
243     ord = zebraExplain_lookup_attr_str(zh->reg->zei,
244                                        zinfo_index_category_sort,
245                                        retrieval_type_cstr,
246                                        retrieval_index_cstr);
247     if (ord == -1)
248         return -1;  /* is not a sort index */
249     else
250     {
251         char dst_buf[IT_MAX_WORD];
252         WRBUF str = wrbuf_alloc();
253         const char *index_type;
254         const char *db = 0;
255         const char *string_index = 0;
256         WRBUF wrbuf = result;
257         
258         zebra_sort_sysno(zh->reg->sort_index, fi->sysno);
259         zebra_sort_type(zh->reg->sort_index, ord);
260         zebra_sort_read(zh->reg->sort_index, str);
261
262         zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db, &string_index);
263         
264         zebra_term_untrans(zh, index_type, dst_buf, wrbuf_cstr(str));
265
266         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
267         {
268             *output_format = yaz_oid_recsyn_xml;
269             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
270                          " sysno=\"" ZINT_FORMAT "\""
271                          " set=\"zebra::index%s/\">\n",
272                          fi->sysno, elemsetname);
273
274             wrbuf_printf(wrbuf, "  <index name=\"%s\"", 
275                          string_index);
276             wrbuf_printf(wrbuf, " type=\"%s\">", index_type);
277             wrbuf_xmlputs(wrbuf, dst_buf);
278             wrbuf_printf(wrbuf, "</index>\n");
279             wrbuf_printf(wrbuf, "</record>\n");
280         }
281         else if (!oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
282         {
283             *output_format = yaz_oid_recsyn_sutrs;
284             
285             wrbuf_printf(wrbuf, "%s %s %s\n", string_index, index_type,
286                          dst_buf);
287         }
288         wrbuf_destroy(str);
289         return 0;
290     }
291 }
292                             
293 int zebra_special_index_fetch(
294     struct special_fetch_s *fi, const char *elemsetname,
295     const Odr_oid *input_format,
296     const Odr_oid **output_format,
297     WRBUF result, WRBUF addinfo,
298     Record rec)
299 {
300     const char *retrieval_index;
301     size_t retrieval_index_len; 
302     const char *retrieval_type;
303     size_t retrieval_type_len;
304     zebra_rec_keys_t keys;
305     int ret_code = 0;
306     char retrieval_type_cstr[256];
307     ZebraHandle zh = fi->zh;
308     
309     /* set output variables before processing possible error states */
310     /* *rec_lenp = 0; */
311
312     /* only accept XML and SUTRS requests */
313     if (oid_oidcmp(input_format, yaz_oid_recsyn_xml)
314         && oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
315     {
316         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
317                 elemsetname);
318         *output_format = 0;
319         return YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
320     }
321
322     if (!parse_zebra_elem(elemsetname,
323                      &retrieval_index, &retrieval_index_len,
324                      &retrieval_type,  &retrieval_type_len))
325         return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
326
327     if (retrieval_type_len)
328     {
329         memcpy(retrieval_type_cstr, retrieval_type, retrieval_type_len);
330         retrieval_type_cstr[retrieval_type_len] = '\0';
331     }
332     
333     if (retrieval_index_len)
334     {
335         char retrieval_index_cstr[256];
336
337         if (retrieval_index_len < sizeof(retrieval_index_cstr) -1)
338         {
339             memcpy(retrieval_index_cstr, retrieval_index, retrieval_index_len);
340             retrieval_index_cstr[retrieval_index_len] = '\0';
341             
342             if (zebraExplain_lookup_attr_str(zh->reg->zei,
343                                              zinfo_index_category_index,
344                                              (retrieval_type_len == 0 ? 0 : 
345                                               retrieval_type_cstr),
346                                              retrieval_index_cstr) == -1)
347                 return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
348         }
349     }
350
351     keys = zebra_rec_keys_open();
352     zebra_rec_keys_set_buf(keys, rec->info[recInfo_delKeys],
353                            rec->size[recInfo_delKeys], 0);
354
355     if (!zebra_rec_keys_rewind(keys))
356     {
357         ret_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
358     }
359     else
360     {
361         size_t slen;
362         const char *str;
363         struct it_key key_in;
364         WRBUF wrbuf = result;
365     
366         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
367         {
368             *output_format = input_format;
369             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
370                          " sysno=\"" ZINT_FORMAT "\""
371                          " set=\"zebra::index%s/\">\n",
372                          fi->sysno, elemsetname);
373         }
374         else if (!oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
375             *output_format = input_format;
376
377         while (zebra_rec_keys_read(keys, &str, &slen, &key_in))
378         {
379             int i;
380             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
381             const char *index_type;
382             const char *db = 0;
383             const char *string_index = 0;
384             size_t string_index_len;
385             char dst_buf[IT_MAX_WORD];
386             
387             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db,
388                                     &string_index);
389             string_index_len = strlen(string_index);
390
391             /* process only if index is not defined, 
392                or if defined and matching */
393             if (retrieval_index == 0 
394                 || (string_index_len == retrieval_index_len 
395                     && !memcmp(string_index, retrieval_index,
396                                string_index_len)))
397             {
398                 /* process only if type is not defined, or is matching */
399                 if (retrieval_type == 0 
400                     || !strcmp(retrieval_type_cstr, index_type))
401                 {
402                     if (zebra_term_untrans(zh, index_type, dst_buf, str))
403                         *dst_buf = '\0'; /* untrans failed */
404
405                     if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
406                     {
407                         wrbuf_printf(wrbuf, "  <index name=\"%s\"", 
408                                      string_index);
409                         
410                         wrbuf_printf(wrbuf, " type=\"%s\"", index_type);
411                         
412                         wrbuf_printf(wrbuf, " seq=\"" ZINT_FORMAT "\">", 
413                                      key_in.mem[key_in.len -1]);
414                         wrbuf_xmlputs(wrbuf, dst_buf);
415                         wrbuf_printf(wrbuf, "</index>\n");
416                     }
417                     else 
418                     {
419                         wrbuf_printf(wrbuf, "%s ", string_index);
420                         
421                         wrbuf_printf(wrbuf, "%s", index_type);
422                         
423                         for (i = 1; i < key_in.len; i++)
424                             wrbuf_printf(wrbuf, " " ZINT_FORMAT, 
425                                              key_in.mem[i]);
426                         
427                         wrbuf_printf(wrbuf, " %s", dst_buf);
428                         
429                         wrbuf_printf(wrbuf, "\n");
430
431                     }
432                     
433                 }
434             }
435         }
436         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
437             wrbuf_printf(wrbuf, "</record>\n");
438     }
439     zebra_rec_keys_close(keys);
440     return ret_code;
441 }
442
443
444 static void retrieve_puts_attr(WRBUF wrbuf, const char *name,
445                                const char *value)
446 {
447     if (value)
448     {
449         wrbuf_printf(wrbuf, " %s=\"", name);
450         wrbuf_xmlputs(wrbuf, value);
451         wrbuf_printf(wrbuf, "\"");
452     }
453 }
454
455 static void retrieve_puts_attr_int(WRBUF wrbuf, const char *name,
456                                const int value)
457 {
458     wrbuf_printf(wrbuf, " %s=\"%i\"", name, value);
459 }
460
461 static void retrieve_puts_str(WRBUF wrbuf, const char *name,
462                                const char *value)
463 {
464     if (value)
465         wrbuf_printf(wrbuf, "%s %s\n", name, value);
466 }
467
468 static void retrieve_puts_int(WRBUF wrbuf, const char *name,
469                                const int value)
470 {
471     wrbuf_printf(wrbuf, "%s %i\n", name, value);
472 }
473
474
475 static void snippet_xml_record(ZebraHandle zh, WRBUF wrbuf, zebra_snippets *doc)
476 {
477     const zebra_snippet_word *doc_w;
478     int mark_state = 0;
479
480     wrbuf_printf(wrbuf, "%s>\n", ZEBRA_XML_HEADER_STR);
481     for (doc_w = zebra_snippets_constlist(doc); doc_w; doc_w = doc_w->next)
482     {
483         if (doc_w->mark)
484         {
485             const char *index_type;
486             const char *db = 0;
487             const char *string_index = 0;
488
489             zebraExplain_lookup_ord(zh->reg->zei, doc_w->ord, 
490                                     &index_type, &db, &string_index);
491
492             if (mark_state == 0)
493             {
494                 wrbuf_printf(wrbuf, "  <snippet name=\"%s\"",  string_index);
495                 wrbuf_printf(wrbuf, " type=\"%s\">", index_type);
496             }
497             if (doc_w->match)
498                 wrbuf_puts(wrbuf, "<s>");
499             /* not printing leading ws */
500             if (mark_state || !doc_w->ws || doc_w->match) 
501                 wrbuf_xmlputs(wrbuf, doc_w->term);
502             if (doc_w->match)
503                 wrbuf_puts(wrbuf, "</s>");
504         }
505         else if (mark_state == 1)
506         {
507             wrbuf_puts(wrbuf, "</snippet>\n");
508         }
509         mark_state = doc_w->mark;
510     }
511     if (mark_state == 1)
512     {
513         wrbuf_puts(wrbuf, "</snippet>\n");
514     }
515     wrbuf_printf(wrbuf, "</record>");
516 }
517
518 int zebra_get_rec_snippets(ZebraHandle zh, zint sysno,
519                            zebra_snippets *snippets)
520 {
521     int return_code = 0;
522     Record rec = rec_get(zh->reg->records, sysno);
523     if (!rec)
524     {
525         yaz_log(YLOG_WARN, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
526         return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
527     }
528     else
529     {
530         const char *file_type = rec->info[recInfo_fileType];
531         void *recTypeClientData;
532         RecType rt = recType_byName(zh->reg->recTypes, zh->res,
533                                     file_type, &recTypeClientData);
534
535         if (!rt)
536             return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
537         else
538         {
539             struct ZebraRecStream stream;
540             return_code = zebra_create_record_stream(zh, &rec, &stream);
541             if (return_code == 0)
542             {
543                 extract_snippet(zh, snippets, &stream,
544                                 rt, recTypeClientData);
545
546                 stream.destroy(&stream);
547             }
548         }
549         rec_free(&rec);
550     }
551     return return_code;
552 }
553
554 static int snippet_fetch(
555     struct special_fetch_s *fi, const char *elemsetname,
556     const Odr_oid *input_format,
557     const Odr_oid **output_format,
558     WRBUF result, WRBUF addinfo)
559 {
560     ZebraHandle zh = fi->zh;
561     zebra_snippets *rec_snippets = zebra_snippets_create();
562     int return_code = zebra_get_rec_snippets(zh, fi->sysno, rec_snippets);
563
564     if (!return_code)
565     {
566         WRBUF wrbuf = result;
567         zebra_snippets *hit_snippet = zebra_snippets_create();
568
569         zebra_snippets_hit_vector(zh, fi->setname, fi->sysno, hit_snippet);
570
571 #if 0
572         /* for debugging purposes */
573         yaz_log(YLOG_LOG, "---------------------------");
574         yaz_log(YLOG_LOG, "REC SNIPPET:");
575         zebra_snippets_log(rec_snippets, YLOG_LOG, 1);
576         yaz_log(YLOG_LOG, "---------------------------");
577         yaz_log(YLOG_LOG, "HIT SNIPPET:");
578         zebra_snippets_log(hit_snippet, YLOG_LOG, 1);
579 #endif
580         
581         zebra_snippets_ring(rec_snippets, hit_snippet, 5, 5);
582         
583 #if 0
584         yaz_log(YLOG_LOG, "---------------------------");
585         yaz_log(YLOG_LOG, "RING SNIPPET:");
586         zebra_snippets_log(rec_snippets, YLOG_LOG, 1);
587 #endif
588         snippet_xml_record(zh, wrbuf, rec_snippets);
589         
590         *output_format = yaz_oid_recsyn_xml;
591         
592         zebra_snippets_destroy(hit_snippet);
593     }
594     zebra_snippets_destroy(rec_snippets);
595     return return_code;
596 }
597
598 struct term_collect {
599     const char *term;
600     int oc;
601     zint set_occur;
602 };
603
604 zint freq_term(ZebraHandle zh, int ord, const char *term, RSET rset_set)
605 {
606     struct rset_key_control *kc = zebra_key_control_create(zh);
607     char ord_buf[IT_MAX_WORD];
608     int ord_len = key_SU_encode(ord, ord_buf);
609     char *info;
610     zint hits = 0;
611     NMEM nmem = nmem_create();
612     
613     strcpy(ord_buf + ord_len, term);
614     
615     info = dict_lookup(zh->reg->dict, ord_buf);
616     if (info)
617     {
618         ISAM_P isam_p;
619         RSET rsets[2], rset;
620         memcpy(&isam_p, info+1, sizeof(ISAM_P));
621         
622         rsets[0] = zebra_create_rset_isam(zh, nmem, kc, kc->scope, isam_p, 0);
623         rsets[1] = rset_dup(rset_set);
624         
625         rset = rset_create_and(nmem, kc, kc->scope, 2, rsets);
626
627         zebra_count_set(zh, rset, &hits, zh->approx_limit);
628
629         rset_delete(rsets[0]);
630         rset_delete(rset);
631     }
632     (*kc->dec)(kc);
633     nmem_destroy(nmem);
634     return hits;
635 }
636
637 int term_qsort_handle(const void *a, const void *b)
638 {
639     const struct term_collect *l = a;
640     const struct term_collect *r = b;
641     if (l->set_occur < r->set_occur)
642         return 1;
643     else if (l->set_occur > r->set_occur)
644         return -1;
645     else
646     {
647         const char *lterm = l->term ? l->term : "";
648         const char *rterm = r->term ? r->term : "";
649         return strcmp(lterm, rterm);
650     }
651 }
652
653 void term_collect_freq(ZebraHandle zh,
654                        struct term_collect *col, int no_terms_collect,
655                        int ord, RSET rset)
656 {
657     int i;
658     for (i = 0; i < no_terms_collect; i++)
659     {
660         if (col[i].term)
661             col[i].set_occur = freq_term(zh, ord, col[i].term, rset);
662     }
663     qsort(col, no_terms_collect, sizeof(*col), term_qsort_handle);
664 }
665
666 struct term_collect *term_collect_create(zebra_strmap_t sm, 
667                                          int no_terms_collect,
668                                          NMEM nmem)
669 {
670     const char *term;
671     void *data_buf;
672     size_t data_len;
673     zebra_strmap_it it;
674     struct term_collect *col = nmem_malloc(nmem, 
675                                            sizeof *col *no_terms_collect);
676     int i;
677     for (i = 0; i < no_terms_collect; i++)
678     {
679         col[i].term = 0;
680         col[i].oc = 0;
681         col[i].set_occur = 0;
682     }
683     /* iterate over terms and collect the most frequent ones */
684     it = zebra_strmap_it_create(sm);
685     while ((term = zebra_strmap_it_next(it, &data_buf, &data_len)))
686     {
687         /* invariant:
688            col[0] has lowest oc .  col[no_terms_collect-1] has highest oc */
689         int oc = *(int*) data_buf;
690         int j = 0;
691         /* insertion may be slow but terms terms will be "infrequent" and
692            thus number of iterations should be small below 
693         */
694         while (j < no_terms_collect && oc > col[j].oc)
695             j++;
696         if (j) 
697         {   /* oc <= col[j] and oc > col[j-1] */
698             --j;
699             memmove(col, col+1, sizeof(*col) * j);
700             col[j].term = term;
701             col[j].oc = oc;
702         }
703     }
704     zebra_strmap_it_destroy(it);
705     return col;
706 }
707
708 static ZEBRA_RES facet_fetch(
709     struct special_fetch_s *fi, const char *elemsetname,
710     const Odr_oid *input_format,
711     const Odr_oid **output_format,
712     WRBUF result, WRBUF addinfo)
713 {
714     zint *pos_array;
715     int i;
716     int num_recs = 10; /* number of records to analyze */
717     int max_chunks = 2;
718     ZebraMetaRecord *poset;
719     ZEBRA_RES ret = ZEBRA_OK;
720     int *ord_array;
721     WRBUF wr = result;
722     int use_xml = 0;
723     int no_ord = 0;
724     struct index_spec *spec, *spec_list;
725     int error;
726     ZebraHandle zh = fi->zh;
727
728     res_get_int(zh->res, "facetNumRecs", &num_recs);
729     res_get_int(zh->res, "facetMaxChunks", &max_chunks);
730
731     /* see if XML is required for response */
732     if (oid_oidcmp(input_format, yaz_oid_recsyn_xml) == 0)
733         use_xml = 1;
734
735     spec_list = parse_index_spec(elemsetname, fi->nmem, &error);
736               
737     if (!spec_list || error)
738     {
739         zebra_setError(
740             zh, 
741             YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
742             0);
743         return ZEBRA_FAIL;
744     }          
745   
746     for (spec = spec_list; spec; spec = spec->next)
747     {
748         if (!spec->index_type)
749         {
750             zebra_setError(
751                 zh, 
752                 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
753                 0);
754             return ZEBRA_FAIL;
755         }
756         no_ord++;
757     }
758
759     ord_array = nmem_malloc(fi->nmem, sizeof(*ord_array) * no_ord);
760
761     for (spec = spec_list, i = 0; spec; spec = spec->next, i++)
762     {
763         int ord = zebraExplain_lookup_attr_str(zh->reg->zei,
764                                                zinfo_index_category_index,
765                                                spec->index_type,
766                                                spec->index_name);
767         if (ord == -1)
768         {
769             zebra_setError(
770                 zh, 
771                 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
772                 0);
773             return ZEBRA_FAIL;
774         }
775         ord_array[i] = ord;
776     }
777     pos_array = (zint *) nmem_malloc(fi->nmem, num_recs * sizeof(*pos_array));
778     for (i = 0; i < num_recs; i++)
779         pos_array[i] = i+1;
780     poset = zebra_meta_records_create(zh, fi->setname, num_recs, pos_array);
781     if (!poset)
782     {
783         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
784                        fi->setname);
785         ret = ZEBRA_FAIL;
786     }
787     else
788     {
789         yaz_timing_t timing = yaz_timing_create();
790         zebra_strmap_t *map_array
791             = nmem_malloc(fi->nmem, sizeof *map_array * no_ord);
792         for (i = 0; i < no_ord; i++)
793             map_array[i] = zebra_strmap_create();
794
795         for (i = 0; i < num_recs; i++)
796         {
797             int j;
798             zint sysnos[MAX_SYSNOS_PER_RECORD];
799             int no_sysnos = MAX_SYSNOS_PER_RECORD;
800             if (!poset[i].sysno)
801                 continue;
802             ret = zebra_result_recid_to_sysno(zh, fi->setname,
803                                               poset[i].sysno,
804                                               sysnos, &no_sysnos);
805             assert(no_sysnos > 0);
806             yaz_log(YLOG_DEBUG, "Analyzing rec=%d ISAM sysno=" ZINT_FORMAT " chunks=%d",
807                     i, poset[i].sysno, no_sysnos);
808             for (j = 0; j < no_sysnos && j < max_chunks; j++)
809             {
810                 size_t slen;
811                 const char *str;
812                 struct it_key key_in;
813                 Record rec = rec_get(zh->reg->records, sysnos[j]);
814                 zebra_rec_keys_t keys = zebra_rec_keys_open();
815                 zebra_rec_keys_set_buf(keys, rec->info[recInfo_delKeys],
816                                        rec->size[recInfo_delKeys], 0);
817
818                 yaz_log(YLOG_DEBUG, "rec %d " ZINT_FORMAT " %s", 
819                         j, sysnos[j], zebra_rec_keys_empty(keys) ? "empty" : "non-empty");
820                 if (zebra_rec_keys_rewind(keys))
821                 {
822                     while (zebra_rec_keys_read(keys, &str, &slen, &key_in))
823                     {
824                         int i;
825                         struct index_spec *spec;
826                         for (spec = spec_list, i = 0; i < no_ord; 
827                              i++, spec = spec->next)
828                         {
829                             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
830                             if (ord == ord_array[i] && 
831                                 str[0] != FIRST_IN_FIELD_CHAR)
832                             {
833                                 int *freq;
834                                 zebra_strmap_t sm = map_array[i];
835                                 
836                                 freq = zebra_strmap_lookup(sm, str, 0, 0);
837                                 if (freq)
838                                     (*freq)++;
839                                 else
840                                 {
841                                     int v = 1;
842                                     zebra_strmap_add(sm, str, &v, sizeof v);
843                                 }
844                             }
845                         }
846                     }
847                 }
848                 zebra_rec_keys_close(keys);
849                 rec_free(&rec);
850             }
851         }
852         yaz_timing_stop(timing);
853         yaz_log(YLOG_LOG, "facet first phase real=%4.2f",
854                 yaz_timing_get_real(timing));
855         yaz_timing_start(timing);
856         if (use_xml)
857             wrbuf_puts(wr, "<facets>\n");
858         for (spec = spec_list, i = 0; i < no_ord; i++, spec = spec->next)
859         {
860             int j;
861             NMEM nmem = nmem_create();
862             struct term_collect *col;
863             int no_collect_terms = 20;
864
865             if (spec->extra)
866                 no_collect_terms = atoi(spec->extra);
867             if (no_collect_terms < 1)
868                 no_collect_terms = 1;
869             col = term_collect_create(map_array[i], no_collect_terms, nmem);
870             term_collect_freq(zh, col, no_collect_terms, ord_array[i],
871                               resultSetRef(zh, fi->setname));
872             
873             if (use_xml)
874                 wrbuf_printf(wr, "  <facet type=\"%s\" index=\"%s\">\n",
875                              spec->index_type, spec->index_name);
876             else
877                 wrbuf_printf(wr, "facet %s %s\n",
878                              spec->index_type, spec->index_name);
879             for (j = 0; j < no_collect_terms; j++)
880             {
881                 if (col[j].term)
882                 {
883                     char dst_buf[IT_MAX_WORD];
884                     zebra_term_untrans(zh, spec->index_type, dst_buf, col[j].term);
885                     if (use_xml)
886                     {
887                         wrbuf_printf(wr, "    <term coccur=\"%d\"", col[j].oc);
888                         if (col[j].set_occur)
889                             wrbuf_printf(wr, " occur=\"" ZINT_FORMAT "\"", 
890                                          col[j].set_occur);
891                         wrbuf_printf(wr, ">");
892                         wrbuf_xmlputs(wr, dst_buf);
893                         wrbuf_printf(wr, "</term>\n");
894                     }
895                     else
896                     {
897                         wrbuf_printf(wr, "term %d", col[j].oc);
898                         if (col[j].set_occur)
899                             wrbuf_printf(wr, " " ZINT_FORMAT, 
900                                          col[j].set_occur);
901                         wrbuf_printf(wr, ": %s\n", dst_buf);
902                     }
903                 }
904             }
905             if (use_xml)
906                 wrbuf_puts(wr, "  </facet>\n");
907             nmem_destroy(nmem);
908         }
909         if (use_xml)
910             wrbuf_puts(wr, "</facets>\n");
911         for (i = 0; i < no_ord; i++)
912             zebra_strmap_destroy(map_array[i]);
913         yaz_timing_stop(timing);
914         yaz_log(YLOG_LOG, "facet second phase real=%4.2f",
915                 yaz_timing_get_real(timing));
916         yaz_timing_destroy(&timing);
917     }
918     *output_format = yaz_oid_recsyn_xml;
919     zebra_meta_records_destroy(zh, poset, num_recs);
920     return ret;
921 }
922
923
924 int zebra_special_fetch(
925     void *handle, const char *elemsetname,
926     const Odr_oid *input_format,
927     const Odr_oid **output_format,
928     WRBUF result, WRBUF addinfo
929     )
930 {
931     Record rec = 0;
932     struct special_fetch_s *fi = (struct special_fetch_s *) handle;
933     ZebraHandle zh = fi->zh;
934     zint sysno = fi->sysno;
935     
936     /* set output variables before processing possible error states */
937     /* *rec_lenp = 0; */
938
939     if (elemsetname && 0 == strncmp(elemsetname, "facet", 5))
940     {
941         return facet_fetch(fi, elemsetname + 5, 
942                            input_format, output_format,
943                            result, addinfo);
944     }
945
946     if (elemsetname && 0 == strcmp(elemsetname, "snippet"))
947     {
948         return snippet_fetch(fi, elemsetname + 7,
949                              input_format, output_format,
950                              result, addinfo);
951     }
952
953     /* processing zebra::meta::sysno elemset without fetching binary data */
954     if (elemsetname && 0 == strcmp(elemsetname, "meta::sysno"))
955     {
956         int ret = 0;
957         WRBUF wrbuf = result;
958         if (!oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
959         {
960             wrbuf_printf(wrbuf, ZINT_FORMAT, fi->sysno);
961             *output_format = input_format;
962         } 
963         else if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
964         {
965             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
966                          " sysno=\"" ZINT_FORMAT "\"/>\n",
967                          fi->sysno);
968             *output_format = input_format;
969         }
970         if (wrbuf_len(wrbuf) == 0)
971             ret = YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
972         return ret;
973     }
974
975     /* processing special elementsetname zebra::index:: for sort elements */
976     if (elemsetname && 0 == strncmp(elemsetname, "index", 5))
977     {
978         int ret = zebra_special_sort_fetch(
979             fi, elemsetname + 5,
980             input_format, output_format,
981             result, addinfo);
982         if (ret != -1)
983             return ret;
984         /* not a sort index so we continue to get the full record */
985     }
986
987
988     /* fetching binary record up for all other display elementsets */
989     rec = rec_get(zh->reg->records, sysno);
990     if (!rec)
991     {
992         yaz_log(YLOG_WARN, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
993         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
994     }
995
996     /* processing special elementsetnames zebra::data */    
997     if (elemsetname && 0 == strcmp(elemsetname, "data"))
998     {
999         struct ZebraRecStream stream;
1000         RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, rec); 
1001         char *b;
1002
1003         zebra_create_record_stream(zh, &rec, &stream);
1004         *output_format = input_format;
1005
1006         b = nmem_malloc(fi->nmem, recordAttr->recordSize);
1007         stream.readf(&stream, b, recordAttr->recordSize);
1008         wrbuf_write(result, b, recordAttr->recordSize);
1009
1010         stream.destroy(&stream);
1011         rec_free(&rec);
1012         return 0;
1013     }
1014
1015     /* only accept XML and SUTRS requests from now */
1016     if (oid_oidcmp(input_format, yaz_oid_recsyn_xml)
1017         && oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
1018     {
1019         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
1020                 elemsetname);
1021         return YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
1022     }
1023     
1024     /* processing special elementsetnames zebra::meta:: */
1025     if (elemsetname && 0 == strcmp(elemsetname, "meta"))
1026     {
1027         int ret = 0;
1028         WRBUF wrbuf = result;
1029         RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, rec); 
1030
1031         if (!oid_oidcmp(input_format, yaz_oid_recsyn_xml))
1032         {
1033             *output_format = input_format;
1034             
1035             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
1036                          " sysno=\"" ZINT_FORMAT "\"", sysno);
1037             retrieve_puts_attr(wrbuf, "base", rec->info[recInfo_databaseName]);
1038             retrieve_puts_attr(wrbuf, "file", rec->info[recInfo_filename]);
1039             retrieve_puts_attr(wrbuf, "type", rec->info[recInfo_fileType]);
1040             if (fi->score >= 0)
1041                 retrieve_puts_attr_int(wrbuf, "score", fi->score);
1042            
1043             wrbuf_printf(wrbuf,
1044                          " rank=\"" ZINT_FORMAT "\""
1045                          " size=\"%i\""
1046                          " set=\"zebra::%s\"/>\n",
1047                          recordAttr->staticrank,
1048                          recordAttr->recordSize,
1049                          elemsetname);
1050         }
1051         else if (!oid_oidcmp(input_format, yaz_oid_recsyn_sutrs))
1052         {
1053             *output_format = input_format;
1054             wrbuf_printf(wrbuf, "sysno " ZINT_FORMAT "\n", sysno);
1055             retrieve_puts_str(wrbuf, "base", rec->info[recInfo_databaseName]);
1056             retrieve_puts_str(wrbuf, "file", rec->info[recInfo_filename]);
1057             retrieve_puts_str(wrbuf, "type", rec->info[recInfo_fileType]);
1058             if (fi->score >= 0)
1059                 retrieve_puts_int(wrbuf, "score", fi->score);
1060
1061             wrbuf_printf(wrbuf,
1062                          "rank " ZINT_FORMAT "\n"
1063                          "size %i\n"
1064                          "set zebra::%s\n",
1065                          recordAttr->staticrank,
1066                          recordAttr->recordSize,
1067                          elemsetname);
1068         }
1069         if (wrbuf_len(wrbuf) == 0)
1070             ret = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1071
1072         rec_free(&rec);
1073         return ret;
1074     }
1075
1076     /* processing special elementsetnames zebra::index:: */
1077     if (elemsetname && 0 == strncmp(elemsetname, "index", 5))
1078     {
1079         int ret = zebra_special_index_fetch(
1080             fi, elemsetname + 5,
1081             input_format, output_format,
1082             result, addinfo, rec);
1083         rec_free(&rec);
1084         return ret;
1085     }
1086
1087     if (rec)
1088         rec_free(&rec);
1089     return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
1090 }
1091
1092 int zebra_record_fetch(ZebraHandle zh, const char *setname,
1093                        zint sysno, int score,
1094                        ODR odr,
1095                        const Odr_oid *input_format, Z_RecordComposition *comp,
1096                        const Odr_oid **output_format,
1097                        char **rec_bufp, int *rec_lenp, char **basenamep,
1098                        char **addinfo)
1099 {
1100     Record rec;
1101     char *fname, *file_type, *basename;
1102     const char *elemsetname;
1103     struct ZebraRecStream stream;
1104     RecordAttr *recordAttr;
1105     void *clientData;
1106     int return_code = 0;
1107     zint sysnos[MAX_SYSNOS_PER_RECORD];
1108     int no_sysnos = MAX_SYSNOS_PER_RECORD;
1109     ZEBRA_RES res;
1110     struct special_fetch_s fetch_info;
1111
1112     res = zebra_result_recid_to_sysno(zh, setname, sysno, sysnos, &no_sysnos);
1113     if (res != ZEBRA_OK)
1114         return ZEBRA_FAIL;
1115
1116     sysno = sysnos[0];
1117     *basenamep = 0;
1118     *addinfo = 0;
1119     elemsetname = yaz_get_esn(comp);
1120
1121     fetch_info.zh = zh;
1122     fetch_info.setname = setname;
1123     fetch_info.sysno = sysno;
1124     fetch_info.score = score;
1125     fetch_info.nmem = odr->mem;
1126
1127     /* processing zebra special elementset names of form 'zebra:: */
1128     if (elemsetname && 0 == strncmp(elemsetname, "zebra::", 7))
1129     {
1130         WRBUF result = wrbuf_alloc();
1131         WRBUF addinfo_w = wrbuf_alloc();
1132         int r = zebra_special_fetch(&fetch_info, elemsetname + 7,
1133                                     input_format, output_format,
1134                                     result, addinfo_w);
1135         if (r == 0)
1136         {
1137             *rec_bufp = odr_strdup(odr, wrbuf_cstr(result));
1138             *rec_lenp = wrbuf_len(result);
1139         }
1140         else 
1141         {
1142             if (wrbuf_len(addinfo_w))
1143                 *addinfo = odr_strdup(odr, wrbuf_cstr(addinfo_w));
1144         }
1145         wrbuf_destroy(result);
1146         wrbuf_destroy(addinfo_w);
1147         return r;
1148     }
1149
1150     /* processing all other element set names */
1151     rec = rec_get(zh->reg->records, sysno);
1152     if (!rec)
1153     {
1154         yaz_log(YLOG_WARN, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
1155         *basenamep = 0;
1156         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1157     }
1158
1159
1160     recordAttr = rec_init_attr(zh->reg->zei, rec);
1161
1162     file_type = rec->info[recInfo_fileType];
1163     fname = rec->info[recInfo_filename];
1164     basename = rec->info[recInfo_databaseName];
1165     *basenamep = (char *) odr_malloc(odr, strlen(basename)+1);
1166     strcpy(*basenamep, basename);
1167
1168     yaz_log(YLOG_DEBUG, "retrieve localno=" ZINT_FORMAT " score=%d",
1169             sysno, score);
1170
1171     return_code = zebra_create_record_stream(zh, &rec, &stream);
1172
1173     if (rec)
1174     {
1175         RecType rt;
1176         struct recRetrieveCtrl retrieveCtrl;
1177
1178         retrieveCtrl.stream = &stream;
1179         retrieveCtrl.fname = fname;
1180         retrieveCtrl.localno = sysno;
1181         retrieveCtrl.staticrank = recordAttr->staticrank;
1182         retrieveCtrl.score = score;
1183         retrieveCtrl.recordSize = recordAttr->recordSize;
1184         retrieveCtrl.odr = odr;
1185         retrieveCtrl.input_format = retrieveCtrl.output_format = input_format;
1186         retrieveCtrl.comp = comp;
1187         retrieveCtrl.encoding = zh->record_encoding;
1188         retrieveCtrl.diagnostic = 0;
1189         retrieveCtrl.addinfo = 0;
1190         retrieveCtrl.dh = zh->reg->dh;
1191         retrieveCtrl.res = zh->res;
1192         retrieveCtrl.rec_buf = 0;
1193         retrieveCtrl.rec_len = -1;
1194         retrieveCtrl.handle = &fetch_info;
1195         retrieveCtrl.special_fetch = zebra_special_fetch;
1196
1197         if (!(rt = recType_byName(zh->reg->recTypes, zh->res,
1198                                   file_type, &clientData)))
1199         {
1200             char addinfo_str[100];
1201
1202             sprintf(addinfo_str, "Could not handle record type %.40s",
1203                     file_type);
1204                     
1205             *addinfo = odr_strdup(odr, addinfo_str);
1206             return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1207         }
1208         else
1209         {
1210             (*rt->retrieve)(clientData, &retrieveCtrl);
1211             return_code = retrieveCtrl.diagnostic;
1212
1213             *output_format = retrieveCtrl.output_format;
1214             *rec_bufp = (char *) retrieveCtrl.rec_buf;
1215             *rec_lenp = retrieveCtrl.rec_len;
1216             *addinfo = retrieveCtrl.addinfo;
1217         }
1218
1219         stream.destroy(&stream);
1220         rec_free(&rec);
1221     }
1222
1223     return return_code;
1224 }
1225
1226 /*
1227  * Local variables:
1228  * c-basic-offset: 4
1229  * indent-tabs-mode: nil
1230  * End:
1231  * vim: shiftwidth=4 tabstop=8 expandtab
1232  */
1233