]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/ADODB.php
fix adodb_sqlite to have the same dsn syntax as pear, use pconnect if requested
[SourceForge/phpwiki.git] / lib / WikiDB / backend / ADODB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: ADODB.php,v 1.35 2004-06-28 14:45:12 rurban Exp $');
3
4 /*
5  Copyright 2002,2004 $ThePhpWikiProgrammingTeam
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
25 /**
26  * Based on PearDB.php. 
27  * @author: Lawrence Akka, Reini Urban
28  *
29  * Now (phpwiki-1.3.10) with adodb-4.22, by Reini Urban:
30  * 1) Extended to use all available database backend, not only mysql.
31  * 2) It uses the ultra-fast binary adodb extension if loaded.
32  * 3) We use FETCH_NUM instead of FETCH_ASSOC (faster and more generic)
33  * 4) To support generic iterators which return ASSOC fields, and to support queries with 
34  *    variable columns, some trickery was needed to use recordset specific fetchMode.
35  *    The first Execute uses the global fetchMode (ASSOC), then it's resetted back to NUM 
36  *    and the recordset fetchmode is set to ASSOC.
37  * 5) Transaction support, and locking as fallback.
38  *
39  * ADODB basic differences to PearDB: It pre-fetches the first row into fields, 
40  * is dirtier in style, layout and more low-level ("worse is better").
41  * It has less needed basic features (modifyQuery, locks, ...), but some more 
42  * unneeded features included: paging, monitoring and sessions, and much more drivers.
43  * No locking (which PearDB supports in some backends), and sequences are very 
44  * bad compared to PearDB.
45
46  * Old Comments, by Lawrence Akka:
47  * 1)  ADODB's GetRow() is slightly different from that in PEAR.  It does not 
48  *     accept a fetchmode parameter
49  *     That doesn't matter too much here, since we only ever use FETCHMODE_ASSOC
50  * 2)  No need for ''s around strings in sprintf arguments - qstr puts them 
51  *     there automatically
52  * 3)  ADODB has a version of GetOne, but it is difficult to use it when 
53  *     FETCH_ASSOC is in effect.
54  *     Instead, use $rs = Execute($query); $value = $rs->fields["$colname"]
55  * 4)  No error handling yet - could use ADOConnection->raiseErrorFn
56  * 5)  It used to be faster then PEAR/DB at the beginning of 2002. 
57  *     Now at August 2002 PEAR/DB with our own page cache added, 
58  *     performance is comparable.
59  */
60
61 require_once('lib/WikiDB/backend.php');
62 // Error handling - calls trigger_error.  NB - does not close the connection.  Does it need to?
63 include_once('lib/WikiDB/adodb/adodb-errorhandler.inc.php');
64 // include the main adodb file
65 require_once('lib/WikiDB/adodb/adodb.inc.php');
66
67 class WikiDB_backend_ADODB
68 extends WikiDB_backend
69 {
70
71     function WikiDB_backend_ADODB ($dbparams) {
72         $parsed = parseDSN($dbparams['dsn']);
73         $this->_dbh = &ADONewConnection($parsed['phptype']);
74         if (!empty($parsed['persistent']))
75             $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'], 
76                                          $parsed['password'], $parsed['database']);
77         else
78             $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'], 
79                                          $parsed['password'], $parsed['database']);
80
81         //$this->_dbh->debug = true;
82         
83         // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
84         // with some ASSOC based recordsets.
85         $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
86         $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
87
88         // Old comment:
89         //  With ADODB_COUNTRECS false it should speed up queries, but:
90         //  1)  It only works with PHP >= 4.0.6; and
91         //  2)  At the moment, I haven't figured out why the wrong results are returned'
92         $GLOBALS['ADODB_COUNTRECS'] = false;
93
94         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
95         $this->_table_names
96             = array('page_tbl'     => $prefix . 'page',
97                     'version_tbl'  => $prefix . 'version',
98                     'link_tbl'     => $prefix . 'link',
99                     'recent_tbl'   => $prefix . 'recent',
100                     'nonempty_tbl' => $prefix . 'nonempty');
101         $page_tbl = $this->_table_names['page_tbl'];
102         $version_tbl = $this->_table_names['version_tbl'];
103         $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
104             . "$page_tbl.hits hits";
105         $this->version_tbl_fields = "$version_tbl.version AS version, "
106             . "$version_tbl.mtime AS mtime, "
107             . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
108             . "$version_tbl.versiondata AS versiondata";
109
110         $this->_expressions
111             = array('maxmajor'     => "MAX(CASE WHEN minor_edit=0 THEN version END)",
112                     'maxminor'     => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
113                     'maxversion'   => "MAX(version)",
114                     'notempty'     => "<>''",
115                     'iscontent'    => "content<>''");
116         $this->_lock_count = 0;
117     }
118
119     /**
120      * Close database connection.
121      */
122     function close () {
123         if (!$this->_dbh)
124             return;
125         if ($this->_lock_count) {
126             trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
127                           E_USER_WARNING);
128         }
129 //      $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
130         $this->unlock(false,'force');
131
132         $this->_dbh->close();
133         $this->_dbh = false;
134     }
135
136     /*
137      * Fast test for wikipage.
138      */
139     function is_wiki_page($pagename) {
140         $dbh = &$this->_dbh;
141         extract($this->_table_names);
142         $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
143                                     . " FROM $nonempty_tbl, $page_tbl"
144                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
145                                     . "   AND pagename=%s",
146                                     $dbh->qstr($pagename)));
147         return $row ? $row[0] : false;
148     }
149         
150     function get_all_pagenames() {
151         $dbh = &$this->_dbh;
152         extract($this->_table_names);
153         $result = $dbh->Execute("SELECT pagename"
154                                 . " FROM $nonempty_tbl, $page_tbl"
155                                 . " WHERE $nonempty_tbl.id=$page_tbl.id");
156         return $result->GetArray();
157     }
158
159     function numPages($filter=false, $exclude='') {
160         $dbh = &$this->_dbh;
161         extract($this->_table_names);
162         $result = $dbh->getRow("SELECT count(*)"
163                             . " FROM $nonempty_tbl, $page_tbl"
164                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
165         return $result[0];
166     }
167     
168     /**
169      * Read page information from database.
170      */
171     function get_pagedata($pagename) {
172         $dbh = &$this->_dbh;
173         $page_tbl = $this->_table_names['page_tbl'];
174         $row = $dbh->GetRow(sprintf("SELECT hits, pagedata FROM $page_tbl WHERE pagename=%s",
175                                        $dbh->qstr($pagename)));
176         return $row ? $this->_extract_page_data($row[1],$row[0]) : false;
177     }
178
179     function  _extract_page_data(&$data, $hits) {
180         $pagedata = empty($data) ? array() : unserialize($data);
181         $pagedata['hits'] = $hits;
182         return $pagedata;
183     }
184
185     function update_pagedata($pagename, $newdata) {
186         $dbh = &$this->_dbh;
187         $page_tbl = $this->_table_names['page_tbl'];
188
189         // Hits is the only thing we can update in a fast manner.
190         if (count($newdata) == 1 && isset($newdata['hits'])) {
191             // Note that this will fail silently if the page does not
192             // have a record in the page table.  Since it's just the
193             // hit count, who cares?
194             $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
195                                   $newdata['hits'], $dbh->qstr($pagename)));
196             return;
197         }
198         $where = sprintf("pagename=%s",$dbh->qstr($pagename));
199         $dbh->BeginTrans( );
200         $dbh->RowLock($page_tbl,$where);
201         
202         $data = $this->get_pagedata($pagename);
203         if (!$data) {
204             $data = array();
205             $this->_get_pageid($pagename, true); // Creates page record
206         }
207         
208         @$hits = (int)$data['hits'];
209         unset($data['hits']);
210
211         foreach ($newdata as $key => $val) {
212             if ($key == 'hits')
213                 $hits = (int)$val;
214             else if (empty($val))
215                 unset($data[$key]);
216             else
217                 $data[$key] = $val;
218         }
219         // FIXME: some DBMs dont support huge strings (pagedata), so we have to bind it.
220         if ($dbh->Execute(sprintf("UPDATE $page_tbl"
221                                   . " SET hits=%d, pagedata=%s"
222                                   . " WHERE pagename=%s",
223                                   $hits,
224                                   $dbh->qstr(serialize($data)),
225                                   $dbh->qstr($pagename))))
226             $dbh->CommitTrans( );
227         else
228             $dbh->RollbackTrans( );
229     }
230
231     function _get_pageid($pagename, $create_if_missing = false) {
232         
233         $dbh = &$this->_dbh;
234         $page_tbl = $this->_table_names['page_tbl'];
235         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
236                          $dbh->qstr($pagename));
237         if (! $create_if_missing ) {
238             $row = $dbh->GetRow($query);
239             return $row ? $row[0] : false;
240         }
241         $row = $dbh->GetRow($query);
242         if (! $row ) {
243             if ((substr($dbh->databaseType,0,5) == 'mysql') or isa($dbh,'ADODB_sqlite')) {
244                 // have auto-incrementing and atomic version
245                 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
246                                             . " (pagename,hits)"
247                                             . " VALUES(%s,0)",
248                                             $dbh->qstr($pagename)));
249                 $id = $dbh->_insertid();
250             } else {
251                 //$id = $dbh->GenID($page_tbl . 'seq');
252                 // Better generic version than with adodob::genID
253                 $this->lock(array('page'));
254                 $dbh->BeginTrans( );
255                 $dbh->CommitLock($page_tbl);
256                 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
257                 $id = $row[0] + 1;
258                 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
259                                             . " (id,pagename,hits)"
260                                             . " VALUES (%d,%s,0)",
261                                             $id, $dbh->qstr($pagename)));
262                 if ($rs) $dbh->CommitTrans( );
263                 else $dbh->RollbackTrans( );
264                 $this->unlock(array('page'));
265             }
266         } else {
267             $id = $row[0];
268         }
269         return $id;
270     }
271
272     function get_latest_version($pagename) {
273         $dbh = &$this->_dbh;
274         extract($this->_table_names);
275         $row = $dbh->GetRow(sprintf("SELECT latestversion"
276                                     . " FROM $page_tbl, $recent_tbl"
277                                     . " WHERE $page_tbl.id=$recent_tbl.id"
278                                     . "  AND pagename=%s",
279                                     $dbh->qstr($pagename)));
280         return $row ? (int)$row[0] : false;
281     }
282
283     function get_previous_version($pagename, $version) {
284         $dbh = &$this->_dbh;
285         extract($this->_table_names);
286         // Use SELECTLIMIT for maximum portability
287         $rs = $dbh->SelectLimit(sprintf("SELECT version"
288                                         . " FROM $version_tbl, $page_tbl"
289                                         . " WHERE $version_tbl.id=$page_tbl.id"
290                                         . "  AND pagename=%s"
291                                         . "  AND version < %d"
292                                         . " ORDER BY version DESC"
293                                         ,$dbh->qstr($pagename),
294                                         $version),
295                                 1);
296         return $rs->fields[0] ? (int)$rs->fields[0] : false;
297     }
298     
299     /**
300      * Get version data.
301      *
302      * @param $version int Which version to get.
303      *
304      * @return hash The version data, or false if specified version does not
305      *              exist.
306      */
307     function get_versiondata($pagename, $version, $want_content = false) {
308         $dbh = &$this->_dbh;
309         extract($this->_table_names);
310                 
311         assert(is_string($pagename) and $pagename != '');
312         assert($version > 0);
313         
314         // FIXME: optimization: sometimes don't get page data?
315         if ($want_content) {
316             $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
317                 . ', ' . $this->version_tbl_fields;
318         } else {
319             $fields = $this->page_tbl_fields
320                 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
321                 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content<>'' as have_content, "
322                 . "$version_tbl.versiondata as versiondata";
323         }
324         $row = $dbh->GetRow(sprintf("SELECT $fields"
325                                     . " FROM $page_tbl, $version_tbl"
326                                     . " WHERE $page_tbl.id=$version_tbl.id"
327                                     . "  AND pagename=%s"
328                                     . "  AND version=%d",
329                                     $dbh->qstr($pagename), $version));
330         return $row ? $this->_extract_version_data_num($row, $want_content) : false;
331     }
332
333     function _extract_version_data_num(&$row, $want_content) {
334         if (!$row)
335             return false;
336
337         //$id       &= $row[0];
338         //$pagename &= $row[1];
339         $data = empty($row[8]) ? array() : unserialize($row[8]);
340         $data['mtime']         = $row[5];
341         $data['is_minor_edit'] = !empty($row[6]);
342         if ($want_content) {
343             $data['%content'] = $row[7];
344         } else {
345             $data['%content'] = !empty($row[7]);
346         }
347         if (!empty($row[3])) {
348             $data['%pagedata'] = $this->_extract_page_data($row[3],$row[2]);
349         }
350         return $data;
351     }
352
353     function _extract_version_data_assoc(&$row) {
354         if (!$row)
355             return false;
356
357         extract($row);
358         $data = empty($versiondata) ? array() : unserialize($versiondata);
359         $data['mtime'] = $mtime;
360         $data['is_minor_edit'] = !empty($minor_edit);
361         if (isset($content))
362             $data['%content'] = $content;
363         elseif ($have_content)
364             $data['%content'] = true;
365         else
366             $data['%content'] = '';
367         if (!empty($pagedata)) {
368             $data['%pagedata'] = $this->_extract_page_data($pagedata,$hits);
369         }
370         return $data;
371     }
372
373     /**
374      * Create a new revision of a page.
375      */
376     function set_versiondata($pagename, $version, $data) {
377         $dbh = &$this->_dbh;
378         $version_tbl = $this->_table_names['version_tbl'];
379         
380         $minor_edit = (int) !empty($data['is_minor_edit']);
381         unset($data['is_minor_edit']);
382         
383         $mtime = (int)$data['mtime'];
384         unset($data['mtime']);
385         assert(!empty($mtime));
386
387         @$content = (string) $data['%content'];
388         unset($data['%content']);
389         unset($data['%pagedata']);
390         
391         $this->lock(array('page','recent','version','nonempty'));
392         $dbh->BeginTrans( );
393         $dbh->CommitLock($version_tbl);
394         $id = $this->_get_pageid($pagename, true);
395
396         // optimize: mysql can do this with one REPLACE INTO.
397         if (substr($dbh->databaseType,0,5) == 'mysql') {
398             $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl"
399                                   . " (id,version,mtime,minor_edit,content,versiondata)"
400                                   . " VALUES(%d,%d,%d,%d,%s,%s)",
401                                   $id, $version, $mtime, $minor_edit,
402                                   $dbh->qstr($content),
403                                   $dbh->qstr(serialize($data))));
404         } else {
405             $dbh->Execute(sprintf("DELETE FROM $version_tbl"
406                                   . " WHERE id=%d AND version=%d",
407                                   $id, $version));
408             $rs = $dbh->Execute(sprintf("INSERT INTO $version_tbl"
409                                   . " (id,version,mtime,minor_edit,content,versiondata)"
410                                   . " VALUES(%d,%d,%d,%d,%s,%s)",
411                                   $id, $version, $mtime, $minor_edit,
412                                   $dbh->qstr($content),
413                                   $dbh->qstr(serialize($data))));
414         }
415         $this->_update_recent_table($id);
416         $this->_update_nonempty_table($id);
417         if ($rs) $dbh->CommitTrans( );
418         else $dbh->RollbackTrans( );
419         $this->unlock(array('page','recent','version','nonempty'));
420     }
421     
422     /**
423      * Delete an old revision of a page.
424      */
425     function delete_versiondata($pagename, $version) {
426         $dbh = &$this->_dbh;
427         extract($this->_table_names);
428
429         $this->lock(array('version'));
430         if ( ($id = $this->_get_pageid($pagename)) ) {
431             $dbh->Execute("DELETE FROM $version_tbl"
432                         . " WHERE id=$id AND version=$version");
433             $this->_update_recent_table($id);
434             // This shouldn't be needed (as long as the latestversion
435             // never gets deleted.)  But, let's be safe.
436             $this->_update_nonempty_table($id);
437         }
438         $this->unlock(array('version'));
439     }
440
441     /**
442      * Delete page from the database.
443      */
444     function delete_page($pagename) {
445         $dbh = &$this->_dbh;
446         extract($this->_table_names);
447         
448         $this->lock(array('version','recent','nonempty','page','link'));
449         if ( ($id = $this->_get_pageid($pagename, false)) ) {
450             $dbh->Execute("DELETE FROM $version_tbl  WHERE id=$id");
451             $dbh->Execute("DELETE FROM $recent_tbl   WHERE id=$id");
452             $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
453             $dbh->Execute("DELETE FROM $link_tbl     WHERE linkfrom=$id");
454             $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
455             if ($row and $row[0]) {
456                 // We're still in the link table (dangling link) so we can't delete this
457                 // altogether.
458                 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
459             }
460             else {
461                 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
462             }
463             $this->_update_recent_table();
464             $this->_update_nonempty_table();
465         }
466         $this->unlock(array('version','recent','nonempty','page','link'));
467     }
468             
469
470     // The only thing we might be interested in updating which we can
471     // do fast in the flags (minor_edit).   I think the default
472     // update_versiondata will work fine...
473     //function update_versiondata($pagename, $version, $data) {
474     //}
475
476     function set_links($pagename, $links) {
477         // Update link table.
478         // FIXME: optimize: mysql can do this all in one big INSERT.
479
480         $dbh = &$this->_dbh;
481         extract($this->_table_names);
482
483         $this->lock(array('link'));
484         $pageid = $this->_get_pageid($pagename, true);
485
486         $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
487
488         if ($links) {
489             foreach($links as $link) {
490                 if (isset($linkseen[$link]))
491                     continue;
492                 $linkseen[$link] = true;
493                 $linkid = $this->_get_pageid($link, true);
494                 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
495                             . " VALUES ($pageid, $linkid)");
496             }
497         }
498         $this->unlock(array('link'));
499     }
500     
501     /**
502      * Find pages which link to or are linked from a page.
503      */
504     function get_links($pagename, $reversed = true) {
505         $dbh = &$this->_dbh;
506         extract($this->_table_names);
507
508         if ($reversed)
509             list($have,$want) = array('linkee', 'linker');
510         else
511             list($have,$want) = array('linker', 'linkee');
512
513         $qpagename = $dbh->qstr($pagename);
514         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
515         // removed ref to FETCH_MODE in next line
516         $result = $dbh->Execute("SELECT $want.id AS id, $want.pagename AS pagename,"
517                                 . " $want.hits AS hits"
518                                 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
519                                 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
520                                 . " AND $have.pagename=$qpagename"
521                                 //. " GROUP BY $want.id"
522                                 . " ORDER BY $want.pagename");
523         $dbh->SetFetchMode(ADODB_FETCH_NUM);
524         return new WikiDB_backend_ADODB_iter($this, $result);
525     }
526
527     function get_all_pages($include_deleted=false,$sortby = false,$limit = false) {
528         $dbh = &$this->_dbh;
529         extract($this->_table_names);
530         //if ($limit)  $limit = "LIMIT $limit";
531         //else         $limit = '';
532         if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
533         else         $orderby = '';
534         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
535         if (strstr($orderby,' mtime')) {
536             if ($include_deleted) {
537                 $sql = "SELECT "
538                     . $this->page_tbl_fields
539                     ." FROM $page_tbl, $recent_tbl, $version_tbl"
540                     . " WHERE $page_tbl.id=$recent_tbl.id"
541                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
542                     . " $orderby";
543             }
544             else {
545                 $sql = "SELECT "
546                     . $this->page_tbl_fields
547                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
548                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
549                     . " AND $page_tbl.id=$recent_tbl.id"
550                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
551                     . " $orderby";
552             }
553         } else {
554             if ($include_deleted) {
555                 $sql = "SELECT "
556                     . $this->page_tbl_fields
557                     . " FROM $page_tbl $orderby";
558             } else {
559                 $sql = "SELECT "
560                     . $this->page_tbl_fields
561                     . " FROM $nonempty_tbl, $page_tbl"
562                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
563                     . " $orderby";
564             }
565         }
566         if ($limit) {
567             // extract from,count from limit
568             require_once("lib/PageList.php");
569             list($offset,$count) = PageList::limit($limit);
570             $result = $dbh->SelectLimit($sql, $count, $offset);
571         } else {
572             $result = $dbh->Execute($sql);
573         }
574         $dbh->SetFetchMode(ADODB_FETCH_NUM);
575         return new WikiDB_backend_ADODB_iter($this, $result);
576     }
577         
578     /**
579      * Title search.
580      */
581     function text_search($search = '', $fullsearch = false) {
582         $dbh = &$this->_dbh;
583         extract($this->_table_names);
584         
585         $table = "$nonempty_tbl, $page_tbl";
586         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
587         $fields = $this->page_tbl_fields;
588         $callback = new WikiMethodCb($this, '_sql_match_clause');
589         
590         if ($fullsearch) {
591             $table .= ", $recent_tbl";
592             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
593
594             $table .= ", $version_tbl";
595             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
596
597             $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
598             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
599         }
600         
601         $search_clause = $search->makeSqlClause($callback);
602         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
603         $result = $dbh->Execute("SELECT $fields FROM $table"
604                                 . " WHERE $join_clause"
605                                 . "  AND ($search_clause)"
606                                 . " ORDER BY pagename");
607
608         $dbh->SetFetchMode(ADODB_FETCH_NUM);
609         return new WikiDB_backend_ADODB_iter($this, $result);
610     }
611
612     function _sql_match_clause($word) {
613         //not sure if we need this.  ADODB may do it for us
614         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  
615
616         // (we need it for at least % and _ --- they're the wildcard characters
617         //  for the LIKE operator, and we need to quote them if we're searching
618         //  for literal '%'s or '_'s.  --- I'm not sure about \, but it seems to
619         //  work as is.
620         $word = $this->_dbh->qstr("%$word%");
621         $page_tbl = $this->_table_names['page_tbl'];
622         return "LOWER($page_tbl.pagename) LIKE $word";
623     }
624
625     function _fullsearch_sql_match_clause($word) {
626         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  //not sure if we need this
627         // (see above)
628         $word = $this->_dbh->qstr("%$word%");
629         $page_tbl = $this->_table_names['page_tbl'];
630         return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
631     }
632
633     /**
634      * Find highest or lowest hit counts.
635      */
636     function most_popular($limit=0, $sortby = '') {
637         $dbh = &$this->_dbh;
638         extract($this->_table_names);
639         $order = "DESC";
640         if ($limit < 0){ 
641             $order = "ASC"; 
642             $limit = -$limit;
643             $where = "";
644         } else {
645             $where = " AND hits > 0";
646         }
647         if ($sortby) $orderby = " ORDER BY " . PageList::sortby($sortby,'db');
648         else         $orderby = " ORDER BY hits $order";
649         $limit = $limit ? $limit : -1;
650
651         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
652         $result = $dbh->SelectLimit("SELECT " 
653                                     . $this->page_tbl_fields
654                                     . " FROM $nonempty_tbl, $page_tbl"
655                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
656                                     . $where
657                                     . $orderby, $limit);
658         $dbh->SetFetchMode(ADODB_FETCH_NUM);
659         return new WikiDB_backend_ADODB_iter($this, $result);
660     }
661
662     /**
663      * Find recent changes.
664      */
665     function most_recent($params) {
666         $limit = 0;
667         $since = 0;
668         $include_minor_revisions = false;
669         $exclude_major_revisions = false;
670         $include_all_revisions = false;
671         extract($params);
672
673         $dbh = &$this->_dbh;
674         extract($this->_table_names);
675
676         $pick = array();
677         if ($since)
678             $pick[] = "mtime >= $since";
679         
680         if ($include_all_revisions) {
681             // Include all revisions of each page.
682             $table = "$page_tbl, $version_tbl";
683             $join_clause = "$page_tbl.id=$version_tbl.id";
684
685             if ($exclude_major_revisions) {
686                 // Include only minor revisions
687                 $pick[] = "minor_edit <> 0";
688             }
689             elseif (!$include_minor_revisions) {
690                 // Include only major revisions
691                 $pick[] = "minor_edit = 0";
692             }
693         }
694         else {
695             $table = "$page_tbl, $recent_tbl";
696             $join_clause = "$page_tbl.id=$recent_tbl.id";
697             $table .= ", $version_tbl";
698             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
699                 
700             if ($exclude_major_revisions) {
701                 // Include only most recent minor revision
702                 $pick[] = 'version=latestminor';
703             }
704             elseif (!$include_minor_revisions) {
705                 // Include only most recent major revision
706                 $pick[] = 'version=latestmajor';
707             }
708             else {
709                 // Include only the latest revision (whether major or minor).
710                 $pick[] ='version=latestversion';
711             }
712         }
713         $order = "DESC";
714         if($limit < 0){
715             $order = "ASC";
716             $limit = -$limit;
717         }
718         $limit = $limit ? $limit : -1;
719         $where_clause = $join_clause;
720         if ($pick)
721             $where_clause .= " AND " . join(" AND ", $pick);
722
723         // FIXME: use SQL_BUFFER_RESULT for mysql?
724         // Use SELECTLIMIT for portability
725         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
726         $result = $dbh->SelectLimit("SELECT "
727                                     . $this->page_tbl_fields . ", " . $this->version_tbl_fields
728                                     . " FROM $table"
729                                     . " WHERE $where_clause"
730                                     . " ORDER BY mtime $order",
731                                     $limit);
732         $dbh->SetFetchMode(ADODB_FETCH_NUM);
733         //$result->fields['version'] = $result->fields[6];
734         return new WikiDB_backend_ADODB_iter($this, $result);
735     }
736
737     /**
738      * Rename page in the database.
739      */
740     function rename_page($pagename, $to) {
741         $dbh = &$this->_dbh;
742         extract($this->_table_names);
743         
744         $this->lock(array('page'));
745         if ( ($id = $this->_get_pageid($pagename, false)) ) {
746             if ($new = $this->_get_pageid($to, false)) {
747                 //cludge alert!
748                 //this page does not exist (already verified before), but exists in the page table.
749                 //so we delete this page.
750                 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
751                                     $dbh->qstr($to)));
752             }
753             $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
754                                 $dbh->qstr($to)));
755         }
756         $this->unlock(array('page'));
757         return $id;
758     }
759
760     function _update_recent_table($pageid = false) {
761         $dbh = &$this->_dbh;
762         extract($this->_table_names);
763         extract($this->_expressions);
764
765         $pageid = (int)$pageid;
766
767         // optimize: mysql can do this with one REPLACE INTO.
768         if (substr($dbh->databaseType,0,5) == 'mysql') {
769             $dbh->Execute("REPLACE INTO $recent_tbl"
770                           . " (id, latestversion, latestmajor, latestminor)"
771                           . " SELECT id, $maxversion, $maxmajor, $maxminor"
772                           . " FROM $version_tbl"
773                           . ( $pageid ? " WHERE id=$pageid" : "")
774                           . " GROUP BY id" );
775         } else {
776             $this->lock(array('recent'));
777             $dbh->Execute("DELETE FROM $recent_tbl"
778                       . ( $pageid ? " WHERE id=$pageid" : ""));
779             $dbh->Execute( "INSERT INTO $recent_tbl"
780                            . " (id, latestversion, latestmajor, latestminor)"
781                            . " SELECT id, $maxversion, $maxmajor, $maxminor"
782                            . " FROM $version_tbl"
783                            . ( $pageid ? " WHERE id=$pageid" : "")
784                            . " GROUP BY id" );
785             $this->unlock(array('recent'));
786         }
787     }
788
789     function _update_nonempty_table($pageid = false) {
790         $dbh = &$this->_dbh;
791         extract($this->_table_names);
792
793         $pageid = (int)$pageid;
794
795         // optimize: mysql can do this with one REPLACE INTO.
796         if (substr($dbh->databaseType,0,5) == 'mysql') {
797             $dbh->Execute("REPLACE INTO $nonempty_tbl (id)"
798                           . " SELECT $recent_tbl.id"
799                           . " FROM $recent_tbl, $version_tbl"
800                           . " WHERE $recent_tbl.id=$version_tbl.id"
801                           . "       AND version=latestversion"
802                           . "  AND content<>''"
803                           . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
804         } else {
805             $this->lock(array('nonempty'));
806             $dbh->Execute("DELETE FROM $nonempty_tbl"
807                           . ( $pageid ? " WHERE id=$pageid" : ""));
808             $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
809                           . " SELECT $recent_tbl.id"
810                           . " FROM $recent_tbl, $version_tbl"
811                           . " WHERE $recent_tbl.id=$version_tbl.id"
812                           . "       AND version=latestversion"
813                           . "  AND content<>''"
814                           . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
815             $this->unlock(array('nonempty'));
816         }
817     }
818
819
820     /**
821      * Grab a write lock on the tables in the SQL database.
822      *
823      * Calls can be nested.  The tables won't be unlocked until
824      * _unlock_database() is called as many times as _lock_database().
825      *
826      * @access protected
827      */
828     function lock($tables, $write_lock = true) {
829         $this->_dbh->StartTrans();
830         if ($this->_lock_count++ == 0) {
831             $this->_current_lock = $tables;
832             $this->_lock_tables($tables, $write_lock);
833         }
834     }
835
836     /**
837      * Overridden by non-transaction safe backends.
838      */
839     function _lock_tables($tables, $write_lock) {
840         return $this->_current_lock;
841     }
842     
843     /**
844      * Release a write lock on the tables in the SQL database.
845      *
846      * @access protected
847      *
848      * @param $force boolean Unlock even if not every call to lock() has been matched
849      * by a call to unlock().
850      *
851      * @see _lock_database
852      */
853     function unlock($tables = false, $force = false) {
854         if ($this->_lock_count == 0) {
855             $this->_dbh->CompleteTrans(! $force);
856             $this->_current_lock = false;
857             return;
858         }
859         if (--$this->_lock_count <= 0 || $force) {
860             $this->_unlock_tables($tables);
861             $this->_current_lock = false;
862             $this->_lock_count = 0;
863         }
864         $this->_dbh->CompleteTrans(! $force);
865     }
866
867     /**
868      * overridden by non-transaction safe backends
869      */
870     function _unlock_tables($tables, $write_lock) {
871         return;
872     }
873
874     /* some variables and functions for DB backend abstraction (action=upgrade) */
875     function database () {
876         return $this->_dbh->database;
877     }
878     function backendType() {
879         return $this->_dbh->databaseType;
880     }
881     function connection() {
882         return $this->_dbh->_connectionID;
883     }
884
885     function listOfTables() {
886         return $this->_dbh->MetaTables();
887     }
888     function listOfFields($database,$table) {
889         $field_list = array();
890         foreach ($this->_dbh->MetaColumns($table,false) as $field) {
891             $field_list[] = $field->name;
892         }
893         return $field_list;
894     }
895
896 };
897
898 class WikiDB_backend_ADODB_generic_iter
899 extends WikiDB_backend_iterator
900 {
901     function WikiDB_backend_ADODB_generic_iter(&$backend, &$query_result) {
902         $this->_backend = &$backend;
903         $this->_result = $query_result;
904     }
905     
906     function count() {
907         if (!$this->_result) {
908             return false;
909         }
910         return $this->_result->numRows();
911     }
912
913     function next() {
914         $result = &$this->_result;
915         $backend = &$this->_backend;
916         if (!$result || $result->EOF) {
917             $this->free();
918             return false;
919         }
920         if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
921             $result->fetchMode = 1;
922         else
923             $result->fetchMode = 2;
924         $record = $result->fields;
925         if (isset($record[0])) {
926             $record = $result->GetRowAssoc(2);
927         } else {
928             $record = $result->fields;
929         }
930         $result->MoveNext();
931         return $record;
932     }
933
934     function free () {
935         if ($this->_result) {
936             $this->_result->Close();
937             $this->_result = false;
938         }
939     }
940 }
941
942 class WikiDB_backend_ADODB_iter
943 extends WikiDB_backend_ADODB_generic_iter
944 {
945     function next() {
946         $result = &$this->_result;
947         $backend = &$this->_backend;
948         if (!$result || $result->EOF) {
949             $this->free();
950             return false;
951         }
952         if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
953             $result->fetchMode = 1;
954         else
955             $result->fetchMode = 2;
956         $record = $result->fields;
957         if (isset($record[0])) {
958             $record = $result->GetRowAssoc(2);
959         } else {
960             $record = $result->fields;
961         }
962         $result->MoveNext();
963         
964         $pagedata = $backend->_extract_page_data($record['pagedata'], $record['hits']);
965         $rec = array('pagename' => $record['pagename'],
966                      'pagedata' => $pagedata);
967         if (!empty($record['version'])) {
968             $rec['versiondata'] = $backend->_extract_version_data_assoc($record);
969             $rec['version'] = $record['version'];
970         }
971         return $rec;
972     }
973 }
974
975 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
976 // Eventually, change index.php to provide the relevant information
977 // directly?
978     /**
979      * Parse a data source name.
980      *
981      * Additional keys can be added by appending a URI query string to the
982      * end of the DSN.
983      *
984      * The format of the supplied DSN is in its fullest form:
985      * <code>
986      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
987      * </code>
988      *
989      * Most variations are allowed:
990      * <code>
991      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
992      *  phptype://username:password@hostspec/database_name
993      *  phptype://username:password@hostspec
994      *  phptype://username@hostspec
995      *  phptype://hostspec/database
996      *  phptype://hostspec
997      *  phptype(dbsyntax)
998      *  phptype
999      * </code>
1000      *
1001      * @param string $dsn Data Source Name to be parsed
1002      *
1003      * @return array an associative array with the following keys:
1004      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
1005      *  + dbsyntax: Database used with regards to SQL syntax etc.
1006      *  + protocol: Communication protocol to use (tcp, unix etc.)
1007      *  + hostspec: Host specification (hostname[:port])
1008      *  + database: Database to use on the DBMS server
1009      *  + username: User name for login
1010      *  + password: Password for login
1011      *
1012      * @author Tomas V.V.Cox <cox@idecnet.com>
1013      */
1014     function parseDSN($dsn)
1015     {
1016         $parsed = array(
1017             'phptype'  => false,
1018             'dbsyntax' => false,
1019             'username' => false,
1020             'password' => false,
1021             'protocol' => false,
1022             'hostspec' => false,
1023             'port'     => false,
1024             'socket'   => false,
1025             'database' => false,
1026         );
1027
1028         if (is_array($dsn)) {
1029             $dsn = array_merge($parsed, $dsn);
1030             if (!$dsn['dbsyntax']) {
1031                 $dsn['dbsyntax'] = $dsn['phptype'];
1032             }
1033             return $dsn;
1034         }
1035
1036         // Find phptype and dbsyntax
1037         if (($pos = strpos($dsn, '://')) !== false) {
1038             $str = substr($dsn, 0, $pos);
1039             $dsn = substr($dsn, $pos + 3);
1040         } else {
1041             $str = $dsn;
1042             $dsn = null;
1043         }
1044
1045         // Get phptype and dbsyntax
1046         // $str => phptype(dbsyntax)
1047         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1048             $parsed['phptype']  = $arr[1];
1049             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1050         } else {
1051             $parsed['phptype']  = $str;
1052             $parsed['dbsyntax'] = $str;
1053         }
1054
1055         if (!count($dsn)) {
1056             return $parsed;
1057         }
1058
1059         // Get (if found): username and password
1060         // $dsn => username:password@protocol+hostspec/database
1061         if (($at = strrpos($dsn,'@')) !== false) {
1062             $str = substr($dsn, 0, $at);
1063             $dsn = substr($dsn, $at + 1);
1064             if (($pos = strpos($str, ':')) !== false) {
1065                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1066                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1067             } else {
1068                 $parsed['username'] = rawurldecode($str);
1069             }
1070         }
1071
1072         // Find protocol and hostspec
1073
1074         // $dsn => proto(proto_opts)/database
1075         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1076             $proto       = $match[1];
1077             $proto_opts  = $match[2] ? $match[2] : false;
1078             $dsn         = $match[3];
1079
1080         // $dsn => protocol+hostspec/database (old format)
1081         } else {
1082             if (strpos($dsn, '+') !== false) {
1083                 list($proto, $dsn) = explode('+', $dsn, 2);
1084             }
1085             if (strpos($dsn, '/') !== false) {
1086                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1087             } else {
1088                 $proto_opts = $dsn;
1089                 $dsn = null;
1090             }
1091         }
1092
1093         // process the different protocol options
1094         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1095         $proto_opts = rawurldecode($proto_opts);
1096         if ($parsed['protocol'] == 'tcp') {
1097             if (strpos($proto_opts, ':') !== false) {
1098                 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1099             } else {
1100                 $parsed['hostspec'] = $proto_opts;
1101             }
1102         } elseif ($parsed['protocol'] == 'unix') {
1103             $parsed['socket'] = $proto_opts;
1104         }
1105
1106         // Get dabase if any
1107         // $dsn => database
1108         if ($dsn) {
1109             // /database
1110             if (($pos = strpos($dsn, '?')) === false) {
1111                 $parsed['database'] = $dsn;
1112             // /database?param1=value1&param2=value2
1113             } else {
1114                 $parsed['database'] = substr($dsn, 0, $pos);
1115                 $dsn = substr($dsn, $pos + 1);
1116                 if (strpos($dsn, '&') !== false) {
1117                     $opts = explode('&', $dsn);
1118                 } else { // database?param1=value1
1119                     $opts = array($dsn);
1120                 }
1121                 foreach ($opts as $opt) {
1122                     list($key, $value) = explode('=', $opt);
1123                     if (!isset($parsed[$key])) {
1124                         // don't allow params overwrite
1125                         $parsed[$key] = rawurldecode($value);
1126                     }
1127                 }
1128             }
1129         }
1130
1131         return $parsed;
1132     }
1133
1134 // $Log: not supported by cvs2svn $
1135 // Revision 1.34  2004/06/28 14:17:38  rurban
1136 // updated DSN parser from Pear. esp. for sqlite
1137 //
1138 // Revision 1.33  2004/06/27 10:26:02  rurban
1139 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1140 //
1141 // Revision 1.32  2004/06/25 14:15:08  rurban
1142 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1143 //
1144 // Revision 1.31  2004/06/16 10:38:59  rurban
1145 // Disallow refernces in calls if the declaration is a reference
1146 // ("allow_call_time_pass_reference clean").
1147 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
1148 //   but several external libraries may not.
1149 //   In detail these libs look to be affected (not tested):
1150 //   * Pear_DB odbc
1151 //   * adodb oracle
1152 //
1153 // Revision 1.30  2004/06/07 19:31:31  rurban
1154 // fixed ADOOB upgrade: listOfFields()
1155 //
1156 // Revision 1.29  2004/05/12 10:49:55  rurban
1157 // require_once fix for those libs which are loaded before FileFinder and
1158 //   its automatic include_path fix, and where require_once doesn't grok
1159 //   dirname(__FILE__) != './lib'
1160 // upgrade fix with PearDB
1161 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1162 //
1163 // Revision 1.28  2004/05/06 19:26:16  rurban
1164 // improve stability, trying to find the InlineParser endless loop on sf.net
1165 //
1166 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1167 //
1168 // Revision 1.27  2004/05/06 17:30:38  rurban
1169 // CategoryGroup: oops, dos2unix eol
1170 // improved phpwiki_version:
1171 //   pre -= .0001 (1.3.10pre: 1030.099)
1172 //   -p1 += .001 (1.3.9-p1: 1030.091)
1173 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1174 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1175 //   backend->backendType(), backend->database(),
1176 //   backend->listOfFields(),
1177 //   backend->listOfTables(),
1178 //
1179 // Revision 1.26  2004/04/26 20:44:35  rurban
1180 // locking table specific for better databases
1181 //
1182 // Revision 1.25  2004/04/20 00:06:04  rurban
1183 // themable paging support
1184 //
1185 // Revision 1.24  2004/04/18 01:34:20  rurban
1186 // protect most_popular from sortby=mtime
1187 //
1188 // Revision 1.23  2004/04/16 14:19:39  rurban
1189 // updated ADODB notes
1190 //
1191
1192 // (c-file-style: "gnu")
1193 // Local Variables:
1194 // mode: php
1195 // tab-width: 8
1196 // c-basic-offset: 4
1197 // c-hanging-comment-ender-p: nil
1198 // indent-tabs-mode: nil
1199 // End:   
1200 ?>