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
20 * along with PhpWiki; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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
58 return _("SemanticSearch");
60 function getDescription() {
61 return _("Search relations and attributes");
63 function getVersion() {
64 return preg_replace("/[Revision: $]/", '',
67 function getDefaultArguments() {
70 PageList::supportedArgs(), // paging and more.
72 's' => "*", // linkvalue query string
73 'page' => "*", // which pages (glob allowed), default: all
74 'relation' => '', // linkname. which relations. default all
75 'attribute' => '', // linkname. which attributes. default all
76 'attr_op' => ':=', // a funny written way for equality for pure aesthetic pleasure
77 // "All attributes which have this value set"
80 'regex' => 'auto',// is different here.
81 // no word splitting, if no regex op is present, defaults to exact match
82 'noform' => false, // don't show form with results.
83 'noheader' => false, // no caption
84 'info' => false // valid: pagename,relation,linkto,attribute,value and all other pagelist columns
88 function showForm (&$dbi, &$request, $args) {
90 $action = $request->getPostURL();
91 $hiddenfield = HiddenInputs($request->getArgs(),'',
92 array('action','page','s','semsearch',
93 'relation','attribute'));
94 $pagefilter = HTML::input(array('name' => 'page',
95 'value' => $args['page'],
96 'title' => _("Search only in these pages. With autocompletion."),
97 'class' => 'dropdown',
98 'acdropdown' => 'true',
99 'autocomplete_complete' => 'true',
100 'autocomplete_matchsubstring' => 'false',
101 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
103 $allrelations = $dbi->listRelations(false,false,true);
104 $svalues = empty($allrelations) ? "" : join("','", $allrelations);
105 $reldef = JavaScript("var semsearch_relations = new Array('".$svalues."')");
106 $relation = HTML::input(array('name' => 'relation',
107 'value' => $args['relation'],
108 'title' => _("Filter by this relation. With autocompletion."),
109 'class' => 'dropdown',
110 'style' => 'width:10em',
111 'acdropdown' => 'true',
112 'autocomplete_assoc' => 'false',
113 'autocomplete_complete' => 'true',
114 'autocomplete_matchsubstring' => 'true',
115 'autocomplete_list' => 'array:semsearch_relations'
117 $queryrel = HTML::input(array('name' => 's',
118 'value' => $args['s'],
119 'title' => _("Filter by this link. These are pagenames. With autocompletion."),
120 'class' => 'dropdown',
121 'acdropdown' => 'true',
122 'autocomplete_complete' => 'true',
123 'autocomplete_matchsubstring' => 'true',
124 'autocomplete_list' => 'xmlrpc:wiki.titleSearch ^[S] 4'
126 $relsubmit = Button('submit:semsearch[relations]', _("Relations"), false);
127 // just testing some dhtml... not yet done
128 $enhancements = HTML();
129 $nbsp = HTML::raw(' ');
130 $this_uri = $_SERVER['REQUEST_URI'].'#';
131 $andbutton = new Button(_("AND"),$this_uri,'wikiaction',
133 'onclick' => "addquery('rel', 'and')",
134 'title' => _("Add an AND query")));
135 $orbutton = new Button(_("OR"),$this_uri,'wikiaction',
137 'onclick' => "addquery('rel', 'or')",
138 'title' => _("Add an OR query")));
140 $enhancements = HTML::span($andbutton, $nbsp, $orbutton);
141 $instructions = _("Search in pages for a relation with that value (a pagename).");
142 $form1 = HTML::form(array('action' => $action,
144 'accept-charset' => $GLOBALS['charset']),
146 $hiddenfield, HiddenInputs(array('attribute'=>'')),
147 $instructions, HTML::br(),
149 (array('border' => 0,'cellspacing' => 2),
150 HTML::colgroup(array('span' => 6)),
153 HTML::th('Pagefilter'),
154 HTML::th('Relation'),
161 HTML::td($pagefilter, ": "),
163 HTML::td(HTML::strong(HTML::tt(' :: '))),
165 HTML::td($nbsp, $relsubmit, $nbsp, $enhancements)))));
167 $allattrs = $dbi->listRelations(false,true,true);
168 if (empty($allrelations) and empty($allattrs)) // be nice to the dummy.
169 $this->_norelations_warning = 1;
170 $svalues = empty($allattrs) ? "" : join("','", $allattrs);
171 $attdef = JavaScript("var semsearch_attributes = new Array('".$svalues."')\n"
172 ."var semsearch_op = new Array('"
173 .join("','", $this->_supported_operators)
175 // TODO: We want some more tricks: Autofill the base unit of the selected
176 // attribute into the s area.
177 $attribute = HTML::input(array('name' => 'attribute',
178 'value' => $args['attribute'],
179 'title' => _("Filter by this attribute name. With autocompletion."),
180 'class' => 'dropdown',
181 'style' => 'width:10em',
182 'acdropdown' => 'true',
183 'autocomplete_complete' => 'true',
184 'autocomplete_matchsubstring' => 'true',
185 'autocomplete_assoc' => 'false',
186 'autocomplete_list' => 'array:semsearch_attributes'
187 /* 'autocomplete_onselect' => 'check_unit' */
189 $attr_op = HTML::input(array('name' => 'attr_op',
190 'value' => $args['attr_op'],
191 'title' => _("Comparison operator. With autocompletion."),
192 'class' => 'dropdown',
193 'style' => 'width:2em',
194 'acdropdown' => 'true',
195 'autocomplete_complete' => 'true',
196 'autocomplete_matchsubstring' => 'true',
197 'autocomplete_assoc' => 'false',
198 'autocomplete_list' => 'array:semsearch_op'
200 $queryatt = HTML::input(array('name' => 's',
201 'value' => $args['s'],
202 'title' => _("Filter by this numeric attribute value. With autocompletion."), //?
203 'class' => 'dropdown',
204 'acdropdown' => 'false',
205 'autocomplete_complete' => 'true',
206 'autocomplete_matchsubstring' => 'false',
207 'autocomplete_assoc' => 'false',
208 'autocomplete_list' => 'plugin:SemanticSearch page='.$args['page'].' attribute=^[S] attr_op==~'
210 $andbutton = new Button(_("AND"),$this_uri,'wikiaction',
212 'onclick' => "addquery('attr', 'and')",
213 'title' => _("Add an AND query")));
214 $orbutton = new Button(_("OR"),$this_uri,'wikiaction',
216 'onclick' => "addquery('attr', 'or')",
217 'title' => _("Add an OR query")));
219 $enhancements = HTML::span($andbutton, $nbsp, $orbutton);
220 $attsubmit = Button('submit:semsearch[attributes]', _("Attributes"), false);
221 $instructions = HTML::span(_("Search in pages for an attribute with that numeric value."),"\n");
223 $instructions->pushContent
224 (HTML(" ", new Button(_("Advanced..."),_("SemanticSearchAdvanced"))));
225 $form2 = HTML::form(array('action' => $action,
227 'accept-charset' => $GLOBALS['charset']),
229 $hiddenfield, HiddenInputs(array('relation'=>'')),
230 $instructions, HTML::br(),
232 (array('border' => 0,'cellspacing' => 2),
233 HTML::colgroup(array('span' => 6)),
236 HTML::th('Pagefilter'),
237 HTML::th('Attribute'),
244 HTML::td($pagefilter, ": "),
245 HTML::td($attribute),
248 HTML::td($nbsp, $attsubmit, $nbsp, $enhancements)))));
250 return HTML($form1, $form2);
253 function regex_query ($string, $case_exact, $regex) {
254 if ($string != '*' and $regex == 'auto') {
255 if (strcspn($string, ".+*?^$\"") == strlen($string)) {
256 // performance hack: construct an exact query w/o parsing. pcre is fastest.
257 $q = new TextSearchQuery($string, $case_exact, 'pcre');
258 // and now override the fields
259 unset ($q->_stoplist);
260 $q->_regex = TSQ_REGEX_NONE;
262 $q->_tree = new TextSearchQuery_node_exact($string); // hardcode this string
264 $q->_tree = new TextSearchQuery_node_word($string);
266 //$string = "\"" . $string ."\"";
267 //$regex = 'none'; // EXACT or WORD match
270 return new TextSearchQuery($string, $case_exact, $regex);
273 function run ($dbi, $argstr, &$request, $basepage) {
276 $this->_supported_operators = array(':=','<','<=','>','>=','!=','==','=~');
277 $this->_text_operators = array(':=','==','=~','!=');
278 $args = $this->getArgs($argstr, $request);
279 if (empty($args['page']))
281 if (!isset($args['s'])) // it might be (integer) 0
283 $posted = $request->getArg("semsearch");
284 $form = $this->showForm($dbi, $request, $args);
285 if (isset($this->_norelations_warning))
287 (HTML::div(array('class' => 'warning'),
288 _("Warning:"),HTML::br(),
289 _("No relations nor attributes in the whole wikidb defined!")
291 ,fmt("See %s",WikiLink(_("Help:SemanticRelations")))));
293 // for convenience and harmony we allow GET requests also.
294 if (!$request->isPost()) {
295 if ($relation or $attribute) // check for good GET request
298 return $form; // nobody called us, so just display our supadupa form
300 $pagequery = $this->regex_query($page, $args['case_exact'], $args['regex']);
301 // we might want to check for semsearch['relations'] and semsearch['attributes'] also
302 if (empty($relation) and empty($attribute)) {
303 // so we just clicked without selecting any relation.
304 // hmm. check which button we clicked, before we do the massive alltogether search.
305 if (isset($posted['relations']) and $posted['relations'])
307 elseif (isset($posted['attributes']) and $posted['attributes']) {
309 // here we have to check for invalid text operators. ignore it then
310 if (!in_array($attr_op, $this->_text_operators))
314 $searchtype = "Text";
315 if (!empty($relation)) {
316 $querydesc = $relation."::".$s;
317 $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']);
318 $relquery = $this->regex_query($relation, $args['case_exact'], $args['regex']);
319 $links = $dbi->linkSearch($pagequery, $linkquery, 'relation', $relquery);
320 $pagelist = new PageList($info, $exclude, $args);
321 $pagelist->_links = array();
322 while ($link = $links->next()) {
323 $pagelist->addPage($link['pagename']);
324 $pagelist->_links[] = $link;
326 // default (=empty info) wants all three. but we want to be able to override this.
327 // $pagelist->_columns_seen is the exploded info
328 if (!$info or ($info and isset($pagelist->_columns_seen['relation'])))
329 $pagelist->addColumnObject
330 (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist));
331 if (!$args['info'] or ($args['info'] and isset($pagelist->_columns_seen['linkto'])))
332 $pagelist->addColumnObject
333 (new _PageList_Column_SemanticSearch_link('linkto', _("Link"), $pagelist));
335 // can we merge two different pagelist?
336 if (!empty($attribute)) {
337 $relquery = $this->regex_query($attribute, $args['case_exact'], $args['regex']);
338 if (!in_array($attr_op, $this->_supported_operators)) {
339 return HTML($form, $this->error(fmt("Illegal operator: %s",
340 HTML::tt($attr_op))));
342 $s_base = preg_replace("/,/","", $s);
343 $units = new Units();
344 if (!is_numeric($s_base)) {
345 $s_base = $units->basevalue($s_base);
346 $is_numeric = is_numeric($s_base);
350 // check which type to search with:
351 // at first check if forced text matcher
352 if ($attr_op == '=~') {
353 if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
354 $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
355 $querydesc = "$attribute $attr_op $s";
356 } elseif ($is_numeric) { // do comparison with numbers
357 /* We want to search for multiple attributes also. linkSearch can do this.
358 * But we have to construct the query somehow. (that's why we try the AND OR dhtml)
359 * population < 1 million AND area > 50 km2
360 * Here we check only for one attribute per page.
361 * See SemanticSearchAdvanced for the full expression.
363 // it might not be the best idea to use '*' as variable to expand. hmm.
364 if ($attribute == '*') $attribute = '_star_';
365 $searchtype = "Numeric";
366 $query = $attribute." ".$attr_op." ".$s_base;
367 $linkquery = new SemanticAttributeSearchQuery($query, $attribute,
368 $units->baseunit($s));
369 if ($attribute == '_star_') $attribute = '*';
370 $querydesc = $attribute." ".$attr_op." ".$s;
372 // no number or unit: check other text matchers or '*' MATCH_ALL
373 } elseif (in_array($attr_op, $this->_text_operators)) {
374 if ($attr_op == '=~') {
375 if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
376 $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'])))
404 $pagelist->addColumnObject
405 (new _PageList_Column_SemanticSearch_relation('attribute',
406 _("Attribute"), $pagelist));
407 if (!$args['info'] or
408 ($args['info'] and isset($pagelist->_columns_seen['value'])))
409 $pagelist->addColumnObject
410 (new _PageList_Column_SemanticSearch_link('value',
411 _("Value"), $pagelist));
414 if (!isset($pagelist)) {
415 $querydesc = _("<empty>");
416 $pagelist = new PageList();
419 // We put the form into the caption just to be able to return one pagelist object,
420 // and to still have the convenience form at the top. we could workaround this by
421 // putting the form as WikiFormRich into the actionpage. but thid doesnt look as
422 // nice as this here.
423 $pagelist->setCaption
424 ( // on mozilla the form doesn't fit into the caption very well.
425 HTML($noform ? '' : HTML($form,HTML::hr()),
426 fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"",
427 $searchtype, $querydesc, $page)));
433 class _PageList_Column_SemanticSearch_relation
434 extends _PageList_Column
436 function _PageList_Column_SemanticSearch_relation ($field, $heading, &$pagelist) {
437 $this->_field = $field;
438 $this->_heading = $heading;
439 $this->_need_rev = false;
440 $this->_iscustom = true;
441 $this->_pagelist =& $pagelist;
443 function _getValue(&$page, $revision_handle) {
444 if (is_object($page)) $text = $page->getName();
446 $link = $this->_pagelist->_links[$this->current_row];
447 return WikiLink($link['linkname'],'if_known');
450 class _PageList_Column_SemanticSearch_link
451 extends _PageList_Column_SemanticSearch_relation
453 function _getValue(&$page, $revision_handle) {
454 if (is_object($page)) $text = $page->getName();
456 $link = $this->_pagelist->_links[$this->current_row];
457 if ($this->_field != 'value')
458 return WikiLink($link['linkvalue'],'if_known');
460 return $link['linkvalue'];
468 // c-hanging-comment-ender-p: nil
469 // indent-tabs-mode: nil