Override setting with same name (do not append) PAZ-945
[pazpar2-moved-to-github.git] / src / session.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 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
60 #define USE_TIMING 1
61 #if USE_TIMING
62 #include <yaz/timing.h>
63 #endif
64
65 #include "ppmutex.h"
66 #include "parameters.h"
67 #include "session.h"
68 #include "eventl.h"
69 #include "http.h"
70 #include "termlists.h"
71 #include "reclists.h"
72 #include "relevance.h"
73 #include "database.h"
74 #include "client.h"
75 #include "settings.h"
76 #include "normalize7bit.h"
77
78 #include <libxml/tree.h>
79
80 #define MAX_CHUNK 15
81
82 #define MAX(a,b) ((a)>(b)?(a):(b))
83
84 // Note: Some things in this structure will eventually move to configuration
85 struct parameters global_parameters =
86 {
87     0,   // dump_records
88     0,   // debug_mode
89     0,   // predictable sessions
90 };
91
92 struct client_list {
93     struct client *client;
94     struct client_list *next;
95 };
96
97 /* session counting (1) , disable client counting (0) */
98 static YAZ_MUTEX g_session_mutex = 0;
99 static int no_sessions = 0;
100
101 static int session_use(int delta)
102 {
103     int sessions;
104     if (!g_session_mutex)
105         yaz_mutex_create(&g_session_mutex);
106     yaz_mutex_enter(g_session_mutex);
107     no_sessions += delta;
108     sessions = no_sessions;
109     yaz_mutex_leave(g_session_mutex);
110     yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" :
111             (delta > 0 ? "INC" : "DEC"), no_sessions);
112     return sessions;
113 }
114
115 int sessions_count(void)
116 {
117     return session_use(0);
118 }
119
120 static void log_xml_doc(xmlDoc *doc)
121 {
122     FILE *lf = yaz_log_file();
123     xmlChar *result = 0;
124     int len = 0;
125 #if LIBXML_VERSION >= 20600
126     xmlDocDumpFormatMemory(doc, &result, &len, 1);
127 #else
128     xmlDocDumpMemory(doc, &result, &len);
129 #endif
130     if (lf && len)
131     {
132         (void) fwrite(result, 1, len, lf);
133         fprintf(lf, "\n");
134     }
135     xmlFree(result);
136 }
137
138 static void session_enter(struct session *s, const char *caller)
139 {
140     if (caller)
141         session_log(s, YLOG_DEBUG, "Session lock by %s", caller);
142     yaz_mutex_enter(s->session_mutex);
143 }
144
145 static void session_leave(struct session *s, const char *caller)
146 {
147     yaz_mutex_leave(s->session_mutex);
148     if (caller)
149         session_log(s, YLOG_DEBUG, "Session unlock by %s", caller);
150 }
151
152 static void session_normalize_facet(struct session *s,
153                                     const char *type, const char *value,
154                                     WRBUF display_wrbuf, WRBUF facet_wrbuf)
155 {
156     struct conf_service *service = s->service;
157     pp2_charset_token_t prt;
158     const char *facet_component;
159     int i;
160     const char *icu_chain_id = 0;
161
162     for (i = 0; i < service->num_metadata; i++)
163         if (!strcmp((service->metadata + i)->name, type))
164             icu_chain_id = (service->metadata + i)->facetrule;
165     if (!icu_chain_id)
166         icu_chain_id = "facet";
167     prt = pp2_charset_token_create(service->charsets, icu_chain_id);
168     if (!prt)
169     {
170         session_log(s, YLOG_FATAL,
171                     "Unknown ICU chain '%s' for facet of type '%s'",
172                 icu_chain_id, type);
173         wrbuf_destroy(facet_wrbuf);
174         wrbuf_destroy(display_wrbuf);
175         return;
176     }
177     pp2_charset_token_first(prt, value, 0);
178     while ((facet_component = pp2_charset_token_next(prt)))
179     {
180         const char *display_component;
181         if (*facet_component)
182         {
183             if (wrbuf_len(facet_wrbuf))
184                 wrbuf_puts(facet_wrbuf, " ");
185             wrbuf_puts(facet_wrbuf, facet_component);
186         }
187         display_component = pp2_get_display(prt);
188         if (display_component)
189         {
190             if (wrbuf_len(display_wrbuf))
191                 wrbuf_puts(display_wrbuf, " ");
192             wrbuf_puts(display_wrbuf, display_component);
193         }
194     }
195     pp2_charset_token_destroy(prt);
196 }
197
198 void add_facet(struct session *s, const char *type, const char *value, int count)
199 {
200     WRBUF facet_wrbuf = wrbuf_alloc();
201     WRBUF display_wrbuf = wrbuf_alloc();
202
203     session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
204
205     if (wrbuf_len(facet_wrbuf))
206     {
207         int i;
208         for (i = 0; i < s->num_termlists; i++)
209             if (!strcmp(s->termlists[i].name, type))
210                 break;
211         if (i == s->num_termlists)
212         {
213             if (i == SESSION_MAX_TERMLISTS)
214             {
215                 session_log(s, YLOG_FATAL, "Too many termlists");
216                 wrbuf_destroy(facet_wrbuf);
217                 wrbuf_destroy(display_wrbuf);
218                 return;
219             }
220
221             s->termlists[i].name = nmem_strdup(s->nmem, type);
222             s->termlists[i].termlist = termlist_create(s->nmem);
223             s->num_termlists = i + 1;
224         }
225
226 #if 0
227         session_log(s, YLOG_LOG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
228 #endif
229         termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
230                         wrbuf_cstr(facet_wrbuf), count);
231     }
232     wrbuf_destroy(facet_wrbuf);
233     wrbuf_destroy(display_wrbuf);
234 }
235
236 static xmlDoc *record_to_xml(struct session *se,
237                              struct session_database *sdb, const char *rec)
238 {
239     struct database *db = sdb->database;
240     xmlDoc *rdoc = 0;
241
242     rdoc = xmlParseMemory(rec, strlen(rec));
243
244     if (!rdoc)
245     {
246         session_log(se, YLOG_WARN, "Non-wellformed XML");
247         return 0;
248     }
249
250     if (global_parameters.dump_records)
251     {
252         session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
253         log_xml_doc(rdoc);
254     }
255
256     return rdoc;
257 }
258
259 #define MAX_XSLT_ARGS 16
260
261 // Add static values from session database settings if applicable
262 static void insert_settings_parameters(struct session_database *sdb,
263                                        struct conf_service *service,
264                                        char **parms,
265                                        NMEM nmem)
266 {
267     int i;
268     int nparms = 0;
269     int offset = 0;
270
271     for (i = 0; i < service->num_metadata; i++)
272     {
273         struct conf_metadata *md = &service->metadata[i];
274         int setting;
275
276         if (md->setting == Metadata_setting_parameter &&
277             (setting = settings_lookup_offset(service, md->name)) >= 0)
278         {
279             const char *val = session_setting_oneval(sdb, setting);
280             if (val && nparms < MAX_XSLT_ARGS)
281             {
282                 char *buf;
283                 int len = strlen(val);
284                 buf = nmem_malloc(nmem, len + 3);
285                 buf[0] = '\'';
286                 strcpy(buf + 1, val);
287                 buf[len+1] = '\'';
288                 buf[len+2] = '\0';
289                 parms[offset++] = md->name;
290                 parms[offset++] = buf;
291                 nparms++;
292             }
293         }
294     }
295     parms[offset] = 0;
296 }
297
298 // Add static values from session database settings if applicable
299 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
300                                    xmlNode *root,
301                                    struct conf_service *service)
302 {
303     int i;
304
305     for (i = 0; i < service->num_metadata; i++)
306     {
307         struct conf_metadata *md = &service->metadata[i];
308         int offset;
309
310         if (md->setting == Metadata_setting_postproc &&
311             (offset = settings_lookup_offset(service, md->name)) >= 0)
312         {
313             const char *val = session_setting_oneval(sdb, offset);
314             if (val)
315             {
316                 xmlNode *n = xmlNewTextChild(root, 0, (xmlChar *) "metadata",
317                                              (xmlChar *) val);
318                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
319             }
320         }
321     }
322 }
323
324 static xmlDoc *normalize_record(struct session *se,
325                                 struct session_database *sdb,
326                                 struct conf_service *service,
327                                 const char *rec, NMEM nmem)
328 {
329     xmlDoc *rdoc = record_to_xml(se, sdb, rec);
330
331     if (rdoc)
332     {
333         char *parms[MAX_XSLT_ARGS*2+1];
334
335         insert_settings_parameters(sdb, service, parms, nmem);
336
337         if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
338         {
339             session_log(se, YLOG_WARN, "Normalize failed");
340         }
341     }
342     return rdoc;
343 }
344
345 void session_settings_dump(struct session *se,
346                            struct session_database *db,
347                            WRBUF w)
348 {
349     if (db->settings)
350     {
351         int i, num = db->num_settings;
352         for (i = 0; i < num; i++)
353         {
354             struct setting *s = db->settings[i];
355             for (;s ; s = s->next)
356             {
357                 wrbuf_puts(w, "<set name=\"");
358                 wrbuf_xmlputs(w, s->name);
359                 wrbuf_puts(w, "\" value=\"");
360                 wrbuf_xmlputs(w, s->value);
361                 wrbuf_puts(w, "\"/>");
362             }
363             if (db->settings[i])
364                 wrbuf_puts(w, "\n");
365         }
366     }
367 }
368
369 // Retrieve first defined value for 'name' for given database.
370 // Will be extended to take into account user associated with session
371 const char *session_setting_oneval(struct session_database *db, int offset)
372 {
373     if (offset >= db->num_settings || !db->settings[offset])
374         return "";
375     return db->settings[offset]->value;
376 }
377
378 // Prepare XSLT stylesheets for record normalization
379 // Structures are allocated on the session_wide nmem to avoid having
380 // to recompute this for every search. This would lead
381 // to leaking if a single session was to repeatedly change the PZ_XSLT
382 // setting. However, this is not a realistic use scenario.
383 static int prepare_map(struct session *se, struct session_database *sdb)
384 {
385     if (sdb->settings && !sdb->map)
386     {
387         const char *s;
388
389         if (sdb->settings[PZ_XSLT] &&
390             (s = session_setting_oneval(sdb, PZ_XSLT)))
391         {
392             char auto_stylesheet[256];
393
394             if (!strcmp(s, "auto"))
395             {
396                 const char *request_syntax = session_setting_oneval(
397                     sdb, PZ_REQUESTSYNTAX);
398                 if (request_syntax)
399                 {
400                     char *cp;
401                     yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
402                                  "%s.xsl", request_syntax);
403                     for (cp = auto_stylesheet; *cp; cp++)
404                     {
405                         /* deliberately only consider ASCII */
406                         if (*cp > 32 && *cp < 127)
407                             *cp = tolower(*cp);
408                     }
409                     s = auto_stylesheet;
410                 }
411                 else
412                 {
413                     session_log(se, YLOG_WARN,
414                                 "No pz:requestsyntax for auto stylesheet");
415                 }
416             }
417             sdb->map = normalize_cache_get(se->normalize_cache,
418                                            se->service, s);
419             if (!sdb->map)
420                 return -1;
421         }
422     }
423     return 0;
424 }
425
426 // called if watch should be removed because http_channel is to be destroyed
427 static void session_watch_cancel(void *data, struct http_channel *c,
428                                  void *data2)
429 {
430     struct session_watchentry *ent = data;
431
432     ent->fun = 0;
433     ent->data = 0;
434     ent->obs = 0;
435 }
436
437 // set watch. Returns 0=OK, -1 if watch is already set
438 int session_set_watch(struct session *s, int what,
439                       session_watchfun fun, void *data,
440                       struct http_channel *chan)
441 {
442     int ret;
443     session_enter(s, "session_set_watch");
444     if (s->watchlist[what].fun)
445         ret = -1;
446     else
447     {
448
449         s->watchlist[what].fun = fun;
450         s->watchlist[what].data = data;
451         s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
452                                                    session_watch_cancel);
453         ret = 0;
454     }
455     session_leave(s, "session_set_watch");
456     return ret;
457 }
458
459 void session_alert_watch(struct session *s, int what)
460 {
461     assert(s);
462     session_enter(s, "session_alert_watch");
463     if (s->watchlist[what].fun)
464     {
465         /* our watch is no longer associated with http_channel */
466         void *data;
467         session_watchfun fun;
468
469         http_remove_observer(s->watchlist[what].obs);
470         fun  = s->watchlist[what].fun;
471         data = s->watchlist[what].data;
472
473         /* reset watch before fun is invoked - in case fun wants to set
474            it again */
475         s->watchlist[what].fun = 0;
476         s->watchlist[what].data = 0;
477         s->watchlist[what].obs = 0;
478
479         session_leave(s, "session_alert_watch");
480         session_log(s, YLOG_DEBUG,
481                     "Alert Watch: %d calling function: %p", what, fun);
482         fun(data);
483     }
484     else
485         session_leave(s,"session_alert_watch");
486 }
487
488 //callback for grep_databases
489 static void select_targets_callback(struct session *se,
490                                     struct session_database *db)
491 {
492     struct client *cl;
493     struct client_list *l;
494
495     for (l = se->clients_cached; l; l = l->next)
496         if (client_get_database(l->client) == db)
497             break;
498
499     if (l)
500         cl = l->client;
501     else
502     {
503         cl = client_create(db->database->id);
504         client_set_database(cl, db);
505
506         l = xmalloc(sizeof(*l));
507         l->client = cl;
508         l->next = se->clients_cached;
509         se->clients_cached = l;
510     }
511     /* set session always. If may be 0 if client is not active */
512     client_set_session(cl, se);
513
514     l = xmalloc(sizeof(*l));
515     l->client = cl;
516     l->next = se->clients_active;
517     se->clients_active = l;
518 }
519
520 static void session_reset_active_clients(struct session *se,
521                                          struct client_list *new_list)
522 {
523     struct client_list *l;
524
525     session_enter(se, "session_reset_active_clients");
526     l = se->clients_active;
527     se->clients_active = new_list;
528     session_leave(se, "session_reset_active_clients");
529
530     while (l)
531     {
532         struct client_list *l_next = l->next;
533
534         client_lock(l->client);
535         client_set_session(l->client, 0); /* mark client inactive */
536         client_unlock(l->client);
537
538         xfree(l);
539         l = l_next;
540     }
541 }
542
543 static void session_remove_cached_clients(struct session *se)
544 {
545     struct client_list *l;
546
547     session_reset_active_clients(se, 0);
548
549     session_enter(se, "session_remove_cached_clients");
550     l = se->clients_cached;
551     se->clients_cached = 0;
552     session_leave(se, "session_remove_cached_clients");
553
554     while (l)
555     {
556         struct client_list *l_next = l->next;
557         client_lock(l->client);
558         client_set_session(l->client, 0);
559         client_set_database(l->client, 0);
560         client_unlock(l->client);
561         client_destroy(l->client);
562         xfree(l);
563         l = l_next;
564     }
565 }
566
567 // Associates a set of clients with a session;
568 // Note: Session-databases represent databases with per-session
569 // setting overrides
570 static int select_targets(struct session *se, const char *filter)
571 {
572     return session_grep_databases(se, filter, select_targets_callback);
573 }
574
575 int session_active_clients(struct session *s)
576 {
577     struct client_list *l;
578     int res = 0;
579
580     for (l = s->clients_active; l; l = l->next)
581         if (client_is_active(l->client))
582             res++;
583
584     return res;
585 }
586
587 int session_is_preferred_clients_ready(struct session *s)
588 {
589     struct client_list *l;
590     int res = 0;
591
592     for (l = s->clients_active; l; l = l->next)
593         if (client_is_active_preferred(l->client))
594             res++;
595     session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
596     return res == 0;
597 }
598
599 static void session_clear_set(struct session *se, struct reclist_sortparms *sp)
600 {
601     reclist_destroy(se->reclist);
602     if (nmem_total(se->nmem))
603         session_log(se, YLOG_DEBUG, "NMEN operation usage %zd",
604                     nmem_total(se->nmem));
605     nmem_reset(se->nmem);
606     se->total_records = se->total_merged = 0;
607     se->num_termlists = 0;
608
609     relevance_clear(se->relevance);
610
611     /* reset list of sorted results and clear to relevance search */
612     se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
613     se->sorted_results->name = nmem_strdup(se->nmem, sp->name);
614     se->sorted_results->increasing = sp->increasing;
615     se->sorted_results->type = sp->type;
616     se->sorted_results->next = 0;
617
618     session_log(se, YLOG_DEBUG, "clear_set session_sort: field=%s increasing=%d type=%d configured",
619             sp->name, sp->increasing, sp->type);
620
621     se->reclist = reclist_create(se->nmem);
622 }
623
624 static void session_sort_unlocked(struct session *se,
625                                   struct reclist_sortparms *sp,
626                                   const char *mergekey,
627                                   const char *rank)
628 {
629     struct client_list *l;
630     const char *field = sp->name;
631     int increasing = sp->increasing;
632     int type  = sp->type;
633     int clients_research = 0;
634
635     session_log(se, YLOG_DEBUG, "session_sort field=%s increasing=%d type=%d",
636                 field, increasing, type);
637
638     if (rank && (!se->rank || strcmp(se->rank, rank)))
639     {
640         /* new rank must research/reingest anyway */
641         assert(rank);
642         xfree(se->rank);
643         se->rank = *rank ? xstrdup(rank) : 0;
644         clients_research = 1;
645         session_log(se, YLOG_DEBUG, "session_sort: new rank = %s",
646                     rank);
647     }
648     if (mergekey && (!se->mergekey || strcmp(se->mergekey, mergekey)))
649     {
650         /* new mergekey must research/reingest anyway */
651         assert(mergekey);
652         xfree(se->mergekey);
653         se->mergekey = *mergekey ? xstrdup(mergekey) : 0;
654         clients_research = 1;
655         session_log(se, YLOG_DEBUG, "session_sort: new mergekey = %s",
656                     mergekey);
657     }
658     if (clients_research == 0)
659     {
660         struct reclist_sortparms *sr;
661         for (sr = se->sorted_results; sr; sr = sr->next)
662             if (!reclist_sortparms_cmp(sr, sp))
663                 break;
664         if (sr)
665         {
666             session_log(se, YLOG_DEBUG, "session_sort: field=%s increasing=%d type=%d already fetched",
667                         field, increasing, type);
668             return;
669         }
670     }
671     session_log(se, YLOG_DEBUG, "session_sort: field=%s increasing=%d type=%d must fetch",
672                 field, increasing, type);
673
674     // We need to reset reclist on every sort that changes the records, not just for position
675     // So if just one client requires new searching, we need to clear set.
676     // Ask each of the client if sorting requires re-search due to native sort
677     // If it does it will require us to
678     for (l = se->clients_active; l; l = l->next)
679     {
680         struct client *cl = l->client;
681         // Assume no re-search is required.
682         client_parse_init(cl, 1);
683         clients_research += client_parse_sort(cl, sp);
684     }
685     if (clients_research)
686     {
687         session_log(se, YLOG_DEBUG,
688                     "session_sort: reset results due to %d clients researching",
689                     clients_research);
690         session_clear_set(se, sp);
691     }
692     else
693     {
694         // A new sorting based on same record set
695         struct reclist_sortparms *sr = nmem_malloc(se->nmem, sizeof(*sr));
696         sr->name = nmem_strdup(se->nmem, field);
697         sr->increasing = increasing;
698         sr->type = type;
699         sr->next = se->sorted_results;
700         se->sorted_results = sr;
701         session_log(se, YLOG_DEBUG, "session_sort: no research/ingesting done");
702         return ;
703     }
704     session_log(se, YLOG_DEBUG, "Re- search/ingesting for clients due to change in sort order");
705
706     for (l = se->clients_active; l; l = l->next)
707     {
708         struct client *cl = l->client;
709         if (client_get_state(cl) == Client_Connecting ||
710             client_get_state(cl) == Client_Idle ||
711             client_get_state(cl) == Client_Working) {
712             client_start_search(cl);
713         }
714         else
715         {
716             session_log(se, YLOG_DEBUG,
717                         "session_sort: %s: No re-start/ingest in show. "
718                         "Wrong client state: %d",
719                         client_get_id(cl), client_get_state(cl));
720         }
721     }
722 }
723
724 void session_sort(struct session *se, struct reclist_sortparms *sp,
725                   const char *mergekey, const char *rank)
726 {
727     //session_enter(se, "session_sort");
728     session_sort_unlocked(se, sp, mergekey, rank);
729     //session_leave(se, "session_sort");
730 }
731
732
733 enum pazpar2_error_code session_search(struct session *se,
734                                        const char *query,
735                                        const char *startrecs,
736                                        const char *maxrecs,
737                                        const char *filter,
738                                        const char *limit,
739                                        const char **addinfo,
740                                        const char **addinfo2,
741                                        struct reclist_sortparms *sp,
742                                        const char *mergekey,
743                                        const char *rank)
744 {
745     int live_channels = 0;
746     int no_working = 0;
747     int no_failed_query = 0;
748     int no_failed_limit = 0;
749     struct client_list *l, *l0;
750
751     session_alert_watch(se, SESSION_WATCH_SHOW);
752     session_alert_watch(se, SESSION_WATCH_BYTARGET);
753     session_alert_watch(se, SESSION_WATCH_TERMLIST);
754     session_alert_watch(se, SESSION_WATCH_SHOW_PREF);
755
756     session_log(se, YLOG_DEBUG, "Search");
757
758     *addinfo = 0;
759
760     if (se->settings_modified) {
761         session_remove_cached_clients(se);
762     }
763     else
764         session_reset_active_clients(se, 0);
765
766     session_enter(se, "session_search");
767     se->settings_modified = 0;
768
769     if (mergekey)
770     {
771         xfree(se->mergekey);
772         se->mergekey = *mergekey ? xstrdup(mergekey) : 0;
773     }
774     if (rank)
775     {
776         xfree(se->rank);
777         se->rank = *rank ? xstrdup(rank) : 0;
778     }
779
780     session_clear_set(se, sp);
781     relevance_destroy(&se->relevance);
782
783     live_channels = select_targets(se, filter);
784     if (!live_channels)
785     {
786         session_leave(se, "session_search");
787         return PAZPAR2_NO_TARGETS;
788     }
789
790     facet_limits_destroy(se->facet_limits);
791     se->facet_limits = facet_limits_create(limit);
792     if (!se->facet_limits)
793     {
794         *addinfo = "limit";
795         session_leave(se, "session_search");
796         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
797     }
798
799     l0 = se->clients_active;
800     se->clients_active = 0;
801     session_leave(se, "session_search");
802
803     for (l = l0; l; l = l->next)
804     {
805         int parse_ret;
806         struct client *cl = l->client;
807         client_parse_init(cl, 1);
808         if (prepare_map(se, client_get_database(cl)) < 0)
809             continue;
810
811         parse_ret = client_parse_query(cl, query, se->facet_limits, addinfo2);
812         if (parse_ret == -1)
813             no_failed_query++;
814         else if (parse_ret == -2)
815             no_failed_limit++;
816         else if (parse_ret < 0)
817             no_working++; /* other error, such as bad CCL map */
818         else
819         {
820             client_parse_range(cl, startrecs, maxrecs);
821             client_parse_sort(cl, sp);
822             client_start_search(cl);
823             no_working++;
824         }
825     }
826     session_reset_active_clients(se, l0);
827
828     if (no_working == 0)
829     {
830         if (no_failed_query > 0)
831         {
832             *addinfo = "query";
833             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
834         }
835         else if (no_failed_limit > 0)
836         {
837             *addinfo = "limit";
838             return PAZPAR2_MALFORMED_PARAMETER_VALUE;
839         }
840         else
841             return PAZPAR2_NO_TARGETS;
842     }
843     return PAZPAR2_NO_ERROR;
844 }
845
846 // Creates a new session_database object for a database
847 static void session_init_databases_fun(void *context, struct database *db)
848 {
849     struct session *se = (struct session *) context;
850     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
851     int i;
852
853     new->database = db;
854
855     new->map = 0;
856     assert(db->settings);
857     new->settings = nmem_malloc(se->session_nmem,
858                                 sizeof(struct settings *) * db->num_settings);
859     new->num_settings = db->num_settings;
860     for (i = 0; i < db->num_settings; i++)
861     {
862         struct setting *setting = db->settings[i];
863         new->settings[i] = setting;
864     }
865     new->next = se->databases;
866     se->databases = new;
867 }
868
869 // Doesn't free memory associated with sdb -- nmem takes care of that
870 static void session_database_destroy(struct session_database *sdb)
871 {
872     sdb->map = 0;
873 }
874
875 // Initialize session_database list -- this represents this session's view
876 // of the database list -- subject to modification by the settings ws command
877 void session_init_databases(struct session *se)
878 {
879     se->databases = 0;
880     predef_grep_databases(se, se->service, session_init_databases_fun);
881 }
882
883 // Probably session_init_databases_fun should be refactored instead of
884 // called here.
885 static struct session_database *load_session_database(struct session *se,
886                                                       char *id)
887 {
888     struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
889     session_init_databases_fun((void*) se, db);
890
891     // New sdb is head of se->databases list
892     return se->databases;
893 }
894
895 // Find an existing session database. If not found, load it
896 static struct session_database *find_session_database(struct session *se,
897                                                       char *id)
898 {
899     struct session_database *sdb;
900
901     for (sdb = se->databases; sdb; sdb = sdb->next)
902         if (!strcmp(sdb->database->id, id))
903             return sdb;
904     return load_session_database(se, id);
905 }
906
907 // Apply a session override to a database
908 void session_apply_setting(struct session *se, char *dbname, char *name,
909                            char *value)
910 {
911     struct session_database *sdb = find_session_database(se, dbname);
912     struct conf_service *service = se->service;
913     struct setting *s;
914     int offset = settings_create_offset(service, name);
915
916     expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
917                           se->session_nmem);
918
919     // Force later recompute of settings-driven data structures
920     // (happens when a search starts and client connections are prepared)
921     if (offset == PZ_XSLT)
922         sdb->map = 0;
923
924     se->settings_modified = 1;
925     for (s = sdb->settings[offset]; s; s = s->next)
926         if (!strcmp(s->name, name) &&
927             dbname && s->target && !strcmp(dbname, s->target))
928         {
929             s->value = value;
930             return;
931         }
932     s = nmem_malloc(se->session_nmem, sizeof(*s));
933     s->precedence = 0;
934     s->target = dbname;
935     s->name = name;
936     s->value = value;
937     s->next = sdb->settings[offset];
938     sdb->settings[offset] = s;
939
940 }
941
942 void session_destroy(struct session *se)
943 {
944     struct session_database *sdb;
945     session_log(se, YLOG_LOG, "destroy");
946     session_use(-1);
947     session_remove_cached_clients(se);
948
949     for (sdb = se->databases; sdb; sdb = sdb->next)
950         session_database_destroy(sdb);
951     normalize_cache_destroy(se->normalize_cache);
952     relevance_destroy(&se->relevance);
953     reclist_destroy(se->reclist);
954     xfree(se->mergekey);
955     xfree(se->rank);
956     if (nmem_total(se->nmem))
957         session_log(se, YLOG_DEBUG, "NMEN operation usage %zd", nmem_total(se->nmem));
958     if (nmem_total(se->session_nmem))
959         session_log(se, YLOG_DEBUG, "NMEN session usage %zd", nmem_total(se->session_nmem));
960     facet_limits_destroy(se->facet_limits);
961     nmem_destroy(se->nmem);
962     service_destroy(se->service);
963     yaz_mutex_destroy(&se->session_mutex);
964 }
965
966 size_t session_get_memory_status(struct session *session) {
967     size_t session_nmem;
968     if (session == 0)
969         return 0;
970     session_enter(session, "session_get_memory_status");
971     session_nmem = nmem_total(session->nmem);
972     session_leave(session, "session_get_memory_status");
973     return session_nmem;
974 }
975
976
977 struct session *new_session(NMEM nmem, struct conf_service *service,
978                             unsigned session_id)
979 {
980     int i;
981     struct session *session = nmem_malloc(nmem, sizeof(*session));
982
983     char tmp_str[50];
984
985     sprintf(tmp_str, "session#%u", session_id);
986
987     session->session_id = session_id;
988     session_log(session, YLOG_DEBUG, "New");
989     session->service = service;
990     session->relevance = 0;
991     session->total_records = 0;
992     session->number_of_warnings_unknown_elements = 0;
993     session->number_of_warnings_unknown_metadata = 0;
994     session->num_termlists = 0;
995     session->reclist = reclist_create(nmem);
996     session->clients_active = 0;
997     session->clients_cached = 0;
998     session->settings_modified = 0;
999     session->session_nmem = nmem;
1000     session->nmem = nmem_create();
1001     session->databases = 0;
1002     session->sorted_results = 0;
1003     session->facet_limits = 0;
1004     session->mergekey = 0;
1005     session->rank = 0;
1006
1007     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1008     {
1009         session->watchlist[i].data = 0;
1010         session->watchlist[i].fun = 0;
1011     }
1012     session->normalize_cache = normalize_cache_create();
1013     session->session_mutex = 0;
1014     pazpar2_mutex_create(&session->session_mutex, tmp_str);
1015     session_log(session, YLOG_LOG, "create");
1016
1017     session_use(1);
1018     return session;
1019 }
1020
1021 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
1022
1023 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
1024                                             int *count, NMEM nmem)
1025 {
1026     struct hitsbytarget *res = 0;
1027     struct client_list *l;
1028     size_t sz = 0;
1029
1030     for (l = se->clients_active; l; l = l->next)
1031         sz++;
1032
1033     res = nmem_malloc(nmem, sizeof(*res) * sz);
1034     *count = 0;
1035     for (l = se->clients_active; l; l = l->next)
1036     {
1037         struct client *cl = l->client;
1038         WRBUF w = wrbuf_alloc();
1039         const char *name = session_setting_oneval(client_get_database(cl),
1040                                                   PZ_NAME);
1041
1042         res[*count].id = client_get_id(cl);
1043         res[*count].name = *name ? name : "Unknown";
1044         res[*count].hits = client_get_hits(cl);
1045         res[*count].approximation = client_get_approximation(cl);
1046         res[*count].records = client_get_num_records(cl);
1047         res[*count].filtered = client_get_num_records_filtered(cl);
1048         res[*count].diagnostic =
1049             client_get_diagnostic(cl, &res[*count].message,
1050                                   &res[*count].addinfo);
1051         res[*count].state = client_get_state_str(cl);
1052         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
1053         session_settings_dump(se, client_get_database(cl), w);
1054         res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
1055         wrbuf_rewind(w);
1056         wrbuf_puts(w, "");
1057         res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1058         wrbuf_destroy(w);
1059         (*count)++;
1060     }
1061     return res;
1062 }
1063
1064 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1065 {
1066     struct hitsbytarget *p;
1067     session_enter(se, "get_hitsbytarget");
1068     p = hitsbytarget_nb(se, count, nmem);
1069     session_leave(se, "get_hitsbytarget");
1070     return p;
1071 }
1072
1073 // Compares two hitsbytarget nodes by hitcount
1074 static int cmp_ht(const void *p1, const void *p2)
1075 {
1076     const struct hitsbytarget *h1 = p1;
1077     const struct hitsbytarget *h2 = p2;
1078     return h2->hits - h1->hits;
1079 }
1080
1081 // Compares two hitsbytarget nodes by hitcount
1082 static int cmp_ht_approx(const void *p1, const void *p2)
1083 {
1084     const struct hitsbytarget *h1 = p1;
1085     const struct hitsbytarget *h2 = p2;
1086     return h2->approximation - h1->approximation;
1087 }
1088
1089 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1090                                NMEM nmem, int version)
1091 {
1092     struct hitsbytarget *ht;
1093     int count, i;
1094
1095     ht = hitsbytarget_nb(se, &count, nmem);
1096     if (version >= 2)
1097         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1098     else
1099         qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1100     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1101     {
1102
1103         // do only print terms which have display names
1104
1105         wrbuf_puts(wrbuf, "<term>\n");
1106
1107         wrbuf_puts(wrbuf, "<id>");
1108         wrbuf_xmlputs(wrbuf, ht[i].id);
1109         wrbuf_puts(wrbuf, "</id>\n");
1110
1111         wrbuf_puts(wrbuf, "<name>");
1112         if (!ht[i].name || !ht[i].name[0])
1113             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1114         else
1115             wrbuf_xmlputs(wrbuf, ht[i].name);
1116         wrbuf_puts(wrbuf, "</name>\n");
1117
1118         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1119                      ht[i].hits);
1120
1121         if (version >= 2) {
1122             // Should not print if we know it isn't a approximation.
1123             wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1124             wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1125             wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1126         }
1127
1128         wrbuf_puts(wrbuf, "<state>");
1129         wrbuf_xmlputs(wrbuf, ht[i].state);
1130         wrbuf_puts(wrbuf, "</state>\n");
1131
1132         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1133                      ht[i].diagnostic);
1134         wrbuf_puts(wrbuf, "</term>\n");
1135     }
1136     return count;
1137 }
1138
1139 void perform_termlist(struct http_channel *c, struct session *se,
1140                       const char *name, int num, int version)
1141 {
1142     int i, j;
1143     NMEM nmem_tmp = nmem_create();
1144     char **names;
1145     int num_names = 0;
1146
1147     if (!name)
1148         name = "*";
1149
1150     nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1151
1152     session_enter(se, "perform_termlist");
1153
1154     for (j = 0; j < num_names; j++)
1155     {
1156         const char *tname;
1157         int must_generate_empty = 1; /* bug 5350 */
1158
1159         for (i = 0; i < se->num_termlists; i++)
1160         {
1161             tname = se->termlists[i].name;
1162             if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1163             {
1164                 struct termlist_score **p = 0;
1165                 int len;
1166
1167                 wrbuf_puts(c->wrbuf, "<list name=\"");
1168                 wrbuf_xmlputs(c->wrbuf, tname);
1169                 wrbuf_puts(c->wrbuf, "\">\n");
1170                 must_generate_empty = 0;
1171
1172                 p = termlist_highscore(se->termlists[i].termlist, &len,
1173                                        nmem_tmp);
1174                 if (p)
1175                 {
1176                     int i;
1177                     for (i = 0; i < len && i < num; i++)
1178                     {
1179                         // prevent sending empty term elements
1180                         if (!p[i]->display_term || !p[i]->display_term[0])
1181                             continue;
1182
1183                         wrbuf_puts(c->wrbuf, "<term>");
1184                         wrbuf_puts(c->wrbuf, "<name>");
1185                         wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1186                         wrbuf_puts(c->wrbuf, "</name>");
1187
1188                         wrbuf_printf(c->wrbuf,
1189                                      "<frequency>%d</frequency>",
1190                                      p[i]->frequency);
1191                         wrbuf_puts(c->wrbuf, "</term>\n");
1192                     }
1193                 }
1194                 wrbuf_puts(c->wrbuf, "</list>\n");
1195             }
1196         }
1197         tname = "xtargets";
1198         if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1199         {
1200             wrbuf_puts(c->wrbuf, "<list name=\"");
1201             wrbuf_xmlputs(c->wrbuf, tname);
1202             wrbuf_puts(c->wrbuf, "\">\n");
1203
1204             targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1205             wrbuf_puts(c->wrbuf, "</list>\n");
1206             must_generate_empty = 0;
1207         }
1208         if (must_generate_empty)
1209         {
1210             wrbuf_puts(c->wrbuf, "<list name=\"");
1211             wrbuf_xmlputs(c->wrbuf, names[j]);
1212             wrbuf_puts(c->wrbuf, "\"/>\n");
1213         }
1214     }
1215     session_leave(se, "perform_termlist");
1216     nmem_destroy(nmem_tmp);
1217 }
1218
1219 #ifdef MISSING_HEADERS
1220 void report_nmem_stats(void)
1221 {
1222     size_t in_use, is_free;
1223
1224     nmem_get_memory_in_use(&in_use);
1225     nmem_get_memory_free(&is_free);
1226
1227     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1228             (long) in_use, (long) is_free);
1229 }
1230 #endif
1231
1232 struct record_cluster *show_single_start(struct session *se, const char *id,
1233                                          struct record_cluster **prev_r,
1234                                          struct record_cluster **next_r)
1235 {
1236     struct record_cluster *r = 0;
1237
1238     session_enter(se, "show_single_start");
1239     *prev_r = 0;
1240     *next_r = 0;
1241     reclist_limit(se->reclist, se, 1);
1242
1243     reclist_enter(se->reclist);
1244     while ((r = reclist_read_record(se->reclist)))
1245     {
1246         if (!strcmp(r->recid, id))
1247         {
1248             *next_r = reclist_read_record(se->reclist);
1249             break;
1250         }
1251         *prev_r = r;
1252     }
1253     reclist_leave(se->reclist);
1254     if (!r)
1255         session_leave(se, "show_single_start");
1256     return r;
1257 }
1258
1259 void show_single_stop(struct session *se, struct record_cluster *rec)
1260 {
1261     session_leave(se, "show_single_stop");
1262 }
1263
1264
1265 int session_fetch_more(struct session *se)
1266 {
1267     struct client_list *l;
1268     int ret = 0;
1269
1270     for (l = se->clients_active; l; l = l->next)
1271     {
1272         struct client *cl = l->client;
1273         if (client_get_state(cl) == Client_Idle)
1274         {
1275             if (client_fetch_more(cl))
1276             {
1277                 session_log(se, YLOG_LOG, "%s: more to fetch",
1278                             client_get_id(cl));
1279                 ret = 1;
1280             }
1281             else
1282             {
1283                 session_log(se, YLOG_LOG, "%s: no more to fetch",
1284                             client_get_id(cl));
1285             }
1286         }
1287         else
1288         {
1289             session_log(se, YLOG_LOG, "%s: no fetch due to state=%s",
1290                         client_get_id(cl), client_get_state_str(cl));
1291         }
1292
1293     }
1294     return ret;
1295 }
1296
1297 struct record_cluster **show_range_start(struct session *se,
1298                                          struct reclist_sortparms *sp,
1299                                          int start, int *num, int *total,
1300                                          Odr_int *sumhits, Odr_int *approx_hits,
1301                                          void (*show_records_ready)(void *data),
1302                                          struct http_channel *chan)
1303 {
1304     struct record_cluster **recs = 0;
1305     struct reclist_sortparms *spp;
1306     struct client_list *l;
1307     int i;
1308 #if USE_TIMING
1309     yaz_timing_t t = yaz_timing_create();
1310 #endif
1311     session_enter(se, "show_range_start");
1312     *sumhits = 0;
1313     *approx_hits = 0;
1314     *total = 0;
1315     reclist_limit(se->reclist, se, 0);
1316     if (se->relevance)
1317     {
1318         for (spp = sp; spp; spp = spp->next)
1319             if (spp->type == Metadata_type_relevance)
1320             {
1321                 relevance_prepare_read(se->relevance, se->reclist);
1322                 break;
1323             }
1324         for (l = se->clients_active; l; l = l->next) {
1325             *sumhits += client_get_hits(l->client);
1326             *approx_hits += client_get_approximation(l->client);
1327         }
1328     }
1329     reclist_sort(se->reclist, sp);
1330
1331     reclist_enter(se->reclist);
1332     *total = reclist_get_num_records(se->reclist);
1333
1334     for (l = se->clients_active; l; l = l->next)
1335         client_update_show_stat(l->client, 0);
1336
1337     for (i = 0; i < start; i++)
1338     {
1339         struct record_cluster *r = reclist_read_record(se->reclist);
1340         if (!r)
1341         {
1342             *num = 0;
1343             break;
1344         }
1345         else
1346         {
1347             struct record *rec = r->records;
1348             for (;rec; rec = rec->next)
1349                 client_update_show_stat(rec->client, 1);
1350         }
1351     }
1352     recs = nmem_malloc(se->nmem, (*num > 0 ? *num : 1) * sizeof(*recs));
1353     for (i = 0; i < *num; i++)
1354     {
1355         struct record_cluster *r = reclist_read_record(se->reclist);
1356         if (!r)
1357         {
1358             *num = i;
1359             break;
1360         }
1361         else
1362         {
1363             struct record *rec = r->records;
1364             for (;rec; rec = rec->next)
1365                 client_update_show_stat(rec->client, 1);
1366             recs[i] = r;
1367         }
1368     }
1369     reclist_leave(se->reclist);
1370 #if USE_TIMING
1371     yaz_timing_stop(t);
1372     session_log(se, YLOG_LOG, "show %6.5f %3.2f %3.2f",
1373             yaz_timing_get_real(t), yaz_timing_get_user(t),
1374             yaz_timing_get_sys(t));
1375     yaz_timing_destroy(&t);
1376 #endif
1377
1378     if (!session_fetch_more(se))
1379         session_log(se, YLOG_LOG, "can not fetch more");
1380     else
1381     {
1382         show_range_stop(se, recs);
1383         session_log(se, YLOG_LOG, "fetching more in progress");
1384         if (session_set_watch(se, SESSION_WATCH_SHOW,
1385                               show_records_ready, chan, chan))
1386         {
1387             session_log(se, YLOG_WARN, "Ignoring show block");
1388             session_enter(se, "show_range_start");
1389         }
1390         else
1391         {
1392             session_log(se, YLOG_LOG, "session watch OK");
1393             return 0;
1394         }
1395     }
1396     return recs;
1397 }
1398
1399 void show_range_stop(struct session *se, struct record_cluster **recs)
1400 {
1401     session_leave(se, "show_range_stop");
1402 }
1403
1404 void statistics(struct session *se, struct statistics *stat)
1405 {
1406     struct client_list *l;
1407     int count = 0;
1408
1409     memset(stat, 0, sizeof(*stat));
1410     stat->num_hits = 0;
1411     for (l = se->clients_active; l; l = l->next)
1412     {
1413         struct client *cl = l->client;
1414         if (!client_get_connection(cl))
1415             stat->num_no_connection++;
1416         stat->num_hits += client_get_hits(cl);
1417         switch (client_get_state(cl))
1418         {
1419         case Client_Connecting: stat->num_connecting++; break;
1420         case Client_Working: stat->num_working++; break;
1421         case Client_Idle: stat->num_idle++; break;
1422         case Client_Failed: stat->num_failed++; break;
1423         case Client_Error: stat->num_error++; break;
1424         default: break;
1425         }
1426         count++;
1427     }
1428     stat->num_records = se->total_records;
1429
1430     stat->num_clients = count;
1431 }
1432
1433 static struct record_metadata *record_metadata_init(
1434     NMEM nmem, const char *value, enum conf_metadata_type type,
1435     struct _xmlAttr *attr)
1436 {
1437     struct record_metadata *rec_md = record_metadata_create(nmem);
1438     struct record_metadata_attr **attrp = &rec_md->attributes;
1439
1440     for (; attr; attr = attr->next)
1441     {
1442         if (attr->children && attr->children->content)
1443         {
1444             if (strcmp((const char *) attr->name, "type")
1445                 && strcmp((const char *) attr->name, "empty"))
1446             {  /* skip the "type" + "empty" attribute..
1447                   The "Type" is already part of the element in output
1448                   (md-%s) and so repeating it here is redundant */
1449                 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1450                 (*attrp)->name =
1451                     nmem_strdup(nmem, (const char *) attr->name);
1452                 (*attrp)->value =
1453                     nmem_strdup(nmem, (const char *) attr->children->content);
1454                 attrp = &(*attrp)->next;
1455             }
1456         }
1457     }
1458     *attrp = 0;
1459
1460     switch (type)
1461     {
1462     case Metadata_type_generic:
1463     case Metadata_type_skiparticle:
1464         if (strstr(value, "://")) /* looks like a URL */
1465             rec_md->data.text.disp = nmem_strdup(nmem, value);
1466         else
1467             rec_md->data.text.disp =
1468                 normalize7bit_generic(nmem_strdup(nmem, value), " ,/.:([");
1469         rec_md->data.text.sort = 0;
1470         rec_md->data.text.snippet = 0;
1471         break;
1472     case Metadata_type_year:
1473     case Metadata_type_date:
1474     {
1475         int first, last;
1476         int longdate = 0;
1477
1478         if (type == Metadata_type_date)
1479             longdate = 1;
1480         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1481             return 0;
1482
1483         rec_md->data.number.min = first;
1484         rec_md->data.number.max = last;
1485     }
1486     break;
1487     case Metadata_type_float:
1488         rec_md->data.fnumber = atof(value);
1489         break;
1490     case Metadata_type_relevance:
1491     case Metadata_type_position:
1492         return 0;
1493     }
1494     return rec_md;
1495 }
1496
1497 static void mergekey_norm_wr(pp2_charset_fact_t charsets,
1498                              WRBUF norm_wr, const char *value)
1499 {
1500     const char *norm_str;
1501     pp2_charset_token_t prt =
1502         pp2_charset_token_create(charsets, "mergekey");
1503
1504     pp2_charset_token_first(prt, value, 0);
1505     while ((norm_str = pp2_charset_token_next(prt)))
1506     {
1507         if (*norm_str)
1508         {
1509             if (wrbuf_len(norm_wr))
1510                 wrbuf_puts(norm_wr, " ");
1511             wrbuf_puts(norm_wr, norm_str);
1512         }
1513     }
1514     pp2_charset_token_destroy(prt);
1515 }
1516
1517 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1518                                  struct conf_service *service, WRBUF norm_wr)
1519 {
1520     xmlNode *n;
1521     int no_found = 0;
1522     for (n = root->children; n; n = n->next)
1523     {
1524         if (n->type != XML_ELEMENT_NODE)
1525             continue;
1526         if (!strcmp((const char *) n->name, "metadata"))
1527         {
1528             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1529             if (type == NULL) {
1530                 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1531             }
1532             else if (!strcmp(name, (const char *) type))
1533             {
1534                 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1535                 if (value && *value)
1536                 {
1537                     if (wrbuf_len(norm_wr) > 0)
1538                         wrbuf_puts(norm_wr, " ");
1539                     wrbuf_puts(norm_wr, name);
1540                     mergekey_norm_wr(service->charsets, norm_wr,
1541                                      (const char *) value);
1542                     no_found++;
1543                 }
1544                 if (value)
1545                     xmlFree(value);
1546             }
1547             xmlFree(type);
1548         }
1549     }
1550     return no_found;
1551 }
1552
1553 static const char *get_mergekey(xmlDoc *doc, xmlNode *root, 
1554                                 struct client *cl, int record_no,
1555                                 struct conf_service *service, NMEM nmem,
1556                                 const char *session_mergekey)
1557 {
1558     char *mergekey_norm = 0;
1559     WRBUF norm_wr = wrbuf_alloc();
1560     xmlChar *mergekey;
1561
1562     if (session_mergekey)
1563     {
1564         int i, num = 0;
1565         char **values = 0;
1566         nmem_strsplit_escape2(nmem, ",", session_mergekey, &values,
1567                               &num, 1, '\\', 1);
1568
1569         for (i = 0; i < num; i++)
1570             get_mergekey_from_doc(doc, root, values[i], service, norm_wr);
1571     }
1572     else if ((mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
1573     {
1574         mergekey_norm_wr(service->charsets, norm_wr, (const char *) mergekey);
1575         xmlFree(mergekey);
1576     }
1577     else
1578     {
1579         /* no mergekey defined in XSL. Look for mergekey metadata instead */
1580         int field_id;
1581         for (field_id = 0; field_id < service->num_metadata; field_id++)
1582         {
1583             struct conf_metadata *ser_md = &service->metadata[field_id];
1584             if (ser_md->mergekey != Metadata_mergekey_no)
1585             {
1586                 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1587                                               service, norm_wr);
1588                 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1589                 {
1590                     /* no mergekey on this one and it is required..
1591                        Generate unique key instead */
1592                     wrbuf_rewind(norm_wr);
1593                     break;
1594                 }
1595             }
1596         }
1597     }
1598
1599     /* generate unique key if none is not generated already or is empty */
1600     if (wrbuf_len(norm_wr) == 0)
1601     {
1602         wrbuf_printf(norm_wr, "position: %s-%d",
1603                      client_get_id(cl), record_no);
1604     }
1605     else
1606     {
1607         const char *lead = "content: ";
1608         wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1609     }
1610     if (wrbuf_len(norm_wr) > 0)
1611         mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1612     wrbuf_destroy(norm_wr);
1613     return mergekey_norm;
1614 }
1615
1616 /** \brief see if metadata for pz:recordfilter exists
1617     \param root xml root element of normalized record
1618     \param sdb session database for client
1619     \retval 0 if there is no metadata for pz:recordfilter
1620     \retval 1 if there is metadata for pz:recordfilter
1621
1622     If there is no pz:recordfilter defined, this function returns 1
1623     as well.
1624 */
1625
1626 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1627 {
1628     int match = 0;
1629     xmlNode *n;
1630     const char *s;
1631     s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1632
1633     if (!s || !*s)
1634         return 1;
1635
1636     for (n = root->children; n; n = n->next)
1637     {
1638         if (n->type != XML_ELEMENT_NODE)
1639             continue;
1640         if (!strcmp((const char *) n->name, "metadata"))
1641         {
1642             xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1643             if (type)
1644             {
1645                 size_t len;
1646                 int substring;
1647                 const char *eq;
1648
1649                 if ((eq = strchr(s, '=')))
1650                     substring = 0;
1651                 else if ((eq = strchr(s, '~')))
1652                     substring = 1;
1653                 if (eq)
1654                     len = eq - s;
1655                 else
1656                     len = strlen(s);
1657                 if (len == strlen((const char *)type) &&
1658                     !memcmp((const char *) type, s, len))
1659                 {
1660                     xmlChar *value = xmlNodeGetContent(n);
1661                     if (value && *value)
1662                     {
1663                         if (!eq ||
1664                             (substring && strstr((const char *) value, eq+1)) ||
1665                             (!substring && !strcmp((const char *) value, eq + 1)))
1666                             match = 1;
1667                     }
1668                     xmlFree(value);
1669                 }
1670                 xmlFree(type);
1671             }
1672         }
1673     }
1674     return match;
1675 }
1676
1677 static int ingest_to_cluster(struct client *cl,
1678                              xmlDoc *xdoc,
1679                              xmlNode *root,
1680                              int record_no,
1681                              struct record_metadata_attr *mergekey);
1682
1683 static int ingest_sub_record(struct client *cl, xmlDoc *xdoc, xmlNode *root,
1684                              int record_no, NMEM nmem,
1685                              struct session_database *sdb,
1686                              struct record_metadata_attr *mergekeys)
1687 {
1688     int ret = 0;
1689     struct session *se = client_get_session(cl);
1690     struct conf_service *service = se->service;
1691
1692     insert_settings_values(sdb, xdoc, root, service);
1693
1694     if (!check_record_filter(root, sdb))
1695     {
1696         session_log(se, YLOG_LOG,
1697                     "Filtered out record no %d from %s",
1698                     record_no, sdb->database->id);
1699         return 0;
1700     }
1701     session_enter(se, "ingest_sub_record");
1702     if (client_get_session(cl) == se && se->relevance)
1703         ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekeys);
1704     session_leave(se, "ingest_sub_record");
1705
1706     return ret;
1707 }
1708
1709 /** \brief ingest XML record
1710     \param cl client holds the result set for record
1711     \param rec record buffer (0 terminated)
1712     \param record_no record position (1, 2, ..)
1713     \param nmem working NMEM
1714     \retval 0 OK
1715     \retval -1 failure
1716     \retval -2 Filtered
1717 */
1718 int ingest_record(struct client *cl, const char *rec,
1719                   int record_no, NMEM nmem)
1720 {
1721     struct session *se = client_get_session(cl);
1722     struct session_database *sdb = client_get_database(cl);
1723     struct conf_service *service = se->service;
1724     xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1725     int r = 0;
1726     xmlNode *root;
1727
1728     if (!xdoc)
1729         return -1;
1730
1731     if (global_parameters.dump_records)
1732     {
1733         session_log(se, YLOG_LOG, "Normalized record from %s",
1734                     sdb->database->id);
1735         log_xml_doc(xdoc);
1736     }
1737
1738     root = xmlDocGetRootElement(xdoc);
1739
1740     if (!strcmp((const char *) root->name, "cluster"))
1741     {
1742         int no_merge_keys = 0;
1743         int no_merge_dups = 0;
1744         xmlNode *sroot;
1745         struct record_metadata_attr *mk = 0;
1746
1747         for (sroot = root->children; sroot; sroot = sroot->next)
1748             if (sroot->type == XML_ELEMENT_NODE &&
1749                 !strcmp((const char *) sroot->name, "record"))
1750             {
1751                 struct record_metadata_attr **mkp;
1752                 const char *mergekey_norm =
1753                     get_mergekey(xdoc, sroot, cl, record_no, service, nmem,
1754                                  se->mergekey);
1755                 if (!mergekey_norm)
1756                 {
1757                     r = -1;
1758                     break;
1759                 }
1760                 for (mkp = &mk; *mkp; mkp = &(*mkp)->next)
1761                     if (!strcmp((*mkp)->value, mergekey_norm))
1762                         break;
1763                 if (!*mkp)
1764                 {
1765                     *mkp = (struct record_metadata_attr*)
1766                         nmem_malloc(nmem, sizeof(**mkp));
1767                     (*mkp)->name = 0;
1768                     (*mkp)->value = nmem_strdup(nmem, mergekey_norm);
1769                     (*mkp)->next = 0;
1770                     no_merge_keys++;
1771                 }
1772                 else
1773                     no_merge_dups++;
1774             }
1775         if (no_merge_keys > 1 || no_merge_dups > 0)
1776         {
1777             yaz_log(YLOG_LOG, "Got %d mergekeys, %d dups for position %d",
1778                     no_merge_keys, no_merge_dups, record_no);
1779         }
1780         for (sroot = root->children; !r && sroot; sroot = sroot->next)
1781             if (sroot->type == XML_ELEMENT_NODE &&
1782                 !strcmp((const char *) sroot->name, "record"))
1783             {
1784                 r = ingest_sub_record(cl, xdoc, sroot, record_no, nmem, sdb,
1785                                       mk);
1786             }
1787     }
1788     else if (!strcmp((const char *) root->name, "record"))
1789     {
1790         const char *mergekey_norm =
1791             get_mergekey(xdoc, root, cl, record_no, service, nmem,
1792                          se->mergekey);
1793         if (mergekey_norm)
1794         {
1795             struct record_metadata_attr *mk = (struct record_metadata_attr*)
1796                 nmem_malloc(nmem, sizeof(*mk));
1797             mk->name = 0;
1798             mk->value = nmem_strdup(nmem, mergekey_norm);
1799             mk->next = 0;
1800
1801             r = ingest_sub_record(cl, xdoc, root, record_no, nmem, sdb, mk);
1802         }
1803     }
1804     else
1805     {
1806         session_log(se, YLOG_WARN, "Bad pz root element: %s",
1807                     (const char *) root->name);
1808         r = -1;
1809     }
1810     xmlFreeDoc(xdoc);
1811     return r;
1812 }
1813
1814
1815 //    struct conf_metadata *ser_md = &service->metadata[md_field_id];
1816 //    struct record_metadata *rec_md = record->metadata[md_field_id];
1817 static int match_metadata_local(struct conf_service *service,
1818                                 struct conf_metadata *ser_md,
1819                                 struct record_metadata *rec_md0,
1820                                 char **values, int num_v)
1821 {
1822     int i;
1823     struct record_metadata *rec_md = rec_md0;
1824     WRBUF val_wr = 0;
1825     WRBUF text_wr = wrbuf_alloc();
1826     for (i = 0; i < num_v; )
1827     {
1828         if (rec_md)
1829         {
1830             if (ser_md->type == Metadata_type_year
1831                 || ser_md->type == Metadata_type_date)
1832             {
1833                 int y = atoi(values[i]);
1834                 if (y >= rec_md->data.number.min
1835                     && y <= rec_md->data.number.max)
1836                     break;
1837             }
1838             else
1839             {
1840                 if (!val_wr)
1841                 {
1842                     val_wr = wrbuf_alloc();
1843                     mergekey_norm_wr(service->charsets, val_wr, values[i]);
1844                 }
1845                 wrbuf_rewind(text_wr);
1846                 mergekey_norm_wr(service->charsets, text_wr,
1847                                  rec_md->data.text.disp);
1848                 if (!strcmp(wrbuf_cstr(val_wr), wrbuf_cstr(text_wr)))
1849                     break;
1850             }
1851             rec_md = rec_md->next;
1852         }
1853         else
1854         {
1855             rec_md = rec_md0;
1856             wrbuf_destroy(val_wr);
1857             val_wr = 0;
1858             i++;
1859         }
1860     }
1861     wrbuf_destroy(val_wr);
1862     wrbuf_destroy(text_wr);
1863     return i < num_v ? 1 : 0;
1864 }
1865
1866 int session_check_cluster_limit(struct session *se, struct record_cluster *rec)
1867 {
1868     int i;
1869     struct conf_service *service = se->service;
1870     int ret = 1;
1871     const char *name;
1872     const char *value;
1873     NMEM nmem_tmp = nmem_create();
1874
1875     for (i = 0; (name = facet_limits_get(se->facet_limits, i, &value)); i++)
1876     {
1877         int j;
1878         for (j = 0; j < service->num_metadata; j++)
1879         {
1880             struct conf_metadata *md = service->metadata + j;
1881             if (!strcmp(md->name, name) && md->limitcluster)
1882             {
1883                 char **values = 0;
1884                 int num = 0;
1885                 int md_field_id =
1886                     conf_service_metadata_field_id(service,
1887                                                    md->limitcluster);
1888
1889                 if (md_field_id < 0)
1890                 {
1891                     ret = 0;
1892                     break;
1893                 }
1894
1895                 nmem_strsplit_escape2(nmem_tmp, "|", value, &values,
1896                                       &num, 1, '\\', 1);
1897
1898                 if (!match_metadata_local(service,
1899                                           &service->metadata[md_field_id],
1900                                           rec->metadata[md_field_id],
1901                                           values, num))
1902                 {
1903                     ret = 0;
1904                     break;
1905                 }
1906             }
1907         }
1908     }
1909     nmem_destroy(nmem_tmp);
1910     return ret;
1911 }
1912
1913 // Skip record on non-zero
1914 static int check_limit_local(struct client *cl,
1915                              struct record *record,
1916                              int record_no)
1917 {
1918     int skip_record = 0;
1919     struct session *se = client_get_session(cl);
1920     struct conf_service *service = se->service;
1921     NMEM nmem_tmp = nmem_create();
1922     struct session_database *sdb = client_get_database(cl);
1923     int l = 0;
1924     while (!skip_record)
1925     {
1926         int md_field_id;
1927         char **values = 0;
1928         int num_v = 0;
1929         const char *name =
1930             client_get_facet_limit_local(cl, sdb, &l, nmem_tmp,
1931                                          &num_v, &values);
1932         if (!name)
1933             break;
1934
1935         if (!strcmp(name, "*"))
1936         {
1937             for (md_field_id = 0; md_field_id < service->num_metadata;
1938                  md_field_id++)
1939             {
1940                 if (match_metadata_local(
1941                         service,
1942                         &service->metadata[md_field_id],
1943                         record->metadata[md_field_id],
1944                         values, num_v))
1945                     break;
1946             }
1947             if (md_field_id == service->num_metadata)
1948                 skip_record = 1;
1949         }
1950         else
1951         {
1952             md_field_id = conf_service_metadata_field_id(service, name);
1953             if (md_field_id < 0)
1954             {
1955                 skip_record = 1;
1956                 break;
1957             }
1958             if (!match_metadata_local(
1959                     service,
1960                     &service->metadata[md_field_id],
1961                     record->metadata[md_field_id],
1962                     values, num_v))
1963             {
1964                 skip_record = 1;
1965             }
1966         }
1967     }
1968     nmem_destroy(nmem_tmp);
1969     return skip_record;
1970 }
1971
1972 static int ingest_to_cluster(struct client *cl,
1973                              xmlDoc *xdoc,
1974                              xmlNode *root,
1975                              int record_no,
1976                              struct record_metadata_attr *merge_keys)
1977 {
1978     xmlNode *n;
1979     xmlChar *type = 0;
1980     xmlChar *value = 0;
1981     struct session *se = client_get_session(cl);
1982     struct conf_service *service = se->service;
1983     int term_factor = 1;
1984     struct record_cluster *cluster;
1985     struct record_metadata **metadata0;
1986     struct session_database *sdb = client_get_database(cl);
1987     NMEM ingest_nmem = 0;
1988     char **rank_values = 0;
1989     int rank_num = 0;
1990     struct record *record = record_create(se->nmem,
1991                                           service->num_metadata,
1992                                           service->num_sortkeys, cl,
1993                                           record_no);
1994
1995     for (n = root->children; n; n = n->next)
1996     {
1997         if (type)
1998             xmlFree(type);
1999         if (value)
2000             xmlFree(value);
2001         type = value = 0;
2002
2003         if (n->type != XML_ELEMENT_NODE)
2004             continue;
2005         if (!strcmp((const char *) n->name, "metadata"))
2006         {
2007             struct conf_metadata *ser_md = 0;
2008             struct record_metadata **wheretoput = 0;
2009             struct record_metadata *rec_md = 0;
2010             int md_field_id = -1;
2011
2012             type = xmlGetProp(n, (xmlChar *) "type");
2013             value = xmlNodeListGetString(xdoc, n->children, 1);
2014             if (!type)
2015                 continue;
2016             if (!value || !*value)
2017             {
2018                 xmlChar *empty = xmlGetProp(n, (xmlChar *) "empty");
2019                 if (!empty)
2020                     continue;
2021                 if (value)
2022                     xmlFree(value);
2023                 value = empty;
2024             }
2025             md_field_id
2026                 = conf_service_metadata_field_id(service, (const char *) type);
2027             if (md_field_id < 0)
2028             {
2029                 if (se->number_of_warnings_unknown_metadata == 0)
2030                 {
2031                     session_log(se, YLOG_WARN,
2032                             "Ignoring unknown metadata element: %s", type);
2033                 }
2034                 se->number_of_warnings_unknown_metadata++;
2035                 continue;
2036             }
2037
2038             ser_md = &service->metadata[md_field_id];
2039
2040             // non-merged metadata
2041             rec_md = record_metadata_init(se->nmem, (const char *) value,
2042                                           ser_md->type, n->properties);
2043             if (!rec_md)
2044             {
2045                 session_log(se, YLOG_WARN, "bad metadata data '%s' "
2046                             "for element '%s'", value, type);
2047                 continue;
2048             }
2049
2050             if (ser_md->type == Metadata_type_generic)
2051             {
2052                 WRBUF w = wrbuf_alloc();
2053                 if (relevance_snippet(se->relevance,
2054                                       (char*) value, ser_md->name, w))
2055                     rec_md->data.text.snippet = nmem_strdup(se->nmem,
2056                                                             wrbuf_cstr(w));
2057                 wrbuf_destroy(w);
2058             }
2059
2060
2061             wheretoput = &record->metadata[md_field_id];
2062             while (*wheretoput)
2063                 wheretoput = &(*wheretoput)->next;
2064             *wheretoput = rec_md;
2065         }
2066     }
2067
2068     if (check_limit_local(cl, record, record_no))
2069     {
2070         session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
2071                     record_no, sdb->database->id);
2072         if (type)
2073             xmlFree(type);
2074         if (value)
2075             xmlFree(value);
2076         return -2;
2077     }
2078     cluster = reclist_insert(se->reclist, se->relevance, service, record,
2079                              merge_keys, &se->total_merged);
2080     if (!cluster)
2081     {
2082         if (type)
2083             xmlFree(type);
2084         if (value)
2085             xmlFree(value);
2086         return 0; // complete match with existing record
2087     }
2088
2089     {
2090         const char *use_term_factor_str =
2091             session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
2092         if (use_term_factor_str && use_term_factor_str[0] == '1')
2093         {
2094             int maxrecs = client_get_maxrecs(cl);
2095             int hits = (int) client_get_hits(cl);
2096             term_factor = MAX(hits, maxrecs) /  MAX(1, maxrecs);
2097             assert(term_factor >= 1);
2098             session_log(se, YLOG_DEBUG, "Using term factor: %d (%d / %d)",
2099                         term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
2100         }
2101     }
2102
2103     if (global_parameters.dump_records)
2104         session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
2105                     sdb->database->id, record_no);
2106
2107     // original metadata, to check if first existence of a field
2108     metadata0 = xmalloc(sizeof(*metadata0) * service->num_metadata);
2109     memcpy(metadata0, cluster->metadata,
2110            sizeof(*metadata0) * service->num_metadata);
2111
2112     ingest_nmem = nmem_create();
2113     if (se->rank)
2114     {
2115         yaz_log(YLOG_LOG, "local in sort : %s", se->rank);
2116         nmem_strsplit_escape2(ingest_nmem, ",", se->rank, &rank_values,
2117                               &rank_num, 1, '\\', 1);
2118     }
2119
2120     // now parsing XML record and adding data to cluster or record metadata
2121     for (n = root->children; n; n = n->next)
2122     {
2123         pp2_charset_token_t prt;
2124         if (type)
2125             xmlFree(type);
2126         if (value)
2127             xmlFree(value);
2128         type = value = 0;
2129
2130         if (n->type != XML_ELEMENT_NODE)
2131             continue;
2132         if (!strcmp((const char *) n->name, "metadata"))
2133         {
2134             struct conf_metadata *ser_md = 0;
2135             struct conf_sortkey *ser_sk = 0;
2136             struct record_metadata **wheretoput = 0;
2137             struct record_metadata *rec_md = 0;
2138             int md_field_id = -1;
2139             int sk_field_id = -1;
2140             const char *rank = 0;
2141             xmlChar *xml_rank = 0;
2142
2143             type = xmlGetProp(n, (xmlChar *) "type");
2144             value = xmlNodeListGetString(xdoc, n->children, 1);
2145
2146             if (!type || !value || !*value)
2147                 continue;
2148
2149             md_field_id
2150                 = conf_service_metadata_field_id(service, (const char *) type);
2151             if (md_field_id < 0)
2152                 continue;
2153
2154             ser_md = &service->metadata[md_field_id];
2155
2156             if (ser_md->sortkey_offset >= 0)
2157             {
2158                 sk_field_id = ser_md->sortkey_offset;
2159                 ser_sk = &service->sortkeys[sk_field_id];
2160             }
2161
2162             // merged metadata
2163             rec_md = record_metadata_init(se->nmem, (const char *) value,
2164                                           ser_md->type, 0);
2165
2166             // see if the field was not in cluster already (from beginning)
2167
2168             if (!rec_md)
2169                 continue;
2170
2171             if (rank_num)
2172             {
2173                 int i;
2174                 for (i = 0; i < rank_num; i++)
2175                 {
2176                     const char *val = rank_values[i];
2177                     const char *cp = strchr(val, '=');
2178                     if (!cp)
2179                         continue;
2180                     if ((cp - val) == strlen((const char *) type)
2181                         && !memcmp(val, type, cp - val))
2182                     {
2183                         rank = cp + 1;
2184                         break;
2185                     }
2186                 }
2187             }
2188             else
2189             {
2190                 xml_rank = xmlGetProp(n, (xmlChar *) "rank");
2191                 rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
2192             }
2193
2194             wheretoput = &cluster->metadata[md_field_id];
2195
2196             if (ser_md->merge == Metadata_merge_first)
2197             {
2198                 if (!metadata0[md_field_id])
2199                 {
2200                     while (*wheretoput)
2201                         wheretoput = &(*wheretoput)->next;
2202                     *wheretoput = rec_md;
2203                 }
2204             }
2205             else if (ser_md->merge == Metadata_merge_unique)
2206             {
2207                 while (*wheretoput)
2208                 {
2209                     if (!strcmp((const char *) (*wheretoput)->data.text.disp,
2210                                 rec_md->data.text.disp))
2211                         break;
2212                     wheretoput = &(*wheretoput)->next;
2213                 }
2214                 if (!*wheretoput)
2215                     *wheretoput = rec_md;
2216             }
2217             else if (ser_md->merge == Metadata_merge_longest)
2218             {
2219                 if (!*wheretoput
2220                     || strlen(rec_md->data.text.disp)
2221                     > strlen((*wheretoput)->data.text.disp))
2222                 {
2223                     *wheretoput = rec_md;
2224                     if (ser_sk)
2225                     {
2226                         const char *sort_str = 0;
2227                         int skip_article =
2228                             ser_sk->type == Metadata_type_skiparticle;
2229
2230                         if (!cluster->sortkeys[sk_field_id])
2231                             cluster->sortkeys[sk_field_id] =
2232                                 nmem_malloc(se->nmem,
2233                                             sizeof(union data_types));
2234
2235                         prt =
2236                             pp2_charset_token_create(service->charsets, "sort");
2237
2238                         pp2_charset_token_first(prt, rec_md->data.text.disp,
2239                                                 skip_article);
2240
2241                         pp2_charset_token_next(prt);
2242
2243                         sort_str = pp2_get_sort(prt);
2244
2245                         cluster->sortkeys[sk_field_id]->text.disp =
2246                             rec_md->data.text.disp;
2247                         if (!sort_str)
2248                         {
2249                             sort_str = rec_md->data.text.disp;
2250                             session_log(se, YLOG_WARN,
2251                                     "Could not make sortkey. Bug #1858");
2252                         }
2253                         cluster->sortkeys[sk_field_id]->text.sort =
2254                             nmem_strdup(se->nmem, sort_str);
2255                         pp2_charset_token_destroy(prt);
2256                     }
2257                 }
2258             }
2259             else if (ser_md->merge == Metadata_merge_all)
2260             {
2261                 while (*wheretoput)
2262                     wheretoput = &(*wheretoput)->next;
2263                 *wheretoput = rec_md;
2264             }
2265             else if (ser_md->merge == Metadata_merge_range)
2266             {
2267                 if (!*wheretoput)
2268                 {
2269                     *wheretoput = rec_md;
2270                     if (ser_sk)
2271                         cluster->sortkeys[sk_field_id]
2272                             = &rec_md->data;
2273                 }
2274                 else
2275                 {
2276                     int this_min = rec_md->data.number.min;
2277                     int this_max = rec_md->data.number.max;
2278                     if (this_min < (*wheretoput)->data.number.min)
2279                         (*wheretoput)->data.number.min = this_min;
2280                     if (this_max > (*wheretoput)->data.number.max)
2281                         (*wheretoput)->data.number.max = this_max;
2282                 }
2283             }
2284
2285             // ranking of _all_ fields enabled ...
2286             if (rank)
2287             {
2288                 relevance_countwords(se->relevance, cluster,
2289                                      (char *) value, rank, ser_md->name);
2290             }
2291             // construct facets ... unless the client already has reported them
2292             if (ser_md->termlist && !client_has_facet(cl, (char *) type))
2293             {
2294                 if (ser_md->type == Metadata_type_year)
2295                 {
2296                     char year[64];
2297                     sprintf(year, "%d", rec_md->data.number.max);
2298
2299                     add_facet(se, (char *) type, year, term_factor);
2300                     if (rec_md->data.number.max != rec_md->data.number.min)
2301                     {
2302                         sprintf(year, "%d", rec_md->data.number.min);
2303                         add_facet(se, (char *) type, year, term_factor);
2304                     }
2305                 }
2306                 else
2307                     add_facet(se, (char *) type, (char *) value, term_factor);
2308             }
2309
2310             // cleaning up
2311             if (xml_rank)
2312                 xmlFree(xml_rank);
2313             xmlFree(type);
2314             xmlFree(value);
2315             type = value = 0;
2316         }
2317         else
2318         {
2319             if (se->number_of_warnings_unknown_elements == 0)
2320                 session_log(se, YLOG_WARN,
2321                         "Unexpected element in internal record: %s", n->name);
2322             se->number_of_warnings_unknown_elements++;
2323         }
2324     }
2325     if (type)
2326         xmlFree(type);
2327     if (value)
2328         xmlFree(value);
2329
2330     nmem_destroy(ingest_nmem);
2331     xfree(metadata0);
2332     relevance_donerecord(se->relevance, cluster);
2333     se->total_records++;
2334
2335     return 0;
2336 }
2337
2338 void session_log(struct session *s, int level, const char *fmt, ...)
2339 {
2340     char buf[1024];
2341     va_list ap;
2342     va_start(ap, fmt);
2343
2344     yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
2345     yaz_log(level, "Session %u: %s", s ? s->session_id : 0, buf);
2346
2347     va_end(ap);
2348 }
2349
2350 /*
2351  * Local variables:
2352  * c-basic-offset: 4
2353  * c-file-style: "Stroustrup"
2354  * indent-tabs-mode: nil
2355  * End:
2356  * vim: shiftwidth=4 tabstop=8 expandtab
2357  */
2358