added suggestions for better workflow in comments
[idzebra-moved-to-github.git] / index / retrieve.c
1 /* $Id: retrieve.c,v 1.50 2006-11-15 14:09:43 marc Exp $
2    Copyright (C) 1995-2006
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 this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
21 */
22
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 <direntz.h>
38
39
40
41
42 static int zebra_create_record_stream(ZebraHandle zh, 
43                                Record *rec,
44                                struct ZebraRecStream *stream){
45
46     RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, *rec);
47
48     if ((*rec)->size[recInfo_storeData] > 0){ 
49         zebra_create_stream_mem(stream, (*rec)->info[recInfo_storeData],
50                                 (*rec)->size[recInfo_storeData]);
51     }
52     else {
53         char full_rep[1024];
54         int fd;
55             
56         if (zh->path_reg && !yaz_is_abspath((*rec)->info[recInfo_filename])){
57             strcpy(full_rep, zh->path_reg);
58             strcat(full_rep, "/");
59             strcat(full_rep, (*rec)->info[recInfo_filename]);
60         }
61         else
62             strcpy(full_rep, (*rec)->info[recInfo_filename]);
63             
64         if ((fd = open (full_rep, O_BINARY|O_RDONLY)) == -1){
65             yaz_log (YLOG_WARN|YLOG_ERRNO, "Retrieve fail; missing file: %s",
66                      full_rep);
67             rec_free(rec);
68             return 14;
69         }
70         zebra_create_stream_fd(stream, fd, recordAttr->recordOffset);
71     }
72     return 0;
73 }
74     
75
76
77 static void parse_zebra_elem(const char *elem,
78                              const char **index, size_t *index_len,
79                              const char **type, size_t *type_len)
80 {
81     *type = 0;
82     *type_len = 0;
83
84     *index = 0;
85     *index_len = 0;
86
87     if (elem && *elem)
88     {
89         const char *cp = strchr(elem, ':');
90
91         if (!cp) /* no colon */
92         {
93             *index = elem;
94             *index_len = strlen(elem);
95         }
96         else if (cp[1] == '\0') /* 'index:' */
97         {
98             *index = elem;
99             *index_len = cp - elem;
100         }
101         else
102         {
103             *index = elem;
104             *index_len = cp - elem;
105             *type = cp+1;
106             *type_len = strlen(cp+1);
107         }
108     }
109 }
110
111
112 int zebra_special_index_fetch(ZebraHandle zh, SYSNO sysno, ODR odr,
113                           Record rec,
114                           const char *elemsetname,
115                           oid_value input_format,
116                           oid_value *output_format,
117                           char **rec_bufp, int *rec_lenp)
118 {
119     const char *retrieval_index;
120     size_t retrieval_index_len; 
121     const char *retrieval_type;
122     size_t retrieval_type_len;
123    
124     /* int return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS; */
125
126     WRBUF wrbuf = wrbuf_alloc();
127     zebra_rec_keys_t keys;
128     
129     /* only accept XML and SUTRS requests */
130     if (input_format != VAL_TEXT_XML
131         && input_format != VAL_SUTRS){
132         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
133                 elemsetname);
134         *output_format = VAL_NONE;
135         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
136     }
137
138     keys = zebra_rec_keys_open();
139     zebra_rec_keys_set_buf(keys, rec->info[recInfo_delKeys],
140                            rec->size[recInfo_delKeys], 0);
141
142     parse_zebra_elem(elemsetname,
143                      &retrieval_index, &retrieval_index_len,
144                      &retrieval_type,  &retrieval_type_len);
145
146     if (zebra_rec_keys_rewind(keys)){
147         size_t slen;
148         const char *str;
149         struct it_key key_in;
150
151         if (input_format == VAL_TEXT_XML){
152             *output_format = VAL_TEXT_XML;
153             /*wrbuf_printf(wrbuf, 
154               "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");*/
155             
156             wrbuf_printf(wrbuf, 
157                          "<record xmlns="
158                          "\"http://www.indexdata.com/zebra/\""
159                          " sysno=\"" ZINT_FORMAT "\""
160                          " set=\"zebra::index::%s\">\n",
161                          sysno, elemsetname);
162         }
163         else if (input_format == VAL_SUTRS)
164             *output_format = VAL_SUTRS;
165
166
167         while(zebra_rec_keys_read(keys, &str, &slen, &key_in)){
168             int i;
169             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
170             int index_type;
171             const char *db = 0;
172             const char *string_index = 0;
173             size_t string_index_len;
174             char dst_buf[IT_MAX_WORD];
175             
176             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db,
177                                     &string_index);
178             string_index_len = strlen(string_index);
179             if (retrieval_index == 0 
180                 || (string_index_len == retrieval_index_len 
181                     && !memcmp(string_index, retrieval_index,
182                                string_index_len))){
183                 
184                 if (retrieval_type == 0 
185                     || (retrieval_type_len == 1 
186                         && retrieval_type[0] == index_type)){
187                     
188                     if (input_format == VAL_TEXT_XML){
189                         wrbuf_printf(wrbuf, "  <index name=\"%s\"", 
190                                      string_index);
191                         
192                         wrbuf_printf(wrbuf, " type=\"%c\"", index_type);
193                         
194                         wrbuf_printf(wrbuf, " seq=\"" ZINT_FORMAT "\">", 
195                                      key_in.mem[key_in.len -1]);
196                         
197                         zebra_term_untrans(zh, index_type, dst_buf, str);
198                         wrbuf_xmlputs(wrbuf, dst_buf);
199                         wrbuf_printf(wrbuf, "</index>\n");
200                     }
201                     else if (input_format == VAL_SUTRS){
202                         wrbuf_printf(wrbuf, "%s ", string_index);
203                     
204                         wrbuf_printf(wrbuf, "%c", index_type);
205                     
206                         for (i = 1; i < key_in.len; i++)
207                             wrbuf_printf(wrbuf, " " ZINT_FORMAT, 
208                                          key_in.mem[i]);
209
210                         zebra_term_untrans(zh, index_type, dst_buf, str);
211                         wrbuf_printf(wrbuf, " %s", dst_buf);
212                         
213                         wrbuf_printf(wrbuf, "\n");
214                     }
215                 }
216             }
217         }
218         if (input_format == VAL_TEXT_XML)
219             wrbuf_printf(wrbuf, "</record>\n");
220      }
221     
222     *rec_lenp = wrbuf_len(wrbuf);
223     *rec_bufp = odr_malloc(odr, *rec_lenp);
224     memcpy(*rec_bufp, wrbuf_buf(wrbuf), *rec_lenp);
225     wrbuf_free(wrbuf, 1);
226     zebra_rec_keys_close(keys);
227     return 0;
228 }
229
230
231 int zebra_special_fetch(ZebraHandle zh, SYSNO sysno, ODR odr,
232                            const char *elemsetname,
233                            oid_value input_format,
234                            oid_value *output_format,
235                            char **rec_bufp, int *rec_lenp)
236 {
237     Record rec;
238
239     /* only accept XML and SUTRS requests */
240     if (input_format != VAL_TEXT_XML
241         && input_format != VAL_SUTRS){
242         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
243                 elemsetname);
244         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
245     }
246
247     /* processing zebra::meta::sysno elemset without fetching binary data */
248     if (elemsetname  && 0 == strcmp(elemsetname, "meta::sysno"))
249     {
250         char rec_str[128];
251         if (input_format == VAL_SUTRS){
252             sprintf(rec_str, ZINT_FORMAT, sysno);
253             *output_format = VAL_SUTRS;
254         } 
255         else if (input_format == VAL_TEXT_XML){
256             sprintf(rec_str, "<record xmlns="
257                              "\"http://www.indexdata.com/zebra/\""
258                              " sysno=\"" ZINT_FORMAT "\""
259                              " set=\"zebra::%s\">\n",
260                              sysno, elemsetname);
261             *output_format = VAL_TEXT_XML;
262         }
263         *rec_lenp = strlen(rec_str);
264         if (*rec_lenp){
265             *rec_bufp = odr_strdup(odr, rec_str);
266             return 0;
267         } else {
268             return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
269         }
270     }
271
272     /* fetching binary record up for all other display elementsets */
273     rec = rec_get(zh->reg->records, sysno);
274     if (!rec){
275         yaz_log(YLOG_DEBUG, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
276         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
277     }
278
279     /* processing special elementsetnames zebra::index:: */
280     if (elemsetname && 0 == strncmp(elemsetname, "index::", 7)){
281         
282         int ret = zebra_special_index_fetch(zh, sysno, odr, rec,
283                                             elemsetname + 7,
284                                             input_format, output_format,
285                                             rec_bufp, rec_lenp);
286         
287         rec_free(&rec);
288         return ret;
289     }
290
291     /* processing special elementsetnames zebra::data */    
292     if (elemsetname && 0 == strcmp(elemsetname, "data")){
293         struct ZebraRecStream stream;
294         RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, rec); 
295         zebra_create_record_stream(zh, &rec, &stream);
296         *output_format = VAL_SUTRS;
297         *rec_lenp = recordAttr->recordSize;
298         *rec_bufp = (char *) odr_malloc(odr, *rec_lenp);
299         stream.readf(&stream, *rec_bufp, *rec_lenp);
300         stream.destroy(&stream);
301         rec_free(&rec);
302         return 0;
303     }
304
305     if (rec)
306         rec_free(&rec);
307     return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
308 }
309
310                           
311 int zebra_record_fetch(ZebraHandle zh, SYSNO sysno, int score,
312                        zebra_snippets *hit_snippet, ODR odr,
313                        oid_value input_format, Z_RecordComposition *comp,
314                        oid_value *output_format,
315                        char **rec_bufp, int *rec_lenp, char **basenamep,
316                        char **addinfo)
317 {
318     Record rec;
319     char *fname, *file_type, *basename;
320     const char *elemsetname;
321     struct ZebraRecStream stream;
322     RecordAttr *recordAttr;
323     void *clientData;
324     int return_code = 0;
325
326     *basenamep = 0;
327     *addinfo = 0;
328     elemsetname = yaz_get_esn(comp);
329
330     /*
331     yaz_log(YLOG_LOG, "ELEMENTSET: '%s'", elemsetname);
332     if (comp && comp->which)
333         {
334             yaz_log(YLOG_LOG, "%i %i", comp, comp->which);
335         }
336         If SRU, comp->which ==2 , and yaz_get_esn(comp) does not work correctly
337         IF Z3055, comp->which ==1 , and everything is fine - except reord 
338         encodning
339     */
340
341     /* processing zebra special elementset names of form 'zebra:: */
342     /* SUGGESTION: do not check elemset nema here, buuuut ... */  
343     if (elemsetname  && 0 == strncmp(elemsetname, "zebra::", 7))
344         return  zebra_special_fetch(zh, sysno, odr,
345                                     elemsetname + 7,
346                                     input_format, output_format,
347                                     rec_bufp, rec_lenp);
348
349
350     /* processing all other element set names */
351     rec = rec_get(zh->reg->records, sysno);
352     if (!rec)
353     {
354         yaz_log(YLOG_DEBUG, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
355         *basenamep = 0;
356         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
357     }
358
359
360     recordAttr = rec_init_attr(zh->reg->zei, rec);
361
362     file_type = rec->info[recInfo_fileType];
363     fname = rec->info[recInfo_filename];
364     basename = rec->info[recInfo_databaseName];
365     *basenamep = (char *) odr_malloc (odr, strlen(basename)+1);
366     strcpy (*basenamep, basename);
367
368
369     yaz_log (YLOG_DEBUG, "retrieve localno=" ZINT_FORMAT " score=%d",
370              sysno, score);
371
372     zebra_create_record_stream(zh, &rec, &stream);
373     
374     {
375         /* snippets code */
376         zebra_snippets *snippet;
377         zebra_rec_keys_t reckeys = zebra_rec_keys_open();
378         RecType rt;
379         struct recRetrieveCtrl retrieveCtrl;
380
381         retrieveCtrl.stream = &stream;
382         retrieveCtrl.fname = fname;
383         retrieveCtrl.localno = sysno;
384         retrieveCtrl.staticrank = recordAttr->staticrank;
385         retrieveCtrl.score = score;
386         retrieveCtrl.recordSize = recordAttr->recordSize;
387         retrieveCtrl.odr = odr;
388         retrieveCtrl.input_format = retrieveCtrl.output_format = input_format;
389         retrieveCtrl.comp = comp;
390         retrieveCtrl.encoding = zh->record_encoding;
391         retrieveCtrl.diagnostic = 0;
392         retrieveCtrl.addinfo = 0;
393         retrieveCtrl.dh = zh->reg->dh;
394         retrieveCtrl.res = zh->res;
395         retrieveCtrl.rec_buf = 0;
396         retrieveCtrl.rec_len = -1;
397         retrieveCtrl.hit_snippet = hit_snippet;
398         retrieveCtrl.doc_snippet = zebra_snippets_create();
399
400         zebra_rec_keys_set_buf(reckeys,
401                                rec->info[recInfo_delKeys],
402                                rec->size[recInfo_delKeys], 
403                                0);
404         zebra_rec_keys_to_snippets(zh, reckeys, retrieveCtrl.doc_snippet);
405         zebra_rec_keys_close(reckeys);
406
407 #if 0
408         /* for debugging purposes */
409         yaz_log(YLOG_LOG, "DOC SNIPPET:");
410         zebra_snippets_log(retrieveCtrl.doc_snippet, YLOG_LOG);
411         yaz_log(YLOG_LOG, "HIT SNIPPET:");
412         zebra_snippets_log(retrieveCtrl.hit_snippet, YLOG_LOG);
413 #endif
414         snippet = zebra_snippets_window(retrieveCtrl.doc_snippet,
415                                         retrieveCtrl.hit_snippet,
416                                         10);
417 #if 0
418         /* for debugging purposes */
419         yaz_log(YLOG_LOG, "WINDOW SNIPPET:");
420         zebra_snippets_log(snippet, YLOG_LOG);
421 #endif
422
423         /* SUGGESTION: do not check elemset name here, buuuut ... 
424            add another recType Struct with zebra internal stuff here,
425            which overrides the Alvis/GRS-1/Safari filters .... 
426         */
427         if (!(rt = recType_byName(zh->reg->recTypes, zh->res,
428                                   file_type, &clientData)))
429         {
430             return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
431         }
432         else
433         {
434         /* SUGGESTION: do not check elemset name here, buuuut ... 
435            add another recType Struct with zebra internal stuff here,
436            which overrides the Alvis/GRS-1/Safari filters .... 
437            (*rt->retrieve) method to make the correct encoded, etc, retrieval,
438            where all needed info already is found in the   &retrieveCtr
439            parameter. This way, we do not need to re-code/dublicate a lot of 
440            logic. 
441         */
442             (*rt->retrieve)(clientData, &retrieveCtrl);
443             return_code = retrieveCtrl.diagnostic;
444
445             *output_format = retrieveCtrl.output_format;
446             *rec_bufp = (char *) retrieveCtrl.rec_buf;
447             *rec_lenp = retrieveCtrl.rec_len;
448             *addinfo = retrieveCtrl.addinfo;
449         }
450         /* another SUGGESTION: throw out all this snippet stuff in this 
451            file, and do it correctly - either inside filters, or in another 
452            new   (*rt->retrieve)(clientData, &retrieveCtrl); type 'snippet'
453         */
454
455         zebra_snippets_destroy(snippet);
456         zebra_snippets_destroy(retrieveCtrl.doc_snippet);
457      }
458
459     stream.destroy(&stream);
460     rec_free(&rec);
461
462     return return_code;
463 }
464
465 /*
466  * Local variables:
467  * c-basic-offset: 4
468  * indent-tabs-mode: nil
469  * End:
470  * vim: shiftwidth=4 tabstop=8 expandtab
471  */
472