-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.cc
2426 lines (2274 loc) · 62.9 KB
/
query.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* query.cc: query executor for omega
*
* Copyright 1999,2000,2001 BrightStation PLC
* Copyright 2001 James Aylett
* Copyright 2001,2002 Ananova Ltd
* Copyright 2002 Intercede 1749 Ltd
* Copyright 2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2013 Olly Betts
* Copyright 2008 Thomas Viehmann
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include <config.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <cassert>
#include <cctype>
#include "safeerrno.h"
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include "strcasecmp.h"
#include <ctime>
#include "safeunistd.h"
#include <sys/types.h>
#include "safesysstat.h"
#include "safefcntl.h"
#include "realtime.h"
#include <cdb.h>
#include "date.h"
#include "datematchdecider.h"
#include "jsonescape.h"
#include "utils.h"
#include "omega.h"
#include "query.h"
#include "cgiparam.h"
#include "loadfile.h"
#include "sample.h"
#include "str.h"
#include "stringutils.h"
#include "transform.h"
#include "urldecode.h"
#include "urlencode.h"
#include "unixperm.h"
#include "values.h"
#include "weight.h"
#include <xapian.h>
using namespace std;
using Xapian::Utf8Iterator;
using Xapian::Unicode::is_wordchar;
#ifndef SNPRINTF
#include <cstdarg>
static int my_snprintf(char *str, size_t size, const char *format, ...)
{
int res;
va_list ap;
va_start(ap, format);
str[size - 1] = '\0';
res = vsprintf(str, format, ap);
if (str[size - 1] || res < 0 || size_t(res) >= size)
abort(); /* Overflowed! */
va_end(ap);
return res;
}
#else
#define my_snprintf SNPRINTF
#endif
static bool query_parsed = false;
static bool done_query = false;
static Xapian::docid last = 0;
static Xapian::MSet mset;
static map<Xapian::docid, bool> ticked;
static void ensure_query_parsed();
static void ensure_match();
static Xapian::Query query;
//static string url_query_string;
Xapian::Query::op default_op = Xapian::Query::OP_AND; // default matching mode
static Xapian::QueryParser qp;
static Xapian::NumberValueRangeProcessor * size_vrp = NULL;
static Xapian::Stem *stemmer = NULL;
static string eval_file(const string &fmtfile);
static set<string> termset;
// Holds mapping from term prefix to user prefix (e.g. 'S' -> 'subject:').
static map<string, string> termprefix_to_userprefix;
static string queryterms;
static string error_msg;
static double secs = -1;
static const char DEFAULT_LOG_ENTRY[] =
"$or{$env{REMOTE_HOST},$env{REMOTE_ADDR},-}\t"
"[$date{$now,%d/%b/%Y:%H:%M:%S} +0000]\t"
"$if{$cgi{X},add,$if{$cgi{MORELIKE},morelike,query}}\t"
"$dbname\t"
"$query\t"
"$msize$if{$env{HTTP_REFERER},\t$env{HTTP_REFERER}}";
class MyStopper : public Xapian::Stopper {
public:
bool operator()(const string &t) const {
switch (t[0]) {
case 'a':
return (t == "a" || t == "about" || t == "an" || t == "and" ||
t == "are" || t == "as" || t == "at");
case 'b':
return (t == "be" || t == "by");
case 'e':
return (t == "en");
case 'f':
return (t == "for" || t == "from");
case 'h':
return (t == "how");
case 'i':
return (t == "i" || t == "in" || t == "is" || t == "it");
case 'o':
return (t == "of" || t == "on" || t == "or");
case 't':
return (t == "that" || t == "the" || t == "this" || t == "to");
case 'w':
return (t == "was" || t == "what" || t == "when" ||
t == "where" || t == "which" || t == "who" ||
t == "why" || t == "will" || t == "with");
case 'y':
return (t == "you" || t == "your");
default:
return false;
}
}
};
static size_t
prefix_from_term(string &prefix, const string &term)
{
if (term.empty()) {
prefix.resize(0);
return 0;
}
if (term[0] == 'X') {
const string::const_iterator begin = term.begin();
string::const_iterator i = begin + 1;
while (i != term.end() && isupper(static_cast<unsigned char>(*i))) ++i;
prefix.assign(begin, i);
if (i != term.end() && *i == ':') ++i;
return i - begin;
}
prefix = term[0];
return 1;
}
// Don't allow ".." in format names, log file names, etc as this would allow
// people to open a format "../../etc/passwd" or similar.
// FIXME: make this check more exact ("foo..bar" is safe)
// FIXME: log when this check fails
static bool
vet_filename(const string &filename)
{
string::size_type i = filename.find("..");
return (i == string::npos);
}
// Heuristics:
// * If any terms have been removed, it's a "fresh query" so we discard any
// relevance judgements
// * If all previous terms are there but more have been added then we keep
// the relevance judgements, but return the first page of hits
//
// NEW_QUERY entirely new query
// SAME_QUERY unchanged query
// EXTENDED_QUERY new query, but based on the old one
// BAD_QUERY parse error (message in error_msg)
typedef enum { NEW_QUERY, SAME_QUERY, EXTENDED_QUERY, BAD_QUERY } querytype;
static map<string, string> probabilistic_query;
void
set_probabilistic_query(const string & prefix, const string & s)
{
string query_string = s;
// Strip leading and trailing whitespace from query_string.
trim(query_string);
if (!query_string.empty())
probabilistic_query.insert(make_pair(prefix, query_string));
}
static unsigned
read_qp_flags(const string & opt_pfx, unsigned f)
{
map<string, string>::const_iterator i = option.lower_bound(opt_pfx);
for (; i != option.end() && startswith(i->first, opt_pfx); ++i) {
unsigned mask = 0;
const char * s = i->first.c_str() + opt_pfx.size();
switch (s[0]) {
case 'a':
if (strcmp(s, "auto_multiword_synonyms") == 0) {
mask = Xapian::QueryParser::FLAG_AUTO_MULTIWORD_SYNONYMS;
break;
}
if (strcmp(s, "auto_synonyms") == 0) {
mask = Xapian::QueryParser::FLAG_AUTO_SYNONYMS;
break;
}
break;
case 'b':
if (strcmp(s, "boolean") == 0) {
mask = Xapian::QueryParser::FLAG_BOOLEAN;
break;
}
if (strcmp(s, "boolean_any_case") == 0) {
mask = Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE;
break;
}
break;
case 'd':
if (strcmp(s, "default") == 0) {
mask = Xapian::QueryParser::FLAG_DEFAULT;
break;
}
break;
case 'l':
if (strcmp(s, "lovehate") == 0) {
mask = Xapian::QueryParser::FLAG_LOVEHATE;
break;
}
break;
case 'p':
if (strcmp(s, "partial") == 0) {
mask = Xapian::QueryParser::FLAG_PARTIAL;
break;
}
if (strcmp(s, "phrase") == 0) {
mask = Xapian::QueryParser::FLAG_PHRASE;
break;
}
if (strcmp(s, "pure_not") == 0) {
mask = Xapian::QueryParser::FLAG_PURE_NOT;
break;
}
break;
case 's':
if (strcmp(s, "spelling_correction") == 0) {
mask = Xapian::QueryParser::FLAG_SPELLING_CORRECTION;
break;
}
if (strcmp(s, "synonym") == 0) {
mask = Xapian::QueryParser::FLAG_SYNONYM;
break;
}
break;
case 'w':
if (strcmp(s, "wildcard") == 0) {
mask = Xapian::QueryParser::FLAG_WILDCARD;
break;
}
break;
}
if (i->second.empty()) {
f &= ~mask;
} else {
f |= mask;
}
}
return f;
}
static querytype
set_probabilistic(const string &oldp)
{
// Parse the query string.
qp.set_stemming_strategy(option["stem_all"] == "true" ? Xapian::QueryParser::STEM_ALL : Xapian::QueryParser::STEM_SOME);
qp.set_stopper(new MyStopper());
qp.set_default_op(default_op);
qp.set_database(db);
// FIXME: provide a custom VRP which handles size:10..20K, etc.
if (!size_vrp)
size_vrp = new Xapian::NumberValueRangeProcessor(VALUE_SIZE, "size:",
true);
qp.add_valuerangeprocessor(size_vrp);
map<string, string>::const_iterator pfx = option.lower_bound("prefix,");
for (; pfx != option.end() && startswith(pfx->first, "prefix,"); ++pfx) {
string user_prefix(pfx->first, 7);
const string & term_pfx_list = pfx->second;
string::size_type i = 0;
do {
string::size_type i0 = i;
i = term_pfx_list.find('\t', i);
const string & term_pfx = term_pfx_list.substr(i0, i - i0);
qp.add_prefix(user_prefix, term_pfx);
// std::map::insert() won't overwrite an existing entry, so we'll
// prefer the first user_prefix for which a particular term prefix
// is specified.
termprefix_to_userprefix.insert(make_pair(term_pfx, user_prefix));
} while (++i);
}
pfx = option.lower_bound("boolprefix,");
for (; pfx != option.end() && startswith(pfx->first, "boolprefix,"); ++pfx) {
string user_prefix = pfx->first.substr(11);
qp.add_boolean_prefix(user_prefix, pfx->second);
termprefix_to_userprefix.insert(make_pair(pfx->second, user_prefix));
}
try {
unsigned default_flags = read_qp_flags("flag_", 0);
if (option["spelling"] == "true")
default_flags |= qp.FLAG_SPELLING_CORRECTION;
vector<Xapian::Query> queries;
queries.reserve(probabilistic_query.size());
map<string, string>::const_iterator j;
for (j = probabilistic_query.begin();
j != probabilistic_query.end();
++j) {
const string & prefix = j->first;
// Choose the stemmer to use for this input.
string stemlang = option[prefix + ":stemmer"];
if (stemlang.empty())
stemlang = option["stemmer"];
qp.set_stemmer(Xapian::Stem(stemlang));
// Work out the flags to use for this input.
unsigned f = read_qp_flags(prefix + ":flag_", default_flags);
const string & query_string = j->second;
queries.push_back(qp.parse_query(query_string, f, prefix));
}
query = Xapian::Query(query.OP_AND, queries.begin(), queries.end());
} catch (Xapian::QueryParserError &e) {
error_msg = e.get_msg();
return BAD_QUERY;
}
Xapian::termcount n_new_terms = 0;
for (Xapian::TermIterator i = query.get_terms_begin();
i != query.get_terms_end(); ++i) {
if (termset.find(*i) == termset.end()) {
termset.insert(*i);
if (!queryterms.empty()) queryterms += '\t';
queryterms += *i;
}
n_new_terms++;
}
// Check new query against the previous one
if (oldp.empty()) {
// FIXME: should take into account other probabilistic prefixes here...
return probabilistic_query[string()].empty() ? SAME_QUERY : NEW_QUERY;
}
// The terms in oldp are separated by tabs.
const char oldp_separator = '\t';
size_t n_old_terms = count(oldp.begin(), oldp.end(), oldp_separator) + 1;
// short-cut: if the new query has fewer terms, it must be a new one
if (n_new_terms < n_old_terms) return NEW_QUERY;
const char *term = oldp.c_str();
const char *pend;
while ((pend = strchr(term, oldp_separator)) != NULL) {
if (termset.find(string(term, pend - term)) == termset.end())
return NEW_QUERY;
term = pend + 1;
}
if (*term) {
if (termset.find(string(term)) == termset.end())
return NEW_QUERY;
}
// Use termset.size() rather than n_new_terms so we correctly handle
// the case when the query has repeated terms.
// This works wrongly in the case when the user extends the query
// by adding a term already in it, but that's unlikely and the behaviour
// isn't too bad (we just don't reset page 1). We also mishandle a few
// other obscure cases e.g. adding quotes to turn a query into a phrase.
if (termset.size() > n_old_terms) return EXTENDED_QUERY;
return SAME_QUERY;
}
static multimap<string, string> filter_map;
typedef multimap<string, string>::const_iterator FMCI;
void add_bterm(const string &term) {
string prefix;
if (prefix_from_term(prefix, term) > 0)
filter_map.insert(multimap<string, string>::value_type(prefix, term));
}
static void
run_query()
{
bool force_boolean = false;
if (!filter_map.empty()) {
// OR together filters with the same prefix, then AND together
vector<Xapian::Query> filter_vec;
vector<string> or_vec;
string current;
for (FMCI i = filter_map.begin(); ; i++) {
bool over = (i == filter_map.end());
if (over || i->first != current) {
switch (or_vec.size()) {
case 0:
break;
case 1:
filter_vec.push_back(Xapian::Query(or_vec[0]));
break;
default:
filter_vec.push_back(Xapian::Query(Xapian::Query::OP_OR,
or_vec.begin(),
or_vec.end()));
break;
}
or_vec.clear();
if (over) break;
current = i->first;
}
or_vec.push_back(i->second);
}
Xapian::Query filter(Xapian::Query::OP_AND,
filter_vec.begin(), filter_vec.end());
if (query.empty()) {
// If no probabilistic query is provided then promote the filters
// to be THE query - filtering an empty query will give no
// matches.
std::swap(query, filter);
if (enquire) force_boolean = true;
} else {
query = Xapian::Query(Xapian::Query::OP_FILTER, query, filter);
}
}
Xapian::MatchDecider * mdecider = NULL;
if (!date_start.empty() || !date_end.empty() || !date_span.empty()) {
MCI i = cgi_params.find("DATEVALUE");
if (i != cgi_params.end()) {
Xapian::valueno datevalue = string_to_int(i->second);
mdecider = new DateMatchDecider(datevalue, date_start, date_end, date_span);
} else {
Xapian::Query date_filter(Xapian::Query::OP_OR,
date_range_filter(date_start, date_end,
date_span),
Xapian::Query("Dlatest"));
// If no probabilistic query is provided then promote the daterange
// filter to be THE query instead of filtering an empty query.
if (query.empty()) {
query = date_filter;
} else {
query = Xapian::Query(Xapian::Query::OP_FILTER, query, date_filter);
}
}
}
if (!enquire || !error_msg.empty()) return;
set_weighting_scheme(*enquire, option, force_boolean);
enquire->set_cutoff(threshold);
if (sort_key != Xapian::BAD_VALUENO) {
if (sort_after) {
enquire->set_sort_by_relevance_then_value(sort_key, sort_ascending);
} else {
enquire->set_sort_by_value_then_relevance(sort_key, sort_ascending);
}
}
enquire->set_docid_order(docid_order);
if (collapse) {
enquire->set_collapse_key(collapse_key);
}
if (!query.empty()) {
#if 0
// FIXME: If we start doing permissions checks based on $REMOTE_USER
// we're going to break some existing setups if users upgrade. We
// probably want a way to set this from OmegaScript.
const char * remote_user = getenv("REMOTE_USER");
if (remote_user)
apply_unix_permissions(query, remote_user);
#endif
enquire->set_query(query);
// We could use the value of topdoc as first parameter, but we
// need to know the first few items in the mset to fake a
// relevance set for topterms.
//
// If min_hits isn't set, check at least one extra result so we
// know if we've reached the end of the matches or not - then we
// can avoid offering a "next" button which leads to an empty page.
mset = enquire->get_mset(0, topdoc + hits_per_page,
topdoc + max(hits_per_page + 1, min_hits),
&rset, mdecider);
}
}
string
html_escape(const string &str)
{
string res;
string::size_type p = 0;
while (p < str.size()) {
char ch = str[p++];
switch (ch) {
case '<':
res += "<";
continue;
case '>':
res += ">";
continue;
case '&':
res += "&";
continue;
case '"':
res += """;
continue;
default:
res += ch;
}
}
return res;
}
static string
html_strip(const string &str)
{
string res;
string::size_type p = 0;
bool skip = false;
while (p < str.size()) {
char ch = str[p++];
switch (ch) {
case '<':
skip = true;
continue;
case '>':
skip = false;
continue;
default:
if (! skip) res += ch;
}
}
return res;
}
// FIXME split list into hash or map and use that rather than linear lookup?
static int word_in_list(const string& word, const string& list)
{
string::size_type split = 0, split2;
int count = 0;
while ((split2 = list.find('\t', split)) != string::npos) {
if (word.size() == split2 - split) {
if (memcmp(word.data(), list.data() + split, word.size()) == 0)
return count;
}
split = split2 + 1;
++count;
}
if (word.size() == list.size() - split) {
if (memcmp(word.data(), list.data() + split, word.size()) == 0)
return count;
}
return -1;
}
// Not a character in an identifier
inline static bool
p_notid(unsigned int c)
{
return !isalnum(static_cast<unsigned char>(c)) && c != '_';
}
// Not a character in an HTML tag name
inline static bool
p_nottag(unsigned int c)
{
return !isalnum(static_cast<unsigned char>(c)) && c != '.' && c != '-';
}
inline static bool
p_plusminus(unsigned int c)
{
return c == '+' || c == '-';
}
// FIXME: shares algorithm with indextext.cc!
static string
html_highlight(const string &s, const string &list,
const string &bra, const string &ket)
{
if (!stemmer) {
stemmer = new Xapian::Stem(option["stemmer"]);
}
string res;
Utf8Iterator j(s);
const Utf8Iterator s_end;
while (true) {
Utf8Iterator first = j;
while (first != s_end && !is_wordchar(*first)) ++first;
if (first == s_end) break;
Utf8Iterator term_end;
string term;
string word;
const char *l = j.raw();
if (*first < 128 && isupper(*first)) {
j = first;
Xapian::Unicode::append_utf8(term, *j);
while (++j != s_end && *j == '.' && ++j != s_end && *j < 128 && isupper(*j)) {
Xapian::Unicode::append_utf8(term, *j);
}
if (term.length() < 2 || (j != s_end && is_wordchar(*j))) {
term.resize(0);
}
term_end = j;
}
if (term.empty()) {
j = first;
while (is_wordchar(*j)) {
Xapian::Unicode::append_utf8(term, *j);
++j;
if (j == s_end) break;
if (*j == '&' || *j == '\'') {
Utf8Iterator next = j;
++next;
if (next == s_end || !is_wordchar(*next)) break;
term += *j;
j = next;
}
}
term_end = j;
if (j != s_end && (*j == '+' || *j == '-' || *j == '#')) {
string::size_type len = term.length();
if (*j == '#') {
term += '#';
do { ++j; } while (j != s_end && *j == '#');
} else {
while (j != s_end && (*j == '+' || *j == '-')) {
Xapian::Unicode::append_utf8(term, *j);
++j;
}
}
if (term.size() - len > 3 || (j != s_end && is_wordchar(*j))) {
term.resize(len);
} else {
term_end = j;
}
}
}
j = term_end;
term = Xapian::Unicode::tolower(term);
int match = word_in_list(term, list);
if (match == -1) {
string stem = "Z";
stem += (*stemmer)(term);
match = word_in_list(stem, list);
}
if (match >= 0) {
res += html_escape(string(l, first.raw() - l));
if (!bra.empty()) {
res += bra;
} else {
static const char * colours[] = {
"ffff66", "99ff99", "99ffff", "ff66ff", "ff9999",
"990000", "009900", "996600", "006699", "990099"
};
size_t idx = match % (sizeof(colours) / sizeof(colours[0]));
const char * bg = colours[idx];
if (strchr(bg, 'f')) {
res += "<b style=\"color:black;background-color:#";
} else {
res += "<b style=\"color:white;background-color:#";
}
res += bg;
res += "\">";
}
word = string(first.raw(), j.raw() - first.raw());
res += html_escape(word);
if (!bra.empty()) {
res += ket;
} else {
res += "</b>";
}
} else {
res += html_escape(string(l, j.raw() - l));
}
}
if (j != s_end) res += html_escape(string(j.raw(), j.left()));
return res;
}
#if 0
static void
print_query_string(const char *after)
{
if (after && strncmp(after, "&B=", 3) == 0) {
char prefix = after[3];
string::size_type start = 0, amp = 0;
while (true) {
amp = url_query_string.find('&', amp);
if (amp == string::npos) {
cout << url_query_string.substr(start);
return;
}
amp++;
while (url_query_string[amp] == 'B' &&
url_query_string[amp + 1] == '=' &&
url_query_string[amp + 2] == prefix) {
cout << url_query_string.substr(start, amp - start - 1);
start = url_query_string.find('&', amp + 3);
if (start == string::npos) return;
amp = start + 1;
}
}
}
cout << url_query_string;
}
#endif
class Fields {
mutable Xapian::docid did_cached;
mutable map<string, string> fields;
void read_fields(Xapian::docid did) const;
public:
Fields() : did_cached(0) { }
const string & get_field(Xapian::docid did, const string & field) const {
if (did != did_cached) read_fields(did);
return fields[field];
}
};
void
Fields::read_fields(Xapian::docid did) const
{
fields.clear();
did_cached = did;
const string & data = db.get_document(did).get_data();
// Parse document data.
string::size_type i = 0;
const string & names = option["fieldnames"];
if (!names.empty()) {
// Each line is a field, with fieldnames taken from corresponding
// entries in the tab-separated list specified by $opt{fieldnames}.
string::size_type n = 0;
do {
string::size_type n0 = n;
n = names.find('\t', n);
string::size_type i0 = i;
i = data.find('\n', i);
fields.insert(make_pair(names.substr(n0, n - n0),
data.substr(i0, i - i0)));
} while (++n && ++i);
} else {
// Each line is a field, in the format NAME=VALUE. We assume the field
// name doesn't contain an "=". Lines without an "=" are currently
// just ignored.
do {
string::size_type i0 = i;
i = data.find('\n', i);
string line = data.substr(i0, i - i0);
string::size_type j = line.find('=');
if (j != string::npos) {
string & value = fields[line.substr(0, j)];
if (!value.empty()) value += '\t';
value += line.substr(j + 1);
}
} while (++i);
}
}
static Fields fields;
static Xapian::docid q0;
static Xapian::doccount hit_no;
static int percent;
static double weight;
static Xapian::doccount collapsed;
static string print_caption(const string &fmt, const vector<string> ¶m);
enum tagval {
CMD_,
CMD_add,
CMD_addfilter,
CMD_allterms,
CMD_and,
CMD_cgi,
CMD_cgilist,
CMD_collapsed,
CMD_date,
CMD_dbname,
CMD_dbsize,
CMD_def,
CMD_defaultop,
CMD_div,
CMD_eq,
CMD_emptydocs,
CMD_env,
CMD_error,
CMD_field,
CMD_filesize,
CMD_filters,
CMD_filterterms,
CMD_find,
CMD_fmt,
CMD_freq,
CMD_ge,
CMD_gt,
CMD_highlight,
CMD_hit,
CMD_hitlist,
CMD_hitsperpage,
CMD_hostname,
CMD_html,
CMD_htmlstrip,
CMD_httpheader,
CMD_id,
CMD_if,
CMD_include,
CMD_json,
CMD_jsonarray,
CMD_last,
CMD_lastpage,
CMD_le,
CMD_length,
CMD_list,
CMD_log,
CMD_lookup,
CMD_lower,
CMD_lt,
CMD_map,
CMD_max,
CMD_min,
CMD_mod,
CMD_msize,
CMD_msizeexact,
CMD_mul,
CMD_muldiv,
CMD_ne,
CMD_nice,
CMD_not,
CMD_now,
CMD_opt,
CMD_or,
CMD_pack,
CMD_percentage,
CMD_prettyterm,
CMD_prettyurl,
CMD_query,
CMD_querydescription,
CMD_queryterms,
CMD_range,
CMD_record,
CMD_relevant,
CMD_relevants,
CMD_score,
CMD_set,
CMD_setmap,
CMD_setrelevant,
CMD_slice,
CMD_split,
CMD_stoplist,
CMD_sub,
CMD_substr,
CMD_suggestion,
CMD_terms,
CMD_thispage,
CMD_time,
CMD_topdoc,
CMD_topterms,
CMD_transform,
CMD_truncate,
CMD_uniq,
CMD_unpack,
CMD_unstem,
CMD_upper,
CMD_url,
CMD_value,
CMD_version,
CMD_weight,
CMD_MACRO // special tag for macro evaluation
};
struct func_attrib {
int tag;
int minargs, maxargs, evalargs;
char ensure;
};
#define T(F,A,B,C,D) {STRINGIZE(F),{CMD_##F,A,B,C,D}}
struct func_desc {
const char *name;
struct func_attrib a;
};
#define N -1
#define M 'M'
#define Q 'Q'
// NB when adding a new command which ensures M or Q, update the list in
// docs/omegascript.rst
static struct func_desc func_tab[] = {
//name minargs maxargs evalargs ensure
{"",{CMD_, N, N, 0, 0}},// commented out code
T(add, 0, N, N, 0), // add a list of numbers
T(addfilter, 1, 1, N, 0), // add filter term
T(allterms, 0, 1, N, 0), // list of all terms matching document
T(and, 1, N, 0, 0), // logical shortcutting and of a list of values
T(cgi, 1, 1, N, 0), // return cgi parameter value
T(cgilist, 1, 1, N, 0), // return list of values for cgi parameter
T(collapsed, 0, 0, N, 0), // return number of hits collapsed into this
T(date, 1, 2, N, 0), // convert time_t to strftime format
// (default: YYYY-MM-DD)
T(dbname, 0, 0, N, 0), // database name
T(dbsize, 0, 0, N, 0), // database size (# of documents)
T(def, 2, 2, 1, 0), // define a macro
T(defaultop, 0, 0, N, 0), // default operator: "and" or "or"
T(div, 2, 2, N, 0), // integer divide
T(emptydocs, 0, 1, N, 0), // list of empty documents
T(env, 1, 1, N, 0), // environment variable
T(error, 0, 0, N, 0), // error message
T(eq, 2, 2, N, 0), // test equality
T(field, 1, 2, N, 0), // lookup field in record
T(filesize, 1, 1, N, 0), // pretty printed filesize
T(filters, 0, 0, N, 0), // serialisation of current filters
T(filterterms, 1, 1, N, 0), // list of terms with a given prefix
T(find, 2, 2, N, 0), // find entry in list
T(fmt, 0, 0, N, 0), // name of current format
T(freq, 1, 1, N, 0), // frequency of a term
T(ge, 2, 2, N, 0), // test >=
T(gt, 2, 2, N, 0), // test >
T(highlight, 2, 4, N, 0), // html escape and highlight words from list
T(hit, 0, 0, N, 0), // hit number of current mset entry (starting
// from 0
T(hitlist, 1, 1, 0, M), // display hitlist using format in argument
T(hitsperpage, 0, 0, N, 0), // hits per page
T(hostname, 1, 1, N, 0), // extract hostname from URL
T(html, 1, 1, N, 0), // html escape string (<>&")
T(htmlstrip, 1, 1, N, 0), // html strip tags string (s/<[^>]*>?//g)
T(httpheader, 2, 2, N, 0), // arbitrary HTTP header
T(id, 0, 0, N, 0), // docid of current doc
T(if, 2, 3, 1, 0), // conditional
T(include, 1, 1, 1, 0), // include another file
T(json, 1, 1, N, 0), // JSON string escaping
T(jsonarray, 1, 1, N, 0), // Format list as a JSON array of strings
T(last, 0, 0, N, M), // m-set number of last hit on page
T(lastpage, 0, 0, N, M), // number of last hit page
T(le, 2, 2, N, 0), // test <=
T(length, 1, 1, N, 0), // length of list
T(list, 2, 5, N, 0), // pretty print list
T(log, 1, 2, 1, 0), // create a log entry
T(lookup, 2, 2, N, 0), // lookup in named cdb file
T(lower, 1, 1, N, 0), // convert string to lower case