]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/SemanticSearch.php
Test 'limit' argument is numeric to avoid SQL injection
[SourceForge/phpwiki.git] / lib / plugin / SemanticSearch.php
1 <?php // -*-php-*-
2 rcs_id('$Id$');
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
20  along with PhpWiki; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 getVersion() {
64         return preg_replace("/[Revision: $]/", '',
65                             "\$Revision$");
66     }
67     function getDefaultArguments() { 
68         return array_merge
69             (
70              PageList::supportedArgs(),  // paging and more.
71              array(
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"
78                    'units'      => '',   // ?
79                    'case_exact' => true,
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
85                    ));
86     }
87
88     function showForm (&$dbi, &$request, $args) {
89         global $WikiTheme;
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'
102                                         ), '');
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'
116                                       ), '');
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'
125                                       ), '');
126         $relsubmit = Button('submit:semsearch[relations]',  _("Relations"), false);
127         // just testing some dhtml... not yet done
128         $enhancements = HTML();
129         $nbsp = HTML::raw('&nbsp;');
130         $this_uri = $_SERVER['REQUEST_URI'].'#';
131         $andbutton = new Button(_("AND"),$this_uri,'wikiaction',
132                                 array(
133                                       'onclick' => "addquery('rel', 'and')",
134                                       'title' => _("Add an AND query")));
135         $orbutton = new Button(_("OR"),$this_uri,'wikiaction',
136                                 array(
137                                       'onclick' => "addquery('rel', 'or')",
138                                       'title' => _("Add an OR query")));
139         if (DEBUG)
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,
143                                   'method' => 'post',
144                                   'accept-charset' => $GLOBALS['charset']),
145                             $reldef,
146                             $hiddenfield, HiddenInputs(array('attribute'=>'')),
147                             $instructions, HTML::br(),
148                             HTML::table
149                             (array('border' => 0,'cellspacing' => 2),
150                              HTML::colgroup(array('span' => 6)),
151                              HTML::thead
152                              (HTML::tr(
153                                        HTML::th('Pagefilter'),
154                                        HTML::th('Relation'),
155                                        HTML::th(),
156                                        HTML::th('Links'),
157                                        HTML::th()
158                                       )),
159                              HTML::tbody
160                              (HTML::tr(
161                                        HTML::td($pagefilter, ": "),
162                                        HTML::td($relation),
163                                        HTML::td(HTML::strong(HTML::tt('  ::  '))), 
164                                        HTML::td($queryrel),
165                                        HTML::td($nbsp, $relsubmit, $nbsp, $enhancements)))));
166
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)
174                                   ."')");
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' */
188                                       ), '');
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'
199                                       ), '');
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==~'
209                                       ), '');
210         $andbutton = new Button(_("AND"),$this_uri,'wikiaction',
211                                 array(
212                                       'onclick' => "addquery('attr', 'and')",
213                                       'title' => _("Add an AND query")));
214         $orbutton = new Button(_("OR"),$this_uri,'wikiaction',
215                                 array(
216                                       'onclick' => "addquery('attr', 'or')",
217                                       'title' => _("Add an OR query")));
218         if (DEBUG)
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");
222         if (DEBUG)
223             $instructions->pushContent
224                 (HTML(" ", new Button(_("Advanced..."),_("SemanticSearchAdvanced"))));
225         $form2 = HTML::form(array('action' => $action,
226                                   'method' => 'post',
227                                   'accept-charset' => $GLOBALS['charset']),
228                             $attdef, 
229                             $hiddenfield, HiddenInputs(array('relation'=>'')),
230                             $instructions, HTML::br(),
231                             HTML::table
232                             (array('border' => 0,'cellspacing' => 2),
233                              HTML::colgroup(array('span' => 6)),
234                              HTML::thead
235                              (HTML::tr(
236                                        HTML::th('Pagefilter'),
237                                        HTML::th('Attribute'),
238                                        HTML::th('Op'),
239                                        HTML::th('Value'),
240                                        HTML::th()
241                                       )),
242                              HTML::tbody
243                              (HTML::tr(
244                                        HTML::td($pagefilter, ": "),
245                                        HTML::td($attribute), 
246                                        HTML::td($attr_op),
247                                        HTML::td($queryatt),
248                                        HTML::td($nbsp, $attsubmit, $nbsp, $enhancements)))));
249         
250         return HTML($form1, $form2);
251     }
252
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;
261                 if ($case_exact)
262                     $q->_tree = new TextSearchQuery_node_exact($string); // hardcode this string
263                 else    
264                     $q->_tree = new TextSearchQuery_node_word($string);
265                 return $q;
266                 //$string = "\"" . $string ."\"";
267                 //$regex = 'none'; // EXACT or WORD match
268             }
269         }
270         return new TextSearchQuery($string, $case_exact, $regex);
271     }
272     
273     function run ($dbi, $argstr, &$request, $basepage) { 
274         global $WikiTheme;
275                                   
276         $this->_supported_operators = array(':=','<','<=','>','>=','!=','==','=~'); 
277         $this->_text_operators = array(':=','==','=~','!=');
278         $args = $this->getArgs($argstr, $request);
279
280         if (!empty($args['limit']) && !is_numeric($args['limit'])) {
281             return $this->error(_("Illegal 'limit' argument: must be numeric"));
282         }
283
284         if (empty($args['page']))
285             $args['page'] = "*";
286         if (!isset($args['s'])) // it might be (integer) 0
287             $args['s'] = "*";
288         $posted = $request->getArg("semsearch");
289         $form = $this->showForm($dbi, $request, $args);
290         if (isset($this->_norelations_warning))
291             $form->pushContent
292                 (HTML::div(array('class' => 'warning'),
293                            _("Warning:"),HTML::br(),
294                            _("No relations nor attributes in the whole wikidb defined!") 
295                            ,"\n"
296                            ,fmt("See %s",WikiLink(_("Help:SemanticRelations")))));
297         extract($args);
298         // for convenience and harmony we allow GET requests also.
299         if (!$request->isPost()) {
300             if ($relation or $attribute) // check for good GET request
301                 ;
302             else     
303                 return $form; // nobody called us, so just display our supadupa form
304         }
305         $pagequery = $this->regex_query($page, $args['case_exact'], $args['regex']);
306         // we might want to check for semsearch['relations'] and semsearch['attributes'] also
307         if (empty($relation) and empty($attribute)) {
308             // so we just clicked without selecting any relation. 
309             // hmm. check which button we clicked, before we do the massive alltogether search.
310             if (isset($posted['relations']) and $posted['relations'])
311                 $relation = '*';
312             elseif (isset($posted['attributes']) and $posted['attributes']) {
313                 $attribute = '*';
314                 // here we have to check for invalid text operators. ignore it then
315                 if (!in_array($attr_op, $this->_text_operators))
316                     $attribute = '';
317             }
318         }
319         $searchtype = "Text";
320         if (!empty($relation)) {
321             $querydesc = $relation."::".$s;
322             $linkquery =  $this->regex_query($s, $args['case_exact'], $args['regex']);
323             $relquery = $this->regex_query($relation, $args['case_exact'], $args['regex']);
324             $links = $dbi->linkSearch($pagequery, $linkquery, 'relation', $relquery);
325             $pagelist = new PageList($info, $exclude, $args);
326             $pagelist->_links = array();
327             while ($link = $links->next()) {
328                 $pagelist->addPage($link['pagename']);
329                 $pagelist->_links[] = $link;
330             }
331             // default (=empty info) wants all three. but we want to be able to override this.
332             // $pagelist->_columns_seen is the exploded info
333             if (!$info or ($info and isset($pagelist->_columns_seen['relation'])))
334                 $pagelist->addColumnObject
335                     (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist));
336             if (!$args['info'] or ($args['info'] and isset($pagelist->_columns_seen['linkto'])))
337                 $pagelist->addColumnObject
338                     (new _PageList_Column_SemanticSearch_link('linkto', _("Link"), $pagelist));
339         }
340         // can we merge two different pagelist?
341         if (!empty($attribute)) {
342             $relquery =  $this->regex_query($attribute, $args['case_exact'], $args['regex']);
343             if (!in_array($attr_op, $this->_supported_operators)) {
344                 return HTML($form, $this->error(fmt("Illegal operator: %s",
345                                                     HTML::tt($attr_op))));
346             }
347             $s_base = preg_replace("/,/","", $s);
348             $units = new Units();
349             if (!is_numeric($s_base)) {
350                 $s_base = $units->basevalue($s_base);
351                 $is_numeric = is_numeric($s_base);
352             } else {
353                 $is_numeric = true;
354             }
355             // check which type to search with:
356             // at first check if forced text matcher
357             if ($attr_op == '=~') {
358                 if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.   
359                 $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
360                 $querydesc = "$attribute $attr_op $s";
361             } elseif ($is_numeric) { // do comparison with numbers 
362                 /* We want to search for multiple attributes also. linkSearch can do this. 
363                  * But we have to construct the query somehow. (that's why we try the AND OR dhtml)
364                  *     population < 1 million AND area > 50 km2
365                  * Here we check only for one attribute per page.  
366                  * See SemanticSearchAdvanced for the full expression.
367                  */
368                 // it might not be the best idea to use '*' as variable to expand. hmm.
369                 if ($attribute == '*') $attribute = '_star_'; 
370                 $searchtype = "Numeric";
371                 $query = $attribute." ".$attr_op." ".$s_base;
372                 $linkquery = new SemanticAttributeSearchQuery($query, $attribute, 
373                                                               $units->baseunit($s));
374                 if ($attribute == '_star_') $attribute = '*'; 
375                 $querydesc = $attribute." ".$attr_op." ".$s;
376
377             // no number or unit: check other text matchers or '*' MATCH_ALL
378             } elseif (in_array($attr_op, $this->_text_operators)) {
379                 if ($attr_op == '=~') {
380                     if ($s == '*') $s = '.*'; // help the poor user. we need pcre syntax.
381                     $linkquery = new TextSearchQuery("$s", $args['case_exact'], 'pcre');
382                 }
383                 else                                             
384                     $linkquery =  $this->regex_query($s, $args['case_exact'], $args['regex']);
385                 $querydesc = "$attribute $attr_op $s";
386
387             // should we fail or skip when the user clicks on Relations?
388             } elseif (isset($posted['relations']) and $posted['relations'])  {
389                 $linkquery = false; // skip
390             } else {
391                 $querydesc = $attribute." ".$attr_op." ".$s;
392                 return HTML($form, $this->error(fmt("Only text operators can be used with strings: %s",
393                                                     HTML::tt($querydesc))));
394                 
395             }
396             if ($linkquery) {
397                 $links = $dbi->linkSearch($pagequery, $linkquery, 'attribute', $relquery);
398                 if (empty($relation)) {
399                     $pagelist = new PageList($args['info'], $args['exclude'], $args);
400                     $pagelist->_links = array();
401                 }
402                 while ($link = $links->next()) {
403                     $pagelist->addPage($link['pagename']);
404                     $pagelist->_links[] = $link;
405                 }
406                 // default (=empty info) wants all three. but we want to override this.
407                 if (!$args['info'] or 
408                     ($args['info'] and isset($pagelist->_columns_seen['attribute'])))
409                     $pagelist->addColumnObject
410                         (new _PageList_Column_SemanticSearch_relation('attribute', 
411                                 _("Attribute"), $pagelist));
412                 if (!$args['info'] or
413                     ($args['info'] and isset($pagelist->_columns_seen['value'])))
414                     $pagelist->addColumnObject
415                         (new _PageList_Column_SemanticSearch_link('value', 
416                                 _("Value"), $pagelist));
417             }
418         }
419         if (!isset($pagelist)) {
420             $querydesc = _("<empty>");
421             $pagelist = new PageList();
422         }
423         if (!$noheader) {
424         // We put the form into the caption just to be able to return one pagelist object, 
425         // and to still have the convenience form at the top. we could workaround this by 
426         // putting the form as WikiFormRich into the actionpage. but thid doesnt look as 
427         // nice as this here.
428             $pagelist->setCaption
429             (   // on mozilla the form doesn't fit into the caption very well.
430                 HTML($noform ? '' : HTML($form,HTML::hr()),
431                      fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"",
432                          $searchtype, $querydesc, $page)));
433         }
434         return $pagelist;
435     }
436 };
437
438 class _PageList_Column_SemanticSearch_relation 
439 extends _PageList_Column 
440 {
441     function _PageList_Column_SemanticSearch_relation ($field, $heading, &$pagelist) {
442         $this->_field = $field;
443         $this->_heading = $heading;
444         $this->_need_rev = false;
445         $this->_iscustom = true;
446         $this->_pagelist =& $pagelist;
447     }
448     function _getValue(&$page, $revision_handle) {
449         if (is_object($page)) $text = $page->getName();
450         else $text = $page;
451         $link = $this->_pagelist->_links[$this->current_row];
452         return WikiLink($link['linkname'],'if_known');
453     }
454 }
455 class _PageList_Column_SemanticSearch_link 
456 extends _PageList_Column_SemanticSearch_relation 
457 {
458     function _getValue(&$page, $revision_handle) {
459         if (is_object($page)) $text = $page->getName();
460         else $text = $page;
461         $link = $this->_pagelist->_links[$this->current_row];
462         if ($this->_field != 'value')
463             return WikiLink($link['linkvalue'],'if_known');
464         else    
465             return $link['linkvalue'];
466     }
467 }
468
469 // Local Variables:
470 // mode: php
471 // tab-width: 8
472 // c-basic-offset: 4
473 // c-hanging-comment-ender-p: nil
474 // indent-tabs-mode: nil
475 // End:
476 ?>