]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/SemanticSearch.php
Whitespace only
[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 getName() {
58         return _("SemanticSearch");
59     }
60     function getDescription() {
61         return _("Search relations and attributes");
62     }
63     function getDefaultArguments() {
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             global $WikiTheme;
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' => $GLOBALS['charset']),
141                             $reldef,
142                             $hiddenfield, HiddenInputs(array('attribute'=>'')),
143                             $instructions, HTML::br(),
144                             HTML::table
145                             (array('border' => 0,'cellspacing' => 2),
146                              HTML::colgroup(array('span' => 6)),
147                              HTML::thead
148                              (HTML::tr(
149                                        HTML::th('Pagefilter'),
150                                        HTML::th('Relation'),
151                                        HTML::th(),
152                                        HTML::th('Links'),
153                                        HTML::th()
154                                       )),
155                              HTML::tbody
156                              (HTML::tr(
157                                        HTML::td($pagefilter, _(": ")),
158                                        HTML::td($relation),
159                                        HTML::td(HTML::strong(HTML::tt('  ::  '))),
160                                        HTML::td($queryrel),
161                                        HTML::td($nbsp, $relsubmit, $nbsp, $enhancements)))));
162
163         $allattrs = $dbi->listRelations(false,true,true);
164         if (empty($allrelations) and empty($allattrs)) // be nice to the dummy.
165             $this->_norelations_warning = 1;
166         $svalues = empty($allattrs) ? "" : join("','", $allattrs);
167         $attdef = JavaScript("var semsearch_attributes = new Array('".$svalues."')\n"
168                             ."var semsearch_op = new Array('"
169                                   .join("','", $this->_supported_operators)
170                                   ."')");
171         // TODO: We want some more tricks: Autofill the base unit of the selected
172         // attribute into the s area.
173         $attribute = HTML::input(array('name' => 'attribute',
174                                        'value' => $args['attribute'],
175                                        'title' => _("Filter by this attribute name. With autocompletion."),
176                                        'class' => 'dropdown',
177                                        'style' => 'width:10em',
178                                        'acdropdown' => 'true',
179                                        'autocomplete_complete' => 'true',
180                                        'autocomplete_matchsubstring' => 'true',
181                                        'autocomplete_assoc' => 'false',
182                                        'autocomplete_list' => 'array:semsearch_attributes'
183                                        /* 'autocomplete_onselect' => 'check_unit' */
184                                       ), '');
185         $attr_op = HTML::input(array('name' => 'attr_op',
186                                         'value' => $args['attr_op'],
187                                         'title' => _("Comparison operator. With autocompletion."),
188                                         'class' => 'dropdown',
189                                         'style' => 'width:2em',
190                                         'acdropdown' => 'true',
191                                         'autocomplete_complete' => 'true',
192                                         'autocomplete_matchsubstring' => 'true',
193                                         'autocomplete_assoc' => 'false',
194                                         'autocomplete_list' => 'array:semsearch_op'
195                                       ), '');
196         $queryatt = HTML::input(array('name' => 's',
197                                       'value' => $args['s'],
198                                       'title' => _("Filter by this numeric attribute value. With autocompletion."), //?
199                                       'class' => 'dropdown',
200                                       'acdropdown' => 'false',
201                                       'autocomplete_complete' => 'true',
202                                       'autocomplete_matchsubstring' => 'false',
203                                       'autocomplete_assoc' => 'false',
204                                       'autocomplete_list' => 'plugin:SemanticSearch page='.$args['page'].' attribute=^[S] attr_op==~'
205                                       ), '');
206         $andbutton = new Button(_("AND"),$this_uri,'wikiaction',
207                                 array(
208                                       'onclick' => "addquery('attr', 'and')",
209                                       'title' => _("Add an AND query")));
210         $orbutton = new Button(_("OR"),$this_uri,'wikiaction',
211                                 array(
212                                       'onclick' => "addquery('attr', 'or')",
213                                       'title' => _("Add an OR query")));
214         if (DEBUG)
215             $enhancements = HTML::span($andbutton, $nbsp, $orbutton);
216         $attsubmit = Button('submit:semsearch[attributes]', _("Attributes"), false);
217         $instructions = HTML::span(_("Search in pages for an attribute with that numeric value."),"\n");
218         if (DEBUG)
219             $instructions->pushContent
220                 (HTML(" ", new Button(_("Advanced..."),_("SemanticSearchAdvanced"))));
221         $form2 = HTML::form(array('action' => $action,
222                                   'method' => 'post',
223                                   'accept-charset' => $GLOBALS['charset']),
224                             $attdef,
225                             $hiddenfield, HiddenInputs(array('relation'=>'')),
226                             $instructions, HTML::br(),
227                             HTML::table
228                             (array('border' => 0,'cellspacing' => 2),
229                              HTML::colgroup(array('span' => 6)),
230                              HTML::thead
231                              (HTML::tr(
232                                        HTML::th('Pagefilter'),
233                                        HTML::th('Attribute'),
234                                        HTML::th('Op'),
235                                        HTML::th('Value'),
236                                        HTML::th()
237                                       )),
238                              HTML::tbody
239                              (HTML::tr(
240                                        HTML::td($pagefilter, _(": ")),
241                                        HTML::td($attribute),
242                                        HTML::td($attr_op),
243                                        HTML::td($queryatt),
244                                        HTML::td($nbsp, $attsubmit, $nbsp, $enhancements)))));
245
246         return HTML($form1, $form2);
247     }
248
249     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;
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         global $WikiTheme;
271
272         $this->_supported_operators = array(':=','<','<=','>','>=','!=','==','=~');
273         $this->_text_operators = array(':=','==','=~','!=');
274         $args = $this->getArgs($argstr, $request);
275         if (empty($args['page']))
276             $args['page'] = "*";
277         if (!isset($args['s'])) // it might be (integer) 0
278             $args['s'] = "*";
279         $posted = $request->getArg("semsearch");
280         $form = $this->showForm($dbi, $request, $args);
281         if (isset($this->_norelations_warning))
282             $form->pushContent
283                 (HTML::div(array('class' => 'warning'),
284                            _("Warning:"),HTML::br(),
285                            _("No relations nor attributes in the whole wikidb defined!")
286                            ,"\n"
287                            ,fmt("See %s",WikiLink(_("Help:SemanticRelations")))));
288         extract($args);
289         // for convenience and harmony we allow GET requests also.
290         if (!$request->isPost()) {
291             if ($relation or $attribute) // check for good GET request
292                 ;
293             else
294                 return $form; // nobody called us, so just display our supadupa form
295         }
296         $pagequery = $this->regex_query($page, $args['case_exact'], $args['regex']);
297         // we might want to check for semsearch['relations'] and semsearch['attributes'] also
298         if (empty($relation) and empty($attribute)) {
299             // so we just clicked without selecting any relation.
300             // hmm. check which button we clicked, before we do the massive alltogether search.
301             if (isset($posted['relations']) and $posted['relations'])
302                 $relation = '*';
303             elseif (isset($posted['attributes']) and $posted['attributes']) {
304                 $attribute = '*';
305                 // here we have to check for invalid text operators. ignore it then
306                 if (!in_array($attr_op, $this->_text_operators))
307                     $attribute = '';
308             }
309         }
310         $searchtype = "Text";
311         if (!empty($relation)) {
312             $querydesc = $relation."::".$s;
313             $linkquery =  $this->regex_query($s, $args['case_exact'], $args['regex']);
314             $relquery = $this->regex_query($relation, $args['case_exact'], $args['regex']);
315             $links = $dbi->linkSearch($pagequery, $linkquery, 'relation', $relquery);
316             $pagelist = new PageList($info, $exclude, $args);
317             $pagelist->_links = array();
318             while ($link = $links->next()) {
319                 $pagelist->addPage($link['pagename']);
320                 $pagelist->_links[] = $link;
321             }
322             // default (=empty info) wants all three. but we want to be able to override this.
323             // $pagelist->_columns_seen is the exploded info
324             if (!$info or ($info and isset($pagelist->_columns_seen['relation'])))
325                 $pagelist->addColumnObject
326                     (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist));
327             if (!$args['info'] or ($args['info'] and isset($pagelist->_columns_seen['linkto'])))
328                 $pagelist->addColumnObject
329                     (new _PageList_Column_SemanticSearch_link('linkto', _("Link"), $pagelist));
330         }
331         // can we merge two different pagelist?
332         if (!empty($attribute)) {
333             $relquery =  $this->regex_query($attribute, $args['case_exact'], $args['regex']);
334             if (!in_array($attr_op, $this->_supported_operators)) {
335                 return HTML($form, $this->error(fmt("Illegal operator: %s",
336                                                     HTML::tt($attr_op))));
337             }
338             $s_base = preg_replace("/,/","", $s);
339             $units = new Units();
340             if (!is_numeric($s_base)) {
341                 $s_base = $units->basevalue($s_base);
342                 $is_numeric = is_numeric($s_base);
343             } else {
344                 $is_numeric = true;
345             }
346             // check which type to search with:
347             // at first check if forced text matcher
348             if ($attr_op == '=~') {
349                 if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
350                 $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
351                 $querydesc = "$attribute $attr_op $s";
352             } elseif ($is_numeric) { // do comparison with numbers
353                 /* We want to search for multiple attributes also. linkSearch can do this.
354                  * But we have to construct the query somehow. (that's why we try the AND OR dhtml)
355                  *     population < 1 million AND area > 50 km2
356                  * Here we check only for one attribute per page.
357                  * See SemanticSearchAdvanced for the full expression.
358                  */
359                 // it might not be the best idea to use '*' as variable to expand. hmm.
360                 if ($attribute == '*') $attribute = '_star_';
361                 $searchtype = "Numeric";
362                 $query = $attribute." ".$attr_op." ".$s_base;
363                 $linkquery = new SemanticAttributeSearchQuery($query, $attribute,
364                                                               $units->baseunit($s));
365                 if ($attribute == '_star_') $attribute = '*';
366                 $querydesc = $attribute." ".$attr_op." ".$s;
367
368             // no number or unit: check other text matchers or '*' MATCH_ALL
369             } elseif (in_array($attr_op, $this->_text_operators)) {
370                 if ($attr_op == '=~') {
371                     if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
372                     $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
373                 }
374                 else
375                     $linkquery =  $this->regex_query($s, $args['case_exact'], $args['regex']);
376                 $querydesc = "$attribute $attr_op $s";
377
378             // should we fail or skip when the user clicks on Relations?
379             } elseif (isset($posted['relations']) and $posted['relations'])  {
380                 $linkquery = false; // skip
381             } else {
382                 $querydesc = $attribute." ".$attr_op." ".$s;
383                 return HTML($form, $this->error(fmt("Only text operators can be used with strings: %s",
384                                                     HTML::tt($querydesc))));
385
386             }
387             if ($linkquery) {
388                 $links = $dbi->linkSearch($pagequery, $linkquery, 'attribute', $relquery);
389                 if (empty($relation)) {
390                     $pagelist = new PageList($args['info'], $args['exclude'], $args);
391                     $pagelist->_links = array();
392                 }
393                 while ($link = $links->next()) {
394                     $pagelist->addPage($link['pagename']);
395                     $pagelist->_links[] = $link;
396                 }
397                 // default (=empty info) wants all three. but we want to override this.
398                 if (!$args['info'] or
399                     ($args['info'] and isset($pagelist->_columns_seen['attribute'])))
400                     $pagelist->addColumnObject
401                         (new _PageList_Column_SemanticSearch_relation('attribute',
402                                 _("Attribute"), $pagelist));
403                 if (!$args['info'] or
404                     ($args['info'] and isset($pagelist->_columns_seen['value'])))
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         $this->_field = $field;
434         $this->_heading = $heading;
435         $this->_need_rev = false;
436         $this->_iscustom = true;
437         $this->_pagelist =& $pagelist;
438     }
439     function _getValue(&$page, $revision_handle) {
440         if (is_object($page)) $text = $page->getName();
441         else $text = $page;
442         $link = $this->_pagelist->_links[$this->current_row];
443         return WikiLink($link['linkname'],'if_known');
444     }
445 }
446 class _PageList_Column_SemanticSearch_link
447 extends _PageList_Column_SemanticSearch_relation
448 {
449     function _getValue(&$page, $revision_handle) {
450         if (is_object($page)) $text = $page->getName();
451         else $text = $page;
452         $link = $this->_pagelist->_links[$this->current_row];
453         if ($this->_field != 'value')
454             return WikiLink($link['linkvalue'],'if_known');
455         else
456             return $link['linkvalue'];
457     }
458 }
459
460 // Local Variables:
461 // mode: php
462 // tab-width: 8
463 // c-basic-offset: 4
464 // c-hanging-comment-ender-p: nil
465 // indent-tabs-mode: nil
466 // End: