]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/SemanticSearchAdvanced.php
more plans
[SourceForge/phpwiki.git] / lib / plugin / SemanticSearchAdvanced.php
1 <?php // -*-php-*-
2 rcs_id('$Id: SemanticSearchAdvanced.php,v 1.2 2008-07-27 21:48:05 rurban Exp $');
3 /*
4  Copyright 2007 Reini Urban
5
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 require_once('lib/plugin/SemanticSearch.php');
24
25 /**
26  * Advanced search for relations/attributes and its values.
27  * Parse the query string, which can contain full mathematical expressions 
28  * and various logical and mathematical functions and operators.
29  * Support subqueries (for _pagename ...) and temporary variables 
30  * starting with _
31  *
32  * Are multiple variables valid for one page only, or is the result 
33  * constructed as list of all matches? We'll stick with one page for now.
34  * This the only way I can see semantic meaning for now.
35  *
36  * Simple queries, with no variables, only against the pagename (implicit):
37  *    "is_a::city and (population < 1.000.000 or population > 10.000.000)"
38  *    "(is_a::city or is_a::country) and population < 10.000.000"
39  *
40  * Subqueries, with variables bound to the matching pagename, with (for ...):
41  *    "works_at::_organization
42  *      and (for _organization located_in::_city
43  *             and (for _city population>1000000))"
44  *
45  *    "works_at::_organization
46  *       and (for _organization
47  *             (located_in::_city 
48  *             and (for _city is_a::City 
49  *                   and population>1000000))
50  *          or (located_in::_country 
51  *               and (for _country is_a::Country and population>5000000)))
52  *
53  * Relation links may contain wildcards. For relation and attribute names I'm not sure yet. 
54  *
55  * @author: Reini Urban
56  */
57
58 class WikiPlugin_SemanticSearchAdvanced
59 extends WikiPlugin_SemanticSearch
60 {
61     function getName() {
62         return _("SemanticSearchAdvanced");
63     }
64     function getDescription() {
65         return _("Parse and execute a full query expression");
66     }
67     function getVersion() {
68         return preg_replace("/[Revision: $]/", '',
69                             "\$Revision: 1.2 $");
70     }
71     function getDefaultArguments() { 
72         return array_merge
73             (
74              PageList::supportedArgs(),  // paging and more.
75              array(
76                    's'          => "",   // query expression
77                    'page'       => "*",  // which pages (glob allowed), default: all
78                    'case_exact' => false,
79                    'regex'      => 'auto', // hmm
80                    'noform'     => false, // don't show form with results.
81                    'noheader'   => false  // no caption
82                    ));
83     }
84
85     function showForm (&$dbi, &$request, $args, $allrelations) {
86         global $WikiTheme;
87         $action = $request->getPostURL();
88         $hiddenfield = HiddenInputs($request->getArgs(),'',
89                                     array('action','page','s'));
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         $help = Button('submit:semsearch[help]', "?", false);
100         $svalues = empty($allrelations) ? "" : join("','", $allrelations);
101         $reldef = JavaScript("var semsearch_relations = new Array('".$svalues."')");
102         $querybox = HTML::textarea(array('name' => 's',
103                                          'title' => _("Enter a valid query expression"),
104                                          'rows' => 4,
105                                          'acdropdown' => 'true', 
106                                          'autocomplete_complete' => 'true', 
107                                          'autocomplete_assoc' => 'false', 
108                                          'autocomplete_matchsubstring' => 'true', 
109                                          'autocomplete_list' => 'array:semsearch_relations'
110                                       ), $args['s']);
111         $submit = Button('submit:semsearch[relations]',  _("Search"), false, 
112                          array('title' => 'Move to help page. No seperate window'));
113         $instructions = _("Search in all specified pages for the expression.");
114         $form = HTML::form(array('action' => $action,
115                                   'method' => 'post',
116                                   'accept-charset' => $GLOBALS['charset']),
117                            $reldef,
118                            $hiddenfield, HiddenInputs(array('attribute'=>'')),
119                            $instructions, HTML::br(),
120                            HTML::table(array('border'=>'0','width' =>'100%'),
121                                        HTML::tr(HTML::td(_("Pagename(s): "), $pagefilter),
122                                                 HTML::td(array('align' => 'right'), 
123                                                          $help)),
124                                        HTML::tr(HTML::td(array('colspan' => 2), 
125                                                          $querybox))), 
126                            HTML::br(),
127                            HTML::div(array('align'=>'center'),$submit));
128         return $form;
129     }
130  
131     function run ($dbi, $argstr, &$request, $basepage) { 
132         global $WikiTheme;
133
134         $this->_supported_operators = array(':=','<','<=','>','>=','!=','==','=~'); 
135         $args = $this->getArgs($argstr, $request);
136         $posted = $request->getArg('semsearch');
137         $request->setArg('semsearch', false);
138         if ($request->isPost() and isset($posted['help'])) {
139             $request->redirect(WikiURL(_("Help/SemanticSearchAdvancedPlugin"),
140                                        array('redirectfrom' => $basepage), true));
141         }
142         $allrelations = $dbi->listRelations();
143         $form = $this->showForm($dbi, $request, $args, $allrelations);
144         if (isset($this->_norelations_warning))
145             $form->pushContent(HTML::div(array('class' => 'warning'),
146                                          _("Warning:").$this->_norelations_warning));
147         extract($args);
148         // For convenience, peace and harmony we allow GET requests also.
149         if (!$args['s']) // check for good GET request
150             return $form; // nobody called us, so just display our form
151
152         // In reality we have to iterate over all found pages.
153         // To makes things shorter extract the next AND required expr and 
154         // iterate only over this, then recurse into the next AND expr.
155         // => Split into an AND and OR expression tree.
156
157         $parsed_relations = $this->detectRelationsAndAttributes($args['s']);
158         $regex = '';
159         if ($parsed_relations)
160             $regex = preg_grep("/[\*\?]/", $parsed_relations);
161         // Check that all those do exist.
162         else
163             $this->error("Invalid query: No relations or attributes in the query $s found");
164         $pagelist = new PageList($args['info'], $args['exclude'], $args);
165         if (!$noheader) {
166             $pagelist->setCaption
167                 (HTML($noform ? '' : HTML($form,HTML::hr()),
168                       fmt("Semantic %s Search Result for \"%s\" in pages \"%s\"",
169                           '',$s,$page)));
170         }
171         if (!$regex and $missing = array_diff($parsed_relations, $allrelations))
172             return $pagelist;
173         $relquery = new TextSearchQuery(join(" ",$parsed_relations));
174         if (!$relquery->match(join(" ",$allrelations)))
175             return $pagelist;
176         $pagequery = new TextSearchQuery($page, $args['case_exact'], $args['regex']);
177         // if we have only numeric or text ops we can optimize.
178         //$parsed_attr_ops = $this->detectAttrOps($args['s']);
179
180         //TODO: writeme
181         $linkquery = new TextSearchQuery($s, $args['case_exact'], $args['regex']);
182         $links = $dbi->linkSearch($pagequery, $linkquery, 'relation', $relquery);
183         $pagelist->_links = array();
184         while ($link = $links->next()) {
185             $pagelist->addPage($link['pagename']);
186             $pagelist->_links[] = $link;
187         }
188         $pagelist->addColumnObject
189             (new _PageList_Column_SemanticSearch_relation('relation', _("Relation"), $pagelist));
190         $pagelist->addColumnObject
191             (new _PageList_Column_SemanticSearch_link('link', _("Link"), $pagelist));
192
193         return $pagelist;
194     }
195
196     // ... (for _variable subquery) ...
197     function bindSubquery($query) {
198     }
199
200     // is_a::city* and (population < 1.000.000 or population > 10.000.000)
201     // => is_a population
202     // Do we support wildcards in relation names also? is_*::city
203     function detectRelationsAndAttributes($subquery) {
204         $relations = array();
205         // relations are easy
206         //$reltoken = preg_grep("/::/", preg_split("/\s+/", $query));
207         //$relations = array_map(create_function('$a','list($f,$b)=split("::",$a); return $f'), 
208         //                     $reltoken);
209         foreach (preg_split("/\s+/", $query) as $whitetok) {
210             if (preg_match("/^([\w\*\?]+)::/", $whitetok))
211                 $relations[] = $m[1];
212         }
213         return $relations;
214         // for attributes we might use the tokenizer. All non-numerics excl. units and non-ops
215     }
216 };
217
218 // $Log: not supported by cvs2svn $
219 // Revision 1.1  2007/05/24 18:40:43  rurban
220 // new plugin
221 //
222
223 // Local Variables:
224 // mode: php
225 // tab-width: 8
226 // c-basic-offset: 4
227 // c-hanging-comment-ender-p: nil
228 // indent-tabs-mode: nil
229 // End:
230 ?>