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