Fix missing return type. Fix function name
[yaz-moved-to-github.git] / src / solr.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2011 Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file solr.c
7  * \brief Implements Solr decoding/encoding
8  */
9 #if HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12
13 #include <stdlib.h>
14 #include <assert.h>
15 #include <yaz/srw.h>
16 #include <yaz/matchstr.h>
17 #include <yaz/yaz-iconv.h>
18 #include <yaz/log.h>
19 #include <yaz/facet.h>
20 #include <yaz/wrbuf.h>
21
22 #include "sru-p.h"
23
24 #define SOLR_MAX_PARAMETERS  100
25
26 #if YAZ_HAVE_XML2
27 #include <libxml/parser.h>
28 #include <libxml/tree.h>
29 #endif
30
31 static void extract_text_node(xmlNodePtr node, WRBUF wrbuf) {
32     xmlNodePtr child;
33     for (child = node->children; child ; child = child->next)
34     {
35         if (child->type == XML_TEXT_NODE)
36             wrbuf_puts(wrbuf, (const char *) child->content);
37     }
38 }
39
40 static int match_xml_node_attribute(
41     xmlNodePtr ptr,
42     const char *node_name, const char *attribute_name, const char *value)
43 {
44     const char *attribute_value;
45     // check if the node name matches
46     if (strcmp((const char*) ptr->name, node_name))
47         return 0;
48     if (attribute_name)
49     {
50         attribute_value = yaz_element_attribute_value_get(ptr, node_name,
51                                                           attribute_name);
52         if (attribute_value && !strcmp(attribute_value, value))
53             return 1;
54     }
55     else /* No attribute to check */
56         return 1;
57     return 0;
58 }
59
60 static void yaz_solr_decode_result_docs(ODR o, xmlNodePtr ptr,
61                                         Odr_int start,
62                                         Z_SRW_searchRetrieveResponse *sr)
63 {
64     xmlNodePtr node;
65     int offset = 0;
66     int i = 0;
67
68     sr->num_records = 0;
69     for (node = ptr->children; node; node = node->next)
70         if (node->type == XML_ELEMENT_NODE)
71             sr->num_records++;
72     
73     if (sr->num_records)
74         sr->records = odr_malloc(o, sizeof(*sr->records) * sr->num_records);
75
76     for (node = ptr->children; node; node = node->next)
77     {
78         if (node->type == XML_ELEMENT_NODE)
79         {
80             Z_SRW_record *record = sr->records + i;
81             xmlBufferPtr buf = xmlBufferCreate();
82             xmlNode *tmp = xmlCopyNode(node, 1);
83
84             xmlNodeDump(buf, tmp->doc, tmp, 0, 0);
85
86             xmlFreeNode(tmp);
87
88             record->recordSchema = 0;
89             record->recordPacking = Z_SRW_recordPacking_XML;
90             record->recordData_len = buf->use;
91             record->recordData_buf = odr_malloc(o, buf->use + 1);
92             memcpy(record->recordData_buf, buf->content, buf->use);
93             record->recordData_buf[buf->use] = '\0';
94             // TODO Solve the real problem in zoom-sru, that doesnt work with 0-based indexes.
95             // Work-around: Making the recordPosition 1-based.
96             record->recordPosition = odr_intdup(o, start + offset + 1);
97
98             xmlBufferFree(buf);
99
100             offset++;
101             i++;
102         }
103     }
104 }
105
106 static int yaz_solr_decode_result(ODR o, xmlNodePtr ptr,
107                                   Z_SRW_searchRetrieveResponse *sr)
108 {
109     Odr_int start = 0;
110     struct _xmlAttr *attr;
111     for (attr = ptr->properties; attr; attr = attr->next)
112         if (attr->children && attr->children->type == XML_TEXT_NODE)
113         {
114             if (!strcmp((const char *) attr->name, "numFound"))
115             {
116                 sr->numberOfRecords = odr_intdup(o, odr_atoi(
117                         (const char *) attr->children->content));
118             } 
119             else if (!strcmp((const char *) attr->name, "start"))
120             {
121                 start = odr_atoi((const char *) attr->children->content);
122             }
123         }
124     if (sr->numberOfRecords && *sr->numberOfRecords > 0)
125         yaz_solr_decode_result_docs(o, ptr, start, sr);
126     if (sr->numberOfRecords)
127         return 0;
128     return -1;
129 }
130
131 static const char *get_facet_term_count(xmlNodePtr node, Odr_int *freq)
132 {
133     const char *term = yaz_element_attribute_value_get(node, "int", "name");
134     xmlNodePtr child;
135     WRBUF wrbuf = wrbuf_alloc();
136     if (!term)
137         return term;
138
139     for (child = node->children; child ; child = child->next)
140     {
141         if (child->type == XML_TEXT_NODE)
142             wrbuf_puts(wrbuf, (const char *) child->content);
143     }
144     *freq = odr_atoi(wrbuf_cstr(wrbuf));
145     wrbuf_destroy(wrbuf);
146     return term;
147 }
148
149 Z_FacetField *yaz_solr_decode_facet_field(ODR o, xmlNodePtr ptr,
150                                           Z_SRW_searchRetrieveResponse *sr)
151
152 {
153     Z_AttributeList *list;
154     Z_FacetField *facet_field;
155     int num_terms = 0;
156     int index = 0;
157     xmlNodePtr node;
158     // USE attribute
159     const char* name = yaz_element_attribute_value_get(ptr, "lst", "name");
160     list = yaz_use_attribute_create(o, name);
161     for (node = ptr->children; node; node = node->next)
162         num_terms++;
163     facet_field = facet_field_create(o, list, num_terms);
164     index = 0;
165     for (node = ptr->children; node; node = node->next)
166     {
167         Odr_int count = 0;
168         const char *term = get_facet_term_count(node, &count);
169         facet_field_term_set(o, facet_field,
170                              facet_term_create_cstr(o, term, count), index);
171         index++;
172     }
173     return facet_field;
174 }
175
176 static int yaz_solr_decode_facet_counts(ODR o, xmlNodePtr root,
177                                         Z_SRW_searchRetrieveResponse *sr)
178 {
179     xmlNodePtr ptr;
180     for (ptr = root->children; ptr; ptr = ptr->next)
181     {
182         if (match_xml_node_attribute(ptr, "lst", "name", "facet_fields"))
183         {
184             xmlNodePtr node;
185             Z_FacetList *facet_list;
186             int num_facets = 0;
187             for (node = ptr->children; node; node= node->next)
188             {
189                 num_facets++;
190             }
191             facet_list = facet_list_create(o, num_facets);
192             num_facets = 0;
193             for (node = ptr->children; node; node= node->next)
194             {
195                 facet_list_field_set(o, facet_list,
196                                      yaz_solr_decode_facet_field(o, node, sr),
197                                      num_facets);
198                 num_facets++;
199             }
200             sr->facetList = facet_list;
201             break;
202         }
203     }
204     return 0;
205 }
206
207 static void yaz_solr_decode_suggestion_values(xmlNodePtr ptr, WRBUF wrbuf)
208 {
209     xmlNodePtr node;
210     for (node = ptr; node; node= node->next) {
211         if (!strcmp((char*)ptr->name, "lst")) {
212             xmlNodePtr child;
213             for (child = ptr->children; child; child= child->next) {
214                 if (match_xml_node_attribute(child, "str", "name", "word")) {
215                     wrbuf_puts(wrbuf, "<suggestion>");
216                     extract_text_node(child, wrbuf);
217                     wrbuf_puts(wrbuf, "</suggestion>\n");
218                 }
219             }
220         }
221     }
222 }
223
224 static void yaz_solr_decode_suggestion_lst(xmlNodePtr lstPtr, WRBUF wrbuf)
225 {
226     xmlNodePtr node;
227     for (node = lstPtr; node; node= node->next) {
228         if (match_xml_node_attribute(node, "arr", "name", "suggestion")) {
229             yaz_solr_decode_suggestion_values(node->children, wrbuf);
230         }
231     }
232 }
233
234 static void yaz_solr_decode_misspelled(xmlNodePtr lstPtr, WRBUF wrbuf)
235 {
236     xmlNodePtr node;
237     for (node = lstPtr; node; node= node->next)
238     {
239         if (strcmp((const char*) node->name, "lst")) {
240             const char *misspelled = yaz_element_attribute_value_get(node, "lst", "name");
241             if (misspelled) {
242                 wrbuf_printf(wrbuf, "<misspelled term=\"%s\">", misspelled);
243                 yaz_solr_decode_suggestion_lst(node->children, wrbuf);
244                 wrbuf_puts(wrbuf, "</misspelled>\n");
245             }
246         }
247     }
248 }
249
250 static int yaz_solr_decode_spellcheck(ODR o, xmlNodePtr spellcheckPtr, Z_SRW_searchRetrieveResponse *sr)
251 {
252     xmlNodePtr ptr;
253     WRBUF wrbuf = wrbuf_alloc();
254     wrbuf_puts(wrbuf, "");
255     for (ptr = spellcheckPtr->children; ptr; ptr = ptr->next)
256     {
257         if (match_xml_node_attribute(ptr, "lst", "name", "suggestions"))
258         {
259             yaz_solr_decode_misspelled(ptr->children, wrbuf);
260         }
261     }
262     sr->suggestions = odr_strdup(o, wrbuf_cstr(wrbuf));
263     return 0;
264 }
265
266 int yaz_solr_decode_response(ODR o, Z_HTTP_Response *hres, Z_SRW_PDU **pdup)
267 {
268 #if YAZ_HAVE_XML2
269     const char *content_buf = hres->content_buf;
270     int content_len = hres->content_len;
271     xmlDocPtr doc = xmlParseMemory(content_buf, content_len);
272     int ret = 0;
273     xmlNodePtr ptr = 0;
274     Z_SRW_PDU *pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
275     Z_SRW_searchRetrieveResponse *sr = pdu->u.response;
276
277     if (!doc)
278     {
279         ret = -1;
280     }
281     if (doc)
282     {
283         xmlNodePtr root = xmlDocGetRootElement(doc);
284         if (!root)
285         {
286             ret = -1;
287         }
288         else if (strcmp((const char *) root->name, "response"))
289         {
290             ret = -1;
291         }
292         else
293         {
294             /** look for result (required) and facets node (optional) */
295             int rc_result = -1;
296             int rc_facets = 0;
297             for (ptr = root->children; ptr; ptr = ptr->next)
298             {
299                 if (ptr->type == XML_ELEMENT_NODE &&
300                     !strcmp((const char *) ptr->name, "result"))
301                         rc_result = yaz_solr_decode_result(o, ptr, sr);
302                 /* TODO The check on hits is a work-around to avoid garbled facets on zero results from the SOLR server.
303                  * The work-around works because the results is before the facets in the xml. */
304                 if (rc_result == 0 &&  *sr->numberOfRecords > 0 &&
305                     match_xml_node_attribute(ptr, "lst", "name", "facet_counts"))
306                     rc_facets =  yaz_solr_decode_facet_counts(o, ptr, sr);
307                 if (rc_result == 0 &&  *sr->numberOfRecords == 0 &&
308                     match_xml_node_attribute(ptr, "lst", "name", "spellcheck"))
309                     rc_facets =  yaz_solr_decode_spellcheck(o, ptr, sr);
310
311             }
312             ret = rc_result + rc_facets;
313         }
314     }
315     if (doc)
316         xmlFreeDoc(doc);
317     if (ret == 0)
318         *pdup = pdu;
319     return ret;
320 #else
321     return -1;
322 #endif
323 }
324
325 static int yaz_solr_encode_facet_field(
326     ODR encode, char **name, char **value, int *i,
327     Z_FacetField *facet_field)
328 {
329     Z_AttributeList *attribute_list = facet_field->attributes;
330     struct yaz_facet_attr attr_values;
331     yaz_facet_attr_init(&attr_values);
332     yaz_facet_attr_get_z_attributes(attribute_list, &attr_values);
333     // TODO do we want to support server decided
334
335     if (attr_values.errcode)
336         return -1;
337     if (attr_values.useattr)
338     {
339         WRBUF wrbuf = wrbuf_alloc();
340         wrbuf_puts(wrbuf, (char *) attr_values.useattr);
341         yaz_add_name_value_str(encode, name, value, i,
342                                "facet.field",
343                                odr_strdup(encode, wrbuf_cstr(wrbuf)));
344         if (attr_values.limit > 0)
345         {
346             WRBUF wrbuf2 = wrbuf_alloc();
347             Odr_int olimit;
348             wrbuf_puts(wrbuf2, "f.");
349             wrbuf_puts(wrbuf2, wrbuf_cstr(wrbuf));
350             wrbuf_puts(wrbuf2, ".facet.limit");
351             olimit = attr_values.limit;
352             yaz_add_name_value_int(encode, name, value, i,
353                                    odr_strdup(encode, wrbuf_cstr(wrbuf2)),
354                                    &olimit);
355             wrbuf_destroy(wrbuf2);
356         }
357         wrbuf_destroy(wrbuf);
358     }
359     return 0;
360 }
361
362 static int yaz_solr_encode_facet_list(
363     ODR encode, char **name, char **value,
364     int *i, Z_FacetList *facet_list)
365 {
366     int index;
367     for (index = 0; index < facet_list->num; index++)
368     {
369         int r = yaz_solr_encode_facet_field(encode, name, value, i,
370                                             facet_list->elements[index]);
371         if (r)
372             return -1;
373         
374     }
375     return 0;
376 }
377
378 int yaz_solr_encode_request(Z_HTTP_Request *hreq, Z_SRW_PDU *srw_pdu,
379                             ODR encode, const char *charset)
380 {
381     const char *solr_op = 0;
382     //TODO Change. not a nice hard coded, unchecked limit.
383     char *name[SOLR_MAX_PARAMETERS], *value[SOLR_MAX_PARAMETERS];
384     char *uri_args;
385     char *path;
386     int i = 0;
387     
388     z_HTTP_header_add_basic_auth(encode, &hreq->headers, 
389                                  srw_pdu->username, srw_pdu->password);
390     if (srw_pdu->which == Z_SRW_searchRetrieve_request)
391     {
392         Z_SRW_searchRetrieveRequest *request = srw_pdu->u.request;
393         solr_op = "select";
394         switch (srw_pdu->u.request->query_type)
395         {
396         case Z_SRW_query_type_pqf:
397             yaz_add_name_value_str(encode, name, value, &i,
398                                    "q", request->query.pqf);
399             break;
400         case Z_SRW_query_type_cql:
401             yaz_add_name_value_str(encode, name, value, &i,
402                                    "q", request->query.cql);
403             break;
404         default:
405             return -1;
406         }
407         if (srw_pdu->u.request->startRecord)
408         {
409             Odr_int start = *request->startRecord - 1;
410             yaz_add_name_value_int(encode, name, value, &i,
411                                    "start", &start);
412         }
413         yaz_add_name_value_int(encode, name, value, &i,
414                                "rows", request->maximumRecords);
415         yaz_add_name_value_str(encode, name, value, &i,
416                                "fl", request->recordSchema);
417
418         if (request->facetList)
419         {
420             Z_FacetList *facet_list = request->facetList;
421             yaz_add_name_value_str(encode, name, value, &i, "facet", "true");
422             yaz_add_name_value_str(encode, name, value, &i, "facet.mincount", "1");
423             if (yaz_solr_encode_facet_list(encode, name, value, &i, facet_list))
424                 return -1;
425         }
426     }
427     else
428         return -1;
429
430     if (srw_pdu->extra_args)
431     {
432         Z_SRW_extra_arg *ea = srw_pdu->extra_args;
433         for (; ea && i < SOLR_MAX_PARAMETERS; ea = ea->next)
434         {
435             name[i] = ea->name;
436             value[i] = ea->value;
437             i++;
438         }
439     }
440
441     name[i++] = 0;
442
443     yaz_array_to_uri(&uri_args, encode, name, value);
444     
445     hreq->method = "GET";
446     
447     path = (char *)
448         odr_malloc(encode, strlen(hreq->path) +
449                    strlen(uri_args) + strlen(solr_op) + 4);
450
451     sprintf(path, "%s/%s?%s", hreq->path, solr_op, uri_args);
452     hreq->path = path;
453
454     z_HTTP_header_add_content_type(encode, &hreq->headers,
455                                    "text/xml", charset);
456     return 0;
457 }
458
459
460 /*
461  * Local variables:
462  * c-basic-offset: 4
463  * c-file-style: "Stroustrup"
464  * indent-tabs-mode: nil
465  * End:
466  * vim: shiftwidth=4 tabstop=8 expandtab
467  */
468