Comma separated value for pz:recordfilter.
[pazpar2-moved-to-github.git] / src / logic.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2009 Index Data
3
4 Pazpar2 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 Pazpar2 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 /** \file logic.c
21     \brief high-level logic; mostly user sessions and settings
22 */
23
24 #if HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #if HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #if HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #include <signal.h>
38 #include <ctype.h>
39 #include <assert.h>
40
41 #include <yaz/marcdisp.h>
42 #include <yaz/comstack.h>
43 #include <yaz/tcpip.h>
44 #include <yaz/proto.h>
45 #include <yaz/readconf.h>
46 #include <yaz/pquery.h>
47 #include <yaz/otherinfo.h>
48 #include <yaz/yaz-util.h>
49 #include <yaz/nmem.h>
50 #include <yaz/query-charset.h>
51 #include <yaz/querytowrbuf.h>
52 #include <yaz/oid_db.h>
53 #include <yaz/snprintf.h>
54
55 #define USE_TIMING 0
56 #if USE_TIMING
57 #include <yaz/timing.h>
58 #endif
59
60 #include "parameters.h"
61 #include "pazpar2.h"
62 #include "eventl.h"
63 #include "http.h"
64 #include "termlists.h"
65 #include "reclists.h"
66 #include "relevance.h"
67 #include "database.h"
68 #include "client.h"
69 #include "settings.h"
70 #include "normalize7bit.h"
71 #include "marcmap.h"
72
73 #define TERMLIST_HIGH_SCORE 25
74
75 #define MAX_CHUNK 15
76
77 // Note: Some things in this structure will eventually move to configuration
78 struct parameters global_parameters = 
79 {
80     0,   // dump_records
81     0,   // debug_mode
82     100,
83 };
84
85 static void log_xml_doc(xmlDoc *doc)
86 {
87     FILE *lf = yaz_log_file();
88     xmlChar *result = 0;
89     int len = 0;
90 #if LIBXML_VERSION >= 20600
91     xmlDocDumpFormatMemory(doc, &result, &len, 1);
92 #else
93     xmlDocDumpMemory(doc, &result, &len);
94 #endif
95     if (lf && len)
96     {
97         fwrite(result, 1, len, lf);
98         fprintf(lf, "\n");
99     }
100     xmlFree(result);
101 }
102
103 // Recursively traverse query structure to extract terms.
104 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
105 {
106     char **words;
107     int numwords;
108     int i;
109
110     switch (n->kind)
111     {
112     case CCL_RPN_AND:
113     case CCL_RPN_OR:
114     case CCL_RPN_NOT:
115     case CCL_RPN_PROX:
116         pull_terms(nmem, n->u.p[0], termlist, num);
117         pull_terms(nmem, n->u.p[1], termlist, num);
118         break;
119     case CCL_RPN_TERM:
120         nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
121         for (i = 0; i < numwords; i++)
122             termlist[(*num)++] = words[i];
123         break;
124     default: // NOOP
125         break;
126     }
127 }
128
129
130
131 static void add_facet(struct session *s, const char *type, const char *value)
132 {
133     int i;
134
135     if (!*value)
136         return;
137     for (i = 0; i < s->num_termlists; i++)
138         if (!strcmp(s->termlists[i].name, type))
139             break;
140     if (i == s->num_termlists)
141     {
142         if (i == SESSION_MAX_TERMLISTS)
143         {
144             yaz_log(YLOG_FATAL, "Too many termlists");
145             return;
146         }
147
148         s->termlists[i].name = nmem_strdup(s->nmem, type);
149         s->termlists[i].termlist 
150             = termlist_create(s->nmem, s->expected_maxrecs,
151                               TERMLIST_HIGH_SCORE);
152         s->num_termlists = i + 1;
153     }
154     termlist_insert(s->termlists[i].termlist, value);
155 }
156
157 xmlDoc *record_to_xml(struct session_database *sdb, const char *rec)
158 {
159     struct database *db = sdb->database;
160     xmlDoc *rdoc = 0;
161
162     rdoc = xmlParseMemory(rec, strlen(rec));
163
164     if (!rdoc)
165     {
166         yaz_log(YLOG_FATAL, "Non-wellformed XML received from %s",
167                 db->url);
168         return 0;
169     }
170
171     if (global_parameters.dump_records)
172     {
173         yaz_log(YLOG_LOG, "Un-normalized record from %s", db->url);
174         log_xml_doc(rdoc);
175     }
176
177     return rdoc;
178 }
179
180 #define MAX_XSLT_ARGS 16
181
182 // Add static values from session database settings if applicable
183 static void insert_settings_parameters(struct session_database *sdb,
184                                        struct session *se, char **parms)
185 {
186     struct conf_service *service = se->service;
187     int i;
188     int nparms = 0;
189     int offset = 0;
190
191     for (i = 0; i < service->num_metadata; i++)
192     {
193         struct conf_metadata *md = &service->metadata[i];
194         int setting;
195
196         if (md->setting == Metadata_setting_parameter &&
197             (setting = settings_offset(service, md->name)) > 0)
198         {
199             const char *val = session_setting_oneval(sdb, setting);
200             if (val && nparms < MAX_XSLT_ARGS)
201             {
202                 char *buf;
203                 int len = strlen(val);
204                 buf = nmem_malloc(se->nmem, len + 3);
205                 buf[0] = '\'';
206                 strcpy(buf + 1, val);
207                 buf[len+1] = '\'';
208                 buf[len+2] = '\0';
209                 parms[offset++] = md->name;
210                 parms[offset++] = buf;
211                 nparms++;
212             }
213         }
214     }
215     parms[offset] = 0;
216 }
217
218 // Add static values from session database settings if applicable
219 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
220     struct conf_service *service)
221 {
222     int i;
223
224     for (i = 0; i < service->num_metadata; i++)
225     {
226         struct conf_metadata *md = &service->metadata[i];
227         int offset;
228
229         if (md->setting == Metadata_setting_postproc &&
230             (offset = settings_offset(service, md->name)) > 0)
231         {
232             const char *val = session_setting_oneval(sdb, offset);
233             if (val)
234             {
235                 xmlNode *r = xmlDocGetRootElement(doc);
236                 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
237                                              (xmlChar *) val);
238                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
239             }
240         }
241     }
242 }
243
244 xmlDoc *normalize_record(struct session_database *sdb, struct session *se,
245                          const char *rec)
246 {
247     struct database_retrievalmap *m;
248     xmlDoc *rdoc = record_to_xml(sdb, rec);
249     if (rdoc)
250     {
251         for (m = sdb->map; m; m = m->next)
252         {
253             xmlDoc *new = 0;
254             
255             {
256                 xmlNodePtr root = 0;
257                 char *parms[MAX_XSLT_ARGS*2+1];
258
259                 insert_settings_parameters(sdb, se, parms);
260
261                 if (m->stylesheet)
262                 {
263                     new = xsltApplyStylesheet(m->stylesheet, rdoc, (const char **) parms);
264                 }
265                 else if (m->marcmap)
266                 {
267                     new = marcmap_apply(m->marcmap, rdoc);
268                 }
269
270                 root = xmlDocGetRootElement(new);
271
272                 if (!new || !root || !(root->children))
273                 {
274                     yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
275                             sdb->database->url);
276                     xmlFreeDoc(new);
277                     xmlFreeDoc(rdoc);
278                     return 0;
279                 }
280             }
281             
282             xmlFreeDoc(rdoc);
283             rdoc = new;
284         }
285
286         insert_settings_values(sdb, rdoc, se->service);
287
288         if (global_parameters.dump_records)
289         {
290             yaz_log(YLOG_LOG, "Normalized record from %s", 
291                     sdb->database->url);
292             log_xml_doc(rdoc);
293         }
294     }
295     return rdoc;
296 }
297
298 // Retrieve first defined value for 'name' for given database.
299 // Will be extended to take into account user associated with session
300 const char *session_setting_oneval(struct session_database *db, int offset)
301 {
302     if (!db->settings[offset])
303         return "";
304     return db->settings[offset]->value;
305 }
306
307 // Prepare XSLT stylesheets for record normalization
308 // Structures are allocated on the session_wide nmem to avoid having
309 // to recompute this for every search. This would lead
310 // to leaking if a single session was to repeatedly change the PZ_XSLT
311 // setting. However, this is not a realistic use scenario.
312 static int prepare_map(struct session *se, struct session_database *sdb)
313 {
314     const char *s;
315
316     if (!sdb->settings)
317     {
318         yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
319         return -1;
320     }
321     if ((s = session_setting_oneval(sdb, PZ_XSLT)))
322     {
323         char **stylesheets;
324         struct database_retrievalmap **m = &sdb->map;
325         int num, i;
326         char auto_stylesheet[256];
327
328         if (!strcmp(s, "auto"))
329         {
330             const char *request_syntax = session_setting_oneval(
331                 sdb, PZ_REQUESTSYNTAX);
332             if (request_syntax)
333             {
334                 char *cp;
335                 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
336                              "%s.xsl", request_syntax);
337                 for (cp = auto_stylesheet; *cp; cp++)
338                 {
339                     /* deliberately only consider ASCII */
340                     if (*cp > 32 && *cp < 127)
341                         *cp = tolower(*cp);
342                 }
343                 s = auto_stylesheet;
344             }
345             else
346             {
347                 yaz_log(YLOG_WARN, "No pz:requestsyntax for auto stylesheet");
348             }
349         }
350         nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
351         for (i = 0; i < num; i++)
352         {
353             (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
354             (*m)->next = 0;
355  
356             // XSLT
357             if (!strcmp(&stylesheets[i][strlen(stylesheets[i])-4], ".xsl")) 
358             {    
359                 (*m)->marcmap = NULL;
360                 if (!((*m)->stylesheet = conf_load_stylesheet(se->service, stylesheets[i])))
361                 {
362                     yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
363                             stylesheets[i]);
364                     return -1;
365                 }
366             }
367             // marcmap
368             else if (!strcmp(&stylesheets[i][strlen(stylesheets[i])-5], ".mmap"))
369             {
370                 (*m)->stylesheet = NULL;
371                 if (!((*m)->marcmap = marcmap_load(stylesheets[i], se->session_nmem)))
372                 {
373                     yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load marcmap: %s",
374                             stylesheets[i]);
375                     return -1;
376                 }
377             }
378
379             m = &(*m)->next;
380         }
381     }
382     if (!sdb->map)
383         yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
384                 sdb->database->url);
385     return 0;
386 }
387
388 // This analyzes settings and recomputes any supporting data structures
389 // if necessary.
390 static int prepare_session_database(struct session *se, 
391                                     struct session_database *sdb)
392 {
393     if (!sdb->settings)
394     {
395         yaz_log(YLOG_WARN, 
396                 "No settings associated with %s", sdb->database->url);
397         return -1;
398     }
399     if (sdb->settings[PZ_XSLT] && !sdb->map)
400     {
401         if (prepare_map(se, sdb) < 0)
402             return -1;
403     }
404     return 0;
405 }
406
407 // called if watch should be removed because http_channel is to be destroyed
408 static void session_watch_cancel(void *data, struct http_channel *c,
409                                  void *data2)
410 {
411     struct session_watchentry *ent = data;
412
413     ent->fun = 0;
414     ent->data = 0;
415     ent->obs = 0;
416 }
417
418 // set watch. Returns 0=OK, -1 if watch is already set
419 int session_set_watch(struct session *s, int what, 
420                       session_watchfun fun, void *data,
421                       struct http_channel *chan)
422 {
423     if (s->watchlist[what].fun)
424         return -1;
425     s->watchlist[what].fun = fun;
426     s->watchlist[what].data = data;
427     s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
428                                                session_watch_cancel);
429     return 0;
430 }
431
432 void session_alert_watch(struct session *s, int what)
433 {
434     if (s->watchlist[what].fun)
435     {
436         /* our watch is no longer associated with http_channel */
437         void *data;
438         session_watchfun fun;
439
440         http_remove_observer(s->watchlist[what].obs);
441         fun = s->watchlist[what].fun;
442         data = s->watchlist[what].data;
443
444         /* reset watch before fun is invoked - in case fun wants to set
445            it again */
446         s->watchlist[what].fun = 0;
447         s->watchlist[what].data = 0;
448         s->watchlist[what].obs = 0;
449
450         fun(data);
451     }
452 }
453
454 //callback for grep_databases
455 static void select_targets_callback(void *context, struct session_database *db)
456 {
457     struct session *se = (struct session*) context;
458     struct client *cl = client_create();
459     client_set_database(cl, db);
460     client_set_session(cl, se);
461 }
462
463 // Associates a set of clients with a session;
464 // Note: Session-databases represent databases with per-session 
465 // setting overrides
466 int select_targets(struct session *se, struct database_criterion *crit)
467 {
468     while (se->clients)
469         client_destroy(se->clients);
470
471     return session_grep_databases(se, crit, select_targets_callback);
472 }
473
474 int session_active_clients(struct session *s)
475 {
476     struct client *c;
477     int res = 0;
478
479     for (c = s->clients; c; c = client_next_in_session(c))
480         if (client_is_active(c))
481             res++;
482
483     return res;
484 }
485
486 // parses crit1=val1,crit2=val2|val3,...
487 static struct database_criterion *parse_filter(NMEM m, const char *buf)
488 {
489     struct database_criterion *res = 0;
490     char **values;
491     int num;
492     int i;
493
494     if (!buf || !*buf)
495         return 0;
496     nmem_strsplit(m, ",", buf,  &values, &num);
497     for (i = 0; i < num; i++)
498     {
499         char **subvalues;
500         int subnum;
501         int subi;
502         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
503         char *eq = strchr(values[i], '=');
504         if (!eq)
505         {
506             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
507             return 0;
508         }
509         *(eq++) = '\0';
510         new->name = values[i];
511         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
512         new->values = 0;
513         for (subi = 0; subi < subnum; subi++)
514         {
515             struct database_criterion_value *newv
516                 = nmem_malloc(m, sizeof(*newv));
517             newv->value = subvalues[subi];
518             newv->next = new->values;
519             new->values = newv;
520         }
521         new->next = res;
522         res = new;
523     }
524     return res;
525 }
526
527 enum pazpar2_error_code search(struct session *se,
528                                const char *query, const char *filter,
529                                const char **addinfo)
530 {
531     int live_channels = 0;
532     int no_working = 0;
533     int no_failed = 0;
534     struct client *cl;
535     struct database_criterion *criteria;
536
537     yaz_log(YLOG_DEBUG, "Search");
538
539     *addinfo = 0;
540     nmem_reset(se->nmem);
541     se->relevance = 0;
542     se->total_records = se->total_hits = se->total_merged = 0;
543     se->reclist = 0;
544     se->num_termlists = 0;
545     criteria = parse_filter(se->nmem, filter);
546     live_channels = select_targets(se, criteria);
547     if (live_channels)
548     {
549         int maxrecs = live_channels * global_parameters.toget; // This is buggy!!!
550         se->reclist = reclist_create(se->nmem, maxrecs);
551         se->expected_maxrecs = maxrecs;
552     }
553     else
554         return PAZPAR2_NO_TARGETS;
555
556     for (cl = se->clients; cl; cl = client_next_in_session(cl))
557     {
558         if (prepare_session_database(se, client_get_database(cl)) < 0)
559         {
560             *addinfo = client_get_database(cl)->database->url;
561             return PAZPAR2_CONFIG_TARGET;
562         }
563         // Parse query for target
564         if (client_parse_query(cl, query) < 0)
565             no_failed++;
566         else
567         {
568             no_working++;
569             if (client_prep_connection(cl, se->service->z3950_connect_timeout,
570                     se->service->z3950_session_timeout))
571                 client_start_search(cl);
572         }
573     }
574
575     // If no queries could be mapped, we signal an error
576     if (no_working == 0)
577     {
578         *addinfo = "query";
579         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
580     }
581     return PAZPAR2_NO_ERROR;
582 }
583
584 // Creates a new session_database object for a database
585 static void session_init_databases_fun(void *context, struct database *db)
586 {
587     struct session *se = (struct session *) context;
588     struct conf_service *service = se->service;
589     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
590     int num = settings_num(service);
591     int i;
592
593     new->database = db;
594     
595     new->map = 0;
596     new->settings 
597         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
598     memset(new->settings, 0, sizeof(struct settings*) * num);
599
600     if (db->settings)
601     {
602         for (i = 0; i < num; i++)
603             new->settings[i] = db->settings[i];
604     }
605     new->next = se->databases;
606     se->databases = new;
607 }
608
609 // Doesn't free memory associated with sdb -- nmem takes care of that
610 static void session_database_destroy(struct session_database *sdb)
611 {
612     struct database_retrievalmap *m;
613
614     for (m = sdb->map; m; m = m->next)
615         xsltFreeStylesheet(m->stylesheet);
616 }
617
618 // Initialize session_database list -- this represents this session's view
619 // of the database list -- subject to modification by the settings ws command
620 void session_init_databases(struct session *se)
621 {
622     se->databases = 0;
623     predef_grep_databases(se, se->service, 0, session_init_databases_fun);
624 }
625
626 // Probably session_init_databases_fun should be refactored instead of
627 // called here.
628 static struct session_database *load_session_database(struct session *se, 
629                                                       char *id)
630 {
631     struct database *db = find_database(id, 0, se->service);
632
633     resolve_database(db);
634
635     session_init_databases_fun((void*) se, db);
636     // New sdb is head of se->databases list
637     return se->databases;
638 }
639
640 // Find an existing session database. If not found, load it
641 static struct session_database *find_session_database(struct session *se, 
642                                                       char *id)
643 {
644     struct session_database *sdb;
645
646     for (sdb = se->databases; sdb; sdb = sdb->next)
647         if (!strcmp(sdb->database->url, id))
648             return sdb;
649     return load_session_database(se, id);
650 }
651
652 // Apply a session override to a database
653 void session_apply_setting(struct session *se, char *dbname, char *setting,
654                            char *value)
655 {
656     struct session_database *sdb = find_session_database(se, dbname);
657     struct conf_service *service = se->service;
658     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
659     int offset = settings_offset_cprefix(service, setting);
660
661     if (offset < 0)
662     {
663         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
664         return;
665     }
666     // Jakub: This breaks the filter setting.
667     /*if (offset == PZ_ID)
668       {
669       yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
670       return;
671       }*/
672     new->precedence = 0;
673     new->target = dbname;
674     new->name = setting;
675     new->value = value;
676     new->next = sdb->settings[offset];
677     sdb->settings[offset] = new;
678
679     // Force later recompute of settings-driven data structures
680     // (happens when a search starts and client connections are prepared)
681     switch (offset)
682     {
683     case PZ_XSLT:
684         if (sdb->map)
685         {
686             struct database_retrievalmap *m;
687             // We don't worry about the map structure -- it's in nmem
688             for (m = sdb->map; m; m = m->next)
689                 xsltFreeStylesheet(m->stylesheet);
690             sdb->map = 0;
691         }
692         break;
693     }
694 }
695
696 void destroy_session(struct session *s)
697 {
698     struct session_database *sdb;
699
700     while (s->clients)
701         client_destroy(s->clients);
702     for (sdb = s->databases; sdb; sdb = sdb->next)
703         session_database_destroy(sdb);
704     nmem_destroy(s->nmem);
705     service_destroy(s->service);
706     wrbuf_destroy(s->wrbuf);
707 }
708
709 struct session *new_session(NMEM nmem, struct conf_service *service) 
710 {
711     int i;
712     struct session *session = nmem_malloc(nmem, sizeof(*session));
713
714     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
715
716     session->service = service;
717     session->relevance = 0;
718     session->total_hits = 0;
719     session->total_records = 0;
720     session->number_of_warnings_unknown_elements = 0;
721     session->number_of_warnings_unknown_metadata = 0;
722     session->num_termlists = 0;
723     session->reclist = 0;
724     session->clients = 0;
725     session->expected_maxrecs = 0;
726     session->session_nmem = nmem;
727     session->nmem = nmem_create();
728     session->wrbuf = wrbuf_alloc();
729     session->databases = 0;
730     for (i = 0; i <= SESSION_WATCH_MAX; i++)
731     {
732         session->watchlist[i].data = 0;
733         session->watchlist[i].fun = 0;
734     }
735     return session;
736 }
737
738 struct hitsbytarget *hitsbytarget(struct session *se, int *count, NMEM nmem)
739 {
740     struct hitsbytarget *res = 0;
741     struct client *cl;
742     size_t sz = 0;
743
744     for (cl = se->clients; cl; cl = client_next_in_session(cl))
745         sz++;
746
747     res = nmem_malloc(nmem, sizeof(*res) * sz);
748     *count = 0;
749     for (cl = se->clients; cl; cl = client_next_in_session(cl))
750     {
751         const char *name = session_setting_oneval(client_get_database(cl),
752                                                   PZ_NAME);
753
754         res[*count].id = client_get_database(cl)->database->url;
755         res[*count].name = *name ? name : "Unknown";
756         res[*count].hits = client_get_hits(cl);
757         res[*count].records = client_get_num_records(cl);
758         res[*count].diagnostic = client_get_diagnostic(cl);
759         res[*count].state = client_get_state_str(cl);
760         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
761         (*count)++;
762     }
763     return res;
764 }
765
766 struct termlist_score **termlist(struct session *s, const char *name, int *num)
767 {
768     int i;
769
770     for (i = 0; i < s->num_termlists; i++)
771         if (!strcmp((const char *) s->termlists[i].name, name))
772             return termlist_highscore(s->termlists[i].termlist, num);
773     return 0;
774 }
775
776 #ifdef MISSING_HEADERS
777 void report_nmem_stats(void)
778 {
779     size_t in_use, is_free;
780
781     nmem_get_memory_in_use(&in_use);
782     nmem_get_memory_free(&is_free);
783
784     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
785             (long) in_use, (long) is_free);
786 }
787 #endif
788
789 struct record_cluster *show_single(struct session *s, const char *id,
790                                    struct record_cluster **prev_r,
791                                    struct record_cluster **next_r)
792 {
793     struct record_cluster *r;
794
795     reclist_rewind(s->reclist);
796     *prev_r = 0;
797     *next_r = 0;
798     while ((r = reclist_read_record(s->reclist)))
799     {
800         if (!strcmp(r->recid, id))
801         {
802             *next_r = reclist_read_record(s->reclist);
803             return r;
804         }
805         *prev_r = r;
806     }
807     return 0;
808 }
809
810 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
811                              int start, int *num, int *total, int *sumhits, 
812                              NMEM nmem_show)
813 {
814     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
815                                                * sizeof(struct record_cluster *));
816     struct reclist_sortparms *spp;
817     int i;
818 #if USE_TIMING    
819     yaz_timing_t t = yaz_timing_create();
820 #endif
821
822     if (!s->relevance)
823     {
824         *num = 0;
825         *total = 0;
826         *sumhits = 0;
827         recs = 0;
828     }
829     else
830     {
831         for (spp = sp; spp; spp = spp->next)
832             if (spp->type == Metadata_sortkey_relevance)
833             {
834                 relevance_prepare_read(s->relevance, s->reclist);
835                 break;
836             }
837         reclist_sort(s->reclist, sp);
838         
839         *total = s->reclist->num_records;
840         *sumhits = s->total_hits;
841         
842         for (i = 0; i < start; i++)
843             if (!reclist_read_record(s->reclist))
844             {
845                 *num = 0;
846                 recs = 0;
847                 break;
848             }
849         
850         for (i = 0; i < *num; i++)
851         {
852             struct record_cluster *r = reclist_read_record(s->reclist);
853             if (!r)
854             {
855                 *num = i;
856                 break;
857             }
858             recs[i] = r;
859         }
860     }
861 #if USE_TIMING
862     yaz_timing_stop(t);
863     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
864             yaz_timing_get_real(t), yaz_timing_get_user(t),
865             yaz_timing_get_sys(t));
866     yaz_timing_destroy(&t);
867 #endif
868     return recs;
869 }
870
871 void statistics(struct session *se, struct statistics *stat)
872 {
873     struct client *cl;
874     int count = 0;
875
876     memset(stat, 0, sizeof(*stat));
877     for (cl = se->clients; cl; cl = client_next_in_session(cl))
878     {
879         if (!client_get_connection(cl))
880             stat->num_no_connection++;
881         switch (client_get_state(cl))
882         {
883         case Client_Connecting: stat->num_connecting++; break;
884         case Client_Working: stat->num_working++; break;
885         case Client_Idle: stat->num_idle++; break;
886         case Client_Failed: stat->num_failed++; break;
887         case Client_Error: stat->num_error++; break;
888         default: break;
889         }
890         count++;
891     }
892     stat->num_hits = se->total_hits;
893     stat->num_records = se->total_records;
894
895     stat->num_clients = count;
896 }
897
898
899 // Master list of connections we're handling events to
900 static IOCHAN channel_list = 0;  /* thread pr */
901
902 void pazpar2_add_channel(IOCHAN chan)
903 {
904     chan->next = channel_list;
905     channel_list = chan;
906 }
907
908 void pazpar2_event_loop()
909 {
910     event_loop(&channel_list);
911 }
912
913 static struct record_metadata *record_metadata_init(
914     NMEM nmem, char *value, enum conf_metadata_type type)
915 {
916     struct record_metadata *rec_md = record_metadata_create(nmem);
917     if (type == Metadata_type_generic)
918     {
919         char * p = value;
920         p = normalize7bit_generic(p, " ,/.:([");
921         
922         rec_md->data.text.disp = nmem_strdup(nmem, p);
923         rec_md->data.text.sort = 0;
924     }
925     else if (type == Metadata_type_year || type == Metadata_type_date)
926     {
927         int first, last;
928         int longdate = 0;
929
930         if (type == Metadata_type_date)
931             longdate = 1;
932         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
933             return 0;
934
935         rec_md->data.number.min = first;
936         rec_md->data.number.max = last;
937     }
938     else
939         return 0;
940     return rec_md;
941 }
942
943 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
944                                 struct conf_service *service, NMEM nmem)
945 {
946     char *mergekey_norm = 0;
947     xmlNode *root = xmlDocGetRootElement(doc);
948     WRBUF norm_wr = wrbuf_alloc();
949     xmlNode *n;
950
951     /* create mergekey based on mergekey attribute from XSL (if any) */
952     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
953     if (mergekey)
954     {
955         const char *norm_str;
956         pp2_relevance_token_t prt =
957             pp2_relevance_tokenize(
958                 service->mergekey_pct,
959                 (const char *) mergekey);
960         
961         while ((norm_str = pp2_relevance_token_next(prt)))
962         {
963             if (*norm_str)
964             {
965                 if (wrbuf_len(norm_wr))
966                     wrbuf_puts(norm_wr, " ");
967                 wrbuf_puts(norm_wr, norm_str);
968             }
969         }
970         pp2_relevance_token_destroy(prt);
971         xmlFree(mergekey);
972     }
973     /* append (if any) mergekey=yes metadata values */
974     for (n = root->children; n; n = n->next)
975     {
976         if (n->type != XML_ELEMENT_NODE)
977             continue;
978         if (!strcmp((const char *) n->name, "metadata"))
979         {
980             struct conf_metadata *ser_md = 0;
981             int md_field_id = -1;
982             
983             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
984             
985             if (!type)
986                 continue;
987                 
988             md_field_id 
989                 = conf_service_metadata_field_id(service, 
990                                                  (const char *) type);
991             if (md_field_id >= 0)
992             {
993                 ser_md = &service->metadata[md_field_id];
994                 if (ser_md->mergekey == Metadata_mergekey_yes)
995                 {
996                     xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
997                     if (value)
998                     {
999                         const char *norm_str;
1000                         pp2_relevance_token_t prt =
1001                             pp2_relevance_tokenize(
1002                                 service->mergekey_pct,
1003                                 (const char *) value);
1004                         
1005                         while ((norm_str = pp2_relevance_token_next(prt)))
1006                         {
1007                             if (*norm_str)
1008                             {
1009                                 if (wrbuf_len(norm_wr))
1010                                     wrbuf_puts(norm_wr, " ");
1011                                 wrbuf_puts(norm_wr, norm_str);
1012                             }
1013                         }
1014                         xmlFree(value);
1015                         pp2_relevance_token_destroy(prt);
1016                     }
1017                 }
1018             }
1019             xmlFree(type);
1020         }
1021     }
1022
1023     /* generate unique key if none is not generated already or is empty */
1024     if (wrbuf_len(norm_wr) == 0)
1025     {
1026         wrbuf_printf(norm_wr, "%s-%d",
1027                      client_get_database(cl)->database->url, record_no);
1028     }
1029     if (wrbuf_len(norm_wr) > 0)
1030         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1031     wrbuf_destroy(norm_wr);
1032     return mergekey_norm;
1033 }
1034
1035 static const char *str_tok_n(const char *s, const char *delim,
1036                              const char **res, size_t *len)
1037 {
1038     *res = s;
1039     while (*s && !strchr(delim, *s))
1040         s++;
1041     *len = s - *res;
1042     if (*len == 0)
1043         return 0;
1044     if (*s && strchr(delim, *s))
1045         s++;
1046     return s;
1047 }
1048
1049 /** \brief see if metadata for pz:recordfilter exists 
1050     \param root xml root element of normalized record
1051     \param sdb session database for client
1052     \retval 0 if there is no metadata for pz:recordfilter
1053     \retval 1 if there is metadata for pz:recordfilter
1054
1055     If there is no pz:recordfilter defined, this function returns 1
1056     as well.
1057 */
1058     
1059 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1060 {
1061     int match = 0;
1062     xmlNode *n;
1063     const char *s;
1064     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1065
1066     if (!s || !*s)
1067         return 1;
1068
1069     for (n = root->children; n; n = n->next)
1070     {
1071         if (n->type != XML_ELEMENT_NODE)
1072             continue;
1073         if (!strcmp((const char *) n->name, "metadata"))
1074         {
1075             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1076             if (type)
1077             {
1078                 const char *s1 = s;
1079                 size_t len;
1080                 const char *value;
1081                 while ((s1 = str_tok_n(s1, ",", &value, &len)) != 0)
1082                 {
1083                     if (len == strlen((const char *)type) &&
1084                         !memcmp((const char *) type, s, len))
1085                     {
1086                         xmlChar *value = xmlNodeGetContent(n);
1087                         if (value && *value)
1088                         {
1089                             xmlFree(value);
1090                             match = 1;
1091                         }
1092                     }
1093                 }
1094                 xmlFree(type);
1095             }
1096         }
1097     }
1098     return match;
1099 }
1100
1101
1102 /** \brief ingest XML record
1103     \param cl client holds the result set for record
1104     \param rec record buffer (0 terminated)
1105     \param record_no record position (1, 2, ..)
1106     \returns resulting record or NULL on failure
1107 */
1108 struct record *ingest_record(struct client *cl, const char *rec,
1109                              int record_no)
1110 {
1111     struct session_database *sdb = client_get_database(cl);
1112     struct session *se = client_get_session(cl);
1113     xmlDoc *xdoc = normalize_record(sdb, se, rec);
1114     xmlNode *root, *n;
1115     struct record *record;
1116     struct record_cluster *cluster;
1117     const char *mergekey_norm;
1118     xmlChar *type = 0;
1119     xmlChar *value = 0;
1120     struct conf_service *service = se->service;
1121
1122     if (!xdoc)
1123         return 0;
1124
1125     root = xmlDocGetRootElement(xdoc);
1126
1127     if (!check_record_filter(root, sdb))
1128     {
1129         yaz_log(YLOG_WARN, "Filtered out record no %d from %s", record_no,
1130             sdb->database->url);
1131         xmlFreeDoc(xdoc);
1132         return 0;
1133     }
1134
1135     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, se->nmem);
1136     if (!mergekey_norm)
1137     {
1138         yaz_log(YLOG_WARN, "Got no mergekey");
1139         xmlFreeDoc(xdoc);
1140         return 0;
1141     }
1142     record = record_create(se->nmem, 
1143                            service->num_metadata, service->num_sortkeys, cl,
1144                            record_no);
1145
1146     cluster = reclist_insert(se->reclist, 
1147                              service, 
1148                              record, (char *) mergekey_norm, 
1149                              &se->total_merged);
1150     if (global_parameters.dump_records)
1151         yaz_log(YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1152                 sdb->database->url, record_no);
1153     if (!cluster)
1154     {
1155         /* no room for record */
1156         xmlFreeDoc(xdoc);
1157         return 0;
1158     }
1159     relevance_newrec(se->relevance, cluster);
1160     
1161     // now parsing XML record and adding data to cluster or record metadata
1162     for (n = root->children; n; n = n->next)
1163     {
1164         pp2_relevance_token_t prt;
1165         if (type)
1166             xmlFree(type);
1167         if (value)
1168             xmlFree(value);
1169         type = value = 0;
1170         
1171         if (n->type != XML_ELEMENT_NODE)
1172             continue;
1173         if (!strcmp((const char *) n->name, "metadata"))
1174         {
1175             struct conf_metadata *ser_md = 0;
1176             struct conf_sortkey *ser_sk = 0;
1177             struct record_metadata **wheretoput = 0;
1178             struct record_metadata *rec_md = 0;
1179             int md_field_id = -1;
1180             int sk_field_id = -1;
1181             
1182             type = xmlGetProp(n, (xmlChar *) "type");
1183             value = xmlNodeListGetString(xdoc, n->children, 1);
1184             
1185             if (!type || !value || !*value)
1186                 continue;
1187             
1188             md_field_id 
1189                 = conf_service_metadata_field_id(service, (const char *) type);
1190             if (md_field_id < 0)
1191             {
1192                 if (se->number_of_warnings_unknown_metadata == 0)
1193                 {
1194                     yaz_log(YLOG_WARN, 
1195                             "Ignoring unknown metadata element: %s", type);
1196                 }
1197                 se->number_of_warnings_unknown_metadata++;
1198                 continue;
1199             }
1200             
1201             ser_md = &service->metadata[md_field_id];
1202             
1203             if (ser_md->sortkey_offset >= 0){
1204                 sk_field_id = ser_md->sortkey_offset;
1205                 ser_sk = &service->sortkeys[sk_field_id];
1206             }
1207
1208             // non-merged metadata
1209             rec_md = record_metadata_init(se->nmem, (char *) value,
1210                                           ser_md->type);
1211             if (!rec_md)
1212             {
1213                 yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1214                         value, type);
1215                 continue;
1216             }
1217             wheretoput = &record->metadata[md_field_id];
1218             while (*wheretoput)
1219                 wheretoput = &(*wheretoput)->next;
1220             *wheretoput = rec_md;
1221
1222             // merged metadata
1223             rec_md = record_metadata_init(se->nmem, (char *) value,
1224                                           ser_md->type);
1225             wheretoput = &cluster->metadata[md_field_id];
1226
1227             // and polulate with data:
1228             // assign cluster or record based on merge action
1229             if (ser_md->merge == Metadata_merge_unique)
1230             {
1231                 struct record_metadata *mnode;
1232                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1233                     if (!strcmp((const char *) mnode->data.text.disp, 
1234                                 rec_md->data.text.disp))
1235                         break;
1236                 if (!mnode)
1237                 {
1238                     rec_md->next = *wheretoput;
1239                     *wheretoput = rec_md;
1240                 }
1241             }
1242             else if (ser_md->merge == Metadata_merge_longest)
1243             {
1244                 if (!*wheretoput 
1245                     || strlen(rec_md->data.text.disp) 
1246                     > strlen((*wheretoput)->data.text.disp))
1247                 {
1248                     *wheretoput = rec_md;
1249                     if (ser_sk)
1250                     {
1251                         const char *sort_str = 0;
1252                         int skip_article = 
1253                             ser_sk->type == Metadata_sortkey_skiparticle;
1254
1255                         if (!cluster->sortkeys[sk_field_id])
1256                             cluster->sortkeys[sk_field_id] = 
1257                                 nmem_malloc(se->nmem, 
1258                                             sizeof(union data_types));
1259                          
1260                         prt = pp2_relevance_tokenize(
1261                             service->sort_pct,
1262                             rec_md->data.text.disp);
1263
1264                         pp2_relevance_token_next(prt);
1265                          
1266                         sort_str = pp2_get_sort(prt, skip_article);
1267                          
1268                         cluster->sortkeys[sk_field_id]->text.disp = 
1269                             rec_md->data.text.disp;
1270                         if (!sort_str)
1271                         {
1272                             sort_str = rec_md->data.text.disp;
1273                             yaz_log(YLOG_WARN, 
1274                                     "Could not make sortkey. Bug #1858");
1275                         }
1276                         cluster->sortkeys[sk_field_id]->text.sort = 
1277                             nmem_strdup(se->nmem, sort_str);
1278 #if 0
1279                         yaz_log(YLOG_LOG, "text disp=%s",
1280                                 cluster->sortkeys[sk_field_id]->text.disp);
1281                         yaz_log(YLOG_LOG, "text sort=%s",
1282                                 cluster->sortkeys[sk_field_id]->text.sort);
1283 #endif
1284                         pp2_relevance_token_destroy(prt);
1285                     }
1286                 }
1287             }
1288             else if (ser_md->merge == Metadata_merge_all)
1289             {
1290                 rec_md->next = *wheretoput;
1291                 *wheretoput = rec_md;
1292             }
1293             else if (ser_md->merge == Metadata_merge_range)
1294             {
1295                 if (!*wheretoput)
1296                 {
1297                     *wheretoput = rec_md;
1298                     if (ser_sk)
1299                         cluster->sortkeys[sk_field_id] 
1300                             = &rec_md->data;
1301                 }
1302                 else
1303                 {
1304                     int this_min = rec_md->data.number.min;
1305                     int this_max = rec_md->data.number.max;
1306                     if (this_min < (*wheretoput)->data.number.min)
1307                         (*wheretoput)->data.number.min = this_min;
1308                     if (this_max > (*wheretoput)->data.number.max)
1309                         (*wheretoput)->data.number.max = this_max;
1310                 }
1311             }
1312
1313
1314             // ranking of _all_ fields enabled ... 
1315             if (ser_md->rank)
1316                 relevance_countwords(se->relevance, cluster, 
1317                                      (char *) value, ser_md->rank);
1318
1319             // construct facets ... 
1320             if (ser_md->termlist)
1321             {
1322                 if (ser_md->type == Metadata_type_year)
1323                 {
1324                     char year[64];
1325                     sprintf(year, "%d", rec_md->data.number.max);
1326                     add_facet(se, (char *) type, year);
1327                     if (rec_md->data.number.max != rec_md->data.number.min)
1328                     {
1329                         sprintf(year, "%d", rec_md->data.number.min);
1330                         add_facet(se, (char *) type, year);
1331                     }
1332                 }
1333                 else
1334                     add_facet(se, (char *) type, (char *) value);
1335             }
1336
1337             // cleaning up
1338             xmlFree(type);
1339             xmlFree(value);
1340             type = value = 0;
1341         }
1342         else
1343         {
1344             if (se->number_of_warnings_unknown_elements == 0)
1345                 yaz_log(YLOG_WARN,
1346                         "Unexpected element in internal record: %s", n->name);
1347             se->number_of_warnings_unknown_elements++;
1348         }
1349     }
1350     if (type)
1351         xmlFree(type);
1352     if (value)
1353         xmlFree(value);
1354
1355     xmlFreeDoc(xdoc);
1356
1357     relevance_donerecord(se->relevance, cluster);
1358     se->total_records++;
1359
1360     return record;
1361 }
1362
1363
1364
1365 /*
1366  * Local variables:
1367  * c-basic-offset: 4
1368  * c-file-style: "Stroustrup"
1369  * indent-tabs-mode: nil
1370  * End:
1371  * vim: shiftwidth=4 tabstop=8 expandtab
1372  */
1373