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