Change logging a bit in ZOOM's Z39.50 layer
[yaz-moved-to-github.git] / src / solr.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 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 =
91                 odr_strdupn(o, (const char *) buf->content, buf->use);
92             record->recordPosition = odr_intdup(o, start + offset + 1);
93
94             xmlBufferFree(buf);
95
96             offset++;
97             i++;
98         }
99     }
100 }
101
102 static int yaz_solr_decode_result(ODR o, xmlNodePtr ptr,
103                                   Z_SRW_searchRetrieveResponse *sr)
104 {
105     Odr_int start = 0;
106     struct _xmlAttr *attr;
107     for (attr = ptr->properties; attr; attr = attr->next)
108         if (attr->children && attr->children->type == XML_TEXT_NODE)
109         {
110             if (!strcmp((const char *) attr->name, "numFound"))
111             {
112                 sr->numberOfRecords = odr_intdup(o, odr_atoi(
113                         (const char *) attr->children->content));
114             }
115             else if (!strcmp((const char *) attr->name, "start"))
116             {
117                 start = odr_atoi((const char *) attr->children->content);
118             }
119         }
120     if (sr->numberOfRecords && *sr->numberOfRecords > 0)
121         yaz_solr_decode_result_docs(o, ptr, start, sr);
122     if (sr->numberOfRecords)
123         return 0;
124     return -1;
125 }
126
127 static const char *get_facet_term_count(xmlNodePtr node, Odr_int *freq)
128 {
129     const char *term = yaz_element_attribute_value_get(node, "int", "name");
130     xmlNodePtr child;
131     WRBUF wrbuf = wrbuf_alloc();
132     if (!term)
133         return term;
134
135     for (child = node->children; child ; child = child->next)
136     {
137         if (child->type == XML_TEXT_NODE)
138             wrbuf_puts(wrbuf, (const char *) child->content);
139     }
140     *freq = odr_atoi(wrbuf_cstr(wrbuf));
141     wrbuf_destroy(wrbuf);
142     return term;
143 }
144
145 Z_FacetField *yaz_solr_decode_facet_field(ODR o, xmlNodePtr ptr,
146                                           Z_SRW_searchRetrieveResponse *sr)
147
148 {
149     Z_AttributeList *list;
150     Z_FacetField *facet_field;
151     int num_terms = 0;
152     int index = 0;
153     xmlNodePtr node;
154     // USE attribute
155     const char* name = yaz_element_attribute_value_get(ptr, "lst", "name");
156     list = yaz_use_attribute_create(o, name);
157     for (node = ptr->children; node; node = node->next)
158         num_terms++;
159     facet_field = facet_field_create(o, list, num_terms);
160     index = 0;
161     for (node = ptr->children; node; node = node->next)
162     {
163         Odr_int count = 0;
164         const char *term = get_facet_term_count(node, &count);
165         facet_field_term_set(o, facet_field,
166                              facet_term_create_cstr(o, term, count), index);
167         index++;
168     }
169     return facet_field;
170 }
171
172 static int yaz_solr_decode_facet_counts(ODR o, xmlNodePtr root,
173                                         Z_SRW_searchRetrieveResponse *sr)
174 {
175     xmlNodePtr ptr;
176     for (ptr = root->children; ptr; ptr = ptr->next)
177     {
178         if (match_xml_node_attribute(ptr, "lst", "name", "facet_fields"))
179         {
180             xmlNodePtr node;
181             Z_FacetList *facet_list;
182             int num_facets = 0;
183             for (node = ptr->children; node; node= node->next)
184             {
185                 num_facets++;
186             }
187             facet_list = facet_list_create(o, num_facets);
188             num_facets = 0;
189             for (node = ptr->children; node; node= node->next)
190             {
191                 facet_list_field_set(o, facet_list,
192                                      yaz_solr_decode_facet_field(o, node, sr),
193                                      num_facets);
194                 num_facets++;
195             }
196             sr->facetList = facet_list;
197             break;
198         }
199     }
200     return 0;
201 }
202
203 static void yaz_solr_decode_suggestion_values(xmlNodePtr listPptr, WRBUF wrbuf)
204 {
205     xmlNodePtr node;
206     for (node = listPptr; node; node= node->next) {
207         if (!strcmp((char*) node->name, "lst")) {
208             xmlNodePtr child;
209             for (child = node->children; child; child= child->next) {
210                 if (match_xml_node_attribute(child, "str", "name", "word")) {
211                     wrbuf_puts(wrbuf, "<suggestion>");
212                     extract_text_node(child, wrbuf);
213                     wrbuf_puts(wrbuf, "</suggestion>\n");
214                 }
215             }
216         }
217     }
218 }
219
220 static void yaz_solr_decode_suggestion_lst(xmlNodePtr lstPtr, WRBUF wrbuf)
221 {
222     xmlNodePtr node;
223     for (node = lstPtr; node; node= node->next) {
224         if (match_xml_node_attribute(node, "arr", "name", "suggestion")) {
225             yaz_solr_decode_suggestion_values(node->children, wrbuf);
226         }
227     }
228 }
229
230 static void yaz_solr_decode_misspelled(xmlNodePtr lstPtr, WRBUF wrbuf)
231 {
232     xmlNodePtr node;
233     for (node = lstPtr; node; node= node->next)
234     {
235         if (!strcmp((const char*) node->name, "lst")) {
236             const char *misspelled = yaz_element_attribute_value_get(node, "lst", "name");
237             if (misspelled) {
238                 wrbuf_printf(wrbuf, "<misspelled term=\"%s\">\n", misspelled);
239                 yaz_solr_decode_suggestion_lst(node->children, wrbuf);
240                 wrbuf_puts(wrbuf, "</misspelled>\n");
241             }
242         }
243     }
244 }
245
246 static int yaz_solr_decode_spellcheck(ODR o, xmlNodePtr spellcheckPtr, Z_SRW_searchRetrieveResponse *sr)
247 {
248     xmlNodePtr ptr;
249     WRBUF wrbuf = wrbuf_alloc();
250     wrbuf_puts(wrbuf, "");
251     for (ptr = spellcheckPtr->children; ptr; ptr = ptr->next)
252     {
253         if (match_xml_node_attribute(ptr, "lst", "name", "suggestions"))
254         {
255             yaz_solr_decode_misspelled(ptr->children, wrbuf);
256         }
257     }
258     sr->suggestions = odr_strdup(o, wrbuf_cstr(wrbuf));
259     return 0;
260 }
261
262 static int yaz_solr_decode_scan_result(ODR o, xmlNodePtr ptr,
263                                        Z_SRW_scanResponse *scr)
264 {
265     xmlNodePtr node;
266     char *pos;
267     int i = 0;
268
269     /* find the actual list */
270     for (node = ptr->children; node; node = node->next)
271         if (node->type == XML_ELEMENT_NODE) {
272             ptr = node;
273             break;
274         }
275
276     scr->num_terms = 0;
277     for (node = ptr->children; node; node = node->next)
278         if (node->type == XML_ELEMENT_NODE && !strcmp((const char *) node->name, "int"))
279             scr->num_terms++;
280
281     if (scr->num_terms)
282         scr->terms = odr_malloc(o, sizeof(*scr->terms) * scr->num_terms);
283
284     for (node = ptr->children; node; node = node->next)
285     {
286         if (node->type == XML_ELEMENT_NODE && !strcmp((const char *) node->name, "int"))
287         {
288             Z_SRW_scanTerm *term = scr->terms + i;
289
290             Odr_int count = 0;
291             const char *val = get_facet_term_count(node, &count);
292
293             term->numberOfRecords = odr_intdup(o, count);
294
295             /* if val contains a ^ then it is probably term<^>display term so separate them. This is due to
296              * SOLR not being able to encode them into 2 separate attributes.
297              */
298             pos = strchr(val, '^');
299             if (pos != NULL) {
300                 term->displayTerm = odr_strdup(o, pos + 1);
301                 *pos = '\0';
302                 term->value = odr_strdup(o, val);
303                 *pos = '^';
304             } else {
305                 term->value = odr_strdup(o, val);
306                 term->displayTerm = NULL;
307             }
308             term->whereInList = NULL;
309
310             i++;
311         }
312     }
313
314     if (scr->num_terms)
315         return 0;
316     return -1;
317 }
318 #endif
319
320 int yaz_solr_decode_response(ODR o, Z_HTTP_Response *hres, Z_SRW_PDU **pdup)
321 {
322 #if YAZ_HAVE_XML2
323     const char *content_buf = hres->content_buf;
324     int content_len = hres->content_len;
325     xmlDocPtr doc = xmlParseMemory(content_buf, content_len);
326     int ret = 0;
327     xmlNodePtr ptr = 0;
328     Z_SRW_PDU *pdu;
329     Z_SRW_searchRetrieveResponse *sr = NULL;
330     Z_SRW_scanResponse *scr = NULL;
331
332     if (!doc)
333     {
334         ret = -1;
335     }
336     if (doc)
337     {
338         xmlNodePtr root = xmlDocGetRootElement(doc);
339         if (!root)
340         {
341             ret = -1;
342         }
343         else if (strcmp((const char *) root->name, "response"))
344         {
345             ret = -1;
346         }
347         else
348         {
349             /** look for result (required) and facets node (optional) */
350             int rc_result = -1;
351             int rc_facets = 0;
352             for (ptr = root->children; ptr; ptr = ptr->next)
353             {
354                 if (ptr->type == XML_ELEMENT_NODE &&
355                     !strcmp((const char *) ptr->name, "result")) {
356                         pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
357                         sr = pdu->u.response;
358                         rc_result = yaz_solr_decode_result(o, ptr, sr);
359                 }
360                 if (ptr->type == XML_ELEMENT_NODE &&
361                     match_xml_node_attribute(ptr, "lst", "name", "terms")) {
362                         pdu = yaz_srw_get(o, Z_SRW_scan_response);
363                         scr = pdu->u.scan_response;
364                         rc_result = yaz_solr_decode_scan_result(o, ptr, scr);
365                 }
366                 /* TODO The check on hits is a work-around to avoid garbled facets on zero results from the SOLR server.
367                  * The work-around works because the results is before the facets in the xml. */
368                 if (sr) {
369                     if (rc_result == 0 &&  *sr->numberOfRecords > 0 &&
370                         match_xml_node_attribute(ptr, "lst", "name", "facet_counts"))
371                             rc_facets =  yaz_solr_decode_facet_counts(o, ptr, sr);
372                     if (rc_result == 0 &&  *sr->numberOfRecords == 0 &&
373                         match_xml_node_attribute(ptr, "lst", "name", "spellcheck"))
374                             rc_facets =  yaz_solr_decode_spellcheck(o, ptr, sr);
375                 }
376
377             }
378             ret = rc_result + rc_facets;
379         }
380     }
381     if (doc)
382         xmlFreeDoc(doc);
383     if (ret == 0)
384         *pdup = pdu;
385     return ret;
386 #else
387     return -1;
388 #endif
389 }
390
391 static int yaz_solr_encode_facet_field(
392     ODR encode, char **name, char **value, int *i,
393     Z_FacetField *facet_field)
394 {
395     Z_AttributeList *attribute_list = facet_field->attributes;
396     struct yaz_facet_attr attr_values;
397     yaz_facet_attr_init(&attr_values);
398     yaz_facet_attr_get_z_attributes(attribute_list, &attr_values);
399
400     if (attr_values.errcode)
401         return -1;
402     if (attr_values.useattr)
403     {
404         WRBUF wrbuf = wrbuf_alloc();
405         yaz_add_name_value_str(encode, name, value, i,
406                                "facet.field",
407                                odr_strdup(encode, attr_values.useattr));
408
409         if (attr_values.limit > 0)
410         {
411             Odr_int v = attr_values.limit;
412             wrbuf_rewind(wrbuf);
413             wrbuf_printf(wrbuf, "f.%s.facet.limit", attr_values.useattr);
414             yaz_add_name_value_int(encode, name, value, i,
415                                    odr_strdup(encode, wrbuf_cstr(wrbuf)),
416                                    &v);
417         }
418         if (attr_values.start > 1)
419         {
420             Odr_int v = attr_values.start - 1;
421             wrbuf_rewind(wrbuf);
422             wrbuf_printf(wrbuf, "f.%s.facet.offset", attr_values.useattr);
423             yaz_add_name_value_int(encode, name, value, i,
424                                    odr_strdup(encode, wrbuf_cstr(wrbuf)),
425                                    &v);
426         }
427         if (attr_values.sortorder == 1)
428         {
429             wrbuf_rewind(wrbuf);
430             wrbuf_printf(wrbuf, "f.%s.facet.sort", attr_values.useattr);
431             yaz_add_name_value_str(encode, name, value, i,
432                                    odr_strdup(encode, wrbuf_cstr(wrbuf)),
433                                    "index");
434         }
435         wrbuf_destroy(wrbuf);
436     }
437     else
438     {
439         if (attr_values.limit > 0)
440         {
441             Odr_int v = attr_values.limit;
442             yaz_add_name_value_int(encode, name, value, i, "facet.limit", &v);
443         }
444         if (attr_values.start > 1)
445         {
446             Odr_int v = attr_values.start - 1;
447             yaz_add_name_value_int(encode, name, value, i, "facet.offset", &v);
448         }
449         if (attr_values.sortorder == 1)
450         {
451             yaz_add_name_value_str(encode, name, value, i, "facet.sort",
452                                    "index");
453         }
454     }
455     return 0;
456 }
457
458 static int yaz_solr_encode_facet_list(
459     ODR encode, char **name, char **value,
460     int *i, Z_FacetList *facet_list)
461 {
462     int index;
463     for (index = 0; index < facet_list->num; index++)
464     {
465         int r = yaz_solr_encode_facet_field(encode, name, value, i,
466                                             facet_list->elements[index]);
467         if (r)
468             return -1;
469
470     }
471     return 0;
472 }
473
474 int yaz_solr_encode_request(Z_HTTP_Request *hreq, Z_SRW_PDU *srw_pdu,
475                             ODR encode, const char *charset)
476 {
477     const char *solr_op = 0;
478     //TODO Change. not a nice hard coded, unchecked limit.
479     char *name[SOLR_MAX_PARAMETERS], *value[SOLR_MAX_PARAMETERS];
480     char *uri_args;
481     char *path;
482     char *q;
483     char *pos;
484     char *cp;
485     const char *path_args = 0;
486     int i = 0;
487
488     z_HTTP_header_add_basic_auth(encode, &hreq->headers,
489                                  srw_pdu->username, srw_pdu->password);
490     if (srw_pdu->which == Z_SRW_searchRetrieve_request)
491     {
492         Z_SRW_searchRetrieveRequest *request = srw_pdu->u.request;
493         solr_op = "select";
494         if (!srw_pdu->u.request->query)
495             return -1;
496         /* not considering query type here ! */
497         yaz_add_name_value_str(encode, name, value, &i, "q", request->query);
498         if (srw_pdu->u.request->startRecord)
499         {
500             Odr_int start = *request->startRecord - 1;
501             yaz_add_name_value_int(encode, name, value, &i,
502                                    "start", &start);
503         }
504         yaz_add_name_value_int(encode, name, value, &i,
505                                "rows", request->maximumRecords);
506         yaz_add_name_value_str(encode, name, value, &i,
507                                "fl", request->recordSchema);
508
509         switch(srw_pdu->u.request->sort_type)
510         {
511         case Z_SRW_sort_type_none:
512             break;
513         case Z_SRW_sort_type_sort:
514             yaz_add_name_value_str(encode, name, value, &i, "sort",
515                                    srw_pdu->u.request->sort.sortKeys);
516             break;
517         }
518         if (request->facetList)
519         {
520             Z_FacetList *facet_list = request->facetList;
521             yaz_add_name_value_str(encode, name, value, &i, "facet", "true");
522             yaz_add_name_value_str(encode, name, value, &i, "facet.mincount", "1");
523             if (yaz_solr_encode_facet_list(encode, name, value, &i, facet_list))
524                 return -1;
525         }
526     }
527     else if (srw_pdu->which == Z_SRW_scan_request) {
528         Z_SRW_scanRequest *request = srw_pdu->u.scan_request;
529         solr_op = "terms";
530         if (!srw_pdu->u.scan_request->scanClause)
531             return -1;
532         if (!strcmp(srw_pdu->u.scan_request->queryType, "pqf"))
533         {
534             yaz_add_name_value_str(encode, name, value, &i,
535                                    "terms.fl", request->scanClause);
536             yaz_add_name_value_str(encode, name, value, &i,
537                                    "terms.lower", request->scanClause);
538         }
539         else if (!strcmp(srw_pdu->u.scan_request->queryType, "cql"))
540         {
541             q = request->scanClause;
542             pos = strchr(q, ':');
543             if (pos != NULL) {
544                 yaz_add_name_value_str(encode, name, value, &i,
545                                        "terms.lower", odr_strdup(encode, pos + 1));
546                 *pos = '\0';
547                 yaz_add_name_value_str(encode, name, value, &i,
548                                        "terms.fl", odr_strdup(encode, q));
549                 *pos = ':';
550             } else {
551                 yaz_add_name_value_str(encode, name, value, &i,
552                                        "terms.lower", odr_strdup(encode, q));
553             }
554         }
555         else
556             return -1;
557         yaz_add_name_value_str(encode, name, value, &i,
558                                "terms.sort", "index");
559         yaz_add_name_value_int(encode, name, value, &i,
560                                "terms.limit", request->maximumTerms);
561     }
562     else
563         return -1;
564
565     if (srw_pdu->extra_args)
566     {
567         Z_SRW_extra_arg *ea = srw_pdu->extra_args;
568         for (; ea && i < SOLR_MAX_PARAMETERS; ea = ea->next)
569         {
570             name[i] = ea->name;
571             value[i] = ea->value;
572             i++;
573         }
574     }
575
576     name[i++] = 0;
577
578     yaz_array_to_uri(&uri_args, encode, name, value);
579
580     hreq->method = "GET";
581
582     path = (char *)
583         odr_malloc(encode, strlen(hreq->path) +
584                    strlen(uri_args) + strlen(solr_op) + 5);
585
586     cp = strchr(hreq->path, '#');
587     if (cp)
588         *cp = '\0';
589     cp = strchr(hreq->path, '?');
590     if (cp)
591     {
592         *cp = '\0'; /* args in path */
593         path_args = cp + 1;
594     }
595     strcpy(path, hreq->path);
596     cp = strrchr(path, '/');
597     if (cp)
598     {
599         if (!strcmp(cp, "/select") || !strcmp(cp, "/"))
600             *cp = '\0';
601     }
602     strcat(path, "/");
603     strcat(path, solr_op);
604     strcat(path, "?");
605     if (path_args)
606     {
607         strcat(path, path_args);
608         strcat(path, "&");
609     }
610     strcat(path, uri_args);
611     hreq->path = path;
612
613     z_HTTP_header_add_content_type(encode, &hreq->headers,
614                                    "text/xml", charset);
615     return 0;
616 }
617
618
619 /*
620  * Local variables:
621  * c-basic-offset: 4
622  * c-file-style: "Stroustrup"
623  * indent-tabs-mode: nil
624  * End:
625  * vim: shiftwidth=4 tabstop=8 expandtab
626  */
627