4 * Copyright 2007 Reini Urban
5 * Copyright 2009 Marc-Etienne Vargenau, Alcatel-Lucent
7 * This file is part of PhpWiki.
9 * PhpWiki is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * PhpWiki is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 require_once 'lib/PageList.php';
25 require_once 'lib/TextSearchQuery.php';
26 require_once 'lib/Units.php';
27 require_once 'lib/SemanticWeb.php';
30 * Search for relations/attributes and its values.
31 * page - relation::object. e.g list all cities: is_a::city => relation=is_a&s=city
32 * We search for both a relation and if the search is valid for attributes also,
33 * and OR combine the result.
35 * An attribute has just a value, which is a number, and which is for sure no pagename,
36 * and its value goes through some units unification. (not yet)
37 * We can also do numerical comparison and unit lifting with attributes.
38 * population > 1000000
39 * population > 1 million
42 * - The backends can already do simple AND/OR combination of multiple
43 * relations and attributes to search for. Just the UI not. TODO: implement the AND/OR buttons.
44 * population < 1 million AND area > 50 km2
45 * - Due to attribute internals a relation search with matching attribute names will also
46 * find those attribute names, but not the values. You must explicitly search for attributes then.
48 * The Advanced query can do a freeform query expression with multiple comparison and nesting.
49 * "is_a::city and population > 1.000.000 and population < 10.000.000"
50 * "(is_a::city or is_a::country) and population < 10.000.000"
52 * @author: Reini Urban
54 class WikiPlugin_SemanticSearch
57 function getDescription()
59 return _("Search relations and attributes.");
62 function getDefaultArguments()
66 PageList::supportedArgs(), // paging and more.
68 's' => "*", // linkvalue query string
69 'page' => "*", // which pages (glob allowed), default: all
70 'relation' => '', // linkname. which relations. default all
71 'attribute' => '', // linkname. which attributes. default all
72 'attr_op' => ':=', // a funny written way for equality for pure aesthetic pleasure
73 // "All attributes which have this value set"
76 'regex' => 'auto', // is different here.
77 // no word splitting, if no regex op is present, defaults to exact match
78 'noform' => false, // don't show form with results.
79 'noheader' => false, // no caption
80 'info' => false // valid: pagename,relation,linkto,attribute,value and all other pagelist columns
84 function showForm(&$dbi, &$request, $args)
86 $action = $request->getPostURL();
87 $hiddenfield = HiddenInputs($request->getArgs(), '',
88 array('action', 'page', 's', 'semsearch',
89 'relation', 'attribute'));
90 $pagefilter = HTML::input(array('name' => 'page',
91 'value' => $args['page'],
92 'title' => _("Search only in these pages. With autocompletion."),
93 'class' => 'dropdown',
94 'acdropdown' => 'true',
95 'autocomplete_complete' => 'true',
96 'autocomplete_matchsubstring' => 'false',
97 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
99 $allrelations = $dbi->listRelations(false, false, true);
100 $svalues = empty($allrelations) ? "" : join("','", $allrelations);
101 $reldef = JavaScript("var semsearch_relations = new Array('" . $svalues . "')");
102 $relation = HTML::input(array('name' => 'relation',
103 'value' => $args['relation'],
104 'title' => _("Filter by this relation. With autocompletion."),
105 'class' => 'dropdown',
106 'style' => 'width:10em',
107 'acdropdown' => 'true',
108 'autocomplete_assoc' => 'false',
109 'autocomplete_complete' => 'true',
110 'autocomplete_matchsubstring' => 'true',
111 'autocomplete_list' => 'array:semsearch_relations'
113 $queryrel = HTML::input(array('name' => 's',
114 'value' => $args['s'],
115 'title' => _("Filter by this link. These are pagenames. With autocompletion."),
116 'class' => 'dropdown',
117 'acdropdown' => 'true',
118 'autocomplete_complete' => 'true',
119 'autocomplete_matchsubstring' => 'true',
120 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
122 $relsubmit = Button('submit:semsearch[relations]', _("Relations"), false);
123 // just testing some dhtml... not yet done
124 $enhancements = HTML();
125 $nbsp = HTML::raw(' ');
126 $this_uri = $_SERVER['REQUEST_URI'] . '#';
127 $andbutton = new Button(_("AND"), $this_uri, 'wikiaction',
129 'onclick' => "addquery('rel', 'and')",
130 'title' => _("Add an AND query")));
131 $orbutton = new Button(_("OR"), $this_uri, 'wikiaction',
133 'onclick' => "addquery('rel', 'or')",
134 'title' => _("Add an OR query")));
136 $enhancements = HTML::span($andbutton, $nbsp, $orbutton);
137 $instructions = _("Search in pages for a relation with that value (a pagename).");
138 $form1 = HTML::form(array('action' => $action,
140 'accept-charset' => 'UTF-8'),
142 $hiddenfield, HiddenInputs(array('attribute' => '')),
143 $instructions, HTML::br(),
145 HTML::colgroup(array('span' => 6)),
148 HTML::th('Pagefilter'),
149 HTML::th('Relation'),
156 HTML::td($pagefilter, _(": ")),
158 HTML::td(HTML::strong(HTML::tt(' :: '))),
160 HTML::td($nbsp, $relsubmit, $nbsp, $enhancements)))));
162 $allattrs = $dbi->listRelations(false, true, true);
163 if (empty($allrelations) and empty($allattrs)) // be nice to the dummy.
164 $this->_norelations_warning = 1;
165 $svalues = empty($allattrs) ? "" : join("','", $allattrs);
166 $attdef = JavaScript("var semsearch_attributes = new Array('" . $svalues . "')\n"
167 . "var semsearch_op = new Array('"
168 . join("','", $this->_supported_operators)
170 // TODO: We want some more tricks: Autofill the base unit of the selected
171 // attribute into the s area.
172 $attribute = HTML::input(array('name' => 'attribute',
173 'value' => $args['attribute'],
174 'title' => _("Filter by this attribute name. With autocompletion."),
175 'class' => 'dropdown',
176 'style' => 'width:10em',
177 'acdropdown' => 'true',
178 'autocomplete_complete' => 'true',
179 'autocomplete_matchsubstring' => 'true',
180 'autocomplete_assoc' => 'false',
181 'autocomplete_list' => 'array:semsearch_attributes'
182 /* 'autocomplete_onselect' => 'check_unit' */
184 $attr_op = HTML::input(array('name' => 'attr_op',
185 'value' => $args['attr_op'],
186 'title' => _("Comparison operator. With autocompletion."),
187 'class' => 'dropdown',
188 'style' => 'width:2em',
189 'acdropdown' => 'true',
190 'autocomplete_complete' => 'true',
191 'autocomplete_matchsubstring' => 'true',
192 'autocomplete_assoc' => 'false',
193 'autocomplete_list' => 'array:semsearch_op'
195 $queryatt = HTML::input(array('name' => 's',
196 'value' => $args['s'],
197 'title' => _("Filter by this numeric attribute value. With autocompletion."), //?
198 'class' => 'dropdown',
199 'acdropdown' => 'false',
200 'autocomplete_complete' => 'true',
201 'autocomplete_matchsubstring' => 'false',
202 'autocomplete_assoc' => 'false',
203 'autocomplete_list' => 'plugin:SemanticSearch page=' . $args['page'] . ' attribute=^[S] attr_op==~'
205 $andbutton = new Button(_("AND"), $this_uri, 'wikiaction',
207 'onclick' => "addquery('attr', 'and')",
208 'title' => _("Add an AND query")));
209 $orbutton = new Button(_("OR"), $this_uri, 'wikiaction',
211 'onclick' => "addquery('attr', 'or')",
212 'title' => _("Add an OR query")));
214 $enhancements = HTML::span($andbutton, $nbsp, $orbutton);
215 $attsubmit = Button('submit:semsearch[attributes]', _("Attributes"), false);
216 $instructions = HTML::span(_("Search in pages for an attribute with that numeric value."), "\n");
218 $instructions->pushContent
219 (HTML(" ", new Button(_("Advanced..."), _("SemanticSearchAdvanced"))));
220 $form2 = HTML::form(array('action' => $action,
222 'accept-charset' => 'UTF-8'),
224 $hiddenfield, HiddenInputs(array('relation' => '')),
225 $instructions, HTML::br(),
227 (array('border' => 0, 'cellspacing' => 2),
228 HTML::colgroup(array('span' => 6)),
231 HTML::th('Pagefilter'),
232 HTML::th('Attribute'),
239 HTML::td($pagefilter, _(": ")),
240 HTML::td($attribute),
243 HTML::td($nbsp, $attsubmit, $nbsp, $enhancements)))));
245 return HTML($form1, $form2);
248 function regex_query($string, $case_exact, $regex)
250 if ($string != '*' and $regex == 'auto') {
251 if (strcspn($string, ".+*?^$\"") == strlen($string)) {
252 // performance hack: construct an exact query w/o parsing. pcre is fastest.
253 $q = new TextSearchQuery($string, $case_exact, 'pcre');
254 // and now override the fields
255 unset ($q->_stoplist);
256 $q->_regex = TSQ_REGEX_NONE;
258 $q->_tree = new TextSearchQuery_node_exact($string); // hardcode this string
260 $q->_tree = new TextSearchQuery_node_word($string);
262 //$string = "\"" . $string ."\"";
263 //$regex = 'none'; // EXACT or WORD match
266 return new TextSearchQuery($string, $case_exact, $regex);
269 function run($dbi, $argstr, &$request, $basepage)
271 $this->_supported_operators = array(':=', '<', '<=', '>', '>=', '!=', '==', '=~');
272 $this->_text_operators = array(':=', '==', '=~', '!=');
273 $args = $this->getArgs($argstr, $request);
274 if (empty($args['page']))
276 if (!isset($args['s'])) // it might be (integer) 0
278 $posted = $request->getArg("semsearch");
279 $form = $this->showForm($dbi, $request, $args);
280 if (isset($this->_norelations_warning))
282 (HTML::div(array('class' => 'warning'),
283 _("Warning:"), HTML::br(),
284 _("No relations nor attributes in the whole wikidb defined!")
286 , fmt("See %s", WikiLink(_("Help").":"._("SemanticRelations")))));
288 // for convenience and harmony we allow GET requests also.
289 if (!$request->isPost()) {
290 if ($relation or $attribute) // check for good GET request
293 return $form; // nobody called us, so just display our supadupa form
295 $pagequery = $this->regex_query($page, $args['case_exact'], $args['regex']);
296 // we might want to check for semsearch['relations'] and semsearch['attributes'] also
297 if (empty($relation) and empty($attribute)) {
298 // so we just clicked without selecting any relation.
299 // hmm. check which button we clicked, before we do the massive alltogether search.
300 if (isset($posted['relations']) and $posted['relations'])
302 elseif (isset($posted['attributes']) and $posted['attributes']) {
304 // here we have to check for invalid text operators. ignore it then
305 if (!in_array($attr_op, $this->_text_operators))
309 $searchtype = "Text";
310 if (!empty($relation)) {
311 $querydesc = $relation . "::" . $s;
312 $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']);
313 $relquery = $this->regex_query($relation, $args['case_exact'], $args['regex']);
314 $links = $dbi->linkSearch($pagequery, $linkquery, 'relation', $relquery);
315 $pagelist = new PageList($info, $exclude, $args);
316 $pagelist->_links = array();
317 while ($link = $links->next()) {
318 $pagelist->addPage($link['pagename']);
319 $pagelist->_links[] = $link;
321 // default (=empty info) wants all three. but we want to be able to override this.
322 // $pagelist->_columns_seen is the exploded info
323 if (!$info or ($info and isset($pagelist->_columns_seen['relation'])))
324 $pagelist->addColumnObject
325 (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist));
326 if (!$args['info'] or ($args['info'] and isset($pagelist->_columns_seen['linkto'])))
327 $pagelist->addColumnObject
328 (new _PageList_Column_SemanticSearch_link('linkto', _("Link"), $pagelist));
330 // can we merge two different pagelist?
331 if (!empty($attribute)) {
332 $relquery = $this->regex_query($attribute, $args['case_exact'], $args['regex']);
333 if (!in_array($attr_op, $this->_supported_operators)) {
334 return HTML($form, $this->error(fmt("Illegal operator: %s",
335 HTML::tt($attr_op))));
337 $s_base = preg_replace("/,/", "", $s);
338 $units = new Units();
339 if (!is_numeric($s_base)) {
340 $s_base = $units->basevalue($s_base);
341 $is_numeric = is_numeric($s_base);
345 // check which type to search with:
346 // at first check if forced text matcher
347 if ($attr_op == '=~') {
348 if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
349 $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
350 $querydesc = "$attribute $attr_op $s";
351 } elseif ($is_numeric) { // do comparison with numbers
352 /* We want to search for multiple attributes also. linkSearch can do this.
353 * But we have to construct the query somehow. (that's why we try the AND OR dhtml)
354 * population < 1 million AND area > 50 km2
355 * Here we check only for one attribute per page.
356 * See SemanticSearchAdvanced for the full expression.
358 // it might not be the best idea to use '*' as variable to expand. hmm.
359 if ($attribute == '*') $attribute = '_star_';
360 $searchtype = "Numeric";
361 $query = $attribute . " " . $attr_op . " " . $s_base;
362 $linkquery = new SemanticAttributeSearchQuery($query, $attribute,
363 $units->baseunit($s));
364 if ($attribute == '_star_') $attribute = '*';
365 $querydesc = $attribute . " " . $attr_op . " " . $s;
367 // no number or unit: check other text matchers or '*' MATCH_ALL
368 } elseif (in_array($attr_op, $this->_text_operators)) {
369 if ($attr_op == '=~') {
370 if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
371 $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
373 $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']);
374 $querydesc = "$attribute $attr_op $s";
376 // should we fail or skip when the user clicks on Relations?
377 } elseif (isset($posted['relations']) and $posted['relations']) {
378 $linkquery = false; // skip
380 $querydesc = $attribute . " " . $attr_op . " " . $s;
381 return HTML($form, $this->error(fmt("Only text operators can be used with strings: %s",
382 HTML::tt($querydesc))));
386 $links = $dbi->linkSearch($pagequery, $linkquery, 'attribute', $relquery);
387 if (empty($relation)) {
388 $pagelist = new PageList($args['info'], $args['exclude'], $args);
389 $pagelist->_links = array();
391 while ($link = $links->next()) {
392 $pagelist->addPage($link['pagename']);
393 $pagelist->_links[] = $link;
395 // default (=empty info) wants all three. but we want to override this.
396 if (!$args['info'] or
397 ($args['info'] and isset($pagelist->_columns_seen['attribute']))
399 $pagelist->addColumnObject
400 (new _PageList_Column_SemanticSearch_relation('attribute',
401 _("Attribute"), $pagelist));
402 if (!$args['info'] or
403 ($args['info'] and isset($pagelist->_columns_seen['value']))
405 $pagelist->addColumnObject
406 (new _PageList_Column_SemanticSearch_link('value',
407 _("Value"), $pagelist));
410 if (!isset($pagelist)) {
411 $querydesc = _("<empty>");
412 $pagelist = new PageList();
415 // We put the form into the caption just to be able to return one pagelist object,
416 // and to still have the convenience form at the top. we could workaround this by
417 // putting the form as WikiFormRich into the actionpage. but thid doesnt look as
418 // nice as this here.
419 $pagelist->setCaption
420 ( // on mozilla the form doesn't fit into the caption very well.
421 HTML($noform ? '' : HTML($form, HTML::hr()),
422 fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"",
423 $searchtype, $querydesc, $page)));
429 class _PageList_Column_SemanticSearch_relation
430 extends _PageList_Column
432 function _PageList_Column_SemanticSearch_relation($field, $heading, &$pagelist)
434 $this->_field = $field;
435 $this->_heading = $heading;
436 $this->_need_rev = false;
437 $this->_iscustom = true;
438 $this->_pagelist =& $pagelist;
441 function _getValue(&$page, $revision_handle)
443 $link = $this->_pagelist->_links[$this->current_row];
444 return WikiLink($link['linkname'], 'if_known');
448 class _PageList_Column_SemanticSearch_link
449 extends _PageList_Column_SemanticSearch_relation
451 function _getValue(&$page, $revision_handle)
453 $link = $this->_pagelist->_links[$this->current_row];
454 if ($this->_field != 'value')
455 return WikiLink($link['linkvalue'], 'if_known');
457 return $link['linkvalue'];
465 // c-hanging-comment-ender-p: nil
466 // indent-tabs-mode: nil