record_conv: change construct prototype
[yaz-moved-to-github.git] / src / solr.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2012 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
30 static void extract_text_node(xmlNodePtr node, WRBUF wrbuf) {
31     xmlNodePtr child;
32     for (child = node->children; child ; child = child->next)
33     {
34         if (child->type == XML_TEXT_NODE)
35             wrbuf_puts(wrbuf, (const char *) child->content);
36     }
37 }
38
39 static int match_xml_node_attribute(
40     xmlNodePtr ptr,
41     const char *node_name, const char *attribute_name, const char *value)
42 {
43     const char *attribute_value;
44     // check if the node name matches
45     if (strcmp((const char*) ptr->name, node_name))
46         return 0;
47     if (attribute_name)
48     {
49         attribute_value = yaz_element_attribute_value_get(ptr, node_name,
50                                                           attribute_name);
51         if (attribute_value && !strcmp(attribute_value, value))
52             return 1;
53     }
54     else /* No attribute to check */
55         return 1;
56     return 0;
57 }
58
59 static void yaz_solr_decode_result_docs(ODR o, xmlNodePtr ptr,
60                                         Odr_int start,
61                                         Z_SRW_searchRetrieveResponse *sr)
62 {
63     xmlNodePtr node;
64     int offset = 0;
65     int i = 0;
66
67     sr->num_records = 0;
68     for (node = ptr->children; node; node = node->next)
69         if (node->type == XML_ELEMENT_NODE)
70             sr->num_records++;
71     
72     if (sr->num_records)
73         sr->records = odr_malloc(o, sizeof(*sr->records) * sr->num_records);
74
75     for (node = ptr->children; node; node = node->next)
76     {
77         if (node->type == XML_ELEMENT_NODE)
78         {
79             Z_SRW_record *record = sr->records + i;
80             xmlBufferPtr buf = xmlBufferCreate();
81             xmlNode *tmp = xmlCopyNode(node, 1);
82
83             xmlNodeDump(buf, tmp->doc, tmp, 0, 0);
84
85             xmlFreeNode(tmp);
86
87             record->recordSchema = 0;
88             record->recordPacking = Z_SRW_recordPacking_XML;
89             record->recordData_len = buf->use;
90             record->recordData_buf = odr_malloc(o, buf->use + 1);
91             memcpy(record->recordData_buf, buf->content, buf->use);
92             record->recordData_buf[buf->use] = '\0';
93             // TODO Solve the real problem in zoom-sru, that doesnt work with 0-based indexes.
94             // Work-around: Making the recordPosition 1-based.
95             record->recordPosition = odr_intdup(o, start + offset + 1);
96
97             xmlBufferFree(buf);
98
99             offset++;
100             i++;
101         }
102     }
103 }
104
105 static int yaz_solr_decode_result(ODR o, xmlNodePtr ptr,
106                                   Z_SRW_searchRetrieveResponse *sr)
107 {
108     Odr_int start = 0;
109     struct _xmlAttr *attr;
110     for (attr = ptr->properties; attr; attr = attr->next)
111         if (attr->children && attr->children->type == XML_TEXT_NODE)
112         {
113             if (!strcmp((const char *) attr->name, "numFound"))
114             {
115                 sr->numberOfRecords = odr_intdup(o, odr_atoi(
116                         (const char *) attr->children->content));
117             } 
118             else if (!strcmp((const char *) attr->name, "start"))
119             {
120                 start = odr_atoi((const char *) attr->children->content);
121             }
122         }
123     if (sr->numberOfRecords && *sr->numberOfRecords > 0)
124         yaz_solr_decode_result_docs(o, ptr, start, sr);
125     if (sr->numberOfRecords)
126         return 0;
127     return -1;
128 }
129
130 static const char *get_facet_term_count(xmlNodePtr node, Odr_int *freq)
131 {
132     const char *term = yaz_element_attribute_value_get(node, "int", "name");
133     xmlNodePtr child;
134     WRBUF wrbuf = wrbuf_alloc();
135     if (!term)
136         return term;
137
138     for (child = node->children; child ; child = child->next)
139     {
140         if (child->type == XML_TEXT_NODE)
141             wrbuf_puts(wrbuf, (const char *) child->content);
142     }
143     *freq = odr_atoi(wrbuf_cstr(wrbuf));
144     wrbuf_destroy(wrbuf);
145     return term;
146 }
147
148 Z_FacetField *yaz_solr_decode_facet_field(ODR o, xmlNodePtr ptr,
149                                           Z_SRW_searchRetrieveResponse *sr)
150
151 {
152     Z_AttributeList *list;
153     Z_FacetField *facet_field;
154     int num_terms = 0;
155     int index = 0;
156     xmlNodePtr node;
157     // USE attribute
158     const char* name = yaz_element_attribute_value_get(ptr, "lst", "name");
159     list = yaz_use_attribute_create(o, name);
160     for (node = ptr->children; node; node = node->next)
161         num_terms++;
162     facet_field = facet_field_create(o, list, num_terms);
163     index = 0;
164     for (node = ptr->children; node; node = node->next)
165     {
166         Odr_int count = 0;
167         const char *term = get_facet_term_count(node, &count);
168         facet_field_term_set(o, facet_field,
169                              facet_term_create_cstr(o, term, count), index);
170         index++;
171     }
172     return facet_field;
173 }
174
175 static int yaz_solr_decode_facet_counts(ODR o, xmlNodePtr root,
176                                         Z_SRW_searchRetrieveResponse *sr)
177 {
178     xmlNodePtr ptr;
179     for (ptr = root->children; ptr; ptr = ptr->next)
180     {
181         if (match_xml_node_attribute(ptr, "lst", "name", "facet_fields"))
182         {
183             xmlNodePtr node;
184             Z_FacetList *facet_list;
185             int num_facets = 0;
186             for (node = ptr->children; node; node= node->next)
187             {
188                 num_facets++;
189             }
190             facet_list = facet_list_create(o, num_facets);
191             num_facets = 0;
192             for (node = ptr->children; node; node= node->next)
193             {
194                 facet_list_field_set(o, facet_list,
195                                      yaz_solr_decode_facet_field(o, node, sr),
196                                      num_facets);
197                 num_facets++;
198             }
199             sr->facetList = facet_list;
200             break;
201         }
202     }
203     return 0;
204 }
205
206 static void yaz_solr_decode_suggestion_values(xmlNodePtr listPptr, WRBUF wrbuf)
207 {
208     xmlNodePtr node;
209     for (node = listPptr; node; node= node->next) {
210         if (!strcmp((char*) node->name, "lst")) {
211             xmlNodePtr child;
212             for (child = node->children; child; child= child->next) {
213                 if (match_xml_node_attribute(child, "str", "name", "word")) {
214                     wrbuf_puts(wrbuf, "<suggestion>");
215                     extract_text_node(child, wrbuf);
216                     wrbuf_puts(wrbuf, "</suggestion>\n");
217                 }
218             }
219         }
220     }
221 }
222
223 static void yaz_solr_decode_suggestion_lst(xmlNodePtr lstPtr, WRBUF wrbuf)
224 {
225     xmlNodePtr node;
226     for (node = lstPtr; node; node= node->next) {
227         if (match_xml_node_attribute(node, "arr", "name", "suggestion")) {
228             yaz_solr_decode_suggestion_values(node->children, wrbuf);
229         }
230     }
231 }
232
233 static void yaz_solr_decode_misspelled(xmlNodePtr lstPtr, WRBUF wrbuf)
234 {
235     xmlNodePtr node;
236     for (node = lstPtr; node; node= node->next)
237     {
238         if (!strcmp((const char*) node->name, "lst")) {
239             const char *misspelled = yaz_element_attribute_value_get(node, "lst", "name");
240             if (misspelled) {
241                 wrbuf_printf(wrbuf, "<misspelled term=\"%s\">\n", misspelled);
242                 yaz_solr_decode_suggestion_lst(node->children, wrbuf);
243                 wrbuf_puts(wrbuf, "</misspelled>\n");
244             }
245         }
246     }
247 }
248
249 static int yaz_solr_decode_spellcheck(ODR o, xmlNodePtr spellcheckPtr, Z_SRW_searchRetrieveResponse *sr)
250 {
251     xmlNodePtr ptr;
252     WRBUF wrbuf = wrbuf_alloc();
253     wrbuf_puts(wrbuf, "");
254     for (ptr = spellcheckPtr->children; ptr; ptr = ptr->next)
255     {
256         if (match_xml_node_attribute(ptr, "lst", "name", "suggestions"))
257         {
258             yaz_solr_decode_misspelled(ptr->children, wrbuf);
259         }
260     }
261     sr->suggestions = odr_strdup(o, wrbuf_cstr(wrbuf));
262     return 0;
263 }
264 #endif
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