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