]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/SqlResult.php
Harmonize file footer
[SourceForge/phpwiki.git] / lib / plugin / SqlResult.php
1 <?php // -*-php-*-
2 // rcs_id('$Id$');
3 /*
4  * Copyright 2004 $ThePhpWikiProgrammingTeam
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 /**
24  * This plugin displays results of arbitrary SQL select statements
25  * in table form.
26  * The database definition, the DSN, must be defined in the local file
27  * config/SqlResult.ini
28  *   A simple textfile with alias = dsn lines.
29  *
30  * Optional template file to format the result and handle some logic.
31  * Template vars: %%where%%, %%sortby%%, %%limit%%
32  * TODO: paging
33  *
34  * Usage:
35  *   <<SqlResult alias=mysql
36  *            SELECT 'mysql password for string "xx":',
37  *                   PASSWORD('xx')
38  *   >>
39  *   <<SqlResult alias=videos template=videos
40  *            SELECT rating,title,date
41  *                   FROM video
42  *                   ORDER BY rating DESC
43  *                   LIMIT 5
44  *   >>
45  *   <<SqlResult alias=imdb template=imdbmovies where||="Davies, Jeremy%"
46  *   SELECT m.title, m.date, n.name, c.role
47  *     FROM movies as m, names as n, jobs as j, characters as c
48  *     WHERE n.name LIKE "%%where%%"
49  *     AND m.title_id = c.title_id
50  *     AND n.name_id = c.name_id
51  *     AND c.job_id = j.job_id
52  *     AND j.description = 'Actor'
53  *     ORDER BY m.date DESC
54  *   >>
55  *
56  * @author: ReiniUrban
57  */
58
59 require_once("lib/PageList.php");
60
61 class WikiPlugin_SqlResult
62 extends WikiPlugin
63 {
64     var $_args;
65
66     function getName () {
67         return _("SqlResult");
68     }
69
70     function getDescription () {
71         return _("Display arbitrary SQL result tables");
72     }
73
74     function getDefaultArguments() {
75         return array(
76                      'alias'       => false, // DSN database specification
77                      'ordered'     => false, // if to display as <ol> list: single col only without template
78                      'template'    => false, // use a custom <theme>/template.tmpl
79                      'where'       => false, // custom filter for the query
80                      'sortby'      => false, // for paging, default none
81                      'limit'       => "0,50", // for paging, default: only the first 50
82                     );
83     }
84
85     function getDsn($alias) {
86         $ini = parse_ini_file(FindFile("config/SqlResult.ini"));
87         return $ini[$alias];
88     }
89
90     /** Get the SQL statement from the rest of the lines
91      */
92     function handle_plugin_args_cruft($argstr, $args) {
93             $this->_sql = str_replace("\n"," ",$argstr);
94         return;
95     }
96
97     function run($dbi, $argstr, &$request, $basepage) {
98         global $DBParams;
99             //$request->setArg('nocache','1');
100         extract($this->getArgs($argstr, $request));
101         if (!$alias)
102             return $this->error(_("No DSN alias for SqlResult.ini specified"));
103         $sql = $this->_sql;
104
105         // apply custom filters
106         if ($where and strstr($sql, "%%where%%"))
107             $sql = str_replace("%%where%%", $where, $sql);
108         // TODO: use a SQL construction library?
109         if ($limit) {
110             $pagelist = new PageList();
111             $limit = $pagelist->limit($limit);
112             if (strstr($sql, "%%limit%%"))
113                 $sql = str_replace("%%limit%%", $limit, $sql);
114             else {
115                 if (strstr($sql, "LIMIT"))
116                     $sql = preg_replace("/LIMIT\s+[\d,]+\s+/m", "LIMIT ".$limit." ", $sql);
117             }
118         }
119         if (strstr($sql, "%%sortby%%")) {
120             if (!$sortby)
121                 $sql = preg_replace("/ORDER BY .*%%sortby%%\s/m", "", $sql);
122             else
123                 $sql = str_replace("%%sortby%%", $sortby, $sql);
124         } elseif (PageList::sortby($sortby,'db')) { // add sorting: support paging sortby links
125             if (preg_match("/\sORDER\s/",$sql))
126                 $sql = preg_replace("/ORDER BY\s\S+\s/m", "ORDER BY " . PageList::sortby($sortby,'db'), $sql);
127             else
128                 $sql .= " ORDER BY " . PageList::sortby($sortby,'db');
129         }
130
131         $inidsn = $this->getDsn($alias);
132         if (!$inidsn)
133             return $this->error(sprintf(_("No DSN for alias %s in SqlResult.ini found"),
134                                         $alias));
135         // adodb or pear? adodb as default, since we distribute per default it.
136         // for pear there may be overrides.
137         // TODO: native PDO support (for now we use ADODB)
138         if ($DBParams['dbtype'] == 'SQL') {
139             $dbh = DB::connect($inidsn);
140             $all = $dbh->getAll($sql);
141             if (DB::isError($all)) {
142                     return $this->error($all->getMessage(). ' ' . $all->userinfo);
143             }
144         } else { // unless PearDB use the included ADODB, regardless if dba, file or PDO, ...
145             if ($DBParams['dbtype'] != 'ADODB') {
146                 require_once('lib/WikiDB/backend/ADODB.php');
147             }
148             $parsed = parseDSN($inidsn);
149             $dbh = &ADONewConnection($parsed['phptype']);
150             $conn = $dbh->Connect($parsed['hostspec'],$parsed['username'],
151                                   $parsed['password'], $parsed['database']);
152             if (!$conn)
153                 return $this->error($dbh->errorMsg());
154             $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_ASSOC;
155             $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
156
157             $all = $dbh->getAll($sql);
158
159             $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
160             $dbh->SetFetchMode(ADODB_FETCH_NUM);
161             if (!$all)
162                 return $this->error($dbh->errorMsg());
163         }
164         $args = array();
165         if ($limit) { // fill paging vars (see PageList)
166             $args = $pagelist->pagingTokens(count($all), count($all[0]), $limit);
167             if (!$args) $args = array();
168         }
169
170         if ($template) {
171             $args = array_merge(
172                       array('SqlResult' => $all,   // the resulting array of rows
173                             'ordered' => $ordered, // whether to display as <ul>/<dt> or <ol>
174                             'where'   => $where,
175                             'sortby'  => $sortby,
176                             'limit'   => $limit),
177                       $args);                // paging params override given params
178             return Template($template, $args);
179         } else {
180             if ($ordered) {
181                 $html = HTML::ol(array('class'=>'sqlresult'));
182                 if ($all)
183                   foreach ($all as $row) {
184                     $html->pushContent(HTML::li(array('class'=> $i++ % 2 ? 'evenrow' : 'oddrow'), $row[0]));
185                   }
186             } else {
187                 $html = HTML::table(array('class'=>'sqlresult'));
188                 $i = 0;
189                 if ($all)
190                 foreach ($all as $row) {
191                     $tr = HTML::tr(array('class'=> $i++ % 2 ? 'evenrow' : 'oddrow'));
192                     if ($row)
193                         foreach ($row as $col) {
194                             $tr->pushContent(HTML::td($col));
195                         }
196                     $html->pushContent($tr);
197                 }
198             }
199         }
200         // do paging via pagelink template
201         if (!empty($args['NUMPAGES'])) {
202             $paging = Template("pagelink", $args);
203             $html = $table->pushContent(HTML::thead($paging),
204                                         HTML::tbody($html),
205                                         HTML::tfoot($paging));
206         }
207         if (0 and DEBUG) { // test deferred error/warning/notice collapsing
208             trigger_error("test notice",  E_USER_NOTICE);
209             trigger_error("test warning", E_USER_WARNING);
210         }
211
212         return $html;
213     }
214
215 };
216
217 // Local Variables:
218 // mode: php
219 // tab-width: 8
220 // c-basic-offset: 4
221 // c-hanging-comment-ender-p: nil
222 // indent-tabs-mode: nil
223 // End:
224 ?>