Mergekey changes - order + required/optional.
[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             WRBUF fname = conf_get_fname(se->service, stylesheets[i]);
354             
355             (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
356             (*m)->next = 0;
357             
358             // XSLT
359             if (!strcmp(&stylesheets[i][strlen(stylesheets[i])-4], ".xsl")) 
360             {    
361                 (*m)->marcmap = NULL;
362                 if (!((*m)->stylesheet =
363                       xsltParseStylesheetFile((xmlChar *) wrbuf_cstr(fname))))
364                 {
365                     yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
366                             stylesheets[i]);
367                     wrbuf_destroy(fname);
368                     return -1;
369                 }
370             }
371             // marcmap
372             else if (!strcmp(&stylesheets[i][strlen(stylesheets[i])-5], ".mmap"))
373             {
374                 (*m)->stylesheet = NULL;
375                 if (!((*m)->marcmap = marcmap_load(wrbuf_cstr(fname), se->session_nmem)))
376                 {
377                     yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load marcmap: %s",
378                             stylesheets[i]);
379                     wrbuf_destroy(fname);
380                     return -1;
381                 }
382             }
383             wrbuf_destroy(fname);
384             m = &(*m)->next;
385         }
386     }
387     if (!sdb->map)
388         yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
389                 sdb->database->url);
390     return 0;
391 }
392
393 // This analyzes settings and recomputes any supporting data structures
394 // if necessary.
395 static int prepare_session_database(struct session *se, 
396                                     struct session_database *sdb)
397 {
398     if (!sdb->settings)
399     {
400         yaz_log(YLOG_WARN, 
401                 "No settings associated with %s", sdb->database->url);
402         return -1;
403     }
404     if (sdb->settings[PZ_XSLT] && !sdb->map)
405     {
406         if (prepare_map(se, sdb) < 0)
407             return -1;
408     }
409     return 0;
410 }
411
412 // called if watch should be removed because http_channel is to be destroyed
413 static void session_watch_cancel(void *data, struct http_channel *c,
414                                  void *data2)
415 {
416     struct session_watchentry *ent = data;
417
418     ent->fun = 0;
419     ent->data = 0;
420     ent->obs = 0;
421 }
422
423 // set watch. Returns 0=OK, -1 if watch is already set
424 int session_set_watch(struct session *s, int what, 
425                       session_watchfun fun, void *data,
426                       struct http_channel *chan)
427 {
428     if (s->watchlist[what].fun)
429         return -1;
430     s->watchlist[what].fun = fun;
431     s->watchlist[what].data = data;
432     s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
433                                                session_watch_cancel);
434     return 0;
435 }
436
437 void session_alert_watch(struct session *s, int what)
438 {
439     if (s->watchlist[what].fun)
440     {
441         /* our watch is no longer associated with http_channel */
442         void *data;
443         session_watchfun fun;
444
445         http_remove_observer(s->watchlist[what].obs);
446         fun = s->watchlist[what].fun;
447         data = s->watchlist[what].data;
448
449         /* reset watch before fun is invoked - in case fun wants to set
450            it again */
451         s->watchlist[what].fun = 0;
452         s->watchlist[what].data = 0;
453         s->watchlist[what].obs = 0;
454
455         fun(data);
456     }
457 }
458
459 //callback for grep_databases
460 static void select_targets_callback(void *context, struct session_database *db)
461 {
462     struct session *se = (struct session*) context;
463     struct client *cl = client_create();
464     client_set_database(cl, db);
465     client_set_session(cl, se);
466 }
467
468 // Associates a set of clients with a session;
469 // Note: Session-databases represent databases with per-session 
470 // setting overrides
471 int select_targets(struct session *se, struct database_criterion *crit)
472 {
473     while (se->clients)
474         client_destroy(se->clients);
475
476     return session_grep_databases(se, crit, select_targets_callback);
477 }
478
479 int session_active_clients(struct session *s)
480 {
481     struct client *c;
482     int res = 0;
483
484     for (c = s->clients; c; c = client_next_in_session(c))
485         if (client_is_active(c))
486             res++;
487
488     return res;
489 }
490
491 // parses crit1=val1,crit2=val2|val3,...
492 static struct database_criterion *parse_filter(NMEM m, const char *buf)
493 {
494     struct database_criterion *res = 0;
495     char **values;
496     int num;
497     int i;
498
499     if (!buf || !*buf)
500         return 0;
501     nmem_strsplit(m, ",", buf,  &values, &num);
502     for (i = 0; i < num; i++)
503     {
504         char **subvalues;
505         int subnum;
506         int subi;
507         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
508         char *eq;
509         if ((eq = strchr(values[i], '=')))
510             new->type = PAZPAR2_STRING_MATCH;
511         if ((eq = strchr(values[i], '~')))
512             new->type = PAZPAR2_SUBSTRING_MATCH;
513         if (!eq)
514         {
515             yaz_log(YLOG_WARN, "Missing equal-signi/tilde in filter");
516             return 0;
517         }
518         *(eq++) = '\0';
519         new->name = values[i];
520         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
521         new->values = 0;
522         for (subi = 0; subi < subnum; subi++)
523         {
524             struct database_criterion_value *newv
525                 = nmem_malloc(m, sizeof(*newv));
526             newv->value = subvalues[subi];
527             newv->next = new->values;
528             new->values = newv;
529         }
530         new->next = res;
531         res = new;
532     }
533     return res;
534 }
535
536 enum pazpar2_error_code search(struct session *se,
537                                const char *query, const char *filter,
538                                const char **addinfo)
539 {
540     int live_channels = 0;
541     int no_working = 0;
542     int no_failed = 0;
543     struct client *cl;
544     struct database_criterion *criteria;
545
546     yaz_log(YLOG_DEBUG, "Search");
547
548     *addinfo = 0;
549     nmem_reset(se->nmem);
550     se->relevance = 0;
551     se->total_records = se->total_hits = se->total_merged = 0;
552     se->reclist = 0;
553     se->num_termlists = 0;
554     criteria = parse_filter(se->nmem, filter);
555     live_channels = select_targets(se, criteria);
556     if (live_channels)
557     {
558         int maxrecs = live_channels * global_parameters.toget; // This is buggy!!!
559         se->reclist = reclist_create(se->nmem, maxrecs);
560         se->expected_maxrecs = maxrecs;
561     }
562     else
563         return PAZPAR2_NO_TARGETS;
564
565     for (cl = se->clients; cl; cl = client_next_in_session(cl))
566     {
567         if (prepare_session_database(se, client_get_database(cl)) < 0)
568         {
569             *addinfo = client_get_database(cl)->database->url;
570             return PAZPAR2_CONFIG_TARGET;
571         }
572         // Parse query for target
573         if (client_parse_query(cl, query) < 0)
574             no_failed++;
575         else
576         {
577             no_working++;
578             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
579                     se->service->z3950_session_timeout))
580                 client_start_search(cl);
581         }
582     }
583
584     // If no queries could be mapped, we signal an error
585     if (no_working == 0)
586     {
587         *addinfo = "query";
588         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
589     }
590     return PAZPAR2_NO_ERROR;
591 }
592
593 // Creates a new session_database object for a database
594 static void session_init_databases_fun(void *context, struct database *db)
595 {
596     struct session *se = (struct session *) context;
597     struct conf_service *service = se->service;
598     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
599     int num = settings_num(service);
600     int i;
601
602     new->database = db;
603     
604     new->map = 0;
605     new->settings 
606         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
607     memset(new->settings, 0, sizeof(struct settings*) * num);
608
609     if (db->settings)
610     {
611         for (i = 0; i < num; i++)
612             new->settings[i] = db->settings[i];
613     }
614     new->next = se->databases;
615     se->databases = new;
616 }
617
618 // Doesn't free memory associated with sdb -- nmem takes care of that
619 static void session_database_destroy(struct session_database *sdb)
620 {
621     struct database_retrievalmap *m;
622
623     for (m = sdb->map; m; m = m->next)
624         xsltFreeStylesheet(m->stylesheet);
625 }
626
627 // Initialize session_database list -- this represents this session's view
628 // of the database list -- subject to modification by the settings ws command
629 void session_init_databases(struct session *se)
630 {
631     se->databases = 0;
632     predef_grep_databases(se, se->service, 0, session_init_databases_fun);
633 }
634
635 // Probably session_init_databases_fun should be refactored instead of
636 // called here.
637 static struct session_database *load_session_database(struct session *se, 
638                                                       char *id)
639 {
640     struct database *db = find_database(id, 0, se->service);
641
642     resolve_database(db);
643
644     session_init_databases_fun((void*) se, db);
645     // New sdb is head of se->databases list
646     return se->databases;
647 }
648
649 // Find an existing session database. If not found, load it
650 static struct session_database *find_session_database(struct session *se, 
651                                                       char *id)
652 {
653     struct session_database *sdb;
654
655     for (sdb = se->databases; sdb; sdb = sdb->next)
656         if (!strcmp(sdb->database->url, id))
657             return sdb;
658     return load_session_database(se, id);
659 }
660
661 // Apply a session override to a database
662 void session_apply_setting(struct session *se, char *dbname, char *setting,
663                            char *value)
664 {
665     struct session_database *sdb = find_session_database(se, dbname);
666     struct conf_service *service = se->service;
667     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
668     int offset = settings_offset_cprefix(service, setting);
669
670     if (offset < 0)
671     {
672         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
673         return;
674     }
675     // Jakub: This breaks the filter setting.
676     /*if (offset == PZ_ID)
677       {
678       yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
679       return;
680       }*/
681     new->precedence = 0;
682     new->target = dbname;
683     new->name = setting;
684     new->value = value;
685     new->next = sdb->settings[offset];
686     sdb->settings[offset] = new;
687
688     // Force later recompute of settings-driven data structures
689     // (happens when a search starts and client connections are prepared)
690     switch (offset)
691     {
692     case PZ_XSLT:
693         if (sdb->map)
694         {
695             struct database_retrievalmap *m;
696             // We don't worry about the map structure -- it's in nmem
697             for (m = sdb->map; m; m = m->next)
698                 xsltFreeStylesheet(m->stylesheet);
699             sdb->map = 0;
700         }
701         break;
702     }
703 }
704
705 void destroy_session(struct session *s)
706 {
707     struct session_database *sdb;
708
709     while (s->clients)
710         client_destroy(s->clients);
711     for (sdb = s->databases; sdb; sdb = sdb->next)
712         session_database_destroy(sdb);
713     nmem_destroy(s->nmem);
714     service_destroy(s->service);
715     wrbuf_destroy(s->wrbuf);
716 }
717
718 struct session *new_session(NMEM nmem, struct conf_service *service) 
719 {
720     int i;
721     struct session *session = nmem_malloc(nmem, sizeof(*session));
722
723     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
724
725     session->service = service;
726     session->relevance = 0;
727     session->total_hits = 0;
728     session->total_records = 0;
729     session->number_of_warnings_unknown_elements = 0;
730     session->number_of_warnings_unknown_metadata = 0;
731     session->num_termlists = 0;
732     session->reclist = 0;
733     session->clients = 0;
734     session->expected_maxrecs = 0;
735     session->session_nmem = nmem;
736     session->nmem = nmem_create();
737     session->wrbuf = wrbuf_alloc();
738     session->databases = 0;
739     for (i = 0; i <= SESSION_WATCH_MAX; i++)
740     {
741         session->watchlist[i].data = 0;
742         session->watchlist[i].fun = 0;
743     }
744     return session;
745 }
746
747 struct hitsbytarget *hitsbytarget(struct session *se, int *count, NMEM nmem)
748 {
749     struct hitsbytarget *res = 0;
750     struct client *cl;
751     size_t sz = 0;
752
753     for (cl = se->clients; cl; cl = client_next_in_session(cl))
754         sz++;
755
756     res = nmem_malloc(nmem, sizeof(*res) * sz);
757     *count = 0;
758     for (cl = se->clients; cl; cl = client_next_in_session(cl))
759     {
760         const char *name = session_setting_oneval(client_get_database(cl),
761                                                   PZ_NAME);
762
763         res[*count].id = client_get_database(cl)->database->url;
764         res[*count].name = *name ? name : "Unknown";
765         res[*count].hits = client_get_hits(cl);
766         res[*count].records = client_get_num_records(cl);
767         res[*count].diagnostic = client_get_diagnostic(cl);
768         res[*count].state = client_get_state_str(cl);
769         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
770         (*count)++;
771     }
772     return res;
773 }
774
775 struct termlist_score **termlist(struct session *s, const char *name, int *num)
776 {
777     int i;
778
779     for (i = 0; i < s->num_termlists; i++)
780         if (!strcmp((const char *) s->termlists[i].name, name))
781             return termlist_highscore(s->termlists[i].termlist, num);
782     return 0;
783 }
784
785 #ifdef MISSING_HEADERS
786 void report_nmem_stats(void)
787 {
788     size_t in_use, is_free;
789
790     nmem_get_memory_in_use(&in_use);
791     nmem_get_memory_free(&is_free);
792
793     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
794             (long) in_use, (long) is_free);
795 }
796 #endif
797
798 struct record_cluster *show_single(struct session *s, const char *id,
799                                    struct record_cluster **prev_r,
800                                    struct record_cluster **next_r)
801 {
802     struct record_cluster *r;
803
804     reclist_rewind(s->reclist);
805     *prev_r = 0;
806     *next_r = 0;
807     while ((r = reclist_read_record(s->reclist)))
808     {
809         if (!strcmp(r->recid, id))
810         {
811             *next_r = reclist_read_record(s->reclist);
812             return r;
813         }
814         *prev_r = r;
815     }
816     return 0;
817 }
818
819 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
820                              int start, int *num, int *total, int *sumhits, 
821                              NMEM nmem_show)
822 {
823     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
824                                                * sizeof(struct record_cluster *));
825     struct reclist_sortparms *spp;
826     int i;
827 #if USE_TIMING    
828     yaz_timing_t t = yaz_timing_create();
829 #endif
830
831     if (!s->relevance)
832     {
833         *num = 0;
834         *total = 0;
835         *sumhits = 0;
836         recs = 0;
837     }
838     else
839     {
840         for (spp = sp; spp; spp = spp->next)
841             if (spp->type == Metadata_sortkey_relevance)
842             {
843                 relevance_prepare_read(s->relevance, s->reclist);
844                 break;
845             }
846         reclist_sort(s->reclist, sp);
847         
848         *total = s->reclist->num_records;
849         *sumhits = s->total_hits;
850         
851         for (i = 0; i < start; i++)
852             if (!reclist_read_record(s->reclist))
853             {
854                 *num = 0;
855                 recs = 0;
856                 break;
857             }
858         
859         for (i = 0; i < *num; i++)
860         {
861             struct record_cluster *r = reclist_read_record(s->reclist);
862             if (!r)
863             {
864                 *num = i;
865                 break;
866             }
867             recs[i] = r;
868         }
869     }
870 #if USE_TIMING
871     yaz_timing_stop(t);
872     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
873             yaz_timing_get_real(t), yaz_timing_get_user(t),
874             yaz_timing_get_sys(t));
875     yaz_timing_destroy(&t);
876 #endif
877     return recs;
878 }
879
880 void statistics(struct session *se, struct statistics *stat)
881 {
882     struct client *cl;
883     int count = 0;
884
885     memset(stat, 0, sizeof(*stat));
886     for (cl = se->clients; cl; cl = client_next_in_session(cl))
887     {
888         if (!client_get_connection(cl))
889             stat->num_no_connection++;
890         switch (client_get_state(cl))
891         {
892         case Client_Connecting: stat->num_connecting++; break;
893         case Client_Working: stat->num_working++; break;
894         case Client_Idle: stat->num_idle++; break;
895         case Client_Failed: stat->num_failed++; break;
896         case Client_Error: stat->num_error++; break;
897         default: break;
898         }
899         count++;
900     }
901     stat->num_hits = se->total_hits;
902     stat->num_records = se->total_records;
903
904     stat->num_clients = count;
905 }
906
907
908 // Master list of connections we're handling events to
909 static IOCHAN channel_list = 0;  /* thread pr */
910
911 void pazpar2_add_channel(IOCHAN chan)
912 {
913     chan->next = channel_list;
914     channel_list = chan;
915 }
916
917 void pazpar2_event_loop()
918 {
919     event_loop(&channel_list);
920 }
921
922 static struct record_metadata *record_metadata_init(
923     NMEM nmem, char *value, enum conf_metadata_type type)
924 {
925     struct record_metadata *rec_md = record_metadata_create(nmem);
926     if (type == Metadata_type_generic)
927     {
928         char * p = value;
929         p = normalize7bit_generic(p, " ,/.:([");
930         
931         rec_md->data.text.disp = nmem_strdup(nmem, p);
932         rec_md->data.text.sort = 0;
933     }
934     else if (type == Metadata_type_year || type == Metadata_type_date)
935     {
936         int first, last;
937         int longdate = 0;
938
939         if (type == Metadata_type_date)
940             longdate = 1;
941         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
942             return 0;
943
944         rec_md->data.number.min = first;
945         rec_md->data.number.max = last;
946     }
947     else
948         return 0;
949     return rec_md;
950 }
951
952 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
953                                  struct conf_service *service, WRBUF norm_wr)
954 {
955     xmlNode *n;
956     int no_found = 0;
957     for (n = root->children; n; n = n->next)
958     {
959         if (n->type != XML_ELEMENT_NODE)
960             continue;
961         if (!strcmp((const char *) n->name, "metadata"))
962         {
963             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
964             if (!strcmp(name, (const char *) type))
965             {
966                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
967                 if (value)
968                 {
969                     const char *norm_str;
970                     pp2_relevance_token_t prt =
971                         pp2_relevance_tokenize(
972                             service->mergekey_pct,
973                             (const char *) value);
974                     
975                     wrbuf_puts(norm_wr, name);
976                     wrbuf_puts(norm_wr, "=");
977                     while ((norm_str =
978                             pp2_relevance_token_next(prt)))
979                     {
980                         if (*norm_str)
981                         {
982                             if (wrbuf_len(norm_wr))
983                                 wrbuf_puts(norm_wr, " ");
984                             wrbuf_puts(norm_wr, norm_str);
985                         }
986                     }
987                     xmlFree(value);
988                     pp2_relevance_token_destroy(prt);
989                     no_found++;
990                 }
991             }
992             xmlFree(type);
993         }
994     }
995     return no_found;
996 }
997
998 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
999                                 struct conf_service *service, NMEM nmem)
1000 {
1001     char *mergekey_norm = 0;
1002     xmlNode *root = xmlDocGetRootElement(doc);
1003     WRBUF norm_wr = wrbuf_alloc();
1004
1005     /* consider mergekey from XSL first */
1006     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1007     if (mergekey)
1008     {
1009         const char *norm_str;
1010         pp2_relevance_token_t prt =
1011             pp2_relevance_tokenize(
1012                 service->mergekey_pct,
1013                 (const char *) mergekey);
1014         
1015         while ((norm_str = pp2_relevance_token_next(prt)))
1016         {
1017             if (*norm_str)
1018             {
1019                 if (wrbuf_len(norm_wr))
1020                     wrbuf_puts(norm_wr, " ");
1021                 wrbuf_puts(norm_wr, norm_str);
1022             }
1023         }
1024         pp2_relevance_token_destroy(prt);
1025         xmlFree(mergekey);
1026     }
1027     else
1028     {
1029         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1030         int field_id;
1031         for (field_id = 0; field_id < service->num_metadata; field_id++)
1032         {
1033             struct conf_metadata *ser_md = &service->metadata[field_id];
1034             if (ser_md->mergekey != Metadata_mergekey_no)
1035             {
1036                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1037                                               service, norm_wr);
1038                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1039                 {
1040                     /* no mergekey on this one and it is required.. 
1041                        Generate unique key instead */
1042                     wrbuf_rewind(norm_wr);
1043                     break;
1044                 }
1045             }
1046         }
1047     }
1048
1049     /* generate unique key if none is not generated already or is empty */
1050     if (wrbuf_len(norm_wr) == 0)
1051     {
1052         wrbuf_printf(norm_wr, "%s-%d",
1053                      client_get_database(cl)->database->url, record_no);
1054     }
1055     if (wrbuf_len(norm_wr) > 0)
1056         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1057     wrbuf_destroy(norm_wr);
1058     return mergekey_norm;
1059 }
1060
1061 /** \brief see if metadata for pz:recordfilter exists 
1062     \param root xml root element of normalized record
1063     \param sdb session database for client
1064     \retval 0 if there is no metadata for pz:recordfilter
1065     \retval 1 if there is metadata for pz:recordfilter
1066
1067     If there is no pz:recordfilter defined, this function returns 1
1068     as well.
1069 */
1070     
1071 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1072 {
1073     int match = 0;
1074     xmlNode *n;
1075     const char *s;
1076     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1077
1078     if (!s || !*s)
1079         return 1;
1080
1081     for (n = root->children; n; n = n->next)
1082     {
1083         if (n->type != XML_ELEMENT_NODE)
1084             continue;
1085         if (!strcmp((const char *) n->name, "metadata"))
1086         {
1087             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1088             if (type)
1089             {
1090                 size_t len;
1091                 const char *eq = strchr(s, '=');
1092                 if (eq)
1093                     len = eq - s;
1094                 else
1095                     len = strlen(s);
1096                 if (len == strlen((const char *)type) &&
1097                     !memcmp((const char *) type, s, len))
1098                 {
1099                     xmlChar *value = xmlNodeGetContent(n);
1100                     if (value && *value)
1101                     {
1102                         if (!eq || strstr((const char *) value, eq+1))
1103                             match = 1;
1104                     }
1105                     xmlFree(value);
1106                 }
1107                 xmlFree(type);
1108             }
1109         }
1110     }
1111     return match;
1112 }
1113
1114
1115 /** \brief ingest XML record
1116     \param cl client holds the result set for record
1117     \param rec record buffer (0 terminated)
1118     \param record_no record position (1, 2, ..)
1119     \returns resulting record or NULL on failure
1120 */
1121 struct record *ingest_record(struct client *cl, const char *rec,
1122                              int record_no)
1123 {
1124     struct session_database *sdb = client_get_database(cl);
1125     struct session *se = client_get_session(cl);
1126     xmlDoc *xdoc = normalize_record(sdb, se, rec);
1127     xmlNode *root, *n;
1128     struct record *record;
1129     struct record_cluster *cluster;
1130     const char *mergekey_norm;
1131     xmlChar *type = 0;
1132     xmlChar *value = 0;
1133     struct conf_service *service = se->service;
1134
1135     if (!xdoc)
1136         return 0;
1137
1138     root = xmlDocGetRootElement(xdoc);
1139
1140     if (!check_record_filter(root, sdb))
1141     {
1142         yaz_log(YLOG_WARN, "Filtered out record no %d from %s", record_no,
1143             sdb->database->url);
1144         xmlFreeDoc(xdoc);
1145         return 0;
1146     }
1147
1148     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, se->nmem);
1149     if (!mergekey_norm)
1150     {
1151         yaz_log(YLOG_WARN, "Got no mergekey");
1152         xmlFreeDoc(xdoc);
1153         return 0;
1154     }
1155     record = record_create(se->nmem, 
1156                            service->num_metadata, service->num_sortkeys, cl,
1157                            record_no);
1158
1159     cluster = reclist_insert(se->reclist, 
1160                              service, 
1161                              record, (char *) mergekey_norm, 
1162                              &se->total_merged);
1163     if (global_parameters.dump_records)
1164         yaz_log(YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1165                 sdb->database->url, record_no);
1166     if (!cluster)
1167     {
1168         /* no room for record */
1169         xmlFreeDoc(xdoc);
1170         return 0;
1171     }
1172     relevance_newrec(se->relevance, cluster);
1173     
1174     // now parsing XML record and adding data to cluster or record metadata
1175     for (n = root->children; n; n = n->next)
1176     {
1177         pp2_relevance_token_t prt;
1178         if (type)
1179             xmlFree(type);
1180         if (value)
1181             xmlFree(value);
1182         type = value = 0;
1183         
1184         if (n->type != XML_ELEMENT_NODE)
1185             continue;
1186         if (!strcmp((const char *) n->name, "metadata"))
1187         {
1188             struct conf_metadata *ser_md = 0;
1189             struct conf_sortkey *ser_sk = 0;
1190             struct record_metadata **wheretoput = 0;
1191             struct record_metadata *rec_md = 0;
1192             int md_field_id = -1;
1193             int sk_field_id = -1;
1194             
1195             type = xmlGetProp(n, (xmlChar *) "type");
1196             value = xmlNodeListGetString(xdoc, n->children, 1);
1197             
1198             if (!type || !value || !*value)
1199                 continue;
1200             
1201             md_field_id 
1202                 = conf_service_metadata_field_id(service, (const char *) type);
1203             if (md_field_id < 0)
1204             {
1205                 if (se->number_of_warnings_unknown_metadata == 0)
1206                 {
1207                     yaz_log(YLOG_WARN, 
1208                             "Ignoring unknown metadata element: %s", type);
1209                 }
1210                 se->number_of_warnings_unknown_metadata++;
1211                 continue;
1212             }
1213             
1214             ser_md = &service->metadata[md_field_id];
1215             
1216             if (ser_md->sortkey_offset >= 0){
1217                 sk_field_id = ser_md->sortkey_offset;
1218                 ser_sk = &service->sortkeys[sk_field_id];
1219             }
1220
1221             // non-merged metadata
1222             rec_md = record_metadata_init(se->nmem, (char *) value,
1223                                           ser_md->type);
1224             if (!rec_md)
1225             {
1226                 yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1227                         value, type);
1228                 continue;
1229             }
1230             wheretoput = &record->metadata[md_field_id];
1231             while (*wheretoput)
1232                 wheretoput = &(*wheretoput)->next;
1233             *wheretoput = rec_md;
1234
1235             // merged metadata
1236             rec_md = record_metadata_init(se->nmem, (char *) value,
1237                                           ser_md->type);
1238             wheretoput = &cluster->metadata[md_field_id];
1239
1240             // and polulate with data:
1241             // assign cluster or record based on merge action
1242             if (ser_md->merge == Metadata_merge_unique)
1243             {
1244                 struct record_metadata *mnode;
1245                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1246                     if (!strcmp((const char *) mnode->data.text.disp, 
1247                                 rec_md->data.text.disp))
1248                         break;
1249                 if (!mnode)
1250                 {
1251                     rec_md->next = *wheretoput;
1252                     *wheretoput = rec_md;
1253                 }
1254             }
1255             else if (ser_md->merge == Metadata_merge_longest)
1256             {
1257                 if (!*wheretoput 
1258                     || strlen(rec_md->data.text.disp) 
1259                     > strlen((*wheretoput)->data.text.disp))
1260                 {
1261                     *wheretoput = rec_md;
1262                     if (ser_sk)
1263                     {
1264                         const char *sort_str = 0;
1265                         int skip_article = 
1266                             ser_sk->type == Metadata_sortkey_skiparticle;
1267
1268                         if (!cluster->sortkeys[sk_field_id])
1269                             cluster->sortkeys[sk_field_id] = 
1270                                 nmem_malloc(se->nmem, 
1271                                             sizeof(union data_types));
1272                          
1273                         prt = pp2_relevance_tokenize(
1274                             service->sort_pct,
1275                             rec_md->data.text.disp);
1276
1277                         pp2_relevance_token_next(prt);
1278                          
1279                         sort_str = pp2_get_sort(prt, skip_article);
1280                          
1281                         cluster->sortkeys[sk_field_id]->text.disp = 
1282                             rec_md->data.text.disp;
1283                         if (!sort_str)
1284                         {
1285                             sort_str = rec_md->data.text.disp;
1286                             yaz_log(YLOG_WARN, 
1287                                     "Could not make sortkey. Bug #1858");
1288                         }
1289                         cluster->sortkeys[sk_field_id]->text.sort = 
1290                             nmem_strdup(se->nmem, sort_str);
1291 #if 0
1292                         yaz_log(YLOG_LOG, "text disp=%s",
1293                                 cluster->sortkeys[sk_field_id]->text.disp);
1294                         yaz_log(YLOG_LOG, "text sort=%s",
1295                                 cluster->sortkeys[sk_field_id]->text.sort);
1296 #endif
1297                         pp2_relevance_token_destroy(prt);
1298                     }
1299                 }
1300             }
1301             else if (ser_md->merge == Metadata_merge_all)
1302             {
1303                 rec_md->next = *wheretoput;
1304                 *wheretoput = rec_md;
1305             }
1306             else if (ser_md->merge == Metadata_merge_range)
1307             {
1308                 if (!*wheretoput)
1309                 {
1310                     *wheretoput = rec_md;
1311                     if (ser_sk)
1312                         cluster->sortkeys[sk_field_id] 
1313                             = &rec_md->data;
1314                 }
1315                 else
1316                 {
1317                     int this_min = rec_md->data.number.min;
1318                     int this_max = rec_md->data.number.max;
1319                     if (this_min < (*wheretoput)->data.number.min)
1320                         (*wheretoput)->data.number.min = this_min;
1321                     if (this_max > (*wheretoput)->data.number.max)
1322                         (*wheretoput)->data.number.max = this_max;
1323                 }
1324             }
1325
1326
1327             // ranking of _all_ fields enabled ... 
1328             if (ser_md->rank)
1329                 relevance_countwords(se->relevance, cluster, 
1330                                      (char *) value, ser_md->rank);
1331
1332             // construct facets ... 
1333             if (ser_md->termlist)
1334             {
1335                 if (ser_md->type == Metadata_type_year)
1336                 {
1337                     char year[64];
1338                     sprintf(year, "%d", rec_md->data.number.max);
1339                     add_facet(se, (char *) type, year);
1340                     if (rec_md->data.number.max != rec_md->data.number.min)
1341                     {
1342                         sprintf(year, "%d", rec_md->data.number.min);
1343                         add_facet(se, (char *) type, year);
1344                     }
1345                 }
1346                 else
1347                     add_facet(se, (char *) type, (char *) value);
1348             }
1349
1350             // cleaning up
1351             xmlFree(type);
1352             xmlFree(value);
1353             type = value = 0;
1354         }
1355         else
1356         {
1357             if (se->number_of_warnings_unknown_elements == 0)
1358                 yaz_log(YLOG_WARN,
1359                         "Unexpected element in internal record: %s", n->name);
1360             se->number_of_warnings_unknown_elements++;
1361         }
1362     }
1363     if (type)
1364         xmlFree(type);
1365     if (value)
1366         xmlFree(value);
1367
1368     xmlFreeDoc(xdoc);
1369
1370     relevance_donerecord(se->relevance, cluster);
1371     se->total_records++;
1372
1373     return record;
1374 }
1375
1376
1377
1378 /*
1379  * Local variables:
1380  * c-basic-offset: 4
1381  * c-file-style: "Stroustrup"
1382  * indent-tabs-mode: nil
1383  * End:
1384  * vim: shiftwidth=4 tabstop=8 expandtab
1385  */
1386