Drop special handling for Compaq C++
[xapian.git] / xapian-applications / omega / query.cc
blob06c075da6154ba41ebc02ccf145badb9e38629c7
1 /* query.cc: query executor for omega
3 * Copyright 1999,2000,2001 BrightStation PLC
4 * Copyright 2001 James Aylett
5 * Copyright 2001,2002 Ananova Ltd
6 * Copyright 2002 Intercede 1749 Ltd
7 * Copyright 2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2013,2014,2015,2016,2017,2018 Olly Betts
8 * Copyright 2008 Thomas Viehmann
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License as
12 * published by the Free Software Foundation; either version 2 of the
13 * License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
23 * USA
26 #include <config.h>
28 #include <algorithm>
29 #include <iostream>
30 #include <map>
31 #include <set>
32 #include <unordered_map>
33 #include <unordered_set>
34 #include <vector>
36 #include <cassert>
37 #include <cctype>
38 #include <cerrno>
39 #include <stdio.h>
40 #include <cstdlib>
41 #include <cstring>
42 #include "strcasecmp.h"
43 #include <ctime>
45 #include "safeunistd.h"
46 #include <sys/types.h>
47 #include "safesysstat.h"
48 #include "safefcntl.h"
50 #include "realtime.h"
52 #include <cdb.h>
54 #include "csvescape.h"
55 #include "date.h"
56 #include "datevalue.h"
57 #include "fields.h"
58 #include "jsonescape.h"
59 #include "utils.h"
60 #include "omega.h"
61 #include "query.h"
62 #include "cgiparam.h"
63 #include "loadfile.h"
64 #include "sample.h"
65 #include "sort.h"
66 #include "str.h"
67 #include "stringutils.h"
68 #include "transform.h"
69 #include "urldecode.h"
70 #include "urlencode.h"
71 #include "unixperm.h"
72 #include "values.h"
73 #include "weight.h"
74 #include "expand.h"
75 #include "md5wrap.h"
77 #include <xapian.h>
79 using namespace std;
81 using Xapian::Utf8Iterator;
83 using Xapian::Unicode::is_wordchar;
85 #ifndef SNPRINTF
86 #include <cstdarg>
88 static int my_snprintf(char *str, size_t size, const char *format, ...)
90 int res;
91 va_list ap;
92 va_start(ap, format);
93 str[size - 1] = '\0';
94 res = vsprintf(str, format, ap);
95 if (str[size - 1] || res < 0 || size_t(res) >= size)
96 abort(); /* Overflowed! */
97 va_end(ap);
98 return res;
100 #else
101 #define my_snprintf SNPRINTF
102 #endif
104 static bool query_parsed = false;
105 static bool done_query = false;
106 static Xapian::docid last = 0;
108 static Xapian::MSet mset;
110 static map<Xapian::docid, bool> ticked;
112 static void ensure_query_parsed();
113 static void ensure_match();
115 static Xapian::Query query;
116 //static string url_query_string;
117 Xapian::Query::op default_op = Xapian::Query::OP_AND; // default matching mode
119 // Maintain an explicit date_filter_set flag - date_filter.empty() will also
120 // be true if a date filter is specified which simplies to Query::MatchNothing
121 // at construction time.
122 static bool date_filter_set = false;
123 static Xapian::Query date_filter;
125 static Xapian::QueryParser qp;
126 static Xapian::NumberRangeProcessor * size_rp = NULL;
127 static Xapian::Stem *stemmer = NULL;
129 static string eval_file(const string &fmtfile);
131 static set<string> termset;
133 // Holds mapping from term prefix to user prefix (e.g. 'S' -> 'subject:').
134 static map<string, string> termprefix_to_userprefix;
136 static string queryterms;
138 static string error_msg;
140 static double secs = -1;
142 static const char DEFAULT_LOG_ENTRY[] =
143 "$or{$env{REMOTE_HOST},$env{REMOTE_ADDR},-}\t"
144 "[$date{$now,%d/%b/%Y:%H:%M:%S} +0000]\t"
145 "$if{$cgi{X},add,$if{$cgi{MORELIKE},morelike,query}}\t"
146 "$dbname\t"
147 "$query\t"
148 "$msize$if{$env{HTTP_REFERER},\t$env{HTTP_REFERER}}";
150 class MyStopper : public Xapian::Stopper {
151 public:
152 bool operator()(const string &t) const {
153 switch (t[0]) {
154 case 'a':
155 return (t == "a" || t == "about" || t == "an" || t == "and" ||
156 t == "are" || t == "as" || t == "at");
157 case 'b':
158 return (t == "be" || t == "by");
159 case 'e':
160 return (t == "en");
161 case 'f':
162 return (t == "for" || t == "from");
163 case 'h':
164 return (t == "how");
165 case 'i':
166 return (t == "i" || t == "in" || t == "is" || t == "it");
167 case 'o':
168 return (t == "of" || t == "on" || t == "or");
169 case 't':
170 return (t == "that" || t == "the" || t == "this" || t == "to");
171 case 'w':
172 return (t == "was" || t == "what" || t == "when" ||
173 t == "where" || t == "which" || t == "who" ||
174 t == "why" || t == "will" || t == "with");
175 case 'y':
176 return (t == "you" || t == "your");
177 default:
178 return false;
183 static size_t
184 prefix_from_term(string* prefix, const string& term)
186 if (!term.empty()) {
187 if (term[0] == 'X') {
188 const string::const_iterator begin = term.begin();
189 string::const_iterator i = begin + 1;
190 while (i != term.end() && C_isupper(*i))
191 ++i;
192 if (prefix)
193 prefix->assign(begin, i);
194 if (i != term.end() && *i == ':')
195 ++i;
196 return i - begin;
199 if (C_isupper(term[0])) {
200 if (prefix)
201 *prefix = term[0];
202 return 1;
206 if (prefix)
207 prefix->resize(0);
208 return 0;
211 // Don't allow ".." in format names, log file names, etc as this would allow
212 // people to open a format "../../etc/passwd" or similar.
213 // FIXME: make this check more exact ("foo..bar" is safe)
214 // FIXME: log when this check fails
215 static bool
216 vet_filename(const string &filename)
218 string::size_type i = filename.find("..");
219 return (i == string::npos);
222 // Heuristics:
223 // * If any terms have been removed, it's a "fresh query" so we discard any
224 // relevance judgements
225 // * If all previous terms are there but more have been added then we keep
226 // the relevance judgements, but return the first page of hits
228 // NEW_QUERY entirely new query
229 // SAME_QUERY unchanged query
230 // EXTENDED_QUERY new query, but based on the old one
231 // BAD_QUERY parse error (message in error_msg)
232 typedef enum { NEW_QUERY, SAME_QUERY, EXTENDED_QUERY, BAD_QUERY } querytype;
234 static multimap<string, string> query_strings;
236 void
237 add_query_string(const string& prefix, const string& s)
239 string query_string = s;
240 // Strip leading and trailing whitespace from query_string.
241 trim(query_string);
242 if (!query_string.empty())
243 query_strings.insert(make_pair(prefix, query_string));
246 static unsigned
247 read_qp_flags(const string & opt_pfx, unsigned f)
249 map<string, string>::const_iterator i = option.lower_bound(opt_pfx);
250 for (; i != option.end() && startswith(i->first, opt_pfx); ++i) {
251 unsigned mask = 0;
252 const char * s = i->first.c_str() + opt_pfx.size();
253 switch (s[0]) {
254 case 'a':
255 if (strcmp(s, "auto_multiword_synonyms") == 0) {
256 mask = Xapian::QueryParser::FLAG_AUTO_MULTIWORD_SYNONYMS;
257 break;
259 if (strcmp(s, "auto_synonyms") == 0) {
260 mask = Xapian::QueryParser::FLAG_AUTO_SYNONYMS;
261 break;
263 break;
264 case 'b':
265 if (strcmp(s, "boolean") == 0) {
266 mask = Xapian::QueryParser::FLAG_BOOLEAN;
267 break;
269 if (strcmp(s, "boolean_any_case") == 0) {
270 mask = Xapian::QueryParser::FLAG_BOOLEAN_ANY_CASE;
271 break;
273 break;
274 case 'c':
275 if (strcmp(s, "cjk_ngram") == 0) {
276 mask = Xapian::QueryParser::FLAG_CJK_NGRAM;
277 break;
279 break;
280 case 'd':
281 if (strcmp(s, "default") == 0) {
282 mask = Xapian::QueryParser::FLAG_DEFAULT;
283 break;
285 break;
286 case 'l':
287 if (strcmp(s, "lovehate") == 0) {
288 mask = Xapian::QueryParser::FLAG_LOVEHATE;
289 break;
291 break;
292 case 'p':
293 if (strcmp(s, "partial") == 0) {
294 mask = Xapian::QueryParser::FLAG_PARTIAL;
295 break;
297 if (strcmp(s, "phrase") == 0) {
298 mask = Xapian::QueryParser::FLAG_PHRASE;
299 break;
301 if (strcmp(s, "pure_not") == 0) {
302 mask = Xapian::QueryParser::FLAG_PURE_NOT;
303 break;
305 break;
306 case 's':
307 if (strcmp(s, "spelling_correction") == 0) {
308 mask = Xapian::QueryParser::FLAG_SPELLING_CORRECTION;
309 break;
311 if (strcmp(s, "synonym") == 0) {
312 mask = Xapian::QueryParser::FLAG_SYNONYM;
313 break;
315 break;
316 case 'w':
317 if (strcmp(s, "wildcard") == 0) {
318 mask = Xapian::QueryParser::FLAG_WILDCARD;
319 break;
321 break;
324 if (i->second.empty()) {
325 f &= ~mask;
326 } else {
327 f |= mask;
330 return f;
333 static querytype
334 parse_queries(const string& oldp)
336 // Parse the query string.
337 auto opt_it = option.find("stem_strategy");
338 if (opt_it != option.end()) {
339 if (opt_it->second == "all") {
340 qp.set_stemming_strategy(Xapian::QueryParser::STEM_ALL);
341 } else if (opt_it->second == "all_z") {
342 qp.set_stemming_strategy(Xapian::QueryParser::STEM_ALL_Z);
343 } else if (opt_it->second == "none") {
344 qp.set_stemming_strategy(Xapian::QueryParser::STEM_NONE);
345 } else if (opt_it->second == "some") {
346 qp.set_stemming_strategy(Xapian::QueryParser::STEM_SOME);
347 } else if (opt_it->second == "some_full_pos") {
348 qp.set_stemming_strategy(Xapian::QueryParser::STEM_SOME_FULL_POS);
350 } else {
351 opt_it = option.find("stem_all");
352 if (opt_it != option.end() && opt_it->second == "true") {
353 qp.set_stemming_strategy(Xapian::QueryParser::STEM_ALL);
356 qp.set_stopper(new MyStopper());
357 qp.set_default_op(default_op);
358 qp.set_database(db);
359 // FIXME: provide a custom RP which handles size:10..20K, etc.
360 if (!size_rp)
361 size_rp = new Xapian::NumberRangeProcessor(VALUE_SIZE, "size:");
362 qp.add_rangeprocessor(size_rp);
363 map<string, string>::const_iterator pfx = option.lower_bound("prefix,");
364 for (; pfx != option.end() && startswith(pfx->first, "prefix,"); ++pfx) {
365 string user_prefix(pfx->first, 7);
366 const string & term_pfx_list = pfx->second;
367 string::size_type i = 0;
368 do {
369 string::size_type i0 = i;
370 i = term_pfx_list.find('\t', i);
371 const string & term_pfx = term_pfx_list.substr(i0, i - i0);
372 qp.add_prefix(user_prefix, term_pfx);
373 // std::map::insert() won't overwrite an existing entry, so we'll
374 // prefer the first user_prefix for which a particular term prefix
375 // is specified.
376 termprefix_to_userprefix.insert(make_pair(term_pfx, user_prefix));
377 } while (++i);
379 pfx = option.lower_bound("boolprefix,");
380 for (; pfx != option.end() && startswith(pfx->first, "boolprefix,"); ++pfx) {
381 string user_prefix(pfx->first, 11, string::npos);
382 auto it = option.find("nonexclusiveprefix," + pfx->second);
383 bool exclusive = (it == option.end() || it->second.empty());
384 qp.add_boolean_prefix(user_prefix, pfx->second, exclusive);
385 termprefix_to_userprefix.insert(make_pair(pfx->second, user_prefix));
388 try {
389 unsigned default_flags = read_qp_flags("flag_", 0);
391 vector<Xapian::Query> queries;
392 queries.reserve(query_strings.size());
394 for (auto& j : query_strings) {
395 const string& prefix = j.first;
396 const string& query_string = j.second;
398 // Choose the stemmer to use for this input.
399 string stemlang = option[prefix + ":stemmer"];
400 if (stemlang.empty())
401 stemlang = option["stemmer"];
402 qp.set_stemmer(Xapian::Stem(stemlang));
404 // Work out the flags to use for this input.
405 unsigned f = read_qp_flags(prefix + ":flag_", default_flags);
407 Xapian::Query q = qp.parse_query(query_string, f, prefix);
408 if (!q.empty())
409 queries.push_back(q);
411 query = Xapian::Query(query.OP_AND, queries.begin(), queries.end());
412 } catch (Xapian::QueryParserError &e) {
413 error_msg = e.get_msg();
414 return BAD_QUERY;
417 Xapian::termcount n_new_terms = 0;
418 for (Xapian::TermIterator i = query.get_terms_begin();
419 i != query.get_terms_end(); ++i) {
420 if (termset.find(*i) == termset.end()) {
421 termset.insert(*i);
422 if (!queryterms.empty()) queryterms += '\t';
423 queryterms += *i;
425 n_new_terms++;
428 // Check new query against the previous one
429 if (oldp.empty()) {
430 // If oldp was empty that means there were no parsed query terms
431 // before, so if there are now this is a new query.
432 return n_new_terms ? NEW_QUERY : SAME_QUERY;
435 // The terms in oldp are separated by tabs.
436 const char oldp_separator = '\t';
437 size_t n_old_terms = count(oldp.begin(), oldp.end(), oldp_separator) + 1;
439 // short-cut: if the new query has fewer terms, it must be a new one
440 if (n_new_terms < n_old_terms) return NEW_QUERY;
442 const char *term = oldp.c_str();
443 const char *pend;
444 while ((pend = strchr(term, oldp_separator)) != NULL) {
445 if (termset.find(string(term, pend - term)) == termset.end())
446 return NEW_QUERY;
447 term = pend + 1;
449 if (*term) {
450 if (termset.find(string(term)) == termset.end())
451 return NEW_QUERY;
454 // Use termset.size() rather than n_new_terms so we correctly handle
455 // the case when the query has repeated terms.
456 // This works wrongly in the case when the user extends the query
457 // by adding a term already in it, but that's unlikely and the behaviour
458 // isn't too bad (we just don't reset page 1). We also mishandle a few
459 // other obscure cases e.g. adding quotes to turn a query into a phrase.
460 if (termset.size() > n_old_terms) return EXTENDED_QUERY;
461 return SAME_QUERY;
464 static multimap<string, string> filter_map;
465 static set<string> neg_filters;
467 void add_bterm(const string &term) {
468 string prefix;
469 if (prefix_from_term(&prefix, term) > 0)
470 filter_map.insert(multimap<string, string>::value_type(prefix, term));
473 void add_nterm(const string &term) {
474 if (!term.empty())
475 neg_filters.insert(term);
478 void
479 add_date_filter(const string& date_start,
480 const string& date_end,
481 const string& date_span,
482 Xapian::valueno date_value_slot)
484 if (date_start.empty() && date_end.empty() && date_span.empty())
485 return;
487 Xapian::Query q;
488 if (date_value_slot != Xapian::BAD_VALUENO) {
489 // The values can be a time_t in 4 bytes, or YYYYMMDD... (with the
490 // latter the sort order just works correctly between different
491 // precisions).
492 bool as_time_t =
493 db.get_value_lower_bound(date_value_slot).size() == 4 &&
494 db.get_value_upper_bound(date_value_slot).size() == 4;
495 q = date_value_range(as_time_t, date_value_slot,
496 date_start, date_end,
497 date_span);
498 } else {
499 q = date_range_filter(date_start, date_end, date_span);
500 q |= Xapian::Query("Dlatest");
503 if (date_filter_set) {
504 date_filter &= q;
505 } else {
506 date_filter_set = true;
507 date_filter = q;
511 static void
512 run_query()
514 string scheme;
515 bool force_boolean = false;
516 if (!filter_map.empty()) {
517 // OR together filters with the same prefix (or AND for non-exclusive
518 // prefixes), then AND together the resultant groups.
519 vector<Xapian::Query> filter_vec;
520 vector<string> same_vec;
521 string current;
522 for (auto i = filter_map.begin(); ; ++i) {
523 bool over = (i == filter_map.end());
524 if (over || i->first != current) {
525 switch (same_vec.size()) {
526 case 0:
527 break;
528 case 1:
529 filter_vec.push_back(Xapian::Query(same_vec[0]));
530 break;
531 default: {
532 Xapian::Query::op op = Xapian::Query::OP_OR;
533 auto it = option.find("nonexclusiveprefix," + current);
534 if (it != option.end() && !it->second.empty()) {
535 op = Xapian::Query::OP_AND;
537 filter_vec.push_back(Xapian::Query(op,
538 same_vec.begin(),
539 same_vec.end()));
540 break;
543 same_vec.clear();
544 if (over) break;
545 current = i->first;
547 same_vec.push_back(i->second);
550 Xapian::Query filter(Xapian::Query::OP_AND,
551 filter_vec.begin(), filter_vec.end());
553 if (query.empty()) {
554 // If no query strings were provided then promote the filters
555 // to be THE query - filtering an empty query will give no
556 // matches.
557 std::swap(query, filter);
558 auto&& it = option.find("weightingpurefilter");
559 if (it != option.end() && !it->second.empty()) {
560 scheme = it->second;
561 } else {
562 force_boolean = true;
564 } else {
565 query = Xapian::Query(Xapian::Query::OP_FILTER, query, filter);
569 if (date_filter_set) {
570 // If no query strings were provided then promote the daterange
571 // filter to be THE query instead of filtering an empty query.
572 if (query.empty()) {
573 query = date_filter;
574 force_boolean = true;
575 } else {
576 query = Xapian::Query(Xapian::Query::OP_FILTER, query, date_filter);
580 if (!neg_filters.empty()) {
581 // OR together all negated filters.
582 Xapian::Query filter(Xapian::Query::OP_OR,
583 neg_filters.begin(), neg_filters.end());
585 if (query.empty() && !date_filter_set) {
586 // If we only have a negative filter for the query, use MatchAll as
587 // the query to apply the filters to.
588 query = Xapian::Query::MatchAll;
589 force_boolean = true;
591 query = Xapian::Query(Xapian::Query::OP_AND_NOT, query, filter);
594 if (!enquire || !error_msg.empty()) return;
596 if (!force_boolean && scheme.empty()) {
597 auto&& it = option.find("weighting");
598 if (it != option.end()) scheme = it->second;
600 set_weighting_scheme(*enquire, scheme, force_boolean);
602 enquire->set_cutoff(threshold);
604 if (sort_keymaker) {
605 if (sort_after) {
606 enquire->set_sort_by_relevance_then_key(sort_keymaker,
607 reverse_sort);
608 } else {
609 enquire->set_sort_by_key_then_relevance(sort_keymaker,
610 reverse_sort);
612 } else if (sort_key != Xapian::BAD_VALUENO) {
613 if (sort_after) {
614 enquire->set_sort_by_relevance_then_value(sort_key, reverse_sort);
615 } else {
616 enquire->set_sort_by_value_then_relevance(sort_key, reverse_sort);
620 enquire->set_docid_order(docid_order);
622 if (collapse) {
623 enquire->set_collapse_key(collapse_key);
626 if (!query.empty()) {
627 #if 0
628 // FIXME: If we start doing permissions checks based on $REMOTE_USER
629 // we're going to break some existing setups if users upgrade. We
630 // probably want a way to set this from OmegaScript.
631 const char * remote_user = getenv("REMOTE_USER");
632 if (remote_user)
633 apply_unix_permissions(query, remote_user);
634 #endif
636 enquire->set_query(query);
637 // We could use the value of topdoc as first parameter, but we
638 // need to know the first few items in the mset to fake a
639 // relevance set for topterms.
641 // If min_hits isn't set, check at least one extra result so we
642 // know if we've reached the end of the matches or not - then we
643 // can avoid offering a "next" button which leads to an empty page.
644 mset = enquire->get_mset(0, topdoc + hits_per_page,
645 topdoc + max(hits_per_page + 1, min_hits),
646 &rset);
650 string
651 html_escape(const string &str)
653 string res;
654 string::size_type p = 0;
655 while (p < str.size()) {
656 char ch = str[p++];
657 switch (ch) {
658 case '<':
659 res += "&lt;";
660 continue;
661 case '>':
662 res += "&gt;";
663 continue;
664 case '&':
665 res += "&amp;";
666 continue;
667 case '"':
668 res += "&quot;";
669 continue;
670 default:
671 res += ch;
674 return res;
677 static string
678 html_strip(const string &str)
680 string res;
681 string::size_type p = 0;
682 bool skip = false;
683 while (p < str.size()) {
684 char ch = str[p++];
685 switch (ch) {
686 case '<':
687 skip = true;
688 continue;
689 case '>':
690 skip = false;
691 continue;
692 default:
693 if (! skip) res += ch;
696 return res;
699 class WordList {
700 static string prev_list;
701 static unordered_map<string, int> word_to_occurrence;
702 public:
703 void build_word_map(const string& list) {
704 // Don't build map again if passed list of terms is same as before.
705 if (prev_list == list) return;
706 word_to_occurrence.clear();
707 string::size_type split = 0, split2;
708 int word_index = 0;
709 string word;
710 while ((split2 = list.find('\t', split)) != string::npos) {
711 word = list.substr(split, split2 - split);
712 if (word_to_occurrence.emplace(make_pair(word, word_index)).second)
713 ++word_index;
714 split = split2 + 1;
716 word = list.substr(split, list.size() - split);
717 if (word_to_occurrence.emplace(make_pair(word, word_index)).second)
718 ++word_index;
719 prev_list = list;
722 int word_in_list(const string& word) {
723 auto it = word_to_occurrence.find(word);
724 if (it == word_to_occurrence.end()) return -1;
725 return it->second;
729 string WordList::prev_list;
730 unordered_map<string, int> WordList::word_to_occurrence;
732 // Not a character in an identifier
733 inline static bool
734 p_notid(unsigned int c)
736 return !C_isalnum(c) && c != '_';
739 // Not a character in an HTML tag name
740 inline static bool
741 p_nottag(unsigned int c)
743 return !C_isalnum(c) && c != '.' && c != '-';
746 // FIXME: shares algorithm with indextext.cc!
747 static string
748 html_highlight(const string &s, const string &list,
749 const string &bra, const string &ket)
751 if (!stemmer) {
752 stemmer = new Xapian::Stem(option["stemmer"]);
755 string res;
757 Utf8Iterator j(s);
758 const Utf8Iterator s_end;
759 while (true) {
760 Utf8Iterator first = j;
761 while (first != s_end && !is_wordchar(*first)) ++first;
762 if (first == s_end) break;
763 Utf8Iterator term_end;
764 string term;
765 string word;
766 const char *l = j.raw();
767 if (*first < 128 && C_isupper(*first)) {
768 j = first;
769 Xapian::Unicode::append_utf8(term, *j);
770 while (++j != s_end && *j == '.' && ++j != s_end && *j < 128 && C_isupper(*j)) {
771 Xapian::Unicode::append_utf8(term, *j);
773 if (term.length() < 2 || (j != s_end && is_wordchar(*j))) {
774 term.resize(0);
776 term_end = j;
778 if (term.empty()) {
779 j = first;
780 while (is_wordchar(*j)) {
781 Xapian::Unicode::append_utf8(term, *j);
782 ++j;
783 if (j == s_end) break;
784 if (*j == '&' || *j == '\'') {
785 Utf8Iterator next = j;
786 ++next;
787 if (next == s_end || !is_wordchar(*next)) break;
788 term += *j;
789 j = next;
792 term_end = j;
793 if (j != s_end && (*j == '+' || *j == '-' || *j == '#')) {
794 string::size_type len = term.length();
795 if (*j == '#') {
796 term += '#';
797 do { ++j; } while (j != s_end && *j == '#');
798 } else {
799 while (j != s_end && (*j == '+' || *j == '-')) {
800 Xapian::Unicode::append_utf8(term, *j);
801 ++j;
804 if (term.size() - len > 3 || (j != s_end && is_wordchar(*j))) {
805 term.resize(len);
806 } else {
807 term_end = j;
811 j = term_end;
812 term = Xapian::Unicode::tolower(term);
813 WordList w;
814 w.build_word_map(list);
815 int match = w.word_in_list(term);
816 if (match == -1) {
817 string stem = "Z";
818 stem += (*stemmer)(term);
819 match = w.word_in_list(stem);
821 if (match >= 0) {
822 res += html_escape(string(l, first.raw() - l));
823 if (!bra.empty()) {
824 res += bra;
825 } else {
826 static const char * colours[] = {
827 "ffff66", "99ff99", "99ffff", "ff66ff", "ff9999",
828 "990000", "009900", "996600", "006699", "990099"
830 size_t idx = match % (sizeof(colours) / sizeof(colours[0]));
831 const char * bg = colours[idx];
832 if (strchr(bg, 'f')) {
833 res += "<b style=\"color:black;background-color:#";
834 } else {
835 res += "<b style=\"color:white;background-color:#";
837 res += bg;
838 res += "\">";
840 word.assign(first.raw(), j.raw() - first.raw());
841 res += html_escape(word);
842 if (!bra.empty()) {
843 res += ket;
844 } else {
845 res += "</b>";
847 } else {
848 res += html_escape(string(l, j.raw() - l));
851 if (j != s_end) res += html_escape(string(j.raw(), j.left()));
852 return res;
855 #if 0
856 static void
857 print_query_string(const char *after)
859 if (after && strncmp(after, "&B=", 3) == 0) {
860 char prefix = after[3];
861 string::size_type start = 0, amp = 0;
862 while (true) {
863 amp = url_query_string.find('&', amp);
864 if (amp == string::npos) {
865 cout << url_query_string.substr(start);
866 return;
868 amp++;
869 while (url_query_string[amp] == 'B' &&
870 url_query_string[amp + 1] == '=' &&
871 url_query_string[amp + 2] == prefix) {
872 cout << url_query_string.substr(start, amp - start - 1);
873 start = url_query_string.find('&', amp + 3);
874 if (start == string::npos) return;
875 amp = start + 1;
879 cout << url_query_string;
881 #endif
883 class CachedFields : private Fields {
884 Xapian::docid did_cached = 0;
886 public:
887 CachedFields() {}
889 const string& get_field(Xapian::docid did, const string& name) {
890 if (did != did_cached) {
891 did_cached = did;
892 auto it = option.find("fieldnames");
893 Fields::parse_fields(db.get_document(did).get_data(),
894 it == option.end() ? nullptr : &it->second);
896 return Fields::get_field(name);
900 static CachedFields fields;
901 static Xapian::docid q0;
902 static Xapian::doccount hit_no;
903 static int percent;
904 static double weight;
905 static Xapian::doccount collapsed;
907 static string print_caption(const string &fmt, const vector<string> &param);
909 enum tagval {
910 CMD_,
911 CMD_add,
912 CMD_addfilter,
913 CMD_allterms,
914 CMD_and,
915 CMD_cgi,
916 CMD_cgilist,
917 CMD_cgiparams,
918 CMD_chr,
919 CMD_collapsed,
920 CMD_cond,
921 CMD_contains,
922 CMD_csv,
923 CMD_date,
924 CMD_dbname,
925 CMD_dbsize,
926 CMD_def,
927 CMD_defaultop,
928 CMD_div,
929 CMD_emptydocs,
930 CMD_env,
931 CMD_eq,
932 CMD_error,
933 CMD_field,
934 CMD_filesize,
935 CMD_filters,
936 CMD_filterterms,
937 CMD_find,
938 CMD_fmt,
939 CMD_freq,
940 CMD_ge,
941 CMD_gt,
942 CMD_hash,
943 CMD_highlight,
944 CMD_hit,
945 CMD_hitlist,
946 CMD_hitsperpage,
947 CMD_hostname,
948 CMD_html,
949 CMD_htmlstrip,
950 CMD_httpheader,
951 CMD_id,
952 CMD_if,
953 CMD_include,
954 CMD_json,
955 CMD_jsonarray,
956 CMD_last,
957 CMD_lastpage,
958 CMD_le,
959 CMD_length,
960 CMD_list,
961 CMD_log,
962 CMD_lookup,
963 CMD_lower,
964 CMD_lt,
965 CMD_map,
966 CMD_match,
967 CMD_max,
968 CMD_min,
969 CMD_mod,
970 CMD_msize,
971 CMD_msizeexact,
972 CMD_msizelower,
973 CMD_msizeupper,
974 CMD_mul,
975 CMD_muldiv,
976 CMD_ne,
977 CMD_nice,
978 CMD_not,
979 CMD_now,
980 CMD_opt,
981 CMD_or,
982 CMD_ord,
983 CMD_pack,
984 CMD_percentage,
985 CMD_prettyterm,
986 CMD_prettyurl,
987 CMD_query,
988 CMD_querydescription,
989 CMD_queryterms,
990 CMD_range,
991 CMD_record,
992 CMD_relevant,
993 CMD_relevants,
994 CMD_score,
995 CMD_set,
996 CMD_seterror,
997 CMD_setmap,
998 CMD_setrelevant,
999 CMD_slice,
1000 CMD_snippet,
1001 CMD_sort,
1002 CMD_split,
1003 CMD_stoplist,
1004 CMD_sub,
1005 CMD_subdb,
1006 CMD_subid,
1007 CMD_substr,
1008 CMD_suggestion,
1009 CMD_switch,
1010 CMD_termprefix,
1011 CMD_terms,
1012 CMD_thispage,
1013 CMD_time,
1014 CMD_topdoc,
1015 CMD_topterms,
1016 CMD_transform,
1017 CMD_truncate,
1018 CMD_uniq,
1019 CMD_unique,
1020 CMD_unpack,
1021 CMD_unprefix,
1022 CMD_unstem,
1023 CMD_upper,
1024 CMD_url,
1025 CMD_value,
1026 CMD_version,
1027 CMD_weight,
1028 CMD_MACRO // special tag for macro evaluation
1031 struct func_attrib {
1032 int tag;
1033 int minargs, maxargs, evalargs;
1034 char ensure;
1037 #define T(F,A,B,C,D) {STRINGIZE(F),{CMD_##F,A,B,C,D}}
1038 struct func_desc {
1039 const char *name;
1040 struct func_attrib a;
1043 #define N -1
1044 #define M 'M'
1045 #define Q 'Q'
1046 // NB when adding a new command which ensures M or Q, update the list in
1047 // docs/omegascript.rst
1048 static struct func_desc func_tab[] = {
1049 //name minargs maxargs evalargs ensure
1050 {"",{CMD_, N, N, 0, 0}},// commented out code
1051 T(add, 0, N, N, 0), // add a list of numbers
1052 T(addfilter, 1, 1, N, 0), // add filter term
1053 T(allterms, 0, 1, N, 0), // list of all terms matching document
1054 T(and, 1, N, 0, 0), // logical shortcutting and of a list of values
1055 T(cgi, 1, 1, N, 0), // return cgi parameter value
1056 T(cgilist, 1, 1, N, 0), // return list of values for cgi parameter
1057 T(cgiparams, 0, 0, N, 0), // return list of cgi parameter names
1058 T(chr, 1, 1, N, 0), // return UTF-8 for given Unicode codepoint
1059 T(collapsed, 0, 0, N, 0), // return number of hits collapsed into this
1060 T(cond, 2, N, 0, 0), // return position of substring, or empty string
1061 T(contains, 2, 2, N, 0), // return position of substring, or empty string
1062 T(csv, 1, 2, N, 0), // CSV string escaping
1063 T(date, 1, 2, N, 0), // convert time_t to strftime format
1064 // (default: YYYY-MM-DD)
1065 T(dbname, 0, 0, N, 0), // database name
1066 T(dbsize, 0, 0, N, 0), // database size (# of documents)
1067 T(def, 2, 2, 1, 0), // define a macro
1068 T(defaultop, 0, 0, N, 0), // default operator: "and" or "or"
1069 T(div, 2, 2, N, 0), // integer divide
1070 T(emptydocs, 0, 1, N, 0), // list of empty documents
1071 T(env, 1, 1, N, 0), // environment variable
1072 T(eq, 2, 2, N, 0), // test equality
1073 T(error, 0, 0, N, 0), // error message
1074 T(field, 1, 2, N, 0), // lookup field in record
1075 T(filesize, 1, 1, N, 0), // pretty printed filesize
1076 T(filters, 0, 0, N, 0), // serialisation of current filters
1077 T(filterterms, 1, 1, N, 0), // list of terms with a given prefix
1078 T(find, 2, 2, N, 0), // find entry in list
1079 T(fmt, 0, 0, N, 0), // name of current format
1080 T(freq, 1, 1, N, 0), // frequency of a term
1081 T(ge, 2, 2, N, 0), // test >=
1082 T(gt, 2, 2, N, 0), // test >
1083 T(hash, 2, 2, N, 0), // hash a string using the specified hash function
1084 T(highlight, 2, 4, N, 0), // html escape and highlight words from list
1085 T(hit, 0, 0, N, 0), // hit number of current mset entry (0-based)
1086 T(hitlist, 1, 1, 0, M), // display hitlist using format in argument
1087 T(hitsperpage, 0, 0, N, 0), // hits per page
1088 T(hostname, 1, 1, N, 0), // extract hostname from URL
1089 T(html, 1, 1, N, 0), // html escape string (<>&")
1090 T(htmlstrip, 1, 1, N, 0), // html strip tags string (s/<[^>]*>?//g)
1091 T(httpheader, 2, 2, N, 0), // arbitrary HTTP header
1092 T(id, 0, 0, N, 0), // docid of current doc
1093 T(if, 2, 3, 1, 0), // conditional
1094 T(include, 1, 1, 1, 0), // include another file
1095 T(json, 1, 1, N, 0), // JSON string escaping
1096 T(jsonarray, 1, 1, N, 0), // Format list as a JSON array of strings
1097 T(last, 0, 0, N, M), // hit number one beyond end of current page
1098 T(lastpage, 0, 0, N, M), // number of last hit page
1099 T(le, 2, 2, N, 0), // test <=
1100 T(length, 1, 1, N, 0), // length of list
1101 T(list, 2, 5, N, 0), // pretty print list
1102 T(log, 1, 2, 1, 0), // create a log entry
1103 T(lookup, 2, 2, N, 0), // lookup in named cdb file
1104 T(lower, 1, 1, N, 0), // convert string to lower case
1105 T(lt, 2, 2, N, 0), // test <
1106 T(map, 2, 2, 1, 0), // map a list into another list
1107 T(match, 2, 3, N, 0), // regex match
1108 T(max, 1, N, N, 0), // maximum of a list of values
1109 T(min, 1, N, N, 0), // minimum of a list of values
1110 T(mod, 2, 2, N, 0), // integer modulus
1111 T(msize, 0, 0, N, M), // number of matches (estimated)
1112 T(msizeexact, 0, 0, N, M), // is $msize exact?
1113 T(msizelower, 0, 0, N, M), // number of matches (lower bound)
1114 T(msizeupper, 0, 0, N, M), // number of matches (upper bound)
1115 T(mul, 2, N, N, 0), // multiply a list of numbers
1116 T(muldiv, 3, 3, N, 0), // calculate A*B/C
1117 T(ne, 2, 2, N, 0), // test not equal
1118 T(nice, 1, 1, N, 0), // pretty print integer (with thousands sep)
1119 T(not, 1, 1, N, 0), // logical not
1120 T(now, 0, 0, N, 0), // current date/time as a time_t
1121 T(opt, 1, 2, N, 0), // lookup an option value
1122 T(or, 1, N, 0, 0), // logical shortcutting or of a list of values
1123 T(ord, 1, 1, N, 0), // return codepoint for first character of UTF-8 string
1124 T(pack, 1, 1, N, 0), // convert a number to a 4 byte big endian binary string
1125 T(percentage, 0, 0, N, 0), // percentage score of current hit
1126 T(prettyterm, 1, 1, N, Q), // pretty print term name
1127 T(prettyurl, 1, 1, N, 0), // pretty version of URL
1128 T(query, 0, 1, N, Q), // query
1129 T(querydescription,0, 0, N, M), // query.get_description() (run_query() adds filters so M)
1130 T(queryterms, 0, 0, N, Q), // list of query terms
1131 T(range, 2, 2, N, 0), // return list of values between start and end
1132 T(record, 0, 1, N, 0), // record contents of document
1133 T(relevant, 0, 1, N, Q), // is document relevant?
1134 T(relevants, 0, 0, N, Q), // return list of relevant documents
1135 T(score, 0, 0, N, 0), // score (0-10) of current hit
1136 T(set, 2, 2, N, 0), // set option value
1137 T(seterror, 1, 1, N, 0), // set error_msg, setting it early stops query execution
1138 T(setmap, 1, N, N, 0), // set map of option values
1139 T(setrelevant, 0, 1, N, Q), // set rset
1140 T(slice, 2, 2, N, 0), // slice a list using a second list
1141 T(snippet, 1, 2, N, M), // generate snippet from text
1142 T(sort, 1, 2, N, M), // alpha sort a list
1143 T(split, 1, 2, N, 0), // split a string to give a list
1144 T(stoplist, 0, 0, N, Q), // return list of stopped terms
1145 T(sub, 2, 2, N, 0), // subtract
1146 T(subdb, 0, 1, N, 0), // name of subdb docid is in
1147 T(subid, 0, 1, N, 0), // docid in the subdb#
1148 T(substr, 2, 3, N, 0), // substring
1149 T(suggestion, 0, 0, N, Q), // misspelled word correction suggestion
1150 T(switch, 3, N, 1, 0), // return position of substring, or empty string
1151 T(termprefix, 1, 1, N, 0), // get any prefix from a term
1152 T(terms, 0, 1, N, M), // list of matching terms
1153 T(thispage, 0, 0, N, M), // page number of current page
1154 T(time, 0, 0, N, M), // how long the match took (in seconds)
1155 T(topdoc, 0, 0, N, M), // first document on current page of hit list
1156 // (counting from 0)
1157 T(topterms, 0, 1, N, M), // list of up to N top relevance feedback terms
1158 // (default 16)
1159 T(transform, 3, 4, N, 0), // transform with a regexp
1160 T(truncate, 2, 4, N, 0), // truncate after a word
1161 T(uniq, 1, 1, N, 0), // removed duplicates from a sorted list
1162 T(unique, 1, 1, N, 0), // removed duplicates from any list
1163 T(unpack, 1, 1, N, 0), // convert 4 byte big endian binary string to a number
1164 T(unprefix, 1, 1, N, 0), // remove any prefix from a term
1165 T(unstem, 1, 1, N, Q), // return list of terms from the parsed query
1166 // which stemmed to this term
1167 T(upper, 1, 1, N, 0), // convert string to upper case
1168 T(url, 1, 1, N, 0), // url encode argument
1169 T(value, 1, 2, N, 0), // return document value
1170 T(version, 0, 0, N, 0), // omega version string
1171 T(weight, 0, 0, N, 0), // weight of the current hit
1172 { NULL,{0, 0, 0, 0, 0}}
1175 #undef T // Leaving T defined screws up Sun's C++ compiler!
1177 static vector<string> macros;
1179 // Call write() repeatedly until all data is written or we get a
1180 // non-recoverable error.
1181 static ssize_t
1182 write_all(int fd, const char * buf, size_t count)
1184 while (count) {
1185 ssize_t r = write(fd, buf, count);
1186 if (rare(r < 0)) {
1187 if (errno == EINTR) continue;
1188 return r;
1190 buf += r;
1191 count -= r;
1193 return 0;
1196 static const vector<string>&
1197 get_subdbs()
1199 static vector<string> subdbs;
1200 if (subdbs.empty()) {
1201 size_t p = 0, q;
1202 while (true) {
1203 q = dbname.find('/', p);
1204 subdbs.emplace_back(dbname, p, q - p);
1205 if (q == string::npos) break;
1206 p = q + 1;
1209 return subdbs;
1212 static string
1213 eval(const string &fmt, const vector<string> &param)
1215 static map<string, const struct func_attrib *> func_map;
1216 if (func_map.empty()) {
1217 struct func_desc *p;
1218 for (p = func_tab; p->name != NULL; ++p) {
1219 func_map[string(p->name)] = &(p->a);
1222 string res;
1223 string::size_type p = 0, q;
1224 while ((q = fmt.find('$', p)) != string::npos) try {
1225 res.append(fmt, p, q - p);
1226 string::size_type code_start = q; // note down for error reporting
1227 q++;
1228 if (q >= fmt.size()) break;
1229 unsigned char ch = fmt[q];
1230 switch (ch) {
1231 // Magic sequences:
1232 // '$$' -> '$', '$(' -> '{', '$)' -> '}', '$.' -> ','
1233 case '$':
1234 res += '$';
1235 p = q + 1;
1236 continue;
1237 case '(':
1238 res += '{';
1239 p = q + 1;
1240 continue;
1241 case ')':
1242 res += '}';
1243 p = q + 1;
1244 continue;
1245 case '.':
1246 res += ',';
1247 p = q + 1;
1248 continue;
1249 case '_':
1250 ch = '0';
1251 // FALL THRU
1252 case '1': case '2': case '3': case '4': case '5':
1253 case '6': case '7': case '8': case '9':
1254 ch -= '0';
1255 if (ch < param.size()) res += param[ch];
1256 p = q + 1;
1257 continue;
1258 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1259 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1260 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
1261 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
1262 case 'y': case 'z':
1263 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1264 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
1265 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
1266 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
1267 case 'Y': case 'Z':
1268 case '{':
1269 break;
1270 default:
1271 string msg = "Unknown $ code in: $";
1272 msg.append(fmt, q, string::npos);
1273 throw msg;
1275 p = find_if(fmt.begin() + q, fmt.end(), p_notid) - fmt.begin();
1276 string var(fmt, q, p - q);
1277 map<string, const struct func_attrib *>::const_iterator func;
1278 func = func_map.find(var);
1279 if (func == func_map.end()) {
1280 throw "Unknown function '" + var + "'";
1282 vector<string> args;
1283 if (fmt[p] == '{') {
1284 q = p + 1;
1285 int nest = 1;
1286 while (true) {
1287 p = fmt.find_first_of(",{}", p + 1);
1288 if (p == string::npos)
1289 throw "missing } in " + fmt.substr(code_start);
1290 if (fmt[p] == '{') {
1291 ++nest;
1292 } else {
1293 if (nest == 1) {
1294 // should we split the args
1295 if (func->second->minargs != N) {
1296 args.push_back(fmt.substr(q, p - q));
1297 q = p + 1;
1300 if (fmt[p] == '}' && --nest == 0) break;
1303 if (func->second->minargs == N)
1304 args.push_back(fmt.substr(q, p - q));
1305 ++p;
1308 if (func->second->minargs != N) {
1309 if (int(args.size()) < func->second->minargs)
1310 throw "too few arguments to $" + var;
1311 if (func->second->maxargs != N &&
1312 int(args.size()) > func->second->maxargs)
1313 throw "too many arguments to $" + var;
1315 vector<string>::size_type n;
1316 if (func->second->evalargs != N)
1317 n = func->second->evalargs;
1318 else
1319 n = args.size();
1321 for (vector<string>::size_type j = 0; j < n; ++j)
1322 args[j] = eval(args[j], param);
1324 if (func->second->ensure == 'Q' || func->second->ensure == 'M')
1325 ensure_query_parsed();
1326 if (func->second->ensure == 'M') ensure_match();
1327 string value;
1328 switch (func->second->tag) {
1329 case CMD_:
1330 break;
1331 case CMD_add: {
1332 int total = 0;
1333 for (auto&& arg : args)
1334 total += string_to_int(arg);
1335 value = str(total);
1336 break;
1338 case CMD_addfilter:
1339 add_bterm(args[0]);
1340 break;
1341 case CMD_allterms: {
1342 // list of all terms indexing document
1343 Xapian::docid id = q0;
1344 if (!args.empty()) id = string_to_int(args[0]);
1345 for (Xapian::TermIterator term = db.termlist_begin(id);
1346 term != db.termlist_end(id); ++term) {
1347 value += *term;
1348 value += '\t';
1351 if (!value.empty()) value.erase(value.size() - 1);
1352 break;
1354 case CMD_and: {
1355 value = "true";
1356 for (auto&& arg : args) {
1357 if (eval(arg, param).empty()) {
1358 value.resize(0);
1359 break;
1362 break;
1364 case CMD_cgi: {
1365 auto i = cgi_params.find(args[0]);
1366 if (i != cgi_params.end()) value = i->second;
1367 break;
1369 case CMD_cgilist: {
1370 auto g = cgi_params.equal_range(args[0]);
1371 for (auto i = g.first; i != g.second; ++i) {
1372 value += i->second;
1373 value += '\t';
1375 if (!value.empty()) value.erase(value.size() - 1);
1376 break;
1378 case CMD_cgiparams: {
1379 const string* prev = NULL;
1380 for (auto&& i : cgi_params) {
1381 if (prev && i.first == *prev) continue;
1382 value += i.first;
1383 value += '\t';
1384 prev = &i.first;
1386 if (!value.empty()) value.erase(value.size() - 1);
1387 break;
1389 case CMD_chr:
1390 Xapian::Unicode::append_utf8(value, string_to_int(args[0]));
1391 break;
1392 case CMD_collapsed: {
1393 value = str(collapsed);
1394 break;
1396 case CMD_cond:
1397 for (size_t i = 0; i < args.size(); i += 2) {
1398 if (i == args.size() - 1) {
1399 // Handle optional "else" value.
1400 value = eval(args[i], param);
1401 break;
1403 if (!eval(args[i], param).empty()) {
1404 value = eval(args[i + 1], param);
1405 break;
1408 break;
1409 case CMD_contains: {
1410 size_t pos = args[1].find(args[0]);
1411 if (pos != string::npos) {
1412 value = str(pos);
1414 break;
1416 case CMD_csv:
1417 value = args[0];
1418 if (args.size() > 1 && !args[1].empty()) {
1419 csv_escape_always(value);
1420 } else {
1421 csv_escape(value);
1423 break;
1424 case CMD_date:
1425 value = args[0];
1426 if (!value.empty()) {
1427 char buf[64] = "";
1428 time_t date = string_to_int(value);
1429 if (date != static_cast<time_t>(-1)) {
1430 struct tm *then;
1431 then = gmtime(&date);
1432 string date_fmt = "%Y-%m-%d";
1433 if (args.size() > 1) date_fmt = eval(args[1], param);
1434 strftime(buf, sizeof buf, date_fmt.c_str(), then);
1436 value = buf;
1438 break;
1439 case CMD_dbname:
1440 value = dbname;
1441 break;
1442 case CMD_dbsize: {
1443 static Xapian::doccount dbsize;
1444 if (!dbsize) dbsize = db.get_doccount();
1445 value = str(dbsize);
1446 break;
1448 case CMD_def: {
1449 func_attrib *fa = new func_attrib;
1450 fa->tag = CMD_MACRO + macros.size();
1451 fa->minargs = 0;
1452 fa->maxargs = 9;
1453 fa->evalargs = N; // FIXME: or 0?
1454 fa->ensure = 0;
1456 macros.push_back(args[1]);
1457 func_map[args[0]] = fa;
1458 break;
1460 case CMD_defaultop:
1461 if (default_op == Xapian::Query::OP_AND) {
1462 value = "and";
1463 } else {
1464 value = "or";
1466 break;
1467 case CMD_div: {
1468 int denom = string_to_int(args[1]);
1469 if (denom == 0) {
1470 value = "divide by 0";
1471 } else {
1472 value = str(string_to_int(args[0]) /
1473 string_to_int(args[1]));
1475 break;
1477 case CMD_emptydocs: {
1478 string t;
1479 if (!args.empty())
1480 t = args[0];
1481 Xapian::PostingIterator i;
1482 for (i = db.postlist_begin(t); i != db.postlist_end(t); ++i) {
1483 if (i.get_doclength() != 0) continue;
1484 if (!value.empty()) value += '\t';
1485 value += str(*i);
1487 break;
1489 case CMD_env: {
1490 char *env = getenv(args[0].c_str());
1491 if (env != NULL) value = env;
1492 break;
1494 case CMD_eq:
1495 if (args[0] == args[1]) value = "true";
1496 break;
1497 case CMD_error:
1498 if (error_msg.empty() && enquire == NULL && !dbname.empty()) {
1499 error_msg = "Database '" + dbname + "' couldn't be opened";
1501 value = error_msg;
1502 break;
1503 case CMD_field: {
1504 Xapian::docid did = q0;
1505 if (args.size() > 1) did = string_to_int(args[1]);
1506 value = fields.get_field(did, args[0]);
1507 break;
1509 case CMD_filesize: {
1510 // FIXME: rounding? i18n?
1511 int size = string_to_int(args[0]);
1512 int intpart = size;
1513 int fraction = -1;
1514 const char * format = 0;
1515 if (size < 0) {
1516 // Negative size -> empty result.
1517 } else if (size == 1) {
1518 format = "%d byte";
1519 } else if (size < 1024) {
1520 format = "%d bytes";
1521 } else {
1522 if (size < 1024 * 1024) {
1523 format = "%d.%cK";
1524 } else {
1525 size /= 1024;
1526 if (size < 1024 * 1024) {
1527 format = "%d.%cM";
1528 } else {
1529 size /= 1024;
1530 format = "%d.%cG";
1533 intpart = unsigned(size) / 1024;
1534 fraction = unsigned(size) % 1024;
1536 if (format) {
1537 char buf[200];
1538 int len;
1539 if (fraction == -1) {
1540 len = my_snprintf(buf, sizeof(buf), format, intpart);
1541 } else {
1542 fraction = (fraction * 10 / 1024) + '0';
1543 len = my_snprintf(buf, sizeof(buf), format, intpart, fraction);
1545 if (len < 0 || unsigned(len) > sizeof(buf)) len = sizeof(buf);
1546 value.assign(buf, len);
1548 break;
1550 case CMD_filters:
1551 value = filters;
1552 break;
1553 case CMD_filterterms: {
1554 Xapian::TermIterator term = db.allterms_begin();
1555 term.skip_to(args[0]);
1556 while (term != db.allterms_end()) {
1557 string t = *term;
1558 if (!startswith(t, args[0])) break;
1559 value += t;
1560 value += '\t';
1561 ++term;
1564 if (!value.empty()) value.erase(value.size() - 1);
1565 break;
1567 case CMD_find: {
1568 string l = args[0], s = args[1];
1569 string::size_type i = 0, j = 0;
1570 size_t count = 0;
1571 while (j != l.size()) {
1572 j = l.find('\t', i);
1573 if (j == string::npos) j = l.size();
1574 if (j - i == s.length()) {
1575 if (memcmp(s.data(), l.data() + i, j - i) == 0) {
1576 value = str(count);
1577 break;
1580 ++count;
1581 i = j + 1;
1583 break;
1585 case CMD_fmt:
1586 value = fmtname;
1587 break;
1588 case CMD_freq: {
1589 const string& term = args[0];
1590 Xapian::doccount termfreq = 0;
1591 if (done_query) {
1592 termfreq = mset.get_termfreq(term);
1594 if (termfreq == 0) {
1595 // We want $freq to work before the match is run, and we
1596 // don't want using it to force the match to run.
1597 termfreq = db.get_termfreq(term);
1599 value = str(termfreq);
1600 break;
1602 case CMD_ge:
1603 if (string_to_int(args[0]) >= string_to_int(args[1]))
1604 value = "true";
1605 break;
1606 case CMD_gt:
1607 if (string_to_int(args[0]) > string_to_int(args[1]))
1608 value = "true";
1609 break;
1610 case CMD_hash: {
1611 const string& data = args[0];
1612 const string& hash = args[1];
1613 if (hash == "md5") {
1614 string md5;
1615 md5_string(data, md5);
1616 value.reserve(md5.size() * 2);
1617 for (unsigned char byte : md5) {
1618 value += "0123456789abcdef"[byte >> 4];
1619 value += "0123456789abcdef"[byte & 0x0f];
1621 } else {
1622 throw "Unknown hash function: " + hash;
1624 break;
1626 case CMD_highlight: {
1627 string bra, ket;
1628 if (args.size() > 2) {
1629 bra = args[2];
1630 if (args.size() > 3) {
1631 ket = args[3];
1632 } else {
1633 string::const_iterator i;
1634 i = find_if(bra.begin() + 2, bra.end(), p_nottag);
1635 ket = "</";
1636 ket.append(bra, 1, i - bra.begin() - 1);
1637 ket += '>';
1641 value = html_highlight(args[0], args[1], bra, ket);
1642 break;
1644 case CMD_hit:
1645 // 0-based mset index
1646 value = str(hit_no);
1647 break;
1648 case CMD_hitlist:
1649 #if 0
1650 url_query_string = "?DB=";
1651 url_query_string += dbname;
1652 for (auto& j : query_strings) {
1653 if (j.first.empty()) {
1654 url_query_string += "&P=";
1655 } else {
1656 url_query_string += "&P."
1657 url_query_string += j.first;
1658 url_query_string += '=';
1660 const char *q = j.second.c_str();
1661 int ch;
1662 while ((ch = *q++) != '\0') {
1663 switch (ch) {
1664 case '+':
1665 url_query_string += "%2b";
1666 break;
1667 case '"':
1668 url_query_string += "%22";
1669 break;
1670 case '%':
1671 url_query_string += "%25";
1672 break;
1673 case '&':
1674 url_query_string += "%26";
1675 break;
1676 case ' ':
1677 ch = '+';
1678 /* fall through */
1679 default:
1680 url_query_string += ch;
1684 // add any boolean terms
1685 for (auto i = filter_map.begin(); i != filter_map.end(); ++i) {
1686 url_query_string += "&B=";
1687 url_query_string += i->second;
1689 #endif
1690 for (hit_no = topdoc; hit_no < last; ++hit_no)
1691 value += print_caption(args[0], param);
1692 hit_no = 0;
1693 break;
1694 case CMD_hitsperpage:
1695 value = str(hits_per_page);
1696 break;
1697 case CMD_hostname: {
1698 value = args[0];
1699 // remove URL scheme and/or path
1700 string::size_type i = value.find("://");
1701 if (i == string::npos) i = 0; else i += 3;
1702 value = value.substr(i, value.find('/', i) - i);
1703 // remove user@ or user:password@
1704 i = value.find('@');
1705 if (i != string::npos) value.erase(0, i + 1);
1706 // remove :port
1707 i = value.find(':');
1708 if (i != string::npos) value.resize(i);
1709 break;
1711 case CMD_html:
1712 value = html_escape(args[0]);
1713 break;
1714 case CMD_htmlstrip:
1715 value = html_strip(args[0]);
1716 break;
1717 case CMD_httpheader:
1718 if (!suppress_http_headers) {
1719 cout << args[0] << ": " << args[1] << endl;
1720 if (!set_content_type && args[0].length() == 12 &&
1721 strcasecmp(args[0].c_str(), "Content-Type") == 0) {
1722 set_content_type = true;
1725 break;
1726 case CMD_id:
1727 // document id
1728 value = str(q0);
1729 break;
1730 case CMD_if:
1731 if (!args[0].empty())
1732 value = eval(args[1], param);
1733 else if (args.size() > 2)
1734 value = eval(args[2], param);
1735 break;
1736 case CMD_include:
1737 value = eval_file(args[0]);
1738 break;
1739 case CMD_json:
1740 value = args[0];
1741 json_escape(value);
1742 break;
1743 case CMD_jsonarray: {
1744 const string & l = args[0];
1745 string::size_type i = 0, j;
1746 if (l.empty()) {
1747 value = "[]";
1748 break;
1750 value = "[\"";
1751 while (true) {
1752 j = l.find('\t', i);
1753 string elt(l, i, j - i);
1754 json_escape(elt);
1755 value += elt;
1756 if (j == string::npos) break;
1757 value += "\",\"";
1758 i = j + 1;
1760 value += "\"]";
1761 break;
1763 case CMD_last:
1764 value = str(last);
1765 break;
1766 case CMD_lastpage: {
1767 int l = mset.get_matches_estimated();
1768 if (l > 0) l = (l - 1) / hits_per_page + 1;
1769 value = str(l);
1770 break;
1772 case CMD_le:
1773 if (string_to_int(args[0]) <= string_to_int(args[1]))
1774 value = "true";
1775 break;
1776 case CMD_length:
1777 if (args[0].empty()) {
1778 value = "0";
1779 } else {
1780 size_t length = count(args[0].begin(), args[0].end(), '\t');
1781 value = str(length + 1);
1783 break;
1784 case CMD_list: {
1785 if (!args[0].empty()) {
1786 string pre, inter, interlast, post;
1787 switch (args.size()) {
1788 case 2:
1789 inter = interlast = args[1];
1790 break;
1791 case 3:
1792 inter = args[1];
1793 interlast = args[2];
1794 break;
1795 case 4:
1796 pre = args[1];
1797 inter = interlast = args[2];
1798 post = args[3];
1799 break;
1800 case 5:
1801 pre = args[1];
1802 inter = args[2];
1803 interlast = args[3];
1804 post = args[4];
1805 break;
1807 value += pre;
1808 string list = args[0];
1809 string::size_type split = 0, split2;
1810 while ((split2 = list.find('\t', split)) != string::npos) {
1811 if (split) value += inter;
1812 value.append(list, split, split2 - split);
1813 split = split2 + 1;
1815 if (split) value += interlast;
1816 value.append(list, split, string::npos);
1817 value += post;
1819 break;
1821 case CMD_log: {
1822 if (!vet_filename(args[0])) break;
1823 string logfile = log_dir + args[0];
1824 int fd = open(logfile.c_str(), O_CREAT|O_APPEND|O_WRONLY, 0644);
1825 if (fd == -1) break;
1826 vector<string> noargs;
1827 noargs.resize(1);
1828 string line;
1829 if (args.size() > 1) {
1830 line = args[1];
1831 } else {
1832 line = DEFAULT_LOG_ENTRY;
1834 line = eval(line, noargs);
1835 line += '\n';
1836 (void)write_all(fd, line.data(), line.length());
1837 close(fd);
1838 break;
1840 case CMD_lookup: {
1841 if (!vet_filename(args[0])) break;
1842 string cdbfile = cdb_dir + args[0];
1843 int fd = open(cdbfile.c_str(), O_RDONLY);
1844 if (fd == -1) break;
1846 struct cdb cdb;
1847 cdb_init(&cdb, fd);
1849 if (cdb_find(&cdb, args[1].data(), args[1].length()) > 0) {
1850 size_t datalen = cdb_datalen(&cdb);
1851 const void *dat = cdb_get(&cdb, datalen, cdb_datapos(&cdb));
1852 if (q) {
1853 value.assign(static_cast<const char *>(dat), datalen);
1857 cdb_free(&cdb);
1858 close(fd); // FIXME: cache fds?
1859 break;
1861 case CMD_lower:
1862 value = Xapian::Unicode::tolower(args[0]);
1863 break;
1864 case CMD_lt:
1865 if (string_to_int(args[0]) < string_to_int(args[1]))
1866 value = "true";
1867 break;
1868 case CMD_map:
1869 if (!args[0].empty()) {
1870 string l = args[0], pat = args[1];
1871 vector<string> new_args(param);
1872 string::size_type i = 0, j;
1873 while (true) {
1874 j = l.find('\t', i);
1875 new_args[0] = l.substr(i, j - i);
1876 value += eval(pat, new_args);
1877 if (j == string::npos) break;
1878 value += '\t';
1879 i = j + 1;
1882 break;
1883 case CMD_match:
1884 omegascript_match(value, args);
1885 break;
1886 case CMD_max: {
1887 vector<string>::const_iterator i = args.begin();
1888 int val = string_to_int(*i++);
1889 for (; i != args.end(); ++i) {
1890 int x = string_to_int(*i);
1891 if (x > val) val = x;
1893 value = str(val);
1894 break;
1896 case CMD_min: {
1897 vector<string>::const_iterator i = args.begin();
1898 int val = string_to_int(*i++);
1899 for (; i != args.end(); ++i) {
1900 int x = string_to_int(*i);
1901 if (x < val) val = x;
1903 value = str(val);
1904 break;
1906 case CMD_msize:
1907 // Estimated number of matches.
1908 value = str(mset.get_matches_estimated());
1909 break;
1910 case CMD_msizeexact:
1911 // Is msize exact?
1912 if (mset.get_matches_lower_bound()
1913 == mset.get_matches_upper_bound())
1914 value = "true";
1915 break;
1916 case CMD_msizelower:
1917 // Lower bound on number of matches.
1918 value = str(mset.get_matches_lower_bound());
1919 break;
1920 case CMD_msizeupper:
1921 // Upper bound on number of matches.
1922 value = str(mset.get_matches_upper_bound());
1923 break;
1924 case CMD_mod: {
1925 int denom = string_to_int(args[1]);
1926 if (denom == 0) {
1927 value = "divide by 0";
1928 } else {
1929 value = str(string_to_int(args[0]) %
1930 string_to_int(args[1]));
1932 break;
1934 case CMD_mul: {
1935 vector<string>::const_iterator i = args.begin();
1936 int total = string_to_int(*i++);
1937 while (i != args.end())
1938 total *= string_to_int(*i++);
1939 value = str(total);
1940 break;
1942 case CMD_muldiv: {
1943 int denom = string_to_int(args[2]);
1944 if (denom == 0) {
1945 value = "divide by 0";
1946 } else {
1947 int num = string_to_int(args[0]) * string_to_int(args[1]);
1948 value = str(num / denom);
1950 break;
1952 case CMD_ne:
1953 if (args[0] != args[1]) value = "true";
1954 break;
1955 case CMD_nice: {
1956 string::const_iterator i = args[0].begin();
1957 int len = args[0].length();
1958 while (len) {
1959 value += *i++;
1960 if (--len && len % 3 == 0) value += option["thousand"];
1962 break;
1964 case CMD_not:
1965 if (args[0].empty()) value = "true";
1966 break;
1967 case CMD_now:
1968 value = str(static_cast<unsigned long>(time(NULL)));
1969 break;
1970 case CMD_opt:
1971 if (args.size() == 2) {
1972 value = option[args[0] + "," + args[1]];
1973 } else {
1974 value = option[args[0]];
1976 break;
1977 case CMD_or: {
1978 for (auto&& arg : args) {
1979 value = eval(arg, param);
1980 if (!value.empty()) break;
1982 break;
1984 case CMD_ord: {
1985 if (!args[0].empty()) {
1986 Utf8Iterator it(args[0]);
1987 value = str(*it);
1989 break;
1991 case CMD_pack:
1992 value = int_to_binary_string(string_to_int(args[0]));
1993 break;
1994 case CMD_percentage:
1995 // percentage score
1996 value = str(percent);
1997 break;
1998 case CMD_prettyterm:
1999 value = pretty_term(args[0]);
2000 break;
2001 case CMD_prettyurl:
2002 value = args[0];
2003 url_prettify(value);
2004 break;
2005 case CMD_query: {
2006 auto r = query_strings.equal_range(args.empty() ?
2007 string() : args[0]);
2008 for (auto j = r.first; j != r.second; ++j) {
2009 if (!value.empty()) value += '\t';
2010 const string & s = j->second;
2011 size_t start = 0, tab;
2012 while ((tab = s.find('\t', start)) != string::npos) {
2013 value.append(s, start, tab - start);
2014 value += ' ';
2015 start = tab + 1;
2017 value.append(s, start, string::npos);
2019 break;
2021 case CMD_querydescription:
2022 value = query.get_description();
2023 break;
2024 case CMD_queryterms:
2025 value = queryterms;
2026 break;
2027 case CMD_range: {
2028 int start = string_to_int(args[0]);
2029 int end = string_to_int(args[1]);
2030 while (start <= end) {
2031 value += str(start);
2032 if (start < end) value += '\t';
2033 start++;
2035 break;
2037 case CMD_record: {
2038 Xapian::docid id = q0;
2039 if (!args.empty()) id = string_to_int(args[0]);
2040 value = db.get_document(id).get_data();
2041 break;
2043 case CMD_relevant: {
2044 // document id if relevant; empty otherwise
2045 Xapian::docid id = q0;
2046 if (!args.empty()) id = string_to_int(args[0]);
2047 auto i = ticked.find(id);
2048 if (i != ticked.end()) {
2049 i->second = false; // icky side-effect
2050 value = str(id);
2052 break;
2054 case CMD_relevants: {
2055 for (auto i : ticked) {
2056 if (i.second) {
2057 value += str(i.first);
2058 value += '\t';
2061 if (!value.empty()) value.erase(value.size() - 1);
2062 break;
2064 case CMD_score:
2065 // Score (0 to 10)
2066 value = str(percent / 10);
2067 break;
2068 case CMD_set:
2069 option[args[0]] = args[1];
2070 break;
2071 case CMD_seterror:
2072 error_msg = args[0];
2073 break;
2074 case CMD_setmap: {
2075 string base = args[0] + ',';
2076 if (args.size() % 2 != 1)
2077 throw string("$setmap requires an odd number of arguments");
2078 for (unsigned int i = 1; i + 1 < args.size(); i += 2) {
2079 option[base + args[i]] = args[i + 1];
2081 break;
2083 case CMD_setrelevant: {
2084 string::size_type i = 0, j;
2085 while (true) {
2086 j = args[0].find_first_not_of("0123456789", i);
2087 Xapian::docid id = atoi(args[0].substr(i, j - i).c_str());
2088 if (id) {
2089 rset.add_document(id);
2090 ticked[id] = true;
2092 if (j == string::npos) break;
2093 i = j + 1;
2095 break;
2097 case CMD_slice: {
2098 string list = args[0], pos = args[1];
2099 vector<string> items;
2100 string::size_type i = 0, j;
2101 while (true) {
2102 j = list.find('\t', i);
2103 items.push_back(list.substr(i, j - i));
2104 if (j == string::npos) break;
2105 i = j + 1;
2107 i = 0;
2108 bool have_added = false;
2109 while (true) {
2110 j = pos.find('\t', i);
2111 int item = string_to_int(pos.substr(i, j - i));
2112 if (item >= 0 && size_t(item) < items.size()) {
2113 if (have_added) value += '\t';
2114 value += items[item];
2115 have_added = true;
2117 if (j == string::npos) break;
2118 i = j + 1;
2120 break;
2122 case CMD_snippet: {
2123 size_t length = 200;
2124 if (args.size() > 1) {
2125 length = string_to_int(args[1]);
2127 if (!stemmer)
2128 stemmer = new Xapian::Stem(option["stemmer"]);
2129 // FIXME: Allow start and end highlight and omit to be specified.
2130 value = mset.snippet(args[0], length, *stemmer,
2131 mset.SNIPPET_BACKGROUND_MODEL|mset.SNIPPET_EXHAUSTIVE,
2132 "<strong>", "</strong>", "...");
2133 break;
2135 case CMD_sort:
2136 omegascript_sort(args, value);
2137 break;
2138 case CMD_split: {
2139 string split;
2140 if (args.size() == 1) {
2141 split = " ";
2142 value = args[0];
2143 } else {
2144 split = args[0];
2145 value = args[1];
2147 string::size_type i = 0;
2148 while (true) {
2149 if (split.empty()) {
2150 ++i;
2151 if (i >= value.size()) break;
2152 } else {
2153 i = value.find(split, i);
2154 if (i == string::npos) break;
2156 value.replace(i, split.size(), 1, '\t');
2157 ++i;
2159 break;
2161 case CMD_stoplist: {
2162 Xapian::TermIterator i = qp.stoplist_begin();
2163 Xapian::TermIterator end = qp.stoplist_end();
2164 while (i != end) {
2165 if (!value.empty()) value += '\t';
2166 value += *i;
2167 ++i;
2169 break;
2171 case CMD_sub:
2172 value = str(string_to_int(args[0]) - string_to_int(args[1]));
2173 break;
2174 case CMD_subdb: {
2175 Xapian::docid id = q0;
2176 if (args.size() > 0) id = string_to_int(args[0]);
2177 auto subdbs = get_subdbs();
2178 value = subdbs[(id - 1) % subdbs.size()];
2179 break;
2181 case CMD_subid: {
2182 Xapian::docid id = q0;
2183 if (args.size() > 0) id = string_to_int(args[0]);
2184 value = str(((id - 1) / get_subdbs().size()) + 1);
2185 break;
2187 case CMD_substr: {
2188 int start = string_to_int(args[1]);
2189 if (start < 0) {
2190 if (static_cast<size_t>(-start) >= args[0].size()) {
2191 start = 0;
2192 } else {
2193 start = static_cast<int>(args[0].size()) + start;
2195 } else {
2196 if (static_cast<size_t>(start) >= args[0].size()) break;
2198 size_t len = string::npos;
2199 if (args.size() > 2) {
2200 int int_len = string_to_int(args[2]);
2201 if (int_len >= 0) {
2202 len = size_t(int_len);
2203 } else {
2204 len = args[0].size() - start;
2205 if (static_cast<size_t>(-int_len) >= len) {
2206 len = 0;
2207 } else {
2208 len -= static_cast<size_t>(-int_len);
2212 value.assign(args[0], start, len);
2213 break;
2215 case CMD_suggestion:
2216 value = qp.get_corrected_query_string();
2217 break;
2218 case CMD_switch: {
2219 const string& val = args[0];
2220 for (size_t i = 1; i < args.size(); i += 2) {
2221 if (i == args.size() - 1) {
2222 // Handle optional "else" value.
2223 value = eval(args[i], param);
2224 break;
2226 if (val == eval(args[i], param)) {
2227 value = eval(args[i + 1], param);
2228 break;
2231 break;
2233 case CMD_termprefix:
2234 (void)prefix_from_term(&value, args[0]);
2235 break;
2236 case CMD_terms: {
2237 // list of matching terms
2238 if (!enquire) break;
2239 Xapian::TermIterator term = enquire->get_matching_terms_begin(q0);
2240 if (args.empty()) {
2241 while (term != enquire->get_matching_terms_end(q0)) {
2242 // check term was in the typed query so we ignore
2243 // boolean filter terms
2244 const string & t = *term;
2245 if (termset.find(t) != termset.end()) {
2246 value += t;
2247 value += '\t';
2249 ++term;
2251 } else {
2252 // Return matching terms with specified prefix. We can't
2253 // use skip_to() as the terms aren't ordered by termname.
2254 const string & pfx = args[0];
2255 while (term != enquire->get_matching_terms_end(q0)) {
2256 const string & t = *term;
2257 if (startswith(t, pfx)) {
2258 value += t;
2259 value += '\t';
2261 ++term;
2265 if (!value.empty()) value.erase(value.size() - 1);
2266 break;
2268 case CMD_thispage:
2269 value = str(topdoc / hits_per_page + 1);
2270 break;
2271 case CMD_time:
2272 if (secs >= 0) {
2273 char buf[64];
2274 my_snprintf(buf, sizeof(buf), "%.6f", secs);
2275 // MSVC's snprintf omits the zero byte if the string if
2276 // sizeof(buf) long.
2277 buf[sizeof(buf) - 1] = '\0';
2278 value = buf;
2280 break;
2281 case CMD_topdoc:
2282 // first document on current page of hit list (counting from 0)
2283 value = str(topdoc);
2284 break;
2285 case CMD_topterms:
2286 if (enquire) {
2287 int howmany = 16;
2288 if (!args.empty()) howmany = string_to_int(args[0]);
2289 if (howmany < 0) howmany = 0;
2291 // List of expand terms
2292 Xapian::ESet eset;
2293 OmegaExpandDecider decider(db, &termset);
2295 if (!rset.empty()) {
2296 set_expansion_scheme(*enquire, option);
2297 eset = enquire->get_eset(howmany * 2, rset, &decider);
2298 } else if (mset.size()) {
2299 // invent an rset
2300 Xapian::RSet tmp;
2302 int c = 5;
2303 // FIXME: what if mset does not start at first match?
2304 for (Xapian::docid did : mset) {
2305 tmp.add_document(did);
2306 if (--c == 0) break;
2309 set_expansion_scheme(*enquire, option);
2310 eset = enquire->get_eset(howmany * 2, tmp, &decider);
2313 // Don't show more than one word with the same stem.
2314 set<string> stems;
2315 Xapian::ESetIterator i;
2316 for (i = eset.begin(); i != eset.end(); ++i) {
2317 string term(*i);
2318 string stem = (*stemmer)(term);
2319 if (stems.find(stem) != stems.end()) continue;
2320 stems.insert(stem);
2321 value += term;
2322 value += '\t';
2323 if (--howmany == 0) break;
2325 if (!value.empty()) value.erase(value.size() - 1);
2327 break;
2328 case CMD_transform:
2329 omegascript_transform(value, args);
2330 break;
2331 case CMD_truncate:
2332 value = generate_sample(args[0],
2333 string_to_int(args[1]),
2334 args.size() > 2 ? args[2] : string(),
2335 args.size() > 3 ? args[3] : string());
2336 break;
2337 case CMD_uniq: {
2338 const string &list = args[0];
2339 if (list.empty()) break;
2340 string::size_type split = 0, split2;
2341 string prev;
2342 do {
2343 split2 = list.find('\t', split);
2344 string item(list, split, split2 - split);
2345 if (split == 0) {
2346 value = item;
2347 } else if (item != prev) {
2348 value += '\t';
2349 value += item;
2351 prev = item;
2352 split = split2 + 1;
2353 } while (split2 != string::npos);
2354 break;
2356 case CMD_unique: {
2357 unordered_set<string> seen;
2358 const string &list = args[0];
2359 if (list.empty()) break;
2360 string::size_type split = 0, split2;
2361 do {
2362 split2 = list.find('\t', split);
2363 string item(list, split, split2 - split);
2364 if (seen.insert(item).second) {
2365 if (split != 0)
2366 value += '\t';
2367 value += item;
2369 split = split2 + 1;
2370 } while (split2 != string::npos);
2371 break;
2373 case CMD_unpack:
2374 value = str(binary_string_to_int(args[0]));
2375 break;
2376 case CMD_unprefix: {
2377 size_t prefix_len = prefix_from_term(NULL, args[0]);
2378 value.assign(args[0], prefix_len, string::npos);
2379 break;
2381 case CMD_unstem: {
2382 const string &term = args[0];
2383 Xapian::TermIterator i = qp.unstem_begin(term);
2384 Xapian::TermIterator end = qp.unstem_end(term);
2385 while (i != end) {
2386 if (!value.empty()) value += '\t';
2387 value += *i;
2388 ++i;
2390 break;
2392 case CMD_upper:
2393 value = Xapian::Unicode::toupper(args[0]);
2394 break;
2395 case CMD_url:
2396 url_encode(value, args[0]);
2397 break;
2398 case CMD_value: {
2399 Xapian::docid id = q0;
2400 Xapian::valueno value_no = string_to_int(args[0]);
2401 if (args.size() > 1) id = string_to_int(args[1]);
2402 value = db.get_document(id).get_value(value_no);
2403 break;
2405 case CMD_version:
2406 value = PACKAGE_STRING;
2407 break;
2408 case CMD_weight:
2409 value = double_to_string(weight);
2410 break;
2411 default: {
2412 args.insert(args.begin(), param[0]);
2413 int macro_no = func->second->tag - CMD_MACRO;
2414 assert(macro_no >= 0 && unsigned(macro_no) < macros.size());
2415 // throw "Unknown function '" + var + "'";
2416 value = eval(macros[macro_no], args);
2417 break;
2420 res += value;
2421 } catch (const Xapian::Error & e) {
2422 // FIXME: this means we only see the most recent error in $error
2423 // - is that the best approach?
2424 error_msg = e.get_msg();
2427 res.append(fmt, p, string::npos);
2428 return res;
2431 static string
2432 eval_file(const string &fmtfile)
2434 string err;
2435 if (vet_filename(fmtfile)) {
2436 string file = template_dir + fmtfile;
2437 string fmt;
2438 if (load_file(file, fmt)) {
2439 vector<string> noargs;
2440 noargs.resize(1);
2441 return eval(fmt, noargs);
2443 err = strerror(errno);
2444 } else {
2445 err = "name contains '..'";
2448 // FIXME: report why!
2449 string msg = string("Couldn't read format template '") + fmtfile + '\'';
2450 if (!err.empty()) msg += " (" + err + ')';
2451 throw msg;
2454 extern string
2455 pretty_term(string term)
2457 // Just leave empty strings and single characters alone.
2458 if (term.length() <= 1) return term;
2460 // Assume unprefixed terms are unstemmed.
2461 if (!C_isupper(term[0])) return term;
2463 // Handle stemmed terms.
2464 bool stemmed = (term[0] == 'Z');
2465 if (stemmed) {
2466 // First of all, check if a term in the query stemmed to this one.
2467 Xapian::TermIterator u = qp.unstem_begin(term);
2468 // There might be multiple words with the same stem, but we only want
2469 // one so just take the first.
2470 if (u != qp.unstem_end(term)) return *u;
2472 // Remove the 'Z'.
2473 term.erase(0, 1);
2476 bool add_quotes = false;
2478 // Check if the term has a prefix.
2479 if (C_isupper(term[0])) {
2480 // See if we have this prefix in the termprefix_to_userprefix map. If
2481 // so, just reverse the mapping (e.g. turn 'Sfish' into 'subject:fish').
2482 string prefix;
2483 size_t prefix_len = prefix_from_term(&prefix, term);
2485 map<string, string>::const_iterator i;
2486 i = termprefix_to_userprefix.find(prefix);
2487 if (i != termprefix_to_userprefix.end()) {
2488 string user_prefix = i->second;
2489 user_prefix += ':';
2490 term.replace(0, prefix_len, user_prefix);
2491 } else {
2492 // We don't have a prefix mapping for this, so just set a flag to
2493 // add quotes around the term.
2494 add_quotes = true;
2498 if (stemmed) term += '.';
2500 if (add_quotes) {
2501 term.insert(0, "\"");
2502 term.append("\"");
2505 return term;
2508 static string
2509 print_caption(const string &fmt, const vector<string> &param)
2511 q0 = *(mset[hit_no]);
2513 weight = mset[hit_no].get_weight();
2514 percent = mset.convert_to_percent(mset[hit_no]);
2515 collapsed = mset[hit_no].get_collapse_count();
2517 return eval(fmt, param);
2520 void
2521 parse_omegascript()
2523 try {
2524 const char * p = getenv("SERVER_PROTOCOL");
2525 if (p && strcmp(p, "INCLUDED") == 0) {
2526 // We're being included in another page, so suppress headers.
2527 suppress_http_headers = true;
2530 string output = eval_file(fmtname);
2531 if (!set_content_type && !suppress_http_headers) {
2532 cout << "Content-Type: text/html" << endl;
2533 set_content_type = true;
2535 if (!suppress_http_headers) cout << endl;
2536 cout << output;
2537 } catch (...) {
2538 // Ensure the headers have been output so that any exception gets
2539 // reported rather than giving a server error.
2540 if (!set_content_type && !suppress_http_headers) {
2541 cout << "Content-Type: text/html" << endl;
2542 set_content_type = true;
2544 if (!suppress_http_headers) cout << endl;
2545 throw;
2549 static void
2550 ensure_query_parsed()
2552 if (query_parsed) return;
2553 query_parsed = true;
2555 // Should we discard the existing R-set recorded in R CGI parameters?
2556 bool discard_rset = false;
2558 // Should we force the first page of hits (and ignore [ > < # and TOPDOC
2559 // CGI parameters)?
2560 bool force_first_page = false;
2562 string v;
2563 // get list of terms from previous iteration of query
2564 auto val = cgi_params.find("xP");
2565 if (val != cgi_params.end()) {
2566 v = val->second;
2567 // If xP given, default to discarding any RSet and forcing the first
2568 // page of results. If the query is the same, or an extension of
2569 // the previous query, we adjust these again below.
2570 discard_rset = true;
2571 force_first_page = true;
2573 querytype result = parse_queries(v);
2574 switch (result) {
2575 case BAD_QUERY:
2576 break;
2577 case NEW_QUERY:
2578 break;
2579 case SAME_QUERY:
2580 case EXTENDED_QUERY:
2581 // If we've changed database, force the first page of hits
2582 // and discard the R-set (since the docids will have changed)
2583 val = cgi_params.find("xDB");
2584 if (val != cgi_params.end() && val->second != dbname) break;
2585 if (result == SAME_QUERY && force_first_page) {
2586 val = cgi_params.find("xFILTERS");
2587 if (val != cgi_params.end() && val->second != filters &&
2588 val->second != old_filters) {
2589 // Filters have changed since last query.
2590 } else {
2591 force_first_page = false;
2594 discard_rset = false;
2595 break;
2598 if (!force_first_page) {
2599 // Work out which mset element is the first hit we want
2600 // to display
2601 val = cgi_params.find("TOPDOC");
2602 if (val != cgi_params.end()) {
2603 topdoc = atol(val->second.c_str());
2606 // Handle next, previous, and page links
2607 if (cgi_params.find(">") != cgi_params.end()) {
2608 topdoc += hits_per_page;
2609 } else if (cgi_params.find("<") != cgi_params.end()) {
2610 if (topdoc >= hits_per_page)
2611 topdoc -= hits_per_page;
2612 else
2613 topdoc = 0;
2614 } else if ((val = cgi_params.find("[")) != cgi_params.end() ||
2615 (val = cgi_params.find("#")) != cgi_params.end()) {
2616 long page = atol(val->second.c_str());
2617 // Do something sensible for page 0 (we count pages from 1).
2618 if (page == 0) page = 1;
2619 topdoc = (page - 1) * hits_per_page;
2622 // raw_search means don't snap TOPDOC to a multiple of HITSPERPAGE.
2623 // Normally we snap TOPDOC like this so that things work nicely if
2624 // HITSPERPAGE is in a <select> or on radio buttons. If we're
2625 // postprocessing the output of omega and want variable sized pages,
2626 // this is unhelpful.
2627 bool raw_search = false;
2628 val = cgi_params.find("RAWSEARCH");
2629 if (val != cgi_params.end()) {
2630 raw_search = bool(atol(val->second.c_str()));
2633 if (!raw_search) topdoc = (topdoc / hits_per_page) * hits_per_page;
2636 if (!discard_rset) {
2637 // put documents marked as relevant into the rset
2638 auto g = cgi_params.equal_range("R");
2639 for (auto i = g.first; i != g.second; ++i) {
2640 const string & value = i->second;
2641 for (size_t j = 0; j < value.size(); j = value.find('.', j)) {
2642 while (value[j] == '.') ++j;
2643 Xapian::docid d = atoi(value.c_str() + j);
2644 if (d) {
2645 rset.add_document(d);
2646 ticked[d] = true;
2653 // run query if we haven't already
2654 static void
2655 ensure_match()
2657 if (done_query) return;
2659 secs = RealTime::now();
2660 run_query();
2661 if (secs != -1)
2662 secs = RealTime::now() - secs;
2664 done_query = true;
2665 last = mset.get_matches_lower_bound();
2666 if (last == 0) {
2667 // Otherwise topdoc ends up being -6 if it's non-zero!
2668 topdoc = 0;
2669 } else {
2670 if (topdoc >= last)
2671 topdoc = ((last - 1) / hits_per_page) * hits_per_page;
2672 // last is the count of documents up to the end of the current page
2673 // (as returned by $last)
2674 if (topdoc + hits_per_page < last)
2675 last = topdoc + hits_per_page;
2679 // OmegaExpandDecider methods.
2681 OmegaExpandDecider::OmegaExpandDecider(const Xapian::Database & db_,
2682 set<string> * querytermset)
2683 : db(db_)
2685 // We'll want the stemmer for testing matches anyway.
2686 if (!stemmer)
2687 stemmer = new Xapian::Stem(option["stemmer"]);
2688 if (querytermset) {
2689 set<string>::const_iterator i;
2690 for (i = querytermset->begin(); i != querytermset->end(); ++i) {
2691 string term(*i);
2692 if (term.empty()) continue;
2694 unsigned char ch = term[0];
2695 bool stemmed = (ch == 'Z');
2696 if (stemmed) {
2697 term.erase(0, 1);
2698 if (term.empty()) continue;
2699 ch = term[0];
2702 if (C_isupper(ch)) {
2703 size_t prefix_len = prefix_from_term(NULL, term);
2704 term.erase(0, prefix_len);
2707 if (!stemmed) term = (*stemmer)(term);
2709 exclude_stems.insert(term);
2714 bool
2715 OmegaExpandDecider::operator()(const string & term) const
2717 unsigned char ch = term[0];
2719 // Reject terms with a prefix.
2720 if (C_isupper(ch)) return false;
2723 MyStopper stopper;
2724 // Don't suggest stopwords.
2725 if (stopper(term)) return false;
2728 // Reject small numbers.
2729 if (term.size() < 4 && C_isdigit(ch)) return false;
2731 // Reject terms containing a space.
2732 if (term.find(' ') != string::npos) return false;
2734 // Skip terms with stems in the exclude_stems set, to avoid suggesting
2735 // terms which are already in the query in some form.
2736 string stem = (*stemmer)(term);
2737 if (exclude_stems.find(stem) != exclude_stems.end())
2738 return false;
2740 // Ignore terms that only occur once (hapaxes) since they aren't
2741 // useful for finding related documents - they only occur in a
2742 // document that's already been marked as relevant.
2743 // FIXME: add an expand option to ignore terms where
2744 // termfreq == rtermfreq.
2745 if (db.get_termfreq(term) <= 1) return false;
2747 return true;