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