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
59 return _("SemanticSearch");
62 function getDescription()
64 return _("Search relations and attributes.");
67 function getDefaultArguments()
71 PageList::supportedArgs(), // paging and more.
73 's' => "*", // linkvalue query string
74 'page' => "*", // which pages (glob allowed), default: all
75 'relation' => '', // linkname. which relations. default all
76 'attribute' => '', // linkname. which attributes. default all
77 'attr_op' => ':=', // a funny written way for equality for pure aesthetic pleasure
78 // "All attributes which have this value set"
81 'regex' => 'auto', // is different here.
82 // no word splitting, if no regex op is present, defaults to exact match
83 'noform' => false, // don't show form with results.
84 'noheader' => false, // no caption
85 'info' => false // valid: pagename,relation,linkto,attribute,value and all other pagelist columns
89 function showForm(&$dbi, &$request, $args)
91 $action = $request->getPostURL();
92 $hiddenfield = HiddenInputs($request->getArgs(), '',
93 array('action', 'page', 's', 'semsearch',
94 'relation', 'attribute'));
95 $pagefilter = HTML::input(array('name' => 'page',
96 'value' => $args['page'],
97 'title' => _("Search only in these pages. With autocompletion."),
98 'class' => 'dropdown',
99 'acdropdown' => 'true',
100 'autocomplete_complete' => 'true',
101 'autocomplete_matchsubstring' => 'false',
102 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
104 $allrelations = $dbi->listRelations(false, false, true);
105 $svalues = empty($allrelations) ? "" : join("','", $allrelations);
106 $reldef = JavaScript("var semsearch_relations = new Array('" . $svalues . "')");
107 $relation = HTML::input(array('name' => 'relation',
108 'value' => $args['relation'],
109 'title' => _("Filter by this relation. With autocompletion."),
110 'class' => 'dropdown',
111 'style' => 'width:10em',
112 'acdropdown' => 'true',
113 'autocomplete_assoc' => 'false',
114 'autocomplete_complete' => 'true',
115 'autocomplete_matchsubstring' => 'true',
116 'autocomplete_list' => 'array:semsearch_relations'
118 $queryrel = HTML::input(array('name' => 's',
119 'value' => $args['s'],
120 'title' => _("Filter by this link. These are pagenames. With autocompletion."),
121 'class' => 'dropdown',
122 'acdropdown' => 'true',
123 'autocomplete_complete' => 'true',
124 'autocomplete_matchsubstring' => 'true',
125 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
127 $relsubmit = Button('submit:semsearch[relations]', _("Relations"), false);
128 // just testing some dhtml... not yet done
129 $enhancements = HTML();
130 $nbsp = HTML::raw(' ');
131 $this_uri = $_SERVER['REQUEST_URI'] . '#';
132 $andbutton = new Button(_("AND"), $this_uri, 'wikiaction',
134 'onclick' => "addquery('rel', 'and')",
135 'title' => _("Add an AND query")));
136 $orbutton = new Button(_("OR"), $this_uri, 'wikiaction',
138 'onclick' => "addquery('rel', 'or')",
139 'title' => _("Add an OR query")));
141 $enhancements = HTML::span($andbutton, $nbsp, $orbutton);
142 $instructions = _("Search in pages for a relation with that value (a pagename).");
143 $form1 = HTML::form(array('action' => $action,
145 'accept-charset' => 'UTF-8'),
147 $hiddenfield, HiddenInputs(array('attribute' => '')),
148 $instructions, HTML::br(),
150 (array('border' => 0, 'cellspacing' => 2),
151 HTML::colgroup(array('span' => 6)),
154 HTML::th('Pagefilter'),
155 HTML::th('Relation'),
162 HTML::td($pagefilter, _(": ")),
164 HTML::td(HTML::strong(HTML::tt(' :: '))),
166 HTML::td($nbsp, $relsubmit, $nbsp, $enhancements)))));
168 $allattrs = $dbi->listRelations(false, true, true);
169 if (empty($allrelations) and empty($allattrs)) // be nice to the dummy.
170 $this->_norelations_warning = 1;
171 $svalues = empty($allattrs) ? "" : join("','", $allattrs);
172 $attdef = JavaScript("var semsearch_attributes = new Array('" . $svalues . "')\n"
173 . "var semsearch_op = new Array('"
174 . join("','", $this->_supported_operators)
176 // TODO: We want some more tricks: Autofill the base unit of the selected
177 // attribute into the s area.
178 $attribute = HTML::input(array('name' => 'attribute',
179 'value' => $args['attribute'],
180 'title' => _("Filter by this attribute name. With autocompletion."),
181 'class' => 'dropdown',
182 'style' => 'width:10em',
183 'acdropdown' => 'true',
184 'autocomplete_complete' => 'true',
185 'autocomplete_matchsubstring' => 'true',
186 'autocomplete_assoc' => 'false',
187 'autocomplete_list' => 'array:semsearch_attributes'
188 /* 'autocomplete_onselect' => 'check_unit' */
190 $attr_op = HTML::input(array('name' => 'attr_op',
191 'value' => $args['attr_op'],
192 'title' => _("Comparison operator. With autocompletion."),
193 'class' => 'dropdown',
194 'style' => 'width:2em',
195 'acdropdown' => 'true',
196 'autocomplete_complete' => 'true',
197 'autocomplete_matchsubstring' => 'true',
198 'autocomplete_assoc' => 'false',
199 'autocomplete_list' => 'array:semsearch_op'
201 $queryatt = HTML::input(array('name' => 's',
202 'value' => $args['s'],
203 'title' => _("Filter by this numeric attribute value. With autocompletion."), //?
204 'class' => 'dropdown',
205 'acdropdown' => 'false',
206 'autocomplete_complete' => 'true',
207 'autocomplete_matchsubstring' => 'false',
208 'autocomplete_assoc' => 'false',
209 'autocomplete_list' => 'plugin:SemanticSearch page=' . $args['page'] . ' attribute=^[S] attr_op==~'
211 $andbutton = new Button(_("AND"), $this_uri, 'wikiaction',
213 'onclick' => "addquery('attr', 'and')",
214 'title' => _("Add an AND query")));
215 $orbutton = new Button(_("OR"), $this_uri, 'wikiaction',
217 'onclick' => "addquery('attr', 'or')",
218 'title' => _("Add an OR query")));
220 $enhancements = HTML::span($andbutton, $nbsp, $orbutton);
221 $attsubmit = Button('submit:semsearch[attributes]', _("Attributes"), false);
222 $instructions = HTML::span(_("Search in pages for an attribute with that numeric value."), "\n");
224 $instructions->pushContent
225 (HTML(" ", new Button(_("Advanced..."), _("SemanticSearchAdvanced"))));
226 $form2 = HTML::form(array('action' => $action,
228 'accept-charset' => 'UTF-8'),
230 $hiddenfield, HiddenInputs(array('relation' => '')),
231 $instructions, HTML::br(),
233 (array('border' => 0, 'cellspacing' => 2),
234 HTML::colgroup(array('span' => 6)),
237 HTML::th('Pagefilter'),
238 HTML::th('Attribute'),
245 HTML::td($pagefilter, _(": ")),
246 HTML::td($attribute),
249 HTML::td($nbsp, $attsubmit, $nbsp, $enhancements)))));
251 return HTML($form1, $form2);
254 function regex_query($string, $case_exact, $regex)
256 if ($string != '*' and $regex == 'auto') {
257 if (strcspn($string, ".+*?^$\"") == strlen($string)) {
258 // performance hack: construct an exact query w/o parsing. pcre is fastest.
259 $q = new TextSearchQuery($string, $case_exact, 'pcre');
260 // and now override the fields
261 unset ($q->_stoplist);
262 $q->_regex = TSQ_REGEX_NONE;
264 $q->_tree = new TextSearchQuery_node_exact($string); // hardcode this string
266 $q->_tree = new TextSearchQuery_node_word($string);
268 //$string = "\"" . $string ."\"";
269 //$regex = 'none'; // EXACT or WORD match
272 return new TextSearchQuery($string, $case_exact, $regex);
275 function run($dbi, $argstr, &$request, $basepage)
277 $this->_supported_operators = array(':=', '<', '<=', '>', '>=', '!=', '==', '=~');
278 $this->_text_operators = array(':=', '==', '=~', '!=');
279 $args = $this->getArgs($argstr, $request);
280 if (empty($args['page']))
282 if (!isset($args['s'])) // it might be (integer) 0
284 $posted = $request->getArg("semsearch");
285 $form = $this->showForm($dbi, $request, $args);
286 if (isset($this->_norelations_warning))
288 (HTML::div(array('class' => 'warning'),
289 _("Warning:"), HTML::br(),
290 _("No relations nor attributes in the whole wikidb defined!")
292 , fmt("See %s", WikiLink(_("Help:SemanticRelations")))));
294 // for convenience and harmony we allow GET requests also.
295 if (!$request->isPost()) {
296 if ($relation or $attribute) // check for good GET request
299 return $form; // nobody called us, so just display our supadupa form
301 $pagequery = $this->regex_query($page, $args['case_exact'], $args['regex']);
302 // we might want to check for semsearch['relations'] and semsearch['attributes'] also
303 if (empty($relation) and empty($attribute)) {
304 // so we just clicked without selecting any relation.
305 // hmm. check which button we clicked, before we do the massive alltogether search.
306 if (isset($posted['relations']) and $posted['relations'])
308 elseif (isset($posted['attributes']) and $posted['attributes']) {
310 // here we have to check for invalid text operators. ignore it then
311 if (!in_array($attr_op, $this->_text_operators))
315 $searchtype = "Text";
316 if (!empty($relation)) {
317 $querydesc = $relation . "::" . $s;
318 $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']);
319 $relquery = $this->regex_query($relation, $args['case_exact'], $args['regex']);
320 $links = $dbi->linkSearch($pagequery, $linkquery, 'relation', $relquery);
321 $pagelist = new PageList($info, $exclude, $args);
322 $pagelist->_links = array();
323 while ($link = $links->next()) {
324 $pagelist->addPage($link['pagename']);
325 $pagelist->_links[] = $link;
327 // default (=empty info) wants all three. but we want to be able to override this.
328 // $pagelist->_columns_seen is the exploded info
329 if (!$info or ($info and isset($pagelist->_columns_seen['relation'])))
330 $pagelist->addColumnObject
331 (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist));
332 if (!$args['info'] or ($args['info'] and isset($pagelist->_columns_seen['linkto'])))
333 $pagelist->addColumnObject
334 (new _PageList_Column_SemanticSearch_link('linkto', _("Link"), $pagelist));
336 // can we merge two different pagelist?
337 if (!empty($attribute)) {
338 $relquery = $this->regex_query($attribute, $args['case_exact'], $args['regex']);
339 if (!in_array($attr_op, $this->_supported_operators)) {
340 return HTML($form, $this->error(fmt("Illegal operator: %s",
341 HTML::tt($attr_op))));
343 $s_base = preg_replace("/,/", "", $s);
344 $units = new Units();
345 if (!is_numeric($s_base)) {
346 $s_base = $units->basevalue($s_base);
347 $is_numeric = is_numeric($s_base);
351 // check which type to search with:
352 // at first check if forced text matcher
353 if ($attr_op == '=~') {
354 if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
355 $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
356 $querydesc = "$attribute $attr_op $s";
357 } elseif ($is_numeric) { // do comparison with numbers
358 /* We want to search for multiple attributes also. linkSearch can do this.
359 * But we have to construct the query somehow. (that's why we try the AND OR dhtml)
360 * population < 1 million AND area > 50 km2
361 * Here we check only for one attribute per page.
362 * See SemanticSearchAdvanced for the full expression.
364 // it might not be the best idea to use '*' as variable to expand. hmm.
365 if ($attribute == '*') $attribute = '_star_';
366 $searchtype = "Numeric";
367 $query = $attribute . " " . $attr_op . " " . $s_base;
368 $linkquery = new SemanticAttributeSearchQuery($query, $attribute,
369 $units->baseunit($s));
370 if ($attribute == '_star_') $attribute = '*';
371 $querydesc = $attribute . " " . $attr_op . " " . $s;
373 // no number or unit: check other text matchers or '*' MATCH_ALL
374 } elseif (in_array($attr_op, $this->_text_operators)) {
375 if ($attr_op == '=~') {
376 if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
377 $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
379 $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']);
380 $querydesc = "$attribute $attr_op $s";
382 // should we fail or skip when the user clicks on Relations?
383 } elseif (isset($posted['relations']) and $posted['relations']) {
384 $linkquery = false; // skip
386 $querydesc = $attribute . " " . $attr_op . " " . $s;
387 return HTML($form, $this->error(fmt("Only text operators can be used with strings: %s",
388 HTML::tt($querydesc))));
392 $links = $dbi->linkSearch($pagequery, $linkquery, 'attribute', $relquery);
393 if (empty($relation)) {
394 $pagelist = new PageList($args['info'], $args['exclude'], $args);
395 $pagelist->_links = array();
397 while ($link = $links->next()) {
398 $pagelist->addPage($link['pagename']);
399 $pagelist->_links[] = $link;
401 // default (=empty info) wants all three. but we want to override this.
402 if (!$args['info'] or
403 ($args['info'] and isset($pagelist->_columns_seen['attribute']))
405 $pagelist->addColumnObject
406 (new _PageList_Column_SemanticSearch_relation('attribute',
407 _("Attribute"), $pagelist));
408 if (!$args['info'] or
409 ($args['info'] and isset($pagelist->_columns_seen['value']))
411 $pagelist->addColumnObject
412 (new _PageList_Column_SemanticSearch_link('value',
413 _("Value"), $pagelist));
416 if (!isset($pagelist)) {
417 $querydesc = _("<empty>");
418 $pagelist = new PageList();
421 // We put the form into the caption just to be able to return one pagelist object,
422 // and to still have the convenience form at the top. we could workaround this by
423 // putting the form as WikiFormRich into the actionpage. but thid doesnt look as
424 // nice as this here.
425 $pagelist->setCaption
426 ( // on mozilla the form doesn't fit into the caption very well.
427 HTML($noform ? '' : HTML($form, HTML::hr()),
428 fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"",
429 $searchtype, $querydesc, $page)));
435 class _PageList_Column_SemanticSearch_relation
436 extends _PageList_Column
438 function _PageList_Column_SemanticSearch_relation($field, $heading, &$pagelist)
440 $this->_field = $field;
441 $this->_heading = $heading;
442 $this->_need_rev = false;
443 $this->_iscustom = true;
444 $this->_pagelist =& $pagelist;
447 function _getValue(&$page, $revision_handle)
449 $link = $this->_pagelist->_links[$this->current_row];
450 return WikiLink($link['linkname'], 'if_known');
454 class _PageList_Column_SemanticSearch_link
455 extends _PageList_Column_SemanticSearch_relation
457 function _getValue(&$page, $revision_handle)
459 $link = $this->_pagelist->_links[$this->current_row];
460 if ($this->_field != 'value')
461 return WikiLink($link['linkvalue'], 'if_known');
463 return $link['linkvalue'];
471 // c-hanging-comment-ender-p: nil
472 // indent-tabs-mode: nil