]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/SemanticSearch.php
Use CSS
[SourceForge/phpwiki.git] / lib / plugin / SemanticSearch.php
1 <?php
2
3 /*
4  * Copyright 2007 Reini Urban
5  * Copyright 2009 Marc-Etienne Vargenau, Alcatel-Lucent
6  *
7  * This file is part of PhpWiki.
8  *
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.
13  *
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.
18  *
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.
22  */
23
24 require_once 'lib/PageList.php';
25 require_once 'lib/TextSearchQuery.php';
26 require_once 'lib/Units.php';
27 require_once 'lib/SemanticWeb.php';
28
29 /**
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.
34  *
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
40  *
41  * Limitation:
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.
47  *
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"
51  *
52  * @author: Reini Urban
53  */
54 class WikiPlugin_SemanticSearch
55     extends WikiPlugin
56 {
57     function getDescription()
58     {
59         return _("Search relations and attributes.");
60     }
61
62     function getDefaultArguments()
63     {
64         return array_merge
65         (
66             PageList::supportedArgs(), // paging and more.
67             array(
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"
74                 'units' => '', // ?
75                 'case_exact' => true,
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
81             ));
82     }
83
84     function showForm(&$dbi, &$request, $args)
85     {
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'
98         ), '');
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'
112         ), '');
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'
121         ), '');
122         $relsubmit = Button('submit:semsearch[relations]', _("Relations"), false);
123         // just testing some dhtml... not yet done
124         $enhancements = HTML();
125         $nbsp = HTML::raw('&nbsp;');
126         $this_uri = $_SERVER['REQUEST_URI'] . '#';
127         $andbutton = new Button(_("AND"), $this_uri, 'wikiaction',
128             array(
129                 'onclick' => "addquery('rel', 'and')",
130                 'title' => _("Add an AND query")));
131         $orbutton = new Button(_("OR"), $this_uri, 'wikiaction',
132             array(
133                 'onclick' => "addquery('rel', 'or')",
134                 'title' => _("Add an OR query")));
135         if (DEBUG)
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,
139                 'method' => 'post',
140                 'accept-charset' => 'UTF-8'),
141             $reldef,
142             $hiddenfield, HiddenInputs(array('attribute' => '')),
143             $instructions, HTML::br(),
144             HTML::table(
145                 HTML::colgroup(array('span' => 6)),
146                 HTML::thead
147                 (HTML::tr(
148                     HTML::th('Pagefilter'),
149                     HTML::th('Relation'),
150                     HTML::th(),
151                     HTML::th('Links'),
152                     HTML::th()
153                 )),
154                 HTML::tbody
155                 (HTML::tr(
156                     HTML::td($pagefilter, _(": ")),
157                     HTML::td($relation),
158                     HTML::td(HTML::strong(HTML::tt('  ::  '))),
159                     HTML::td($queryrel),
160                     HTML::td($nbsp, $relsubmit, $nbsp, $enhancements)))));
161
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)
169             . "')");
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' */
183         ), '');
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'
194         ), '');
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==~'
204         ), '');
205         $andbutton = new Button(_("AND"), $this_uri, 'wikiaction',
206             array(
207                 'onclick' => "addquery('attr', 'and')",
208                 'title' => _("Add an AND query")));
209         $orbutton = new Button(_("OR"), $this_uri, 'wikiaction',
210             array(
211                 'onclick' => "addquery('attr', 'or')",
212                 'title' => _("Add an OR query")));
213         if (DEBUG)
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");
217         if (DEBUG)
218             $instructions->pushContent
219             (HTML(" ", new Button(_("Advanced..."), _("SemanticSearchAdvanced"))));
220         $form2 = HTML::form(array('action' => $action,
221                 'method' => 'post',
222                 'accept-charset' => 'UTF-8'),
223             $attdef,
224             $hiddenfield, HiddenInputs(array('relation' => '')),
225             $instructions, HTML::br(),
226             HTML::table
227             (array('border' => 0, 'cellspacing' => 2),
228                 HTML::colgroup(array('span' => 6)),
229                 HTML::thead
230                 (HTML::tr(
231                     HTML::th('Pagefilter'),
232                     HTML::th('Attribute'),
233                     HTML::th('Op'),
234                     HTML::th('Value'),
235                     HTML::th()
236                 )),
237                 HTML::tbody
238                 (HTML::tr(
239                     HTML::td($pagefilter, _(": ")),
240                     HTML::td($attribute),
241                     HTML::td($attr_op),
242                     HTML::td($queryatt),
243                     HTML::td($nbsp, $attsubmit, $nbsp, $enhancements)))));
244
245         return HTML($form1, $form2);
246     }
247
248     function regex_query($string, $case_exact, $regex)
249     {
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;
257                 if ($case_exact)
258                     $q->_tree = new TextSearchQuery_node_exact($string); // hardcode this string
259                 else
260                     $q->_tree = new TextSearchQuery_node_word($string);
261                 return $q;
262                 //$string = "\"" . $string ."\"";
263                 //$regex = 'none'; // EXACT or WORD match
264             }
265         }
266         return new TextSearchQuery($string, $case_exact, $regex);
267     }
268
269     function run($dbi, $argstr, &$request, $basepage)
270     {
271         $this->_supported_operators = array(':=', '<', '<=', '>', '>=', '!=', '==', '=~');
272         $this->_text_operators = array(':=', '==', '=~', '!=');
273         $args = $this->getArgs($argstr, $request);
274         if (empty($args['page']))
275             $args['page'] = "*";
276         if (!isset($args['s'])) // it might be (integer) 0
277             $args['s'] = "*";
278         $posted = $request->getArg("semsearch");
279         $form = $this->showForm($dbi, $request, $args);
280         if (isset($this->_norelations_warning))
281             $form->pushContent
282             (HTML::div(array('class' => 'warning'),
283                 _("Warning:"), HTML::br(),
284                 _("No relations nor attributes in the whole wikidb defined!")
285                 , "\n"
286                 , fmt("See %s", WikiLink(_("Help").":"._("SemanticRelations")))));
287         extract($args);
288         // for convenience and harmony we allow GET requests also.
289         if (!$request->isPost()) {
290             if ($relation or $attribute) // check for good GET request
291                 ;
292             else
293                 return $form; // nobody called us, so just display our supadupa form
294         }
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'])
301                 $relation = '*';
302             elseif (isset($posted['attributes']) and $posted['attributes']) {
303                 $attribute = '*';
304                 // here we have to check for invalid text operators. ignore it then
305                 if (!in_array($attr_op, $this->_text_operators))
306                     $attribute = '';
307             }
308         }
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;
320             }
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));
329         }
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))));
336             }
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);
342             } else {
343                 $is_numeric = true;
344             }
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.
357                  */
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;
366
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');
372                 } else
373                     $linkquery = $this->regex_query($s, $args['case_exact'], $args['regex']);
374                 $querydesc = "$attribute $attr_op $s";
375
376                 // should we fail or skip when the user clicks on Relations?
377             } elseif (isset($posted['relations']) and $posted['relations']) {
378                 $linkquery = false; // skip
379             } else {
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))));
383
384             }
385             if ($linkquery) {
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();
390                 }
391                 while ($link = $links->next()) {
392                     $pagelist->addPage($link['pagename']);
393                     $pagelist->_links[] = $link;
394                 }
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']))
398                 )
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']))
404                 )
405                     $pagelist->addColumnObject
406                     (new _PageList_Column_SemanticSearch_link('value',
407                         _("Value"), $pagelist));
408             }
409         }
410         if (!isset($pagelist)) {
411             $querydesc = _("<empty>");
412             $pagelist = new PageList();
413         }
414         if (!$noheader) {
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)));
424         }
425         return $pagelist;
426     }
427 }
428
429 class _PageList_Column_SemanticSearch_relation
430     extends _PageList_Column
431 {
432     function _PageList_Column_SemanticSearch_relation($field, $heading, &$pagelist)
433     {
434         $this->_field = $field;
435         $this->_heading = $heading;
436         $this->_need_rev = false;
437         $this->_iscustom = true;
438         $this->_pagelist =& $pagelist;
439     }
440
441     function _getValue(&$page, $revision_handle)
442     {
443         $link = $this->_pagelist->_links[$this->current_row];
444         return WikiLink($link['linkname'], 'if_known');
445     }
446 }
447
448 class _PageList_Column_SemanticSearch_link
449     extends _PageList_Column_SemanticSearch_relation
450 {
451     function _getValue(&$page, $revision_handle)
452     {
453         $link = $this->_pagelist->_links[$this->current_row];
454         if ($this->_field != 'value')
455             return WikiLink($link['linkvalue'], 'if_known');
456         else
457             return $link['linkvalue'];
458     }
459 }
460
461 // Local Variables:
462 // mode: php
463 // tab-width: 8
464 // c-basic-offset: 4
465 // c-hanging-comment-ender-p: nil
466 // indent-tabs-mode: nil
467 // End: