e243d58b77687fb794504070ff096394f0234565
[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     /* consider mergekey from XSL first */
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     else
974     {
975         /* no mergekey defined in XSL. Look for mergekey metadata instead */
976         for (n = root->children; n; n = n->next)
977         {
978             if (n->type != XML_ELEMENT_NODE)
979                 continue;
980             if (!strcmp((const char *) n->name, "metadata"))
981             {
982                 struct conf_metadata *ser_md = 0;
983                 int md_field_id = -1;
984                 
985                 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
986                 
987                 if (!type)
988                     continue;
989                 
990                 md_field_id 
991                     = conf_service_metadata_field_id(service, 
992                                                      (const char *) type);
993                 if (md_field_id >= 0)
994                 {
995                     ser_md = &service->metadata[md_field_id];
996                     if (ser_md->mergekey == Metadata_mergekey_yes)
997                     {
998                         xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
999                         if (value)
1000                         {
1001                             const char *norm_str;
1002                             pp2_relevance_token_t prt =
1003                                 pp2_relevance_tokenize(
1004                                     service->mergekey_pct,
1005                                     (const char *) value);
1006                             
1007                             while ((norm_str = pp2_relevance_token_next(prt)))
1008                             {
1009                                 if (*norm_str)
1010                                 {
1011                                     if (wrbuf_len(norm_wr))
1012                                         wrbuf_puts(norm_wr, " ");
1013                                     wrbuf_puts(norm_wr, norm_str);
1014                                 }
1015                             }
1016                             xmlFree(value);
1017                             pp2_relevance_token_destroy(prt);
1018                         }
1019                     }
1020                 }
1021                 xmlFree(type);
1022             }
1023         }
1024     }
1025
1026     /* generate unique key if none is not generated already or is empty */
1027     if (wrbuf_len(norm_wr) == 0)
1028     {
1029         wrbuf_printf(norm_wr, "%s-%d",
1030                      client_get_database(cl)->database->url, record_no);
1031     }
1032     if (wrbuf_len(norm_wr) > 0)
1033         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1034     wrbuf_destroy(norm_wr);
1035     return mergekey_norm;
1036 }
1037
1038 static const char *str_tok_n(const char *s, const char *delim,
1039                              const char **res, size_t *len)
1040 {
1041     *res = s;
1042     while (*s && !strchr(delim, *s))
1043         s++;
1044     *len = s - *res;
1045     if (*len == 0)
1046         return 0;
1047     if (*s && strchr(delim, *s))
1048         s++;
1049     return s;
1050 }
1051
1052 /** \brief see if metadata for pz:recordfilter exists 
1053     \param root xml root element of normalized record
1054     \param sdb session database for client
1055     \retval 0 if there is no metadata for pz:recordfilter
1056     \retval 1 if there is metadata for pz:recordfilter
1057
1058     If there is no pz:recordfilter defined, this function returns 1
1059     as well.
1060 */
1061     
1062 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1063 {
1064     int match = 0;
1065     xmlNode *n;
1066     const char *s;
1067     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1068
1069     if (!s || !*s)
1070         return 1;
1071
1072     for (n = root->children; n; n = n->next)
1073     {
1074         if (n->type != XML_ELEMENT_NODE)
1075             continue;
1076         if (!strcmp((const char *) n->name, "metadata"))
1077         {
1078             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1079             if (type)
1080             {
1081                 const char *s1 = s;
1082                 size_t len;
1083                 const char *value;
1084                 while ((s1 = str_tok_n(s1, ",", &value, &len)) != 0)
1085                 {
1086                     if (len == strlen((const char *)type) &&
1087                         !memcmp((const char *) type, s, len))
1088                     {
1089                         xmlChar *value = xmlNodeGetContent(n);
1090                         if (value && *value)
1091                         {
1092                             xmlFree(value);
1093                             match = 1;
1094                         }
1095                     }
1096                 }
1097                 xmlFree(type);
1098             }
1099         }
1100     }
1101     return match;
1102 }
1103
1104
1105 /** \brief ingest XML record
1106     \param cl client holds the result set for record
1107     \param rec record buffer (0 terminated)
1108     \param record_no record position (1, 2, ..)
1109     \returns resulting record or NULL on failure
1110 */
1111 struct record *ingest_record(struct client *cl, const char *rec,
1112                              int record_no)
1113 {
1114     struct session_database *sdb = client_get_database(cl);
1115     struct session *se = client_get_session(cl);
1116     xmlDoc *xdoc = normalize_record(sdb, se, rec);
1117     xmlNode *root, *n;
1118     struct record *record;
1119     struct record_cluster *cluster;
1120     const char *mergekey_norm;
1121     xmlChar *type = 0;
1122     xmlChar *value = 0;
1123     struct conf_service *service = se->service;
1124
1125     if (!xdoc)
1126         return 0;
1127
1128     root = xmlDocGetRootElement(xdoc);
1129
1130     if (!check_record_filter(root, sdb))
1131     {
1132         yaz_log(YLOG_WARN, "Filtered out record no %d from %s", record_no,
1133             sdb->database->url);
1134         xmlFreeDoc(xdoc);
1135         return 0;
1136     }
1137
1138     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, se->nmem);
1139     if (!mergekey_norm)
1140     {
1141         yaz_log(YLOG_WARN, "Got no mergekey");
1142         xmlFreeDoc(xdoc);
1143         return 0;
1144     }
1145     record = record_create(se->nmem, 
1146                            service->num_metadata, service->num_sortkeys, cl,
1147                            record_no);
1148
1149     cluster = reclist_insert(se->reclist, 
1150                              service, 
1151                              record, (char *) mergekey_norm, 
1152                              &se->total_merged);
1153     if (global_parameters.dump_records)
1154         yaz_log(YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1155                 sdb->database->url, record_no);
1156     if (!cluster)
1157     {
1158         /* no room for record */
1159         xmlFreeDoc(xdoc);
1160         return 0;
1161     }
1162     relevance_newrec(se->relevance, cluster);
1163     
1164     // now parsing XML record and adding data to cluster or record metadata
1165     for (n = root->children; n; n = n->next)
1166     {
1167         pp2_relevance_token_t prt;
1168         if (type)
1169             xmlFree(type);
1170         if (value)
1171             xmlFree(value);
1172         type = value = 0;
1173         
1174         if (n->type != XML_ELEMENT_NODE)
1175             continue;
1176         if (!strcmp((const char *) n->name, "metadata"))
1177         {
1178             struct conf_metadata *ser_md = 0;
1179             struct conf_sortkey *ser_sk = 0;
1180             struct record_metadata **wheretoput = 0;
1181             struct record_metadata *rec_md = 0;
1182             int md_field_id = -1;
1183             int sk_field_id = -1;
1184             
1185             type = xmlGetProp(n, (xmlChar *) "type");
1186             value = xmlNodeListGetString(xdoc, n->children, 1);
1187             
1188             if (!type || !value || !*value)
1189                 continue;
1190             
1191             md_field_id 
1192                 = conf_service_metadata_field_id(service, (const char *) type);
1193             if (md_field_id < 0)
1194             {
1195                 if (se->number_of_warnings_unknown_metadata == 0)
1196                 {
1197                     yaz_log(YLOG_WARN, 
1198                             "Ignoring unknown metadata element: %s", type);
1199                 }
1200                 se->number_of_warnings_unknown_metadata++;
1201                 continue;
1202             }
1203             
1204             ser_md = &service->metadata[md_field_id];
1205             
1206             if (ser_md->sortkey_offset >= 0){
1207                 sk_field_id = ser_md->sortkey_offset;
1208                 ser_sk = &service->sortkeys[sk_field_id];
1209             }
1210
1211             // non-merged metadata
1212             rec_md = record_metadata_init(se->nmem, (char *) value,
1213                                           ser_md->type);
1214             if (!rec_md)
1215             {
1216                 yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1217                         value, type);
1218                 continue;
1219             }
1220             wheretoput = &record->metadata[md_field_id];
1221             while (*wheretoput)
1222                 wheretoput = &(*wheretoput)->next;
1223             *wheretoput = rec_md;
1224
1225             // merged metadata
1226             rec_md = record_metadata_init(se->nmem, (char *) value,
1227                                           ser_md->type);
1228             wheretoput = &cluster->metadata[md_field_id];
1229
1230             // and polulate with data:
1231             // assign cluster or record based on merge action
1232             if (ser_md->merge == Metadata_merge_unique)
1233             {
1234                 struct record_metadata *mnode;
1235                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1236                     if (!strcmp((const char *) mnode->data.text.disp, 
1237                                 rec_md->data.text.disp))
1238                         break;
1239                 if (!mnode)
1240                 {
1241                     rec_md->next = *wheretoput;
1242                     *wheretoput = rec_md;
1243                 }
1244             }
1245             else if (ser_md->merge == Metadata_merge_longest)
1246             {
1247                 if (!*wheretoput 
1248                     || strlen(rec_md->data.text.disp) 
1249                     > strlen((*wheretoput)->data.text.disp))
1250                 {
1251                     *wheretoput = rec_md;
1252                     if (ser_sk)
1253                     {
1254                         const char *sort_str = 0;
1255                         int skip_article = 
1256                             ser_sk->type == Metadata_sortkey_skiparticle;
1257
1258                         if (!cluster->sortkeys[sk_field_id])
1259                             cluster->sortkeys[sk_field_id] = 
1260                                 nmem_malloc(se->nmem, 
1261                                             sizeof(union data_types));
1262                          
1263                         prt = pp2_relevance_tokenize(
1264                             service->sort_pct,
1265                             rec_md->data.text.disp);
1266
1267                         pp2_relevance_token_next(prt);
1268                          
1269                         sort_str = pp2_get_sort(prt, skip_article);
1270                          
1271                         cluster->sortkeys[sk_field_id]->text.disp = 
1272                             rec_md->data.text.disp;
1273                         if (!sort_str)
1274                         {
1275                             sort_str = rec_md->data.text.disp;
1276                             yaz_log(YLOG_WARN, 
1277                                     "Could not make sortkey. Bug #1858");
1278                         }
1279                         cluster->sortkeys[sk_field_id]->text.sort = 
1280                             nmem_strdup(se->nmem, sort_str);
1281 #if 0
1282                         yaz_log(YLOG_LOG, "text disp=%s",
1283                                 cluster->sortkeys[sk_field_id]->text.disp);
1284                         yaz_log(YLOG_LOG, "text sort=%s",
1285                                 cluster->sortkeys[sk_field_id]->text.sort);
1286 #endif
1287                         pp2_relevance_token_destroy(prt);
1288                     }
1289                 }
1290             }
1291             else if (ser_md->merge == Metadata_merge_all)
1292             {
1293                 rec_md->next = *wheretoput;
1294                 *wheretoput = rec_md;
1295             }
1296             else if (ser_md->merge == Metadata_merge_range)
1297             {
1298                 if (!*wheretoput)
1299                 {
1300                     *wheretoput = rec_md;
1301                     if (ser_sk)
1302                         cluster->sortkeys[sk_field_id] 
1303                             = &rec_md->data;
1304                 }
1305                 else
1306                 {
1307                     int this_min = rec_md->data.number.min;
1308                     int this_max = rec_md->data.number.max;
1309                     if (this_min < (*wheretoput)->data.number.min)
1310                         (*wheretoput)->data.number.min = this_min;
1311                     if (this_max > (*wheretoput)->data.number.max)
1312                         (*wheretoput)->data.number.max = this_max;
1313                 }
1314             }
1315
1316
1317             // ranking of _all_ fields enabled ... 
1318             if (ser_md->rank)
1319                 relevance_countwords(se->relevance, cluster, 
1320                                      (char *) value, ser_md->rank);
1321
1322             // construct facets ... 
1323             if (ser_md->termlist)
1324             {
1325                 if (ser_md->type == Metadata_type_year)
1326                 {
1327                     char year[64];
1328                     sprintf(year, "%d", rec_md->data.number.max);
1329                     add_facet(se, (char *) type, year);
1330                     if (rec_md->data.number.max != rec_md->data.number.min)
1331                     {
1332                         sprintf(year, "%d", rec_md->data.number.min);
1333                         add_facet(se, (char *) type, year);
1334                     }
1335                 }
1336                 else
1337                     add_facet(se, (char *) type, (char *) value);
1338             }
1339
1340             // cleaning up
1341             xmlFree(type);
1342             xmlFree(value);
1343             type = value = 0;
1344         }
1345         else
1346         {
1347             if (se->number_of_warnings_unknown_elements == 0)
1348                 yaz_log(YLOG_WARN,
1349                         "Unexpected element in internal record: %s", n->name);
1350             se->number_of_warnings_unknown_elements++;
1351         }
1352     }
1353     if (type)
1354         xmlFree(type);
1355     if (value)
1356         xmlFree(value);
1357
1358     xmlFreeDoc(xdoc);
1359
1360     relevance_donerecord(se->relevance, cluster);
1361     se->total_records++;
1362
1363     return record;
1364 }
1365
1366
1367
1368 /*
1369  * Local variables:
1370  * c-basic-offset: 4
1371  * c-file-style: "Stroustrup"
1372  * indent-tabs-mode: nil
1373  * End:
1374  * vim: shiftwidth=4 tabstop=8 expandtab
1375  */
1376