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