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