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