Show command may re-search for targets that support it
[pazpar2-moved-to-github.git] / src / session.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2011 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 session.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 <time.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #if HAVE_SYS_TIME_H
33 #include <sys/time.h>
34 #endif
35 #if HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #ifdef WIN32
39 #include <windows.h>
40 #endif
41 #include <signal.h>
42 #include <ctype.h>
43 #include <assert.h>
44 #include <math.h>
45
46 #include <yaz/marcdisp.h>
47 #include <yaz/comstack.h>
48 #include <yaz/tcpip.h>
49 #include <yaz/proto.h>
50 #include <yaz/readconf.h>
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/yaz-util.h>
54 #include <yaz/nmem.h>
55 #include <yaz/query-charset.h>
56 #include <yaz/querytowrbuf.h>
57 #include <yaz/oid_db.h>
58 #include <yaz/snprintf.h>
59 #include <yaz/gettimeofday.h>
60
61 #define USE_TIMING 0
62 #if USE_TIMING
63 #include <yaz/timing.h>
64 #endif
65
66 #include "ppmutex.h"
67 #include "parameters.h"
68 #include "session.h"
69 #include "eventl.h"
70 #include "http.h"
71 #include "termlists.h"
72 #include "reclists.h"
73 #include "relevance.h"
74 #include "database.h"
75 #include "client.h"
76 #include "settings.h"
77 #include "normalize7bit.h"
78
79 #define TERMLIST_HIGH_SCORE 25
80
81 #define MAX_CHUNK 15
82
83 #define MAX(a,b) ((a)>(b)?(a):(b))
84
85 // Note: Some things in this structure will eventually move to configuration
86 struct parameters global_parameters = 
87 {
88     0,   // dump_records
89     0,   // debug_mode
90     0,   // predictable sessions
91 };
92
93 struct client_list {
94     struct client *client;
95     struct client_list *next;
96 };
97
98 /* session counting (1) , disable client counting (0) */
99 static YAZ_MUTEX g_session_mutex = 0;
100 static int no_sessions = 0;
101 static int no_session_total = 0;
102
103 static int session_use(int delta)
104 {
105     int sessions;
106     if (!g_session_mutex)
107         yaz_mutex_create(&g_session_mutex);
108     yaz_mutex_enter(g_session_mutex);
109     no_sessions += delta;
110     if (delta > 0)
111         no_session_total += delta;
112     sessions = no_sessions;
113     yaz_mutex_leave(g_session_mutex);
114     yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
115     return sessions;
116 }
117
118 int sessions_count(void)
119 {
120     return session_use(0);
121 }
122
123 int session_count_total(void)
124 {
125     int total = 0;
126     if (!g_session_mutex)
127         return 0;
128     yaz_mutex_enter(g_session_mutex);
129     total = no_session_total;
130     yaz_mutex_leave(g_session_mutex);
131     return total;
132 }
133
134 static void log_xml_doc(xmlDoc *doc)
135 {
136     FILE *lf = yaz_log_file();
137     xmlChar *result = 0;
138     int len = 0;
139 #if LIBXML_VERSION >= 20600
140     xmlDocDumpFormatMemory(doc, &result, &len, 1);
141 #else
142     xmlDocDumpMemory(doc, &result, &len);
143 #endif
144     if (lf && len)
145     {
146         (void) fwrite(result, 1, len, lf);
147         fprintf(lf, "\n");
148     }
149     xmlFree(result);
150 }
151
152 static void session_enter(struct session *s)
153 {
154     yaz_mutex_enter(s->session_mutex);
155 }
156
157 static void session_leave(struct session *s)
158 {
159     yaz_mutex_leave(s->session_mutex);
160 }
161
162 void add_facet(struct session *s, const char *type, const char *value, int count)
163 {
164     struct conf_service *service = s->service;
165     pp2_charset_token_t prt;
166     const char *facet_component;
167     WRBUF facet_wrbuf = wrbuf_alloc();
168     WRBUF display_wrbuf = wrbuf_alloc();
169     int i;
170     const char *icu_chain_id = 0;
171
172     for (i = 0; i < service->num_metadata; i++)
173         if (!strcmp((service->metadata + i)->name, type))
174             icu_chain_id = (service->metadata + i)->facetrule;
175     if (!icu_chain_id)
176         icu_chain_id = "facet";
177     prt = pp2_charset_token_create(service->charsets, icu_chain_id);
178     if (!prt)
179     {
180         yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
181                 icu_chain_id, type);
182         wrbuf_destroy(facet_wrbuf);
183         wrbuf_destroy(display_wrbuf);
184         return;
185     }
186     pp2_charset_token_first(prt, value, 0);
187     while ((facet_component = pp2_charset_token_next(prt)))
188     {
189         const char *display_component;
190         if (*facet_component)
191         {
192             if (wrbuf_len(facet_wrbuf))
193                 wrbuf_puts(facet_wrbuf, " ");
194             wrbuf_puts(facet_wrbuf, facet_component);
195         }
196         display_component = pp2_get_display(prt);
197         if (display_component)
198         {
199             if (wrbuf_len(display_wrbuf))
200                 wrbuf_puts(display_wrbuf, " ");
201             wrbuf_puts(display_wrbuf, display_component);
202         }
203     }
204     pp2_charset_token_destroy(prt);
205  
206     if (wrbuf_len(facet_wrbuf))
207     {
208         int i;
209         for (i = 0; i < s->num_termlists; i++)
210             if (!strcmp(s->termlists[i].name, type))
211                 break;
212         if (i == s->num_termlists)
213         {
214             if (i == SESSION_MAX_TERMLISTS)
215             {
216                 session_log(s, YLOG_FATAL, "Too many termlists");
217                 wrbuf_destroy(facet_wrbuf);
218                 wrbuf_destroy(display_wrbuf);
219                 return;
220             }
221             
222             s->termlists[i].name = nmem_strdup(s->nmem, type);
223             s->termlists[i].termlist 
224                 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
225             s->num_termlists = i + 1;
226         }
227         
228 #if 0
229         session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
230 #endif
231         termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
232                         wrbuf_cstr(facet_wrbuf), count);
233     }
234     wrbuf_destroy(facet_wrbuf);
235     wrbuf_destroy(display_wrbuf);
236 }
237
238 static xmlDoc *record_to_xml(struct session *se,
239                              struct session_database *sdb, const char *rec)
240 {
241     struct database *db = sdb->database;
242     xmlDoc *rdoc = 0;
243
244     rdoc = xmlParseMemory(rec, strlen(rec));
245
246     if (!rdoc)
247     {
248         session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
249                     db->id);
250         return 0;
251     }
252
253     if (global_parameters.dump_records)
254     {
255         session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
256         log_xml_doc(rdoc);
257     }
258
259     return rdoc;
260 }
261
262 #define MAX_XSLT_ARGS 16
263
264 // Add static values from session database settings if applicable
265 static void insert_settings_parameters(struct session_database *sdb,
266                                        struct conf_service *service,
267                                        char **parms,
268                                        NMEM nmem)
269 {
270     int i;
271     int nparms = 0;
272     int offset = 0;
273
274     for (i = 0; i < service->num_metadata; i++)
275     {
276         struct conf_metadata *md = &service->metadata[i];
277         int setting;
278
279         if (md->setting == Metadata_setting_parameter &&
280             (setting = settings_lookup_offset(service, md->name)) >= 0)
281         {
282             const char *val = session_setting_oneval(sdb, setting);
283             if (val && nparms < MAX_XSLT_ARGS)
284             {
285                 char *buf;
286                 int len = strlen(val);
287                 buf = nmem_malloc(nmem, len + 3);
288                 buf[0] = '\'';
289                 strcpy(buf + 1, val);
290                 buf[len+1] = '\'';
291                 buf[len+2] = '\0';
292                 parms[offset++] = md->name;
293                 parms[offset++] = buf;
294                 nparms++;
295             }
296         }
297     }
298     parms[offset] = 0;
299 }
300
301 // Add static values from session database settings if applicable
302 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
303     struct conf_service *service)
304 {
305     int i;
306
307     for (i = 0; i < service->num_metadata; i++)
308     {
309         struct conf_metadata *md = &service->metadata[i];
310         int offset;
311
312         if (md->setting == Metadata_setting_postproc &&
313             (offset = settings_lookup_offset(service, md->name)) >= 0)
314         {
315             const char *val = session_setting_oneval(sdb, offset);
316             if (val)
317             {
318                 xmlNode *r = xmlDocGetRootElement(doc);
319                 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
320                                              (xmlChar *) val);
321                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
322             }
323         }
324     }
325 }
326
327 static xmlDoc *normalize_record(struct session *se,
328                                 struct session_database *sdb,
329                                 struct conf_service *service,
330                                 const char *rec, NMEM nmem)
331 {
332     xmlDoc *rdoc = record_to_xml(se, sdb, rec);
333
334     if (rdoc)
335     {
336         char *parms[MAX_XSLT_ARGS*2+1];
337         
338         insert_settings_parameters(sdb, service, parms, nmem);
339         
340         if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
341         {
342             session_log(se, YLOG_WARN, "Normalize failed from %s",
343                         sdb->database->id);
344         }
345         else
346         {
347             insert_settings_values(sdb, rdoc, service);
348             
349             if (global_parameters.dump_records)
350             {
351                 session_log(se, YLOG_LOG, "Normalized record from %s", 
352                             sdb->database->id);
353                 log_xml_doc(rdoc);
354             }
355         }
356     }
357     return rdoc;
358 }
359
360 void session_settings_dump(struct session *se,
361                            struct session_database *db,
362                            WRBUF w)
363 {
364     if (db->settings)
365     {
366         int i, num = db->num_settings;
367         for (i = 0; i < num; i++)
368         {
369             struct setting *s = db->settings[i];
370             for (;s ; s = s->next)
371             {
372                 wrbuf_puts(w, "<set name=\"");
373                 wrbuf_xmlputs(w, s->name);
374                 wrbuf_puts(w, "\" value=\"");
375                 wrbuf_xmlputs(w, s->value);
376                 wrbuf_puts(w, "\"/>");
377             }
378             if (db->settings[i])
379                 wrbuf_puts(w, "\n");
380         }
381     }
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 const char *session_setting_oneval(struct session_database *db, int offset)
387 {
388     if (offset >= db->num_settings || !db->settings[offset])
389         return "";
390     return db->settings[offset]->value;
391 }
392
393 // Prepare XSLT stylesheets for record normalization
394 // Structures are allocated on the session_wide nmem to avoid having
395 // to recompute this for every search. This would lead
396 // to leaking if a single session was to repeatedly change the PZ_XSLT
397 // setting. However, this is not a realistic use scenario.
398 static int prepare_map(struct session *se, struct session_database *sdb)
399 {
400     const char *s;
401
402     if (!sdb->settings)
403     {
404         session_log(se, YLOG_WARN, "No settings on %s", sdb->database->id);
405         return -1;
406     }
407     if ((s = session_setting_oneval(sdb, PZ_XSLT)))
408     {
409         char auto_stylesheet[256];
410
411         if (!strcmp(s, "auto"))
412         {
413             const char *request_syntax = session_setting_oneval(
414                 sdb, PZ_REQUESTSYNTAX);
415             if (request_syntax)
416             {
417                 char *cp;
418                 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
419                              "%s.xsl", request_syntax);
420                 for (cp = auto_stylesheet; *cp; cp++)
421                 {
422                     /* deliberately only consider ASCII */
423                     if (*cp > 32 && *cp < 127)
424                         *cp = tolower(*cp);
425                 }
426                 s = auto_stylesheet;
427             }
428             else
429             {
430                 session_log(se, YLOG_WARN,
431                             "No pz:requestsyntax for auto stylesheet");
432             }
433         }
434         sdb->map = normalize_cache_get(se->normalize_cache,
435                                        se->service->server->config, s);
436         if (!sdb->map)
437             return -1;
438     }
439     return 0;
440 }
441
442 // This analyzes settings and recomputes any supporting data structures
443 // if necessary.
444 static int prepare_session_database(struct session *se, 
445                                     struct session_database *sdb)
446 {
447     if (!sdb->settings)
448     {
449         session_log(se, YLOG_WARN, 
450                 "No settings associated with %s", sdb->database->id);
451         return -1;
452     }
453     if (sdb->settings[PZ_XSLT] && !sdb->map)
454     {
455         if (prepare_map(se, sdb) < 0)
456             return -1;
457     }
458     return 0;
459 }
460
461 // called if watch should be removed because http_channel is to be destroyed
462 static void session_watch_cancel(void *data, struct http_channel *c,
463                                  void *data2)
464 {
465     struct session_watchentry *ent = data;
466
467     ent->fun = 0;
468     ent->data = 0;
469     ent->obs = 0;
470 }
471
472 // set watch. Returns 0=OK, -1 if watch is already set
473 int session_set_watch(struct session *s, int what, 
474                       session_watchfun fun, void *data,
475                       struct http_channel *chan)
476 {
477     int ret;
478     session_enter(s);
479     if (s->watchlist[what].fun)
480         ret = -1;
481     else
482     {
483         
484         s->watchlist[what].fun = fun;
485         s->watchlist[what].data = data;
486         s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
487                                                    session_watch_cancel);
488         ret = 0;
489     }
490     session_leave(s);
491     return ret;
492 }
493
494 void session_alert_watch(struct session *s, int what)
495 {
496     assert(s);
497     session_enter(s);
498     if (s->watchlist[what].fun)
499     {
500         /* our watch is no longer associated with http_channel */
501         void *data;
502         session_watchfun fun;
503
504         http_remove_observer(s->watchlist[what].obs);
505         fun  = s->watchlist[what].fun;
506         data = s->watchlist[what].data;
507
508         /* reset watch before fun is invoked - in case fun wants to set
509            it again */
510         s->watchlist[what].fun = 0;
511         s->watchlist[what].data = 0;
512         s->watchlist[what].obs = 0;
513
514         session_leave(s);
515         session_log(s, YLOG_DEBUG,
516                     "Alert Watch: %d calling function: %p", what, fun);
517         fun(data);
518     }
519     else
520         session_leave(s);
521 }
522
523 //callback for grep_databases
524 static void select_targets_callback(struct session *se,
525                                     struct session_database *db)
526 {
527     struct client *cl = client_create(db->database->id);
528     struct client_list *l;
529
530     client_set_database(cl, db);
531
532     client_set_session(cl, se);
533
534     l = xmalloc(sizeof(*l));
535     l->client = cl;
536     l->next = se->clients;
537     se->clients = l;
538 }
539
540 static void session_remove_clients(struct session *se)
541 {
542     struct client_list *l;
543
544     session_enter(se);
545     l = se->clients;
546     se->clients = 0;
547     session_leave(se);
548
549     while (l)
550     {
551         struct client_list *l_next = l->next;
552         client_lock(l->client);
553         client_set_session(l->client, 0);
554         client_set_database(l->client, 0);
555         client_unlock(l->client);
556         client_destroy(l->client);
557         xfree(l);
558         l = l_next;
559     }
560 }
561
562 // Associates a set of clients with a session;
563 // Note: Session-databases represent databases with per-session 
564 // setting overrides
565 static int select_targets(struct session *se, const char *filter)
566 {
567     return session_grep_databases(se, filter, select_targets_callback);
568 }
569
570 int session_active_clients(struct session *s)
571 {
572     struct client_list *l;
573     int res = 0;
574
575     for (l = s->clients; l; l = l->next)
576         if (client_is_active(l->client))
577             res++;
578
579     return res;
580 }
581
582 int session_is_preferred_clients_ready(struct session *s)
583 {
584     struct client_list *l;
585     int res = 0;
586
587     for (l = s->clients; l; l = l->next)
588         if (client_is_active_preferred(l->client))
589             res++;
590     session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
591     return res == 0;
592 }
593
594 void search_sort(struct session *se, const char *field, int increasing)
595 {
596     struct client_list *l;
597     struct timeval tval;
598
599     session_enter(se);
600     for (l = se->clients; l; l = l->next)
601     {
602         struct client *cl = l->client;
603         struct session_database *sdb = client_get_database(cl);
604         struct setting *s;
605         const char *strategy_plus_sort = 0;
606         
607         for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
608         {
609             char *p = strchr(s->name + 3, ':');
610             if (!p)
611             {
612                 yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
613                 continue;
614             }
615             p++;
616             if (!strcmp(p, field))
617             {
618                 strategy_plus_sort = s->value;
619                 break;
620             }
621         }
622
623         if (strategy_plus_sort)
624         {
625             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
626                                        se->service->z3950_session_timeout,
627                                        se->service->server->iochan_man,
628                                        &tval))
629             {
630                 char **array;
631                 int num;
632                 nmem_strsplit(se->nmem, ":", strategy_plus_sort, &array, &num);
633
634                 if (num == 2)
635                 {
636                     const char *sort_spec = array[1];
637                     while (*sort_spec == ' ')
638                         sort_spec++;
639                     client_start_search(cl, array[0], sort_spec);
640                 }
641             }
642         }
643     }
644     session_leave(se);
645 }
646
647 enum pazpar2_error_code search(struct session *se,
648                                const char *query,
649                                const char *startrecs, const char *maxrecs,
650                                const char *filter,
651                                const char *limit,
652                                const char **addinfo)
653 {
654     int live_channels = 0;
655     int no_working = 0;
656     int no_failed = 0;
657     struct client_list *l;
658     struct timeval tval;
659     facet_limits_t facet_limits;
660
661     session_log(se, YLOG_DEBUG, "Search");
662
663     *addinfo = 0;
664
665     session_remove_clients(se);
666     
667     session_enter(se);
668     reclist_destroy(se->reclist);
669     se->reclist = 0;
670     relevance_destroy(&se->relevance);
671     nmem_reset(se->nmem);
672     se->total_records = se->total_hits = se->total_merged = 0;
673     se->num_termlists = 0;
674     live_channels = select_targets(se, filter);
675     if (!live_channels)
676     {
677         session_leave(se);
678         return PAZPAR2_NO_TARGETS;
679     }
680     se->reclist = reclist_create(se->nmem);
681
682     yaz_gettimeofday(&tval);
683     
684     tval.tv_sec += 5;
685
686     facet_limits = facet_limits_create(limit);
687     if (!facet_limits)
688     {
689         *addinfo = "limit";
690         session_leave(se);
691         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
692     }
693     for (l = se->clients; l; l = l->next)
694     {
695         struct client *cl = l->client;
696
697         if (maxrecs)
698             client_set_maxrecs(cl, atoi(maxrecs));
699         if (startrecs)
700             client_set_startrecs(cl, atoi(startrecs));
701         if (prepare_session_database(se, client_get_database(cl)) < 0)
702             ;
703         else if (client_parse_query(cl, query, facet_limits) < 0)
704             no_failed++;
705         else
706         {
707             no_working++;
708             if (client_prep_connection(cl, se->service->z3950_operation_timeout,
709                                        se->service->z3950_session_timeout,
710                                        se->service->server->iochan_man,
711                                        &tval))
712                 client_start_search(cl, 0, 0);
713         }
714     }
715     facet_limits_destroy(facet_limits);
716     session_leave(se);
717     if (no_working == 0)
718     {
719         if (no_failed > 0)
720         {
721             *addinfo = "query";
722             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
723         }
724         else
725             return PAZPAR2_NO_TARGETS;
726     }
727     return PAZPAR2_NO_ERROR;
728 }
729
730 // Creates a new session_database object for a database
731 static void session_init_databases_fun(void *context, struct database *db)
732 {
733     struct session *se = (struct session *) context;
734     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
735     int i;
736
737     new->database = db;
738     
739     new->map = 0;
740     assert(db->settings);
741     new->settings = nmem_malloc(se->session_nmem,
742                                 sizeof(struct settings *) * db->num_settings);
743     new->num_settings = db->num_settings;
744     for (i = 0; i < db->num_settings; i++)
745     {
746         struct setting *setting = db->settings[i];
747         new->settings[i] = setting;
748     }
749     new->next = se->databases;
750     se->databases = new;
751 }
752
753 // Doesn't free memory associated with sdb -- nmem takes care of that
754 static void session_database_destroy(struct session_database *sdb)
755 {
756     sdb->map = 0;
757 }
758
759 // Initialize session_database list -- this represents this session's view
760 // of the database list -- subject to modification by the settings ws command
761 void session_init_databases(struct session *se)
762 {
763     se->databases = 0;
764     predef_grep_databases(se, se->service, session_init_databases_fun);
765 }
766
767 // Probably session_init_databases_fun should be refactored instead of
768 // called here.
769 static struct session_database *load_session_database(struct session *se, 
770                                                       char *id)
771 {
772     struct database *db = new_database(id, se->session_nmem);
773
774     session_init_databases_fun((void*) se, db);
775
776     // New sdb is head of se->databases list
777     return se->databases;
778 }
779
780 // Find an existing session database. If not found, load it
781 static struct session_database *find_session_database(struct session *se, 
782                                                       char *id)
783 {
784     struct session_database *sdb;
785
786     for (sdb = se->databases; sdb; sdb = sdb->next)
787         if (!strcmp(sdb->database->id, id))
788             return sdb;
789     return load_session_database(se, id);
790 }
791
792 // Apply a session override to a database
793 void session_apply_setting(struct session *se, char *dbname, char *setting,
794                            char *value)
795 {
796     struct session_database *sdb = find_session_database(se, dbname);
797     struct conf_service *service = se->service;
798     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
799     int offset = settings_create_offset(service, setting);
800
801     expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
802                           se->session_nmem);
803     new->precedence = 0;
804     new->target = dbname;
805     new->name = setting;
806     new->value = value;
807     new->next = sdb->settings[offset];
808     sdb->settings[offset] = new;
809
810     // Force later recompute of settings-driven data structures
811     // (happens when a search starts and client connections are prepared)
812     switch (offset)
813     {
814     case PZ_XSLT:
815         if (sdb->map)
816         {
817             sdb->map = 0;
818         }
819         break;
820     }
821 }
822
823 void session_destroy(struct session *se) {
824     struct session_database *sdb;
825     session_log(se, YLOG_DEBUG, "Destroying");
826     session_use(-1);
827     session_remove_clients(se);
828
829     for (sdb = se->databases; sdb; sdb = sdb->next)
830         session_database_destroy(sdb);
831     normalize_cache_destroy(se->normalize_cache);
832     relevance_destroy(&se->relevance);
833     reclist_destroy(se->reclist);
834     nmem_destroy(se->nmem);
835     service_destroy(se->service);
836     yaz_mutex_destroy(&se->session_mutex);
837 }
838
839 /* Depreciated: use session_destroy */
840 void destroy_session(struct session *se)
841 {
842     session_destroy(se);
843 }
844
845 size_t session_get_memory_status(struct session *session) {
846     size_t session_nmem;
847     if (session == 0)
848         return 0;
849     session_enter(session);
850     session_nmem = nmem_total(session->nmem);
851     session_leave(session);
852     return session_nmem;
853 }
854
855
856 struct session *new_session(NMEM nmem, struct conf_service *service,
857                             unsigned session_id)
858 {
859     int i;
860     struct session *session = nmem_malloc(nmem, sizeof(*session));
861
862     char tmp_str[50];
863
864     sprintf(tmp_str, "session#%u", session_id);
865
866     session->session_id = session_id;
867     session_log(session, YLOG_DEBUG, "New");
868     session->service = service;
869     session->relevance = 0;
870     session->total_hits = 0;
871     session->total_records = 0;
872     session->number_of_warnings_unknown_elements = 0;
873     session->number_of_warnings_unknown_metadata = 0;
874     session->num_termlists = 0;
875     session->reclist = 0;
876     session->clients = 0;
877     session->session_nmem = nmem;
878     session->nmem = nmem_create();
879     session->databases = 0;
880     for (i = 0; i <= SESSION_WATCH_MAX; i++)
881     {
882         session->watchlist[i].data = 0;
883         session->watchlist[i].fun = 0;
884     }
885     session->normalize_cache = normalize_cache_create();
886     session->session_mutex = 0;
887     pazpar2_mutex_create(&session->session_mutex, tmp_str);
888     session_use(1);
889     return session;
890 }
891
892 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
893                                             int *count, NMEM nmem)
894 {
895     struct hitsbytarget *res = 0;
896     struct client_list *l;
897     size_t sz = 0;
898
899     for (l = se->clients; l; l = l->next)
900         sz++;
901
902     res = nmem_malloc(nmem, sizeof(*res) * sz);
903     *count = 0;
904     for (l = se->clients; l; l = l->next)
905     {
906         struct client *cl = l->client;
907         WRBUF w = wrbuf_alloc();
908         const char *name = session_setting_oneval(client_get_database(cl),
909                                                   PZ_NAME);
910
911         res[*count].id = client_get_id(cl);
912         res[*count].name = *name ? name : "Unknown";
913         res[*count].hits = client_get_hits(cl);
914         res[*count].records = client_get_num_records(cl);
915         res[*count].diagnostic = client_get_diagnostic(cl);
916         res[*count].state = client_get_state_str(cl);
917         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
918         session_settings_dump(se, client_get_database(cl), w);
919         res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
920         wrbuf_destroy(w);
921         (*count)++;
922     }
923     return res;
924 }
925
926 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
927 {
928     struct hitsbytarget *p;
929     session_enter(se);
930     p = hitsbytarget_nb(se, count, nmem);
931     session_leave(se);
932     return p;
933 }
934     
935 struct termlist_score **get_termlist_score(struct session *se,
936                                            const char *name, int *num)
937 {
938     int i;
939     struct termlist_score **tl = 0;
940
941     session_enter(se);
942     for (i = 0; i < se->num_termlists; i++)
943         if (!strcmp((const char *) se->termlists[i].name, name))
944         {
945             tl = termlist_highscore(se->termlists[i].termlist, num);
946             break;
947         }
948     session_leave(se);
949     return tl;
950 }
951
952 // Compares two hitsbytarget nodes by hitcount
953 static int cmp_ht(const void *p1, const void *p2)
954 {
955     const struct hitsbytarget *h1 = p1;
956     const struct hitsbytarget *h2 = p2;
957     return h2->hits - h1->hits;
958 }
959
960 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
961                                NMEM nmem)
962 {
963     struct hitsbytarget *ht;
964     int count, i;
965
966     ht = hitsbytarget_nb(se, &count, nmem);
967     qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
968     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
969     {
970
971         // do only print terms which have display names
972     
973         wrbuf_puts(wrbuf, "<term>\n");
974
975         wrbuf_puts(wrbuf, "<id>");
976         wrbuf_xmlputs(wrbuf, ht[i].id);
977         wrbuf_puts(wrbuf, "</id>\n");
978         
979         wrbuf_puts(wrbuf, "<name>");
980         if (!ht[i].name || !ht[i].name[0])
981             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
982         else
983             wrbuf_xmlputs(wrbuf, ht[i].name);
984         wrbuf_puts(wrbuf, "</name>\n");
985         
986         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
987                      ht[i].hits);
988         
989         wrbuf_puts(wrbuf, "<state>");
990         wrbuf_xmlputs(wrbuf, ht[i].state);
991         wrbuf_puts(wrbuf, "</state>\n");
992         
993         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
994                      ht[i].diagnostic);
995         wrbuf_puts(wrbuf, "</term>\n");
996     }
997     return count;
998 }
999
1000 void perform_termlist(struct http_channel *c, struct session *se,
1001                       const char *name, int num)
1002 {
1003     int i, j;
1004     NMEM nmem_tmp = nmem_create();
1005     char **names;
1006     int num_names = 0;
1007
1008     if (name)
1009         nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1010
1011     session_enter(se);
1012
1013     for (j = 0; j < num_names; j++)
1014     {
1015         const char *tname;
1016         for (i = 0; i < se->num_termlists; i++)
1017         {
1018             tname = se->termlists[i].name;
1019             if (num_names > 0 && !strcmp(names[j], tname))
1020             {
1021                 struct termlist_score **p = 0;
1022                 int len;
1023                 p = termlist_highscore(se->termlists[i].termlist, &len);
1024                 if (p)
1025                 {
1026                     int i;
1027                     wrbuf_puts(c->wrbuf, "<list name=\"");
1028                     wrbuf_xmlputs(c->wrbuf, tname);
1029                     wrbuf_puts(c->wrbuf, "\">\n");
1030                     for (i = 0; i < len && i < num; i++)
1031                     {
1032                         // prevent sending empty term elements
1033                         if (!p[i]->display_term || !p[i]->display_term[0])
1034                             continue;
1035                         
1036                         wrbuf_puts(c->wrbuf, "<term>");
1037                         wrbuf_puts(c->wrbuf, "<name>");
1038                         wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1039                         wrbuf_puts(c->wrbuf, "</name>");
1040                         
1041                         wrbuf_printf(c->wrbuf, 
1042                                      "<frequency>%d</frequency>", 
1043                                      p[i]->frequency);
1044                         wrbuf_puts(c->wrbuf, "</term>\n");
1045                     }
1046                     wrbuf_puts(c->wrbuf, "</list>\n");
1047                 }
1048             }
1049         }
1050         tname = "xtargets";
1051         if (num_names > 0 && !strcmp(names[j], tname))
1052         {
1053             wrbuf_puts(c->wrbuf, "<list name=\"");
1054             wrbuf_xmlputs(c->wrbuf, tname);
1055             wrbuf_puts(c->wrbuf, "\">\n");
1056             targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1057             wrbuf_puts(c->wrbuf, "</list>\n");
1058         }
1059     }
1060     session_leave(se);
1061     nmem_destroy(nmem_tmp);
1062 }
1063
1064 #ifdef MISSING_HEADERS
1065 void report_nmem_stats(void)
1066 {
1067     size_t in_use, is_free;
1068
1069     nmem_get_memory_in_use(&in_use);
1070     nmem_get_memory_free(&is_free);
1071
1072     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1073             (long) in_use, (long) is_free);
1074 }
1075 #endif
1076
1077 struct record_cluster *show_single_start(struct session *se, const char *id,
1078                                          struct record_cluster **prev_r,
1079                                          struct record_cluster **next_r)
1080 {
1081     struct record_cluster *r = 0;
1082
1083     session_enter(se);
1084     *prev_r = 0;
1085     *next_r = 0;
1086     if (se->reclist)
1087     {
1088         reclist_enter(se->reclist);
1089         while ((r = reclist_read_record(se->reclist)))
1090         {
1091             if (!strcmp(r->recid, id))
1092             {
1093                 *next_r = reclist_read_record(se->reclist);
1094                 break;
1095             }
1096             *prev_r = r;
1097         }
1098         reclist_leave(se->reclist);
1099     }
1100     if (!r)
1101         session_leave(se);
1102     return r;
1103 }
1104
1105 void show_single_stop(struct session *se, struct record_cluster *rec)
1106 {
1107     session_leave(se);
1108 }
1109
1110 struct record_cluster **show_range_start(struct session *se,
1111                                          struct reclist_sortparms *sp, 
1112                                          int start, int *num, int *total, Odr_int *sumhits)
1113 {
1114     struct record_cluster **recs;
1115     struct reclist_sortparms *spp;
1116     int i;
1117 #if USE_TIMING    
1118     yaz_timing_t t = yaz_timing_create();
1119 #endif
1120     session_enter(se);
1121     recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1122     if (!se->relevance)
1123     {
1124         *num = 0;
1125         *total = 0;
1126         *sumhits = 0;
1127         recs = 0;
1128     }
1129     else
1130     {
1131         for (spp = sp; spp; spp = spp->next)
1132             if (spp->type == Metadata_sortkey_relevance)
1133             {
1134                 relevance_prepare_read(se->relevance, se->reclist);
1135                 break;
1136             }
1137         reclist_sort(se->reclist, sp);
1138         
1139         reclist_enter(se->reclist);
1140         *total = reclist_get_num_records(se->reclist);
1141         *sumhits = se->total_hits;
1142         
1143         for (i = 0; i < start; i++)
1144             if (!reclist_read_record(se->reclist))
1145             {
1146                 *num = 0;
1147                 recs = 0;
1148                 break;
1149             }
1150         
1151         for (i = 0; i < *num; i++)
1152         {
1153             struct record_cluster *r = reclist_read_record(se->reclist);
1154             if (!r)
1155             {
1156                 *num = i;
1157                 break;
1158             }
1159             recs[i] = r;
1160         }
1161         reclist_leave(se->reclist);
1162     }
1163 #if USE_TIMING
1164     yaz_timing_stop(t);
1165     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1166             yaz_timing_get_real(t), yaz_timing_get_user(t),
1167             yaz_timing_get_sys(t));
1168     yaz_timing_destroy(&t);
1169 #endif
1170     return recs;
1171 }
1172
1173 void show_range_stop(struct session *se, struct record_cluster **recs)
1174 {
1175     session_leave(se);
1176 }
1177
1178 void statistics(struct session *se, struct statistics *stat)
1179 {
1180     struct client_list *l;
1181     int count = 0;
1182
1183     memset(stat, 0, sizeof(*stat));
1184     for (l = se->clients; l; l = l->next)
1185     {
1186         struct client *cl = l->client;
1187         if (!client_get_connection(cl))
1188             stat->num_no_connection++;
1189         switch (client_get_state(cl))
1190         {
1191         case Client_Connecting: stat->num_connecting++; break;
1192         case Client_Working: stat->num_working++; break;
1193         case Client_Idle: stat->num_idle++; break;
1194         case Client_Failed: stat->num_failed++; break;
1195         case Client_Error: stat->num_error++; break;
1196         default: break;
1197         }
1198         count++;
1199     }
1200     stat->num_hits = se->total_hits;
1201     stat->num_records = se->total_records;
1202
1203     stat->num_clients = count;
1204 }
1205
1206 static struct record_metadata *record_metadata_init(
1207     NMEM nmem, const char *value, enum conf_metadata_type type,
1208     struct _xmlAttr *attr)
1209 {
1210     struct record_metadata *rec_md = record_metadata_create(nmem);
1211     struct record_metadata_attr **attrp = &rec_md->attributes;
1212     
1213     for (; attr; attr = attr->next)
1214     {
1215         if (attr->children && attr->children->content)
1216         {
1217             if (strcmp((const char *) attr->name, "type"))
1218             {  /* skip the "type" attribute.. Its value is already part of
1219                   the element in output (md-%s) and so repeating it here
1220                   is redundant */
1221                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1222                 (*attrp)->name =
1223                     nmem_strdup(nmem, (const char *) attr->name);
1224                 (*attrp)->value =
1225                     nmem_strdup(nmem, (const char *) attr->children->content);
1226                 attrp = &(*attrp)->next;
1227             }
1228         }
1229     }
1230     *attrp = 0;
1231
1232     if (type == Metadata_type_generic)
1233     {
1234         char *p = nmem_strdup(nmem, value);
1235
1236         p = normalize7bit_generic(p, " ,/.:([");
1237         
1238         rec_md->data.text.disp = p;
1239         rec_md->data.text.sort = 0;
1240     }
1241     else if (type == Metadata_type_year || type == Metadata_type_date)
1242     {
1243         int first, last;
1244         int longdate = 0;
1245
1246         if (type == Metadata_type_date)
1247             longdate = 1;
1248         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1249             return 0;
1250
1251         rec_md->data.number.min = first;
1252         rec_md->data.number.max = last;
1253     }
1254     else
1255         return 0;
1256     return rec_md;
1257 }
1258
1259 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1260                                  struct conf_service *service, WRBUF norm_wr)
1261 {
1262     xmlNode *n;
1263     int no_found = 0;
1264     for (n = root->children; n; n = n->next)
1265     {
1266         if (n->type != XML_ELEMENT_NODE)
1267             continue;
1268         if (!strcmp((const char *) n->name, "metadata"))
1269         {
1270             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1271             if (type == NULL) {
1272                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1273             }
1274             else if (!strcmp(name, (const char *) type))
1275             {
1276                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1277                 if (value)
1278                 {
1279                     const char *norm_str;
1280                     pp2_charset_token_t prt =
1281                         pp2_charset_token_create(service->charsets, "mergekey");
1282                     
1283                     pp2_charset_token_first(prt, (const char *) value, 0);
1284                     if (wrbuf_len(norm_wr) > 0)
1285                         wrbuf_puts(norm_wr, " ");
1286                     wrbuf_puts(norm_wr, name);
1287                     while ((norm_str =
1288                             pp2_charset_token_next(prt)))
1289                     {
1290                         if (*norm_str)
1291                         {
1292                             wrbuf_puts(norm_wr, " ");
1293                             wrbuf_puts(norm_wr, norm_str);
1294                         }
1295                     }
1296                     xmlFree(value);
1297                     pp2_charset_token_destroy(prt);
1298                     no_found++;
1299                 }
1300             }
1301             xmlFree(type);
1302         }
1303     }
1304     return no_found;
1305 }
1306
1307 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1308                                 struct conf_service *service, NMEM nmem)
1309 {
1310     char *mergekey_norm = 0;
1311     xmlNode *root = xmlDocGetRootElement(doc);
1312     WRBUF norm_wr = wrbuf_alloc();
1313
1314     /* consider mergekey from XSL first */
1315     xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1316     if (mergekey)
1317     {
1318         const char *norm_str;
1319         pp2_charset_token_t prt =
1320             pp2_charset_token_create(service->charsets, "mergekey");
1321
1322         pp2_charset_token_first(prt, (const char *) mergekey, 0);
1323         while ((norm_str = pp2_charset_token_next(prt)))
1324         {
1325             if (*norm_str)
1326             {
1327                 if (wrbuf_len(norm_wr))
1328                     wrbuf_puts(norm_wr, " ");
1329                 wrbuf_puts(norm_wr, norm_str);
1330             }
1331         }
1332         pp2_charset_token_destroy(prt);
1333         xmlFree(mergekey);
1334     }
1335     else
1336     {
1337         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1338         int field_id;
1339         for (field_id = 0; field_id < service->num_metadata; field_id++)
1340         {
1341             struct conf_metadata *ser_md = &service->metadata[field_id];
1342             if (ser_md->mergekey != Metadata_mergekey_no)
1343             {
1344                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1345                                               service, norm_wr);
1346                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1347                 {
1348                     /* no mergekey on this one and it is required.. 
1349                        Generate unique key instead */
1350                     wrbuf_rewind(norm_wr);
1351                     break;
1352                 }
1353             }
1354         }
1355     }
1356
1357     /* generate unique key if none is not generated already or is empty */
1358     if (wrbuf_len(norm_wr) == 0)
1359     {
1360         wrbuf_printf(norm_wr, "%s-%d",
1361                      client_get_id(cl), record_no);
1362     }
1363     if (wrbuf_len(norm_wr) > 0)
1364         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1365     wrbuf_destroy(norm_wr);
1366     return mergekey_norm;
1367 }
1368
1369 /** \brief see if metadata for pz:recordfilter exists 
1370     \param root xml root element of normalized record
1371     \param sdb session database for client
1372     \retval 0 if there is no metadata for pz:recordfilter
1373     \retval 1 if there is metadata for pz:recordfilter
1374
1375     If there is no pz:recordfilter defined, this function returns 1
1376     as well.
1377 */
1378     
1379 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1380 {
1381     int match = 0;
1382     xmlNode *n;
1383     const char *s;
1384     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1385
1386     if (!s || !*s)
1387         return 1;
1388
1389     for (n = root->children; n; n = n->next)
1390     {
1391         if (n->type != XML_ELEMENT_NODE)
1392             continue;
1393         if (!strcmp((const char *) n->name, "metadata"))
1394         {
1395             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1396             if (type)
1397             {
1398                 size_t len;
1399                 int substring;
1400                 const char *eq;
1401
1402                 if ((eq = strchr(s, '=')))
1403                     substring = 0;
1404                 else if ((eq = strchr(s, '~')))
1405                     substring = 1;
1406                 if (eq)
1407                     len = eq - s;
1408                 else
1409                     len = strlen(s);
1410                 if (len == strlen((const char *)type) &&
1411                     !memcmp((const char *) type, s, len))
1412                 {
1413                     xmlChar *value = xmlNodeGetContent(n);
1414                     if (value && *value)
1415                     {
1416                         if (!eq ||
1417                             (substring && strstr((const char *) value, eq+1)) ||
1418                             (!substring && !strcmp((const char *) value, eq + 1)))
1419                             match = 1;
1420                     }
1421                     xmlFree(value);
1422                 }
1423                 xmlFree(type);
1424             }
1425         }
1426     }
1427     return match;
1428 }
1429
1430
1431 static int ingest_to_cluster(struct client *cl,
1432                              xmlDoc *xdoc,
1433                              xmlNode *root,
1434                              int record_no,
1435                              const char *mergekey_norm);
1436
1437 /** \brief ingest XML record
1438     \param cl client holds the result set for record
1439     \param rec record buffer (0 terminated)
1440     \param record_no record position (1, 2, ..)
1441     \param nmem working NMEM
1442     \retval 0 OK
1443     \retval -1 failure
1444     \retval -2 Filtered
1445 */
1446 int ingest_record(struct client *cl, const char *rec,
1447                   int record_no, NMEM nmem)
1448 {
1449     struct session *se = client_get_session(cl);
1450     int ret = 0;
1451     struct session_database *sdb = client_get_database(cl);
1452     struct conf_service *service = se->service;
1453     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1454     xmlNode *root;
1455     const char *mergekey_norm;
1456     
1457     if (!xdoc)
1458         return -1;
1459     
1460     root = xmlDocGetRootElement(xdoc);
1461     
1462     if (!check_record_filter(root, sdb))
1463     {
1464         session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1465                     record_no, sdb->database->id);
1466         xmlFreeDoc(xdoc);
1467         return -2;
1468     }
1469     
1470     mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1471     if (!mergekey_norm)
1472     {
1473         session_log(se, YLOG_WARN, "Got no mergekey");
1474         xmlFreeDoc(xdoc);
1475         return -1;
1476     }
1477     session_enter(se);
1478     if (client_get_session(cl) == se)
1479         ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1480     session_leave(se);
1481     
1482     xmlFreeDoc(xdoc);
1483     return ret;
1484 }
1485
1486 static int ingest_to_cluster(struct client *cl,
1487                              xmlDoc *xdoc,
1488                              xmlNode *root,
1489                              int record_no,
1490                              const char *mergekey_norm)
1491 {
1492     xmlNode *n;
1493     xmlChar *type = 0;
1494     xmlChar *value = 0;
1495     struct session_database *sdb = client_get_database(cl);
1496     struct session *se = client_get_session(cl);
1497     struct conf_service *service = se->service;
1498     struct record *record = record_create(se->nmem, 
1499                                           service->num_metadata,
1500                                           service->num_sortkeys, cl,
1501                                           record_no);
1502     struct record_cluster *cluster = reclist_insert(se->reclist,
1503                                                     service, 
1504                                                     record,
1505                                                     mergekey_norm,
1506                                                     &se->total_merged);
1507
1508     const char *use_term_factor_str = session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1509     int use_term_factor = 0;
1510     int term_factor = 1; 
1511     if (use_term_factor_str && use_term_factor_str[0] != 0)
1512        use_term_factor =  atoi(use_term_factor_str);
1513     if (use_term_factor) {
1514         int maxrecs = client_get_maxrecs(cl);
1515         int hits = (int) client_get_hits(cl);
1516         term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
1517         assert(term_factor >= 1);
1518         yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1519     }
1520
1521     if (!cluster)
1522         return -1;
1523     if (global_parameters.dump_records)
1524         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1525                     sdb->database->id, record_no);
1526     relevance_newrec(se->relevance, cluster);
1527     
1528     // now parsing XML record and adding data to cluster or record metadata
1529     for (n = root->children; n; n = n->next)
1530     {
1531         pp2_charset_token_t prt;
1532         if (type)
1533             xmlFree(type);
1534         if (value)
1535             xmlFree(value);
1536         type = value = 0;
1537         
1538         if (n->type != XML_ELEMENT_NODE)
1539             continue;
1540         if (!strcmp((const char *) n->name, "metadata"))
1541         {
1542             struct conf_metadata *ser_md = 0;
1543             struct conf_sortkey *ser_sk = 0;
1544             struct record_metadata **wheretoput = 0;
1545             struct record_metadata *rec_md = 0;
1546             int md_field_id = -1;
1547             int sk_field_id = -1;
1548             
1549             type = xmlGetProp(n, (xmlChar *) "type");
1550             value = xmlNodeListGetString(xdoc, n->children, 1);
1551             
1552             if (!type || !value || !*value)
1553                 continue;
1554             
1555             md_field_id 
1556                 = conf_service_metadata_field_id(service, (const char *) type);
1557             if (md_field_id < 0)
1558             {
1559                 if (se->number_of_warnings_unknown_metadata == 0)
1560                 {
1561                     session_log(se, YLOG_WARN, 
1562                             "Ignoring unknown metadata element: %s", type);
1563                 }
1564                 se->number_of_warnings_unknown_metadata++;
1565                 continue;
1566             }
1567             
1568             ser_md = &service->metadata[md_field_id];
1569             
1570             if (ser_md->sortkey_offset >= 0){
1571                 sk_field_id = ser_md->sortkey_offset;
1572                 ser_sk = &service->sortkeys[sk_field_id];
1573             }
1574
1575             // non-merged metadata
1576             rec_md = record_metadata_init(se->nmem, (const char *) value,
1577                                           ser_md->type, n->properties);
1578             if (!rec_md)
1579             {
1580                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1581                             "for element '%s'", value, type);
1582                 continue;
1583             }
1584             wheretoput = &record->metadata[md_field_id];
1585             while (*wheretoput)
1586                 wheretoput = &(*wheretoput)->next;
1587             *wheretoput = rec_md;
1588
1589             // merged metadata
1590             rec_md = record_metadata_init(se->nmem, (const char *) value,
1591                                           ser_md->type, 0);
1592             wheretoput = &cluster->metadata[md_field_id];
1593
1594             // and polulate with data:
1595             // assign cluster or record based on merge action
1596             if (ser_md->merge == Metadata_merge_unique)
1597             {
1598                 while (*wheretoput)
1599                 {
1600                     if (!strcmp((const char *) (*wheretoput)->data.text.disp, 
1601                                 rec_md->data.text.disp))
1602                         break;
1603                     wheretoput = &(*wheretoput)->next;
1604                 }
1605                 if (!*wheretoput)
1606                     *wheretoput = rec_md;
1607             }
1608             else if (ser_md->merge == Metadata_merge_longest)
1609             {
1610                 if (!*wheretoput 
1611                     || strlen(rec_md->data.text.disp) 
1612                     > strlen((*wheretoput)->data.text.disp))
1613                 {
1614                     *wheretoput = rec_md;
1615                     if (ser_sk)
1616                     {
1617                         const char *sort_str = 0;
1618                         int skip_article = 
1619                             ser_sk->type == Metadata_sortkey_skiparticle;
1620
1621                         if (!cluster->sortkeys[sk_field_id])
1622                             cluster->sortkeys[sk_field_id] = 
1623                                 nmem_malloc(se->nmem, 
1624                                             sizeof(union data_types));
1625                          
1626                         prt =
1627                             pp2_charset_token_create(service->charsets, "sort");
1628
1629                         pp2_charset_token_first(prt, rec_md->data.text.disp,
1630                                                 skip_article);
1631
1632                         pp2_charset_token_next(prt);
1633                          
1634                         sort_str = pp2_get_sort(prt);
1635                          
1636                         cluster->sortkeys[sk_field_id]->text.disp = 
1637                             rec_md->data.text.disp;
1638                         if (!sort_str)
1639                         {
1640                             sort_str = rec_md->data.text.disp;
1641                             session_log(se, YLOG_WARN, 
1642                                     "Could not make sortkey. Bug #1858");
1643                         }
1644                         cluster->sortkeys[sk_field_id]->text.sort = 
1645                             nmem_strdup(se->nmem, sort_str);
1646                         pp2_charset_token_destroy(prt);
1647                     }
1648                 }
1649             }
1650             else if (ser_md->merge == Metadata_merge_all)
1651             {
1652                 while (*wheretoput)
1653                     wheretoput = &(*wheretoput)->next;
1654                 *wheretoput = rec_md;
1655             }
1656             else if (ser_md->merge == Metadata_merge_range)
1657             {
1658                 if (!*wheretoput)
1659                 {
1660                     *wheretoput = rec_md;
1661                     if (ser_sk)
1662                         cluster->sortkeys[sk_field_id] 
1663                             = &rec_md->data;
1664                 }
1665                 else
1666                 {
1667                     int this_min = rec_md->data.number.min;
1668                     int this_max = rec_md->data.number.max;
1669                     if (this_min < (*wheretoput)->data.number.min)
1670                         (*wheretoput)->data.number.min = this_min;
1671                     if (this_max > (*wheretoput)->data.number.max)
1672                         (*wheretoput)->data.number.max = this_max;
1673                 }
1674             }
1675
1676
1677             // ranking of _all_ fields enabled ... 
1678             if (ser_md->rank)
1679                 relevance_countwords(se->relevance, cluster, 
1680                                      (char *) value, ser_md->rank,
1681                                      ser_md->name);
1682
1683             // construct facets ... unless the client already has reported them
1684             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1685             {
1686                 if (ser_md->type == Metadata_type_year)
1687                 {
1688                     char year[64];
1689                     sprintf(year, "%d", rec_md->data.number.max);
1690
1691                     add_facet(se, (char *) type, year, term_factor);
1692                     if (rec_md->data.number.max != rec_md->data.number.min)
1693                     {
1694                         sprintf(year, "%d", rec_md->data.number.min);
1695                         add_facet(se, (char *) type, year, term_factor);
1696                     }
1697                 }
1698                 else
1699                     add_facet(se, (char *) type, (char *) value, term_factor);
1700             }
1701
1702             // cleaning up
1703             xmlFree(type);
1704             xmlFree(value);
1705             type = value = 0;
1706         }
1707         else
1708         {
1709             if (se->number_of_warnings_unknown_elements == 0)
1710                 session_log(se, YLOG_WARN,
1711                         "Unexpected element in internal record: %s", n->name);
1712             se->number_of_warnings_unknown_elements++;
1713         }
1714     }
1715     if (type)
1716         xmlFree(type);
1717     if (value)
1718         xmlFree(value);
1719
1720     relevance_donerecord(se->relevance, cluster);
1721     se->total_records++;
1722
1723     return 0;
1724 }
1725
1726 void session_log(struct session *s, int level, const char *fmt, ...)
1727 {
1728     char buf[1024];
1729     va_list ap;
1730     va_start(ap, fmt);
1731
1732     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1733     yaz_log(level, "Session (%u): %s", s->session_id, buf);
1734
1735     va_end(ap);
1736 }
1737
1738 /*
1739  * Local variables:
1740  * c-basic-offset: 4
1741  * c-file-style: "Stroustrup"
1742  * indent-tabs-mode: nil
1743  * End:
1744  * vim: shiftwidth=4 tabstop=8 expandtab
1745  */
1746