]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/ADODB.php
themable paging support
[SourceForge/phpwiki.git] / lib / WikiDB / backend / ADODB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: ADODB.php,v 1.25 2004-04-20 00:06:04 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
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, but no locking yet.
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         $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'], 
75                                      $parsed['password'], $parsed['database']);
76
77         //$this->_dbh->debug = true;
78         
79         // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
80         // with some ASSOC based recordsets.
81         $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
82         $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
83
84         // Old comment:
85         //  With ADODB_COUNTRECS false it should speed up queries, but:
86         //  1)  It only works with PHP >= 4.0.6; and
87         //  2)  At the moment, I haven't figured out why the wrong results are returned'
88         $GLOBALS['ADODB_COUNTRECS'] = false;
89
90         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
91         $this->_table_names
92             = array('page_tbl'     => $prefix . 'page',
93                     'version_tbl'  => $prefix . 'version',
94                     'link_tbl'     => $prefix . 'link',
95                     'recent_tbl'   => $prefix . 'recent',
96                     'nonempty_tbl' => $prefix . 'nonempty');
97         $page_tbl = $this->_table_names['page_tbl'];
98         $version_tbl = $this->_table_names['version_tbl'];
99         $this->page_tbl_fields = "$page_tbl.id as id, $page_tbl.pagename as pagename, "
100             . "$page_tbl.hits as hits, $page_tbl.pagedata as pagedata";
101         $this->version_tbl_fields = "$version_tbl.version as version, "
102             . "$version_tbl.mtime as mtime, "
103             . "$version_tbl.minor_edit as minor_edit, $version_tbl.content as content, "
104             . "$version_tbl.versiondata as versiondata";
105
106         $this->_expressions
107             = array('maxmajor'     => "MAX(CASE WHEN minor_edit=0 THEN version END)",
108                     'maxminor'     => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
109                     'maxversion'   => "MAX(version)");
110         /*
111         // FIXME: Older MySQL's don't have CASE WHEN ... END
112         $this->_expressions['maxmajor'] = "MAX(IF(minor_edit=0,version,0))";
113         $this->_expressions['maxminor'] = "MAX(IF(minor_edit<>0,version,0))"; 
114         */
115         $this->_lock_count = 0;
116     }
117     
118     /**
119      * Close database connection.
120      */
121     function close () {
122         if (!$this->_dbh)
123             return;
124         if ($this->_lock_count) {
125             trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
126                           E_USER_WARNING);
127         }
128 //      $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
129         $this->unlock('force');
130
131         $this->_dbh->close();
132         $this->_dbh = false;
133     }
134
135     /*
136      * Fast test for wikipage.
137      */
138     function is_wiki_page($pagename) {
139         $dbh = &$this->_dbh;
140         extract($this->_table_names);
141         $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
142                                     . " FROM $nonempty_tbl, $page_tbl"
143                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
144                                     . "   AND pagename=%s",
145                                     $dbh->qstr($pagename)));
146         return $row ? $row[0] : false;
147     }
148         
149     function get_all_pagenames() {
150         $dbh = &$this->_dbh;
151         extract($this->_table_names);
152         $result = $dbh->Execute("SELECT pagename"
153                                 . " FROM $nonempty_tbl, $page_tbl"
154                                 . " WHERE $nonempty_tbl.id=$page_tbl.id");
155         return $result->GetArray();
156     }
157
158     function numPages($filter=false, $exclude='') {
159         $dbh = &$this->_dbh;
160         extract($this->_table_names);
161         $result = $dbh->getRow("SELECT count(*)"
162                             . " FROM $nonempty_tbl, $page_tbl"
163                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
164         return $result[0];
165     }
166     
167     /**
168      * Read page information from database.
169      */
170     function get_pagedata($pagename) {
171         $dbh = &$this->_dbh;
172         $page_tbl = $this->_table_names['page_tbl'];
173         $row = $dbh->GetRow(sprintf("SELECT hits,pagedata FROM $page_tbl WHERE pagename=%s",
174                                        $dbh->qstr($pagename)));
175         return $row ? $this->_extract_page_data($row[1],$row[0]) : false;
176     }
177
178     function  _extract_page_data($data, $hits) {
179         $pagedata = empty($data) ? array() : unserialize($data);
180         $pagedata['hits'] = $hits;
181         return $pagedata;
182     }
183
184     function update_pagedata($pagename, $newdata) {
185         $dbh = &$this->_dbh;
186         $page_tbl = $this->_table_names['page_tbl'];
187
188         // Hits is the only thing we can update in a fast manner.
189         if (count($newdata) == 1 && isset($newdata['hits'])) {
190             // Note that this will fail silently if the page does not
191             // have a record in the page table.  Since it's just the
192             // hit count, who cares?
193             $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
194                                   $newdata['hits'], $dbh->qstr($pagename)));
195             return;
196         }
197         $where = sprintf("pagename=%s",$dbh->qstr($pagename));
198         $dbh->BeginTrans( );
199         $dbh->RowLock($page_tbl,$where);
200         
201         $data = $this->get_pagedata($pagename);
202         if (!$data) {
203             $data = array();
204             $this->_get_pageid($pagename, true); // Creates page record
205         }
206         
207         @$hits = (int)$data['hits'];
208         unset($data['hits']);
209
210         foreach ($newdata as $key => $val) {
211             if ($key == 'hits')
212                 $hits = (int)$val;
213             else if (empty($val))
214                 unset($data[$key]);
215             else
216                 $data[$key] = $val;
217         }
218         if ($dbh->Execute(sprintf("UPDATE $page_tbl"
219                                   . " SET hits=%d, pagedata=%s"
220                                   . " WHERE pagename=%s",
221                                   $hits,
222                                   $dbh->qstr(serialize($data)),
223                                   $dbh->qstr($pagename))))
224             $dbh->CommitTrans( );
225         else
226             $dbh->RollbackTrans( );
227     }
228
229     function _get_pageid($pagename, $create_if_missing = false) {
230         
231         $dbh = &$this->_dbh;
232         $page_tbl = $this->_table_names['page_tbl'];
233         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
234                          $dbh->qstr($pagename));
235         if (! $create_if_missing ) {
236             $row = $dbh->GetRow($query);
237             return $row ? $row[0] : false;
238         }
239         $row = $dbh->GetRow($query);
240         if (! $row) {
241             if ((substr($dbh->databaseType,0,5) == 'mysql') or isa($dbh,'ADODB_sqlite')) {
242                 // have auto-incrementing and atomic version
243                 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
244                                             . " (pagename,hits)"
245                                             . " VALUES (%s,0)",
246                                             $dbh->qstr($pagename)));
247                 $id = $dbh->_insertid();
248             } else {
249                 //$id = $dbh->GenID($page_tbl . 'seq');
250                 // Better generic version than with adodob::genID
251                 $this->lock();
252                 $dbh->BeginTrans( );
253                 $dbh->CommitLock($page_tbl);
254                 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
255                 $id = $row[0] + 1;
256                 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
257                                             . " (id,pagename,hits)"
258                                             . " VALUES (%d,%s,0)",
259                                             $id, $dbh->qstr($pagename)));
260                 if ($rs) $dbh->CommitTrans( );
261                 else $dbh->RollbackTrans( );
262                 $this->unlock();
263             }
264         } else {
265             $id = $row[0];
266         }
267         return $id;
268     }
269
270     function get_latest_version($pagename) {
271         $dbh = &$this->_dbh;
272         extract($this->_table_names);
273         $row = $dbh->GetRow(sprintf("SELECT latestversion"
274                                     . " FROM $page_tbl, $recent_tbl"
275                                     . " WHERE $page_tbl.id=$recent_tbl.id"
276                                     . "  AND pagename=%s",
277                                     $dbh->qstr($pagename)));
278         return $row ? (int)$row[0] : false;
279     }
280
281     function get_previous_version($pagename, $version) {
282         $dbh = &$this->_dbh;
283         extract($this->_table_names);
284         // Use SELECTLIMIT for maximum portability
285         $rs = $dbh->SelectLimit(sprintf("SELECT version"
286                                         . " FROM $version_tbl, $page_tbl"
287                                         . " WHERE $version_tbl.id=$page_tbl.id"
288                                         . "  AND pagename=%s"
289                                         . "  AND version < %d"
290                                         . " ORDER BY version DESC"
291                                         ,$dbh->qstr($pagename),
292                                         $version),
293                                 1);
294         return $rs->fields[0] ? (int)$rs->fields[0] : false;
295     }
296     
297     /**
298      * Get version data.
299      *
300      * @param $version int Which version to get.
301      *
302      * @return hash The version data, or false if specified version does not
303      *              exist.
304      */
305     function get_versiondata($pagename, $version, $want_content = false) {
306         $dbh = &$this->_dbh;
307         extract($this->_table_names);
308                 
309         assert(is_string($pagename) and $pagename != '');
310         assert($version > 0);
311         
312         // FIXME: optimization: sometimes don't get page data?
313         if ($want_content) {
314             $fields = $this->page_tbl_fields
315                 . ', ' . $this->version_tbl_fields;
316         } else {
317             $fields = $this->page_tbl_fields
318                 . ", $version_tbl.version as version, $version_tbl.mtime as mtime, "
319                 . "$version_tbl.minor_edit as minor_edit, $version_tbl.content<>'' as have_content, "
320                 . "$version_tbl.versiondata as versiondata";
321         }
322         $row = $dbh->GetRow(sprintf("SELECT $fields"
323                                     . " FROM $page_tbl, $version_tbl"
324                                     . " WHERE $page_tbl.id=$version_tbl.id"
325                                     . "  AND pagename=%s"
326                                     . "  AND version=%d",
327                                     $dbh->qstr($pagename), $version));
328         return $row ? $this->_extract_version_data_num($row, $want_content) : false;
329     }
330
331     function _extract_version_data_num(&$row, $want_content) {
332         if (!$row)
333             return false;
334
335         //$id       &= $row[0];
336         //$pagename &= $row[1];
337         $data = empty($row[8]) ? array() : unserialize($row[8]);
338         $data['mtime']         = $row[5];
339         $data['is_minor_edit'] = !empty($row[6]);
340         if ($want_content) {
341             $data['%content'] = $row[7];
342         } else {
343             $data['%content'] = !empty($row[7]);
344         }
345         if (!empty($row[3])) {
346             $data['%pagedata'] = $this->_extract_page_data($row[3],$row[2]);
347         }
348         return $data;
349     }
350
351     function _extract_version_data_assoc(&$row) {
352         if (!$row)
353             return false;
354
355         extract($row);
356         $data = empty($versiondata) ? array() : unserialize($versiondata);
357         $data['mtime'] = $mtime;
358         $data['is_minor_edit'] = !empty($minor_edit);
359         if (isset($content))
360             $data['%content'] = $content;
361         elseif ($have_content)
362             $data['%content'] = true;
363         else
364             $data['%content'] = '';
365         if (!empty($pagedata)) {
366             $data['%pagedata'] = $this->_extract_page_data($pagedata,$hits);
367         }
368         return $data;
369     }
370
371     /**
372      * Create a new revision of a page.
373      */
374     function set_versiondata($pagename, $version, $data) {
375         $dbh = &$this->_dbh;
376         $version_tbl = $this->_table_names['version_tbl'];
377         
378         $minor_edit = (int) !empty($data['is_minor_edit']);
379         unset($data['is_minor_edit']);
380         
381         $mtime = (int)$data['mtime'];
382         unset($data['mtime']);
383         assert(!empty($mtime));
384
385         @$content = (string) $data['%content'];
386         unset($data['%content']);
387         unset($data['%pagedata']);
388         
389         $this->lock();
390         $dbh->BeginTrans( );
391         $dbh->CommitLock($version_tbl);
392         $id = $this->_get_pageid($pagename, true);
393
394         // optimize: mysql can do this with one REPLACE INTO.
395         if (substr($dbh->databaseType,0,5) == 'mysql') {
396             $dbh->Execute(sprintf("REPLACE INTO $version_tbl"
397                                   . " (id,version,mtime,minor_edit,content,versiondata)"
398                                   . " VALUES(%d,%d,%d,%d,%s,%s)",
399                                   $id, $version, $mtime, $minor_edit,
400                                   $dbh->qstr($content),
401                                   $dbh->qstr(serialize($data))));
402         } else {
403             $dbh->Execute(sprintf("DELETE FROM $version_tbl"
404                                   . " WHERE id=%d AND version=%d",
405                                   $id, $version));
406             $dbh->Execute(sprintf("INSERT INTO $version_tbl"
407                                   . " (id,version,mtime,minor_edit,content,versiondata)"
408                                   . " VALUES(%d,%d,%d,%d,%s,%s)",
409                                   $id, $version, $mtime, $minor_edit,
410                                   $dbh->qstr($content),
411                                   $dbh->qstr(serialize($data))));
412         }
413         $this->_update_recent_table($id);
414         $this->_update_nonempty_table($id);
415         if ($rs) $dbh->CommitTrans( );
416         else $dbh->RollbackTrans( );
417         $this->unlock();
418     }
419     
420     /**
421      * Delete an old revision of a page.
422      */
423     function delete_versiondata($pagename, $version) {
424         $dbh = &$this->_dbh;
425         extract($this->_table_names);
426
427         $this->lock();
428         if ( ($id = $this->_get_pageid($pagename)) ) {
429             $dbh->Execute("DELETE FROM $version_tbl"
430                         . " WHERE id=$id AND version=$version");
431             $this->_update_recent_table($id);
432             // This shouldn't be needed (as long as the latestversion
433             // never gets deleted.)  But, let's be safe.
434             $this->_update_nonempty_table($id);
435         }
436         $this->unlock();
437     }
438
439     /**
440      * Delete page from the database.
441      */
442     function delete_page($pagename) {
443         $dbh = &$this->_dbh;
444         extract($this->_table_names);
445         
446         $this->lock();
447         if ( ($id = $this->_get_pageid($pagename, false)) ) {
448             $dbh->Execute("DELETE FROM $version_tbl  WHERE id=$id");
449             $dbh->Execute("DELETE FROM $recent_tbl   WHERE id=$id");
450             $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
451             $dbh->Execute("DELETE FROM $link_tbl     WHERE linkfrom=$id");
452             $rs = $dbh->Execute("SELECT COUNT(*) AS C FROM $link_tbl WHERE linkto=$id");
453             $nlinks = $rs->fields['C'];
454             if ($nlinks) {
455                 // We're still in the link table (dangling link) so we can't delete this
456                 // altogether.
457                 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
458             }
459             else {
460                 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
461             }
462             $this->_update_recent_table();
463             $this->_update_nonempty_table();
464         }
465         $this->unlock();
466     }
467             
468
469     // The only thing we might be interested in updating which we can
470     // do fast in the flags (minor_edit).   I think the default
471     // update_versiondata will work fine...
472     //function update_versiondata($pagename, $version, $data) {
473     //}
474
475     function set_links($pagename, $links) {
476         // Update link table.
477         // FIXME: optimize: mysql can do this all in one big INSERT.
478
479         $dbh = &$this->_dbh;
480         extract($this->_table_names);
481
482         $this->lock();
483         $pageid = $this->_get_pageid($pagename, true);
484
485         $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
486
487         if ($links) {
488             foreach($links as $link) {
489                 if (isset($linkseen[$link]))
490                     continue;
491                 $linkseen[$link] = true;
492                 $linkid = $this->_get_pageid($link, true);
493                 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
494                             . " VALUES ($pageid, $linkid)");
495             }
496         }
497         $this->unlock();
498     }
499     
500     /**
501      * Find pages which link to or are linked from a page.
502      */
503     function get_links($pagename, $reversed = true) {
504         $dbh = &$this->_dbh;
505         extract($this->_table_names);
506
507         if ($reversed)
508             list($have,$want) = array('linkee', 'linker');
509         else
510             list($have,$want) = array('linker', 'linkee');
511
512         $qpagename = $dbh->qstr($pagename);
513         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
514         // removed ref to FETCH_MODE in next line
515         $result = $dbh->Execute("SELECT $want.id as id, $want.pagename as pagename,"
516                                 . " $want.hits as hits, $want.pagedata as pagedata"
517                                 . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
518                                 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
519                                 . " AND $have.pagename=$qpagename"
520                                 //. " GROUP BY $want.id"
521                                 . " ORDER BY $want.pagename");
522         $dbh->SetFetchMode(ADODB_FETCH_NUM);
523         return new WikiDB_backend_ADODB_iter($this, $result);
524     }
525
526     function get_all_pages($include_deleted=false,$sortby = false,$limit = false) {
527         $dbh = &$this->_dbh;
528         extract($this->_table_names);
529         if ($limit)  $limit = "LIMIT $limit";
530         else         $limit = '';
531         if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
532         else         $orderby = '';
533         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
534         if (strstr($orderby,' mtime')) {
535             if ($include_deleted) {
536                 $result = $dbh->Execute("SELECT * FROM $page_tbl, $recent_tbl, $version_tbl"
537                                         . " WHERE $page_tbl.id=$recent_tbl.id"
538                                         . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
539                                         . " $orderby $limit");
540             }
541             else {
542                 $result = $dbh->Execute("SELECT "
543                                         . $this->page_tbl_fields
544                                         . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
545                                         . " WHERE $nonempty_tbl.id=$page_tbl.id"
546                                         . " AND $page_tbl.id=$recent_tbl.id"
547                                         . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
548                                         . " $orderby $limit");
549             }
550         } else {
551             if ($include_deleted) {
552                 $result = $dbh->Execute("SELECT "
553                                         . $this->page_tbl_fields
554                                         . " FROM $page_tbl $orderby $limit");
555             } else {
556                 $result = $dbh->Execute("SELECT "
557                                         . $this->page_tbl_fields
558                                         . " FROM $nonempty_tbl, $page_tbl"
559                                         . " WHERE $nonempty_tbl.id=$page_tbl.id"
560                                         . " $orderby $limit");
561             }
562         }
563         $dbh->SetFetchMode(ADODB_FETCH_NUM);
564         return new WikiDB_backend_ADODB_iter($this, $result);
565     }
566         
567     /**
568      * Title search.
569      */
570     function text_search($search = '', $fullsearch = false) {
571         $dbh = &$this->_dbh;
572         extract($this->_table_names);
573         
574         $table = "$nonempty_tbl, $page_tbl";
575         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
576         $fields = $this->page_tbl_fields;
577         $callback = new WikiMethodCb($this, '_sql_match_clause');
578         
579         if ($fullsearch) {
580             $table .= ", $recent_tbl";
581             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
582
583             $table .= ", $version_tbl";
584             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
585
586             $fields .= "," . $this->version_tbl_fields;
587             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
588         }
589         
590         $search_clause = $search->makeSqlClause($callback);
591         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
592         $result = $dbh->Execute("SELECT $fields FROM $table"
593                                 . " WHERE $join_clause"
594                                 . "  AND ($search_clause)"
595                                 . " ORDER BY pagename");
596
597         $dbh->SetFetchMode(ADODB_FETCH_NUM);
598         return new WikiDB_backend_ADODB_iter($this, $result);
599     }
600
601     function _sql_match_clause($word) {
602         //not sure if we need this.  ADODB may do it for us
603         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  
604
605         // (we need it for at least % and _ --- they're the wildcard characters
606         //  for the LIKE operator, and we need to quote them if we're searching
607         //  for literal '%'s or '_'s.  --- I'm not sure about \, but it seems to
608         //  work as is.
609         $word = $this->_dbh->qstr("%$word%");
610         $page_tbl = $this->_table_names['page_tbl'];
611         return "LOWER($page_tbl.pagename) LIKE $word";
612     }
613
614     function _fullsearch_sql_match_clause($word) {
615         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  //not sure if we need this
616         // (see above)
617         $word = $this->_dbh->qstr("%$word%");
618         $page_tbl = $this->_table_names['page_tbl'];
619         return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
620     }
621
622     /**
623      * Find highest or lowest hit counts.
624      */
625     function most_popular($limit=0,$sortby = '') {
626         $dbh = &$this->_dbh;
627         extract($this->_table_names);
628         $order = "DESC";
629         if ($limit < 0){ 
630             $order = "ASC"; 
631             $limit = -$limit;
632             $where = "";
633         } else {
634             $where = " AND hits > 0";
635         }
636         if ($sortby) $orderby = " ORDER BY " . PageList::sortby($sortby,'db');
637         else         $orderby = " ORDER BY hits $order";
638         $limit = $limit ? $limit : -1;
639
640         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
641         $result = $dbh->SelectLimit("SELECT " 
642                                     . $this->page_tbl_fields
643                                     . " FROM $nonempty_tbl, $page_tbl"
644                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
645                                     . $where
646                                     . $orderby
647                                     , $limit);
648         $dbh->SetFetchMode(ADODB_FETCH_NUM);
649         return new WikiDB_backend_ADODB_iter($this, $result);
650     }
651
652     /**
653      * Find recent changes.
654      */
655     function most_recent($params) {
656         $limit = 0;
657         $since = 0;
658         $include_minor_revisions = false;
659         $exclude_major_revisions = false;
660         $include_all_revisions = false;
661         extract($params);
662
663         $dbh = &$this->_dbh;
664         extract($this->_table_names);
665
666         $pick = array();
667         if ($since)
668             $pick[] = "mtime >= $since";
669         
670         if ($include_all_revisions) {
671             // Include all revisions of each page.
672             $table = "$page_tbl, $version_tbl";
673             $join_clause = "$page_tbl.id=$version_tbl.id";
674
675             if ($exclude_major_revisions) {
676                 // Include only minor revisions
677                 $pick[] = "minor_edit <> 0";
678             }
679             elseif (!$include_minor_revisions) {
680                 // Include only major revisions
681                 $pick[] = "minor_edit = 0";
682             }
683         }
684         else {
685             $table = "$page_tbl, $recent_tbl";
686             $join_clause = "$page_tbl.id=$recent_tbl.id";
687             $table .= ", $version_tbl";
688             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
689                 
690             if ($exclude_major_revisions) {
691                 // Include only most recent minor revision
692                 $pick[] = 'version=latestminor';
693             }
694             elseif (!$include_minor_revisions) {
695                 // Include only most recent major revision
696                 $pick[] = 'version=latestmajor';
697             }
698             else {
699                 // Include only the latest revision (whether major or minor).
700                 $pick[] ='version=latestversion';
701             }
702         }
703         $order = "DESC";
704         if($limit < 0){
705             $order = "ASC";
706             $limit = -$limit;
707         }
708         $limit = $limit ? $limit : -1;
709         $where_clause = $join_clause;
710         if ($pick)
711             $where_clause .= " AND " . join(" AND ", $pick);
712
713         // FIXME: use SQL_BUFFER_RESULT for mysql?
714         // Use SELECTLIMIT for portability
715         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
716         $result = $dbh->SelectLimit("SELECT "
717                                     . $this->page_tbl_fields . ", " . $this->version_tbl_fields
718                                     . " FROM $table"
719                                     . " WHERE $where_clause"
720                                     . " ORDER BY mtime $order",
721                                     $limit);
722         $dbh->SetFetchMode(ADODB_FETCH_NUM);
723         //$result->fields['version'] = $result->fields[6];
724         return new WikiDB_backend_ADODB_iter($this, $result);
725     }
726
727     /**
728      * Rename page in the database.
729      */
730     function rename_page($pagename, $to) {
731         $dbh = &$this->_dbh;
732         extract($this->_table_names);
733         
734         $this->lock();
735         if ( ($id = $this->_get_pageid($pagename, false)) ) {
736             if ($new = $this->_get_pageid($to, false)) {
737                 //cludge alert!
738                 //this page does not exist (already verified before), but exists in the page table.
739                 //so we delete this page.
740                 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
741                                     $dbh->qstr($to)));
742             }
743             $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
744                                 $dbh->qstr($to)));
745         }
746         $this->unlock();
747         return $id;
748     }
749
750     function _update_recent_table($pageid = false) {
751         $dbh = &$this->_dbh;
752         extract($this->_table_names);
753         extract($this->_expressions);
754
755         $pageid = (int)$pageid;
756
757         // optimize: mysql can do this with one REPLACE INTO.
758         if (substr($dbh->databaseType,0,5) == 'mysql') {
759             $dbh->Execute("REPLACE INTO $recent_tbl"
760                           . " (id, latestversion, latestmajor, latestminor)"
761                           . " SELECT id, $maxversion, $maxmajor, $maxminor"
762                           . " FROM $version_tbl"
763                           . ( $pageid ? " WHERE id=$pageid" : "")
764                           . " GROUP BY id" );
765         } else {
766             $this->lock();
767             $dbh->Execute("DELETE FROM $recent_tbl"
768                       . ( $pageid ? " WHERE id=$pageid" : ""));
769             $dbh->Execute( "INSERT 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             $this->unlock();
776         }
777     }
778
779     function _update_nonempty_table($pageid = false) {
780         $dbh = &$this->_dbh;
781         extract($this->_table_names);
782
783         $pageid = (int)$pageid;
784
785         // optimize: mysql can do this with one REPLACE INTO.
786         if (substr($dbh->databaseType,0,5) == 'mysql') {
787             $dbh->Execute("REPLACE INTO $nonempty_tbl (id)"
788                           . " SELECT $recent_tbl.id"
789                           . " FROM $recent_tbl, $version_tbl"
790                           . " WHERE $recent_tbl.id=$version_tbl.id"
791                           . "       AND version=latestversion"
792                           . "  AND content<>''"
793                           . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
794         } else {
795             $this->lock();
796             $dbh->Execute("DELETE FROM $nonempty_tbl"
797                           . ( $pageid ? " WHERE id=$pageid" : ""));
798             $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
799                           . " SELECT $recent_tbl.id"
800                           . " FROM $recent_tbl, $version_tbl"
801                           . " WHERE $recent_tbl.id=$version_tbl.id"
802                           . "       AND version=latestversion"
803                           . "  AND content<>''"
804                           . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
805             $this->unlock();
806         }
807     }
808
809
810     /**
811      * Grab a write lock on the tables in the SQL database.
812      *
813      * Calls can be nested.  The tables won't be unlocked until
814      * _unlock_database() is called as many times as _lock_database().
815      *
816      * @access protected
817      */
818     function lock($write_lock = true) {
819         $this->_dbh->StartTrans();
820         if ($this->_lock_count++ == 0)
821             $this->_lock_tables($write_lock);
822     }
823
824     /**
825      * Actually lock the required tables.
826      */
827     function _lock_tables($write_lock) {
828         return;
829         trigger_error("virtual", E_USER_ERROR);
830     }
831     
832     /**
833      * Release a write lock on the tables in the SQL database.
834      *
835      * @access protected
836      *
837      * @param $force boolean Unlock even if not every call to lock() has been matched
838      * by a call to unlock().
839      *
840      * @see _lock_database
841      */
842     function unlock($force = false) {
843         if ($this->_lock_count == 0) {
844             $this->_dbh->CompleteTrans(! $force);
845             return;
846         }
847         if (--$this->_lock_count <= 0 || $force) {
848             $this->_unlock_tables();
849             $this->_lock_count = 0;
850         }
851         $this->_dbh->CompleteTrans(! $force);
852     }
853
854     /**
855      * Actually unlock the required tables.
856      */
857     function _unlock_tables($write_lock) {
858         return;
859         trigger_error("virtual", E_USER_ERROR);
860     }
861 };
862
863 class WikiDB_backend_ADODB_generic_iter
864 extends WikiDB_backend_iterator
865 {
866     function WikiDB_backend_ADODB_generic_iter(&$backend, &$query_result) {
867         $this->_backend = &$backend;
868         $this->_result = $query_result;
869     }
870     
871     function count() {
872         if (!$this->_result) {
873             return false;
874         }
875         return $this->_result->numRows();
876     }
877
878     function next() {
879         $result = &$this->_result;
880         $backend = &$this->_backend;
881         if (!$result || $result->EOF) {
882             $this->free();
883             return false;
884         }
885         if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
886             $result->fetchMode = 1;
887         else
888             $result->fetchMode = 2;
889         $record = $result->fields;
890         if (isset($record[0])) {
891             $record = $result->GetRowAssoc(2);
892         } else {
893             $record = $result->fields;
894         }
895         $result->MoveNext();
896         return $record;
897     }
898
899     function free () {
900         if ($this->_result) {
901             $this->_result->Close();
902             $this->_result = false;
903         }
904     }
905 }
906
907 class WikiDB_backend_ADODB_iter
908 extends WikiDB_backend_ADODB_generic_iter
909 {
910     function next() {
911         $result = &$this->_result;
912         $backend = &$this->_backend;
913         if (!$result || $result->EOF) {
914             $this->free();
915             return false;
916         }
917         if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
918             $result->fetchMode = 1;
919         else
920             $result->fetchMode = 2;
921         $record = $result->fields;
922         if (isset($record[0])) {
923             $record = $result->GetRowAssoc(2);
924         } else {
925             $record = $result->fields;
926         }
927         $result->MoveNext();
928         
929         $pagedata = $backend->_extract_page_data(&$record['pagedata'], $record['hits']);
930         $rec = array('pagename' => $record['pagename'],
931                      'pagedata' => $pagedata);
932         if (!empty($record['version'])) {
933             $rec['versiondata'] = $backend->_extract_version_data_assoc($record);
934             $rec['version'] = $record['version'];
935         }
936         return $rec;
937     }
938 }
939
940 // Following function taken from adodb-pear.inc.php.  
941 // Eventually, change index.php to provide the relevant information
942 // directly?
943     /**
944      * Parse a data source name
945      *
946      * @param $dsn string Data Source Name to be parsed
947      *
948      * @return array an associative array with the following keys:
949      *
950      *  phptype: Database backend used in PHP (mysql, odbc etc.)
951      *  dbsyntax: Database used with regards to SQL syntax etc.
952      *  protocol: Communication protocol to use (tcp, unix etc.)
953      *  hostspec: Host specification (hostname[:port])
954      *  database: Database to use on the DBMS server
955      *  username: User name for login
956      *  password: Password for login
957      *
958      * The format of the supplied DSN is in its fullest form:
959      *
960      *  phptype(dbsyntax)://username:password@protocol+hostspec/database
961      *
962      * Most variations are allowed:
963      *
964      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
965      *  phptype://username:password@hostspec/database_name
966      *  phptype://username:password@hostspec
967      *  phptype://username@hostspec
968      *  phptype://hostspec/database
969      *  phptype://hostspec
970      *  phptype(dbsyntax)
971      *  phptype
972      *
973      * @author Tomas V.V.Cox <cox@idecnet.com>
974      */
975     function parseDSN($dsn) {
976         if (is_array($dsn)) {
977             return $dsn;
978         }
979
980         $parsed = array(
981             'phptype'  => false,
982             'dbsyntax' => false,
983             'protocol' => false,
984             'hostspec' => false,
985             'database' => false,
986             'username' => false,
987             'password' => false
988         );
989
990         // Find phptype and dbsyntax
991         if (($pos = strpos($dsn, '://')) !== false) {
992             $str = substr($dsn, 0, $pos);
993             $dsn = substr($dsn, $pos + 3);
994         } else {
995             $str = $dsn;
996             $dsn = NULL;
997         }
998
999         // Get phptype and dbsyntax
1000         // $str => phptype(dbsyntax)
1001         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1002             $parsed['phptype'] = $arr[1];
1003             $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
1004         } else {
1005             $parsed['phptype'] = $str;
1006             $parsed['dbsyntax'] = $str;
1007         }
1008
1009         if (empty($dsn)) {
1010             return $parsed;
1011         }
1012
1013         // Get (if found): username and password
1014         // $dsn => username:password@protocol+hostspec/database
1015         if (($at = strpos($dsn,'@')) !== false) {
1016             $str = substr($dsn, 0, $at);
1017             $dsn = substr($dsn, $at + 1);
1018             if (($pos = strpos($str, ':')) !== false) {
1019                 $parsed['username'] = urldecode(substr($str, 0, $pos));
1020                 $parsed['password'] = urldecode(substr($str, $pos + 1));
1021             } else {
1022                 $parsed['username'] = urldecode($str);
1023             }
1024         }
1025
1026         // Find protocol and hostspec
1027         // $dsn => protocol+hostspec/database
1028         if (($pos = strpos($dsn, '/')) !== false) {
1029             $str = substr($dsn, 0, $pos);
1030             $dsn = substr($dsn, $pos + 1);
1031         } else {
1032             $str = $dsn;
1033             $dsn = NULL;
1034         }
1035
1036         // Get protocol + hostspec
1037         // $str => protocol+hostspec
1038         if (($pos = strpos($str, '+')) !== false) {
1039             $parsed['protocol'] = substr($str, 0, $pos);
1040             $parsed['hostspec'] = urldecode(substr($str, $pos + 1));
1041         } else {
1042             $parsed['hostspec'] = urldecode($str);
1043         }
1044
1045         // Get dabase if any
1046         // $dsn => database
1047         if (!empty($dsn)) {
1048             $parsed['database'] = $dsn;
1049         }
1050
1051         return $parsed;
1052     }
1053
1054 // $Log: not supported by cvs2svn $
1055 // Revision 1.24  2004/04/18 01:34:20  rurban
1056 // protect most_popular from sortby=mtime
1057 //
1058 // Revision 1.23  2004/04/16 14:19:39  rurban
1059 // updated ADODB notes
1060 //
1061
1062 // (c-file-style: "gnu")
1063 // Local Variables:
1064 // mode: php
1065 // tab-width: 8
1066 // c-basic-offset: 4
1067 // c-hanging-comment-ender-p: nil
1068 // indent-tabs-mode: nil
1069 // End:   
1070 ?>