]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/ADODB.php
enhance titleSearch
[SourceForge/phpwiki.git] / lib / WikiDB / backend / ADODB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: ADODB.php,v 1.75 2005-09-10 21:30:16 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 backends, 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  * 6) 2004-12-10 added extra page.cached_html
39  *
40  * phpwiki-1.3.11, by Philippe Vanhaesendonck
41  * - pass column list to iterators so we can FETCH_NUM in all cases
42  *
43  * ADODB basic differences to PearDB: It pre-fetches the first row into fields, 
44  * is dirtier in style, layout and more low-level ("worse is better").
45  * It has less needed basic features (modifyQuery, locks, ...), but some more 
46  * unneeded features included: paging, monitoring and sessions, and much more drivers.
47  * No locking (which PearDB supports in some backends), and sequences are very 
48  * bad compared to PearDB.
49
50  * Old Comments, by Lawrence Akka:
51  * 1)  ADODB's GetRow() is slightly different from that in PEAR.  It does not 
52  *     accept a fetchmode parameter
53  *     That doesn't matter too much here, since we only ever use FETCHMODE_ASSOC
54  * 2)  No need for ''s around strings in sprintf arguments - qstr puts them 
55  *     there automatically
56  * 3)  ADODB has a version of GetOne, but it is difficult to use it when 
57  *     FETCH_ASSOC is in effect.
58  *     Instead, use $rs = Execute($query); $value = $rs->fields["$colname"]
59  * 4)  No error handling yet - could use ADOConnection->raiseErrorFn
60  * 5)  It used to be faster then PEAR/DB at the beginning of 2002. 
61  *     Now at August 2002 PEAR/DB with our own page cache added, 
62  *     performance is comparable.
63  */
64
65 require_once('lib/WikiDB/backend.php');
66 // Error handling - calls trigger_error.  NB - does not close the connection.  Does it need to?
67 include_once('lib/WikiDB/adodb/adodb-errorhandler.inc.php');
68 // include the main adodb file
69 require_once('lib/WikiDB/adodb/adodb.inc.php');
70
71 class WikiDB_backend_ADODB
72 extends WikiDB_backend
73 {
74
75     function WikiDB_backend_ADODB ($dbparams) {
76         $parsed = parseDSN($dbparams['dsn']);
77         $this->_dbparams = $dbparams;
78         $this->_parsedDSN =& $parsed;
79         $this->_dbh = &ADONewConnection($parsed['phptype']);
80         if (DEBUG & _DEBUG_SQL) {
81             $this->_dbh->debug = true;
82             $GLOBALS['ADODB_OUTP'] = '_sql_debuglog';
83         }
84         $this->_dsn = $parsed;
85         // persistent is defined as DSN option, or with a config value.
86         //   phptype://username:password@hostspec/database?persistent=false
87         if (!empty($parsed['persistent']) or DATABASE_PERSISTENT)
88             $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'], 
89                                           $parsed['password'], $parsed['database']);
90         else
91             $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'], 
92                                          $parsed['password'], $parsed['database']);
93
94         // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
95         // with some ASSOC based recordsets.
96         $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
97         $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
98         $GLOBALS['ADODB_COUNTRECS'] = false;
99
100         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
101         $this->_table_names
102             = array('page_tbl'     => $prefix . 'page',
103                     'version_tbl'  => $prefix . 'version',
104                     'link_tbl'     => $prefix . 'link',
105                     'recent_tbl'   => $prefix . 'recent',
106                     'nonempty_tbl' => $prefix . 'nonempty');
107         $page_tbl = $this->_table_names['page_tbl'];
108         $version_tbl = $this->_table_names['version_tbl'];
109         $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
110             . "$page_tbl.hits hits";
111         $this->page_tbl_field_list = array('id', 'pagename', 'hits');
112         $this->version_tbl_fields = "$version_tbl.version AS version, "
113             . "$version_tbl.mtime AS mtime, "
114             . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
115             . "$version_tbl.versiondata AS versiondata";
116         $this->version_tbl_field_list = array('version', 'mtime', 'minor_edit', 'content',
117             'versiondata');
118
119         $this->_expressions
120             = array('maxmajor'     => "MAX(CASE WHEN minor_edit=0 THEN version END)",
121                     'maxminor'     => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
122                     'maxversion'   => "MAX(version)",
123                     'notempty'     => "<>''",
124                     'iscontent'    => "$version_tbl.content<>''");
125         $this->_lock_count = 0;
126     }
127
128     /**
129      * Close database connection.
130      */
131     function close () {
132         if (!$this->_dbh)
133             return;
134         if ($this->_lock_count) {
135             trigger_error("WARNING: database still locked " . 
136                           '(lock_count = $this->_lock_count)' . "\n<br />",
137                           E_USER_WARNING);
138         }
139 //      $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
140         $this->unlock(false,'force');
141
142         $this->_dbh->close();
143         $this->_dbh = false;
144     }
145
146     /*
147      * Fast test for wikipage.
148      */
149     function is_wiki_page($pagename) {
150         $dbh = &$this->_dbh;
151         extract($this->_table_names);
152         $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
153                                     . " FROM $nonempty_tbl, $page_tbl"
154                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
155                                     . "   AND pagename=%s",
156                                     $dbh->qstr($pagename)));
157         return $row ? $row[0] : false;
158     }
159         
160     function get_all_pagenames() {
161         $dbh = &$this->_dbh;
162         extract($this->_table_names);
163         $result = $dbh->Execute("SELECT pagename"
164                                 . " FROM $nonempty_tbl, $page_tbl"
165                                 . " WHERE $nonempty_tbl.id=$page_tbl.id");
166         return $result->GetArray();
167     }
168
169     function numPages($filter=false, $exclude='') {
170         $dbh = &$this->_dbh;
171         extract($this->_table_names);
172         $result = $dbh->getRow("SELECT count(*)"
173                             . " FROM $nonempty_tbl, $page_tbl"
174                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
175         return $result[0];
176     }
177
178     function increaseHitCount($pagename) {
179         $dbh = &$this->_dbh;
180         // Hits is the only thing we can update in a fast manner.
181         // Note that this will fail silently if the page does not
182         // have a record in the page table.  Since it's just the
183         // hit count, who cares?
184         $dbh->Execute(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename=%s LIMIT 1",
185                               $this->_table_names['page_tbl'],
186                               $dbh->qstr($pagename)));
187         return;
188     }
189
190     /**
191      * Read page information from database.
192      */
193     function get_pagedata($pagename) {
194         $dbh = &$this->_dbh;
195         $row = $dbh->GetRow(sprintf("SELECT id,pagename,hits,pagedata FROM %s WHERE pagename=%s",
196                                     $this->_table_names['page_tbl'],
197                                     $dbh->qstr($pagename)));
198         return $row ? $this->_extract_page_data($row[3], $row[2]) : false;
199     }
200
201     function  _extract_page_data($data, $hits) {
202         if (empty($data))
203             return array('hits' => $hits);
204         else 
205             return array_merge(array('hits' => $hits), $this->_unserialize($data));
206     }
207
208     function update_pagedata($pagename, $newdata) {
209         $dbh = &$this->_dbh;
210         $page_tbl = $this->_table_names['page_tbl'];
211
212         // Hits is the only thing we can update in a fast manner.
213         if (count($newdata) == 1 && isset($newdata['hits'])) {
214             // Note that this will fail silently if the page does not
215             // have a record in the page table.  Since it's just the
216             // hit count, who cares?
217             $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
218                                   $newdata['hits'], $dbh->qstr($pagename)));
219             return;
220         }
221         $where = sprintf("pagename=%s", $dbh->qstr($pagename));
222         $dbh->BeginTrans( );
223         $dbh->RowLock($page_tbl,$where);
224         
225         $data = $this->get_pagedata($pagename);
226         if (!$data) {
227             $data = array();
228             $this->_get_pageid($pagename, true); // Creates page record
229         }
230         
231         $hits = (empty($data['hits'])) ? 0 : (int)$data['hits'];
232         unset($data['hits']);
233
234         foreach ($newdata as $key => $val) {
235             if ($key == 'hits')
236                 $hits = (int)$val;
237             else if (empty($val))
238                 unset($data[$key]);
239             else
240                 $data[$key] = $val;
241         }
242         if ($dbh->Execute("UPDATE $page_tbl"
243                           . " SET hits=?, pagedata=?"
244                           . " WHERE pagename=?",
245                           array($hits, $this->_serialize($data),$pagename))) {
246             $dbh->CommitTrans( );
247             return true;
248         } else {
249             $dbh->RollbackTrans( );
250             return false;
251         }
252     }
253
254     function get_cached_html($pagename) {
255         $dbh = &$this->_dbh;
256         $page_tbl = $this->_table_names['page_tbl'];
257         $row = $dbh->GetRow(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename=%s",
258                                     $dbh->qstr($pagename)));
259         return $row ? $row[0] : false;
260     }
261
262     function set_cached_html($pagename, $data) {
263         $dbh = &$this->_dbh;
264         $page_tbl = $this->_table_names['page_tbl'];
265         if (empty($data)) $data = '';
266         $rs = $dbh->Execute("UPDATE $page_tbl"
267                             . " SET cached_html=?"
268                             . " WHERE pagename=?",
269                             array($data, $pagename));
270     }
271
272     function _get_pageid($pagename, $create_if_missing = false) {
273
274         // check id_cache
275         global $request;
276         $cache =& $request->_dbi->_cache->_id_cache;
277         if (isset($cache[$pagename])) {
278             if ($cache[$pagename] or !$create_if_missing) {
279                 return $cache[$pagename];
280             }
281         }
282         
283         $dbh = &$this->_dbh;
284         $page_tbl = $this->_table_names['page_tbl'];
285         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
286                          $dbh->qstr($pagename));
287         if (! $create_if_missing ) {
288             $row = $dbh->GetRow($query);
289             return $row ? $row[0] : false;
290         }
291         $row = $dbh->GetRow($query);
292         if (! $row ) {
293             //mysql, mysqli or mysqlt
294             if (substr($dbh->databaseType,0,5) == 'mysql') {
295                 // have auto-incrementing, atomic version
296                 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
297                                             . " (id,pagename)"
298                                             . " VALUES(NULL,%s)",
299                                             $dbh->qstr($pagename)));
300                 $id = $dbh->_insertid();
301             } else {
302                 //$id = $dbh->GenID($page_tbl . 'seq');
303                 // Better generic version than with adodob::genID
304                 //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1
305                 $this->lock(array('page'));
306                 $dbh->BeginTrans( );
307                 $dbh->CommitLock($page_tbl);
308                 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
309                 $id = $row[0] + 1;
310                 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
311                                             . " (id,pagename,hits)"
312                                             . " VALUES (%d,%s,0)",
313                                             $id, $dbh->qstr($pagename)));
314                 if ($rs) $dbh->CommitTrans( );
315                 else $dbh->RollbackTrans( );
316                 $this->unlock(array('page'));
317             }
318         } else {
319             $id = $row[0];
320         }
321         assert($id);
322         return $id;
323     }
324
325     function get_latest_version($pagename) {
326         $dbh = &$this->_dbh;
327         extract($this->_table_names);
328         $row = $dbh->GetRow(sprintf("SELECT latestversion"
329                                     . " FROM $page_tbl, $recent_tbl"
330                                     . " WHERE $page_tbl.id=$recent_tbl.id"
331                                     . "  AND pagename=%s",
332                                     $dbh->qstr($pagename)));
333         return $row ? (int)$row[0] : false;
334     }
335
336     function get_previous_version($pagename, $version) {
337         $dbh = &$this->_dbh;
338         extract($this->_table_names);
339         // Use SELECTLIMIT for maximum portability
340         $rs = $dbh->SelectLimit(sprintf("SELECT version"
341                                         . " FROM $version_tbl, $page_tbl"
342                                         . " WHERE $version_tbl.id=$page_tbl.id"
343                                         . "  AND pagename=%s"
344                                         . "  AND version < %d"
345                                         . " ORDER BY version DESC"
346                                         ,$dbh->qstr($pagename),
347                                         $version),
348                                 1);
349         return $rs->fields ? (int)$rs->fields[0] : false;
350     }
351     
352     /**
353      * Get version data.
354      *
355      * @param $version int Which version to get.
356      *
357      * @return hash The version data, or false if specified version does not
358      *              exist.
359      */
360     function get_versiondata($pagename, $version, $want_content = false) {
361         $dbh = &$this->_dbh;
362         extract($this->_table_names);
363         extract($this->_expressions);
364                 
365         assert(is_string($pagename) and $pagename != '');
366         assert($version > 0);
367         
368         // FIXME: optimization: sometimes don't get page data?
369         if ($want_content) {
370             $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
371                 . ', ' . $this->version_tbl_fields;
372         } else {
373             $fields = $this->page_tbl_fields . ", '' AS pagedata"
374                 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
375                 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
376                 . "$version_tbl.versiondata as versiondata";
377         }
378         $row = $dbh->GetRow(sprintf("SELECT $fields"
379                                     . " FROM $page_tbl, $version_tbl"
380                                     . " WHERE $page_tbl.id=$version_tbl.id"
381                                     . "  AND pagename=%s"
382                                     . "  AND version=%d",
383                                     $dbh->qstr($pagename), $version));
384         return $row ? $this->_extract_version_data_num($row, $want_content) : false;
385     }
386
387     function _extract_version_data_num($row, $want_content) {
388         if (!$row)
389             return false;
390
391         //$id       &= $row[0];
392         //$pagename &= $row[1];
393         $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
394         $data['mtime']         = $row[5];
395         $data['is_minor_edit'] = !empty($row[6]);
396         if ($want_content) {
397             $data['%content'] = $row[7];
398         } else {
399             $data['%content'] = !empty($row[7]);
400         }
401         if (!empty($row[3])) {
402             $data['%pagedata'] = $this->_extract_page_data($row[3], $row[2]);
403         }
404         return $data;
405     }
406
407     function _extract_version_data_assoc($row) {
408         if (!$row)
409             return false;
410
411         extract($row);
412         $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
413         $data['mtime'] = $mtime;
414         $data['is_minor_edit'] = !empty($minor_edit);
415         if (isset($content))
416             $data['%content'] = $content;
417         elseif ($have_content)
418             $data['%content'] = true;
419         else
420             $data['%content'] = '';
421         if (!empty($pagedata)) {
422             $data['%pagedata'] = $this->_extract_page_data($pagedata, $hits);
423         }
424         return $data;
425     }
426
427     /**
428      * Create a new revision of a page.
429      */
430     function set_versiondata($pagename, $version, $data) {
431         $dbh = &$this->_dbh;
432         $version_tbl = $this->_table_names['version_tbl'];
433         
434         $minor_edit = (int) !empty($data['is_minor_edit']);
435         unset($data['is_minor_edit']);
436         
437         $mtime = (int)$data['mtime'];
438         unset($data['mtime']);
439         assert(!empty($mtime));
440
441         @$content = (string) $data['%content'];
442         unset($data['%content']);
443         unset($data['%pagedata']);
444         
445         $this->lock(array('page','recent','version','nonempty'));
446         $dbh->BeginTrans( );
447         $dbh->CommitLock($version_tbl);
448         $id = $this->_get_pageid($pagename, true);
449         $backend_type = $this->backendType();
450         // optimize: mysql can do this with one REPLACE INTO.
451         if (substr($backend_type,0,5) == 'mysql') {
452             $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl"
453                                   . " (id,version,mtime,minor_edit,content,versiondata)"
454                                   . " VALUES(%d,%d,%d,%d,%s,%s)",
455                                   $id, $version, $mtime, $minor_edit,
456                                   $dbh->qstr($content),
457                                   $dbh->qstr($this->_serialize($data))));
458         } else {
459             $dbh->Execute(sprintf("DELETE FROM $version_tbl"
460                                   . " WHERE id=%d AND version=%d",
461                                   $id, $version));
462             $rs = $dbh->Execute("INSERT INTO $version_tbl"
463                                 . " (id,version,mtime,minor_edit,content,versiondata)"
464                                 . " VALUES(?,?,?,?,?,?)",
465                                   array($id, $version, $mtime, $minor_edit,
466                                   $content, $this->_serialize($data)));
467         }
468         $this->_update_recent_table($id);
469         $this->_update_nonempty_table($id);
470         if ($rs) $dbh->CommitTrans( );
471         else $dbh->RollbackTrans( );
472         $this->unlock(array('page','recent','version','nonempty'));
473     }
474     
475     /**
476      * Delete an old revision of a page.
477      */
478     function delete_versiondata($pagename, $version) {
479         $dbh = &$this->_dbh;
480         extract($this->_table_names);
481
482         $this->lock(array('version'));
483         if ( ($id = $this->_get_pageid($pagename)) ) {
484             $dbh->Execute("DELETE FROM $version_tbl"
485                         . " WHERE id=$id AND version=$version");
486             $this->_update_recent_table($id);
487             // This shouldn't be needed (as long as the latestversion
488             // never gets deleted.)  But, let's be safe.
489             $this->_update_nonempty_table($id);
490         }
491         $this->unlock(array('version'));
492     }
493
494     /**
495      * Delete page from the database with backup possibility.
496      * i.e save_page('') and DELETE nonempty id
497      * 
498      * deletePage increments latestversion in recent to a non-existent version, 
499      * and removes the nonempty row,
500      * so that get_latest_version returns id+1 and get_previous_version returns prev id 
501      * and page->exists returns false.
502      */
503     function delete_page($pagename) {
504         $dbh = &$this->_dbh;
505         extract($this->_table_names);
506
507         $dbh->BeginTrans();
508         $dbh->CommitLock($recent_tbl);
509         if (($id = $this->_get_pageid($pagename, false)) === false) {
510             $dbh->RollbackTrans( );
511             return false;
512         }
513         $mtime = time();
514         $user =& $GLOBALS['request']->_user;
515         $meta = array('author' => $user->getId(),
516                       'author_id' => $user->getAuthenticatedId(),
517                       'mtime' => $mtime);
518         $this->lock(array('version','recent','nonempty','page','link'));
519         $version = $this->get_latest_version($pagename);
520         if ($dbh->Execute("UPDATE $recent_tbl SET latestversion=latestversion+1,"
521                           . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id")
522             and $dbh->Execute("INSERT INTO $version_tbl"
523                                 . " (id,version,mtime,minor_edit,content,versiondata)"
524                                 . " VALUES(?,?,?,?,?,?)",
525                                   array($id, $version+1, $mtime, 0,
526                                         '', $this->_serialize($meta)))
527             and $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id")
528             and $this->set_links($pagename, false)
529             // need to keep perms and LOCKED, otherwise you can reset the perm 
530             // by action=remove and re-create it with default perms
531             // keep hits but delete meta-data 
532             //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id") 
533            )
534         {
535             $this->unlock(array('version','recent','nonempty','page','link'));  
536             $dbh->CommitTrans( );
537             return true;
538         } else {
539             $this->unlock(array('version','recent','nonempty','page','link'));  
540             $dbh->RollbackTrans( );
541             return false;
542         }
543     }
544
545     function purge_page($pagename) {
546         $dbh = &$this->_dbh;
547         extract($this->_table_names);
548         
549         $this->lock(array('version','recent','nonempty','page','link'));
550         if ( ($id = $this->_get_pageid($pagename, false)) ) {
551             $dbh->Execute("DELETE FROM $version_tbl  WHERE id=$id");
552             $dbh->Execute("DELETE FROM $recent_tbl   WHERE id=$id");
553             $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
554             $this->set_links($pagename, false);
555             $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
556             if ($row and $row[0]) {
557                 // We're still in the link table (dangling link) so we can't delete this
558                 // altogether.
559                 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
560                 $result = 0;
561             }
562             else {
563                 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
564                 $result = 1;
565             }
566         } else {
567             $result = -1; // already purged or not existing
568         }
569         $this->unlock(array('version','recent','nonempty','page','link'));
570         return $result;
571     }
572
573
574     // The only thing we might be interested in updating which we can
575     // do fast in the flags (minor_edit).   I think the default
576     // update_versiondata will work fine...
577     //function update_versiondata($pagename, $version, $data) {
578     //}
579
580     function set_links($pagename, $links) {
581         // Update link table.
582         // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
583
584         $dbh = &$this->_dbh;
585         extract($this->_table_names);
586
587         $this->lock(array('link'));
588         $pageid = $this->_get_pageid($pagename, true);
589
590         if ($links) {
591             $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
592             foreach ($links as $link) {
593                 if (isset($linkseen[$link]))
594                     continue;
595                 $linkseen[$link] = true;
596                 $linkid = $this->_get_pageid($link, true);
597                 assert($linkid);
598                 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
599                             . " VALUES ($pageid, $linkid)");
600             }
601         } elseif (DEBUG) {
602             // purge page table: delete all non-referenced pages
603             // for all previously linked pages...
604             foreach ($dbh->getRow("SELECT $link_tbl.linkto as id FROM $link_tbl".
605                                   " WHERE linkfrom=$pageid") as $id) {
606                 // ...check if the page is empty and has no version
607                 if ($dbh->getRow("SELECT $page_tbl.id FROM $page_tbl"
608                                  . " LEFT JOIN $nonempty_tbl USING (id) "
609                                  . " LEFT JOIN $version_tbl USING (id)"
610                                  . " WHERE ISNULL($nonempty_tbl.id) AND"
611                                  . " ISNULL($version_tbl.id) AND $page_tbl.id=$id")) {
612                     $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");   // this purges the link
613                     $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
614                 }
615             }
616             $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
617         }
618         $this->unlock(array('link'));
619         return true;
620     }
621     
622     /**
623      * Find pages which link to or are linked from a page.
624      *
625      * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
626      * (linkExistingWikiWord or linkUnknownWikiWord)
627      * This is called on every page header GleanDescription, so we can store all the existing links.
628      */
629     function get_links($pagename, $reversed=true, $include_empty=false,
630                        $sortby=false, $limit=false, $exclude='') {
631         $dbh = &$this->_dbh;
632         extract($this->_table_names);
633
634         if ($reversed)
635             list($have,$want) = array('linkee', 'linker');
636         else
637             list($have,$want) = array('linker', 'linkee');
638         $orderby = $this->sortby($sortby, 'db', array('pagename'));
639         if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
640         if ($exclude) // array of pagenames
641             $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
642         else 
643             $exclude='';
644         if ($limit) {
645             list($offset, $count) = $this->limit($limit);
646             // TODO: check pqsql LIMIT count OFFSET offset 
647             $limit = " LIMIT $offset, $count";
648         } else 
649             $limit = '';
650
651         $qpagename = $dbh->qstr($pagename);
652         // removed ref to FETCH_MODE in next line
653         $result = $dbh->Execute("SELECT $want.id AS id, $want.pagename AS pagename,"
654                                 . " $want.hits AS hits"
655                                 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
656                                 . (!$include_empty ? ", $nonempty_tbl" : '')
657                                 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
658                                 . " AND $have.pagename=$qpagename"
659                                 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
660                                 //. " GROUP BY $want.id"
661                                 . $exclude
662                                 . $orderby
663                                 . $limit);
664         return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
665     }
666
667     /**
668      * Find if a page links to another page
669      */
670     function exists_link($pagename, $link, $reversed=false) {
671         $dbh = &$this->_dbh;
672         extract($this->_table_names);
673
674         if ($reversed)
675             list($have, $want) = array('linkee', 'linker');
676         else
677             list($have, $want) = array('linker', 'linkee');
678         $qpagename = $dbh->qstr($pagename);
679         $qlink = $dbh->qstr($link);
680         $row = $dbh->GetRow("SELECT IF($want.pagename,1,0)"
681                                 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
682                                 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
683                                 . " AND $have.pagename=$qpagename"
684                                 . " AND $want.pagename=$qlink"
685                                 . "LIMIT 1");
686         return $row[0];
687     }
688
689     function get_all_pages($include_empty=false, $sortby=false, $limit=false, $exclude='') {
690         $dbh = &$this->_dbh;
691         extract($this->_table_names);
692         $orderby = $this->sortby($sortby, 'db');
693         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
694         if ($exclude) // array of pagenames
695             $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
696         else 
697             $exclude='';
698
699         //$dbh->SetFetchMode(ADODB_FETCH_ASSOC);
700         if (strstr($orderby, 'mtime ')) { // was ' mtime'
701             if ($include_empty) {
702                 $sql = "SELECT "
703                     . $this->page_tbl_fields
704                     ." FROM $page_tbl, $recent_tbl, $version_tbl"
705                     . " WHERE $page_tbl.id=$recent_tbl.id"
706                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
707                     . $exclude
708                     . $orderby;
709             }
710             else {
711                 $sql = "SELECT "
712                     . $this->page_tbl_fields
713                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
714                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
715                     . " AND $page_tbl.id=$recent_tbl.id"
716                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
717                     . $exclude
718                     . $orderby;
719             }
720         } else {
721             if ($include_empty) {
722                 $sql = "SELECT "
723                     . $this->page_tbl_fields
724                     . " FROM $page_tbl"
725                     . ($exclude ? " WHERE $exclude" : '')
726                     . $orderby;
727             } else {
728                 $sql = "SELECT "
729                     . $this->page_tbl_fields
730                     . " FROM $nonempty_tbl, $page_tbl"
731                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
732                     . $exclude
733                     . $orderby;
734             }
735         }
736         if ($limit) {
737             // extract from,count from limit
738             list($offset,$count) = $this->limit($limit);
739             $result = $dbh->SelectLimit($sql, $count, $offset);
740         } else {
741             $result = $dbh->Execute($sql);
742         }
743         //$dbh->SetFetchMode(ADODB_FETCH_NUM);
744         return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
745     }
746         
747     /**
748      * Title search.
749      */
750     function text_search($search, $fullsearch=false, $sortby=false, $limit=false, $exclude=false)) {
751         $dbh = &$this->_dbh;
752         extract($this->_table_names);
753         $orderby = $this->sortby($sortby, 'db');
754         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
755         
756         $table = "$nonempty_tbl, $page_tbl";
757         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
758         $fields = $this->page_tbl_fields;
759         $field_list = $this->page_tbl_field_list;
760         $searchobj = new WikiDB_backend_ADODB_search($search, $dbh);
761         
762         if ($fullsearch) {
763             $table .= ", $recent_tbl";
764             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
765
766             $table .= ", $version_tbl";
767             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
768
769             $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
770             $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
771             $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
772         } else {
773             $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
774         }
775         
776         $search_clause = $search->makeSqlClauseObj($callback);
777         $result = $dbh->Execute("SELECT $fields FROM $table"
778                                 . " WHERE $join_clause"
779                                 . " AND ($search_clause)"
780                                 . $orderby);
781         return new WikiDB_backend_ADODB_iter($this, $result, $field_list);
782     }
783     /*
784     function _sql_match_clause($word) {
785         //not sure if we need this.  ADODB may do it for us
786         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  
787
788         // (we need it for at least % and _ --- they're the wildcard characters
789         //  for the LIKE operator, and we need to quote them if we're searching
790         //  for literal '%'s or '_'s.  --- I'm not sure about \, but it seems to
791         //  work as is.
792         $word = $this->_dbh->qstr("%".strtolower($word)."%");
793         $page_tbl = $this->_table_names['page_tbl'];
794         return "LOWER($page_tbl.pagename) LIKE $word";
795     }
796     function _fullsearch_sql_match_clause($word) {
797         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  //not sure if we need this
798         // (see above)
799         $word = $this->_dbh->qstr("%".strtolower($word)."%");
800         $page_tbl = $this->_table_names['page_tbl'];
801         return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
802     }
803     */
804
805     /*
806      * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%', 
807      *       not sets. See above, but the above methods find too much. 
808      * This is only for already resolved wildcards:
809      * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
810      */
811     function _sql_set(&$pagenames) {
812         $s = '(';
813         foreach ($pagenames as $p) {
814             $s .= ($this->_dbh->qstr($p).",");
815         }
816         return substr($s,0,-1).")";
817     }
818
819     /**
820      * Find highest or lowest hit counts.
821      */
822     function most_popular($limit=20, $sortby='-hits') {
823         $dbh = &$this->_dbh;
824         extract($this->_table_names);
825         $order = "DESC";
826         if ($limit < 0){ 
827             $order = "ASC"; 
828             $limit = -$limit;
829             $where = "";
830         } else {
831             $where = " AND hits > 0";
832         }
833         if ($sortby != '-hits') {
834             if ($order = $this->sortby($sortby, 'db'))  $orderby = " ORDER BY " . $order;
835             else $orderby = "";
836         } else
837             $orderby = " ORDER BY hits $order";
838         $sql = "SELECT " 
839             . $this->page_tbl_fields
840             . " FROM $nonempty_tbl, $page_tbl"
841             . " WHERE $nonempty_tbl.id=$page_tbl.id"
842             . $where
843             . $orderby;
844         if ($limit) {
845             // extract from,count from limit
846             list($offset,$count) = $this->limit($limit);
847             $result = $dbh->SelectLimit($sql, $count, $offset);
848         } else {
849             $result = $dbh->Execute($sql);
850         }
851         return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
852     }
853
854     /**
855      * Find recent changes.
856      */
857     function most_recent($params) {
858         $limit = 0;
859         $since = 0;
860         $include_minor_revisions = false;
861         $exclude_major_revisions = false;
862         $include_all_revisions = false;
863         extract($params);
864
865         $dbh = &$this->_dbh;
866         extract($this->_table_names);
867
868         $pick = array();
869         if ($since)
870             $pick[] = "mtime >= $since";
871         
872         if ($include_all_revisions) {
873             // Include all revisions of each page.
874             $table = "$page_tbl, $version_tbl";
875             $join_clause = "$page_tbl.id=$version_tbl.id";
876
877             if ($exclude_major_revisions) {
878                 // Include only minor revisions
879                 $pick[] = "minor_edit <> 0";
880             }
881             elseif (!$include_minor_revisions) {
882                 // Include only major revisions
883                 $pick[] = "minor_edit = 0";
884             }
885         }
886         else {
887             $table = "$page_tbl, $recent_tbl";
888             $join_clause = "$page_tbl.id=$recent_tbl.id";
889             $table .= ", $version_tbl";
890             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
891                 
892             if ($exclude_major_revisions) {
893                 // Include only most recent minor revision
894                 $pick[] = 'version=latestminor';
895             }
896             elseif (!$include_minor_revisions) {
897                 // Include only most recent major revision
898                 $pick[] = 'version=latestmajor';
899             }
900             else {
901                 // Include only the latest revision (whether major or minor).
902                 $pick[] ='version=latestversion';
903             }
904         }
905         $order = "DESC";
906         if($limit < 0){
907             $order = "ASC";
908             $limit = -$limit;
909         }
910         $where_clause = $join_clause;
911         if ($pick)
912             $where_clause .= " AND " . join(" AND ", $pick);
913         $sql = "SELECT "
914             . $this->page_tbl_fields . ", " . $this->version_tbl_fields
915             . " FROM $table"
916             . " WHERE $where_clause"
917             . " ORDER BY mtime $order";
918         // FIXME: use SQL_BUFFER_RESULT for mysql?
919         if ($limit) {
920             // extract from,count from limit
921             list($offset,$count) = $this->limit($limit);
922             $result = $dbh->SelectLimit($sql, $count, $offset);
923         } else {
924             $result = $dbh->Execute($sql);
925         }
926         //$result->fields['version'] = $result->fields[6];
927         return new WikiDB_backend_ADODB_iter($this, $result, 
928             array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
929     }
930
931     /**
932      * Find referenced empty pages.
933      */
934     function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
935         $dbh = &$this->_dbh;
936         extract($this->_table_names);
937         if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
938             $orderby = 'ORDER BY ' . $orderby;
939             
940         if ($exclude_from) // array of pagenames
941             $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
942         if ($exclude) // array of pagenames
943             $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
944
945         /* 
946          all empty pages, independent of linkstatus:
947            select pagename as empty from page left join nonempty using(id) where isnull(nonempty.id);
948          only all empty pages, which have a linkto:
949            select page.pagename, linked.pagename as wantedfrom from link, page as linked 
950              left join page on(link.linkto=page.id) left join nonempty on(link.linkto=nonempty.id) 
951              where isnull(nonempty.id) and linked.id=link.linkfrom;  
952         */
953         $sql = "SELECT $page_tbl.pagename,linked.pagename as wantedfrom"
954             . " FROM $link_tbl,$page_tbl as linked "
955             . " LEFT JOIN $page_tbl ON($link_tbl.linkto=$page_tbl.id)"
956             . " LEFT JOIN $nonempty_tbl ON($link_tbl.linkto=$nonempty_tbl.id)" 
957             . " WHERE ISNULL($nonempty_tbl.id) AND linked.id=$link_tbl.linkfrom"
958             . $exclude_from
959             . $exclude
960             . $orderby;
961         if ($limit) {
962             // extract from,count from limit
963             list($offset,$count) = $this->limit($limit);
964             $result = $dbh->SelectLimit($sql, $count, $offset);
965         } else {
966             $result = $dbh->Execute($sql);
967         }
968         return new WikiDB_backend_ADODB_iter($this, $result, array('pagename','wantedfrom'));
969     }
970
971     /**
972      * Rename page in the database.
973      */
974     function rename_page($pagename, $to) {
975         $dbh = &$this->_dbh;
976         extract($this->_table_names);
977         
978         $this->lock(array('page','version','recent','nonempty','link'));
979         if ( ($id = $this->_get_pageid($pagename, false)) ) {
980             if ($new = $this->_get_pageid($to, false)) {
981                 // Cludge Alert!
982                 // This page does not exist (already verified before), but exists in the page table.
983                 // So we delete this page.
984                 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
985                 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
986                 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
987                 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
988                 // We have to fix all referring tables to the old id
989                 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
990                 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
991             }
992             $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
993                                 $dbh->qstr($to)));
994         }
995         $this->unlock(array('page'));
996         return $id;
997     }
998
999     function _update_recent_table($pageid = false) {
1000         $dbh = &$this->_dbh;
1001         extract($this->_table_names);
1002         extract($this->_expressions);
1003
1004         $pageid = (int)$pageid;
1005
1006         // optimize: mysql can do this with one REPLACE INTO.
1007         $backend_type = $this->backendType();
1008         if (substr($backend_type,0,5) == 'mysql') {
1009             $dbh->Execute("REPLACE INTO $recent_tbl"
1010                           . " (id, latestversion, latestmajor, latestminor)"
1011                           . " SELECT id, $maxversion, $maxmajor, $maxminor"
1012                           . " FROM $version_tbl"
1013                           . ( $pageid ? " WHERE id=$pageid" : "")
1014                           . " GROUP BY id" );
1015         } else {
1016             $this->lock(array('recent'));
1017             $dbh->Execute("DELETE FROM $recent_tbl"
1018                       . ( $pageid ? " WHERE id=$pageid" : ""));
1019             $dbh->Execute( "INSERT INTO $recent_tbl"
1020                            . " (id, latestversion, latestmajor, latestminor)"
1021                            . " SELECT id, $maxversion, $maxmajor, $maxminor"
1022                            . " FROM $version_tbl"
1023                            . ( $pageid ? " WHERE id=$pageid" : "")
1024                            . " GROUP BY id" );
1025             $this->unlock(array('recent'));
1026         }
1027     }
1028
1029     function _update_nonempty_table($pageid = false) {
1030         $dbh = &$this->_dbh;
1031         extract($this->_table_names);
1032         extract($this->_expressions);
1033
1034         $pageid = (int)$pageid;
1035
1036         extract($this->_expressions);
1037         $this->lock(array('nonempty'));
1038         $dbh->Execute("DELETE FROM $nonempty_tbl"
1039                       . ( $pageid ? " WHERE id=$pageid" : ""));
1040         $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
1041                       . " SELECT $recent_tbl.id"
1042                       . " FROM $recent_tbl, $version_tbl"
1043                       . " WHERE $recent_tbl.id=$version_tbl.id"
1044                       . "       AND version=latestversion"
1045                       // We have some specifics here (Oracle)
1046                       //. "  AND content<>''"
1047                       . "  AND content $notempty"
1048                       . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
1049         $this->unlock(array('nonempty'));
1050     }
1051
1052     /**
1053      * Grab a write lock on the tables in the SQL database.
1054      *
1055      * Calls can be nested.  The tables won't be unlocked until
1056      * _unlock_database() is called as many times as _lock_database().
1057      *
1058      * @access protected
1059      */
1060     function lock($tables, $write_lock = true) {
1061             $this->_dbh->StartTrans();
1062         if ($this->_lock_count++ == 0) {
1063             $this->_current_lock = $tables;
1064             $this->_lock_tables($tables, $write_lock);
1065         }
1066     }
1067
1068     /**
1069      * Overridden by non-transaction safe backends.
1070      */
1071     function _lock_tables($tables, $write_lock) {
1072         return $this->_current_lock;
1073     }
1074     
1075     /**
1076      * Release a write lock on the tables in the SQL database.
1077      *
1078      * @access protected
1079      *
1080      * @param $force boolean Unlock even if not every call to lock() has been matched
1081      * by a call to unlock().
1082      *
1083      * @see _lock_database
1084      */
1085     function unlock($tables = false, $force = false) {
1086         if ($this->_lock_count == 0) {
1087             $this->_dbh->CompleteTrans(! $force);
1088             $this->_current_lock = false;
1089             return;
1090         }
1091         if (--$this->_lock_count <= 0 || $force) {
1092             $this->_unlock_tables($tables);
1093             $this->_current_lock = false;
1094             $this->_lock_count = 0;
1095         }
1096             $this->_dbh->CompleteTrans(! $force);
1097     }
1098
1099     /**
1100      * overridden by non-transaction safe backends
1101      */
1102     function _unlock_tables($tables, $write_lock) {
1103         return;
1104     }
1105
1106     /**
1107      * Serialize data
1108      */
1109     function _serialize($data) {
1110         if (empty($data))
1111             return '';
1112         assert(is_array($data));
1113         return serialize($data);
1114     }
1115
1116     /**
1117      * Unserialize data
1118      */
1119     function _unserialize($data) {
1120         return empty($data) ? array() : unserialize($data);
1121     }
1122
1123     /* some variables and functions for DB backend abstraction (action=upgrade) */
1124     function database () {
1125         return $this->_dbh->database;
1126     }
1127     function backendType() {
1128         return $this->_dbh->databaseType;
1129     }
1130     function connection() {
1131         return $this->_dbh->_connectionID;
1132     }
1133     function getRow($query) {
1134         return $this->_dbh->getRow($query);
1135     }
1136
1137     function listOfTables() {
1138         return $this->_dbh->MetaTables();
1139     }
1140     
1141     // other database needs another connection and other privileges.
1142     function listOfFields($database, $table) {
1143         $field_list = array();
1144         $old_db = $this->database();
1145         if ($database != $old_db) {
1146             $conn = $this->_dbh->Connect($this->_parsedDSN['hostspec'], 
1147                                          DBADMIN_USER ? DBADMIN_USER : $this->_parsedDSN['username'], 
1148                                          DBADMIN_PASSWD ? DBADMIN_PASSWD : $this->_parsedDSN['password'], 
1149                                          $database);
1150         }
1151         foreach ($this->_dbh->MetaColumns($table, false) as $field) {
1152             $field_list[] = $field->name;
1153         }
1154         if ($database != $old_db) {
1155             $this->_dbh->close();
1156             $conn = $this->_dbh->Connect($this->_parsedDSN['hostspec'], 
1157                                          $this->_parsedDSN['username'], 
1158                                          $this->_parsedDSN['password'], 
1159                                          $old_db);
1160         }
1161         return $field_list;
1162     }
1163
1164 };
1165
1166 class WikiDB_backend_ADODB_generic_iter
1167 extends WikiDB_backend_iterator
1168 {
1169     function WikiDB_backend_ADODB_generic_iter($backend, $query_result, $field_list = NULL) {
1170         $this->_backend = &$backend;
1171         $this->_result = $query_result;
1172
1173         if (is_null($field_list)) {
1174             // No field list passed, retrieve from DB
1175             // WikiLens is using the iterator behind the scene
1176             $field_list = array();
1177             $fields = $query_result->FieldCount();
1178             for ($i = 0; $i < $fields ; $i++) {
1179                 $field_info = $query_result->FetchField($i);
1180                 array_push($field_list, $field_info->name);
1181             }
1182         }
1183
1184         $this->_fields = $field_list;
1185     }
1186     
1187     function count() {
1188         if (!$this->_result) {
1189             return false;
1190         }
1191         $count = $this->_result->numRows();
1192         //$this->_result->Close();
1193         return $count;
1194     }
1195
1196     function next() {
1197         $result = &$this->_result;
1198         $backend = &$this->_backend;
1199         if (!$result || $result->EOF) {
1200             $this->free();
1201             return false;
1202         }
1203
1204         // Convert array to hash
1205         $i = 0;
1206         $rec_num = $result->fields;
1207         foreach ($this->_fields as $field) {
1208             $rec_assoc[$field] = $rec_num[$i++];
1209         }
1210         // check if the cache can be populated here?
1211
1212         $result->MoveNext();
1213         return $rec_assoc;
1214     }
1215
1216     function free () {
1217         if ($this->_result) {
1218             /* call mysql_free_result($this->_queryID) */
1219             $this->_result->Close();
1220             $this->_result = false;
1221         }
1222     }
1223 }
1224
1225 class WikiDB_backend_ADODB_iter
1226 extends WikiDB_backend_ADODB_generic_iter
1227 {
1228     function next() {
1229         $result = &$this->_result;
1230         $backend = &$this->_backend;
1231         if (!$result || $result->EOF) {
1232             $this->free();
1233             return false;
1234         }
1235
1236         // Convert array to hash
1237         $i = 0;
1238         $rec_num = $result->fields;
1239         foreach ($this->_fields as $field) {
1240             $rec_assoc[$field] = $rec_num[$i++];
1241         }
1242
1243         $result->MoveNext();
1244         if (isset($rec_assoc['pagedata']))
1245             $rec_assoc['pagedata'] = $backend->_extract_page_data($rec_assoc['pagedata'], $rec_assoc['hits']);
1246         if (!empty($rec_assoc['version'])) {
1247             $rec_assoc['versiondata'] = $backend->_extract_version_data_assoc($rec_assoc);
1248         }
1249         return $rec_assoc;
1250     }
1251 }
1252
1253 class WikiDB_backend_ADODB_search
1254 extends WikiDB_backend_search
1255 {
1256     function WikiDB_backend_ADODB_search(&$search, &$dbh) {
1257         $this->_dbh =& $dbh;
1258         $this->_case_exact = $search->_case_exact;
1259     }
1260     function _pagename_match_clause($node) {
1261         $word = $node->sql();
1262         return ($this->_case_exact 
1263                 ? "pagename LIKE '$word'"
1264                 : "LOWER(pagename) LIKE '$word'");
1265     }
1266     function _fulltext_match_clause($node) { 
1267         $word = $node->sql();
1268         return ($this->_case_exact
1269                 ? "pagename LIKE '$word' OR content LIKE '$word'"
1270                 : "LOWER(pagename) LIKE '$word' OR content LIKE '$word'");
1271     }
1272 }
1273
1274 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1275 // Eventually, change index.php to provide the relevant information
1276 // directly?
1277     /**
1278      * Parse a data source name.
1279      *
1280      * Additional keys can be added by appending a URI query string to the
1281      * end of the DSN.
1282      *
1283      * The format of the supplied DSN is in its fullest form:
1284      * <code>
1285      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1286      * </code>
1287      *
1288      * Most variations are allowed:
1289      * <code>
1290      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1291      *  phptype://username:password@hostspec/database_name
1292      *  phptype://username:password@hostspec
1293      *  phptype://username@hostspec
1294      *  phptype://hostspec/database
1295      *  phptype://hostspec
1296      *  phptype(dbsyntax)
1297      *  phptype
1298      * </code>
1299      *
1300      * @param string $dsn Data Source Name to be parsed
1301      *
1302      * @return array an associative array with the following keys:
1303      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
1304      *  + dbsyntax: Database used with regards to SQL syntax etc.
1305      *  + protocol: Communication protocol to use (tcp, unix etc.)
1306      *  + hostspec: Host specification (hostname[:port])
1307      *  + database: Database to use on the DBMS server
1308      *  + username: User name for login
1309      *  + password: Password for login
1310      *
1311      * @author Tomas V.V.Cox <cox@idecnet.com>
1312      */
1313     function parseDSN($dsn)
1314     {
1315         $parsed = array(
1316             'phptype'  => false,
1317             'dbsyntax' => false,
1318             'username' => false,
1319             'password' => false,
1320             'protocol' => false,
1321             'hostspec' => false,
1322             'port'     => false,
1323             'socket'   => false,
1324             'database' => false,
1325         );
1326
1327         if (is_array($dsn)) {
1328             $dsn = array_merge($parsed, $dsn);
1329             if (!$dsn['dbsyntax']) {
1330                 $dsn['dbsyntax'] = $dsn['phptype'];
1331             }
1332             return $dsn;
1333         }
1334
1335         // Find phptype and dbsyntax
1336         if (($pos = strpos($dsn, '://')) !== false) {
1337             $str = substr($dsn, 0, $pos);
1338             $dsn = substr($dsn, $pos + 3);
1339         } else {
1340             $str = $dsn;
1341             $dsn = null;
1342         }
1343
1344         // Get phptype and dbsyntax
1345         // $str => phptype(dbsyntax)
1346         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1347             $parsed['phptype']  = $arr[1];
1348             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1349         } else {
1350             $parsed['phptype']  = $str;
1351             $parsed['dbsyntax'] = $str;
1352         }
1353
1354         if (!count($dsn)) {
1355             return $parsed;
1356         }
1357
1358         // Get (if found): username and password
1359         // $dsn => username:password@protocol+hostspec/database
1360         if (($at = strrpos($dsn,'@')) !== false) {
1361             $str = substr($dsn, 0, $at);
1362             $dsn = substr($dsn, $at + 1);
1363             if (($pos = strpos($str, ':')) !== false) {
1364                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1365                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1366             } else {
1367                 $parsed['username'] = rawurldecode($str);
1368             }
1369         }
1370
1371         // Find protocol and hostspec
1372
1373         // $dsn => proto(proto_opts)/database
1374         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1375             $proto       = $match[1];
1376             $proto_opts  = $match[2] ? $match[2] : false;
1377             $dsn         = $match[3];
1378
1379         // $dsn => protocol+hostspec/database (old format)
1380         } else {
1381             if (strpos($dsn, '+') !== false) {
1382                 list($proto, $dsn) = explode('+', $dsn, 2);
1383             }
1384             if (strpos($dsn, '/') !== false) {
1385                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1386             } else {
1387                 $proto_opts = $dsn;
1388                 $dsn = null;
1389             }
1390         }
1391
1392         // process the different protocol options
1393         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1394         $proto_opts = rawurldecode($proto_opts);
1395         if ($parsed['protocol'] == 'tcp') {
1396             if (strpos($proto_opts, ':') !== false) {
1397                 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1398             } else {
1399                 $parsed['hostspec'] = $proto_opts;
1400             }
1401         } elseif ($parsed['protocol'] == 'unix') {
1402             $parsed['socket'] = $proto_opts;
1403         }
1404
1405         // Get dabase if any
1406         // $dsn => database
1407         if ($dsn) {
1408             // /database
1409             if (($pos = strpos($dsn, '?')) === false) {
1410                 $parsed['database'] = $dsn;
1411             // /database?param1=value1&param2=value2
1412             } else {
1413                 $parsed['database'] = substr($dsn, 0, $pos);
1414                 $dsn = substr($dsn, $pos + 1);
1415                 if (strpos($dsn, '&') !== false) {
1416                     $opts = explode('&', $dsn);
1417                 } else { // database?param1=value1
1418                     $opts = array($dsn);
1419                 }
1420                 foreach ($opts as $opt) {
1421                     list($key, $value) = explode('=', $opt);
1422                     if (!isset($parsed[$key])) {
1423                         // don't allow params overwrite
1424                         $parsed[$key] = rawurldecode($value);
1425                     }
1426                 }
1427             }
1428         }
1429
1430         return $parsed;
1431     }
1432
1433 // $Log: not supported by cvs2svn $
1434 // Revision 1.74  2005/02/10 19:04:22  rurban
1435 // move getRow up one level to our backend class
1436 //
1437 // Revision 1.73  2005/02/04 13:43:30  rurban
1438 // fix purge cache error
1439 //
1440 // Revision 1.72  2005/01/29 19:51:03  rurban
1441 // Bugs item #1077769 fixed by frugal.
1442 // Deleted the wrong page. Fix all other tables also.
1443 //
1444 // Revision 1.71  2005/01/25 08:01:00  rurban
1445 // fix listOfFields with different database
1446 //
1447 // Revision 1.70  2005/01/18 20:55:43  rurban
1448 // reformatting and two bug fixes: adding missing parens
1449 //
1450 // Revision 1.69  2004/12/26 17:14:03  rurban
1451 // fix ADODB MostPopular, avoid limit -1, pass hits on empty data
1452 //
1453 // Revision 1.68  2004/12/22 18:33:25  rurban
1454 // fix page _id_cache logic for _get_pageid create_if_missing
1455 //
1456 // Revision 1.67  2004/12/22 15:47:41  rurban
1457 // fix wrong _update_nonempty_table on empty content (i.e. the new deletePage)
1458 //
1459 // Revision 1.66  2004/12/13 14:39:16  rurban
1460 // avoid warning
1461 //
1462 // Revision 1.65  2004/12/10 22:15:00  rurban
1463 // fix $page->get('_cached_html)
1464 // refactor upgrade db helper _convert_cached_html() to be able to call them from WikiAdminUtils also.
1465 // support 2nd genericSqlQuery param (bind huge arg)
1466 //
1467 // Revision 1.64  2004/12/10 02:45:27  rurban
1468 // SQL optimization:
1469 //   put _cached_html from pagedata into a new seperate blob, not huge serialized string.
1470 //   it is only rarelely needed: for current page only, if-not-modified
1471 //   but was extracted for every simple page iteration.
1472 //
1473 // Revision 1.63  2004/12/08 12:55:51  rurban
1474 // support new non-destructive delete_page via generic backend method
1475 //
1476 // Revision 1.62  2004/12/06 19:50:04  rurban
1477 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
1478 // renamed delete_page to purge_page.
1479 // enable action=edit&version=-1 to force creation of a new version.
1480 // added BABYCART_PATH config
1481 // fixed magiqc in adodb.inc.php
1482 // and some more docs
1483 //
1484 // Revision 1.61  2004/11/30 17:45:53  rurban
1485 // exists_links backend implementation
1486 //
1487 // Revision 1.60  2004/11/28 20:42:18  rurban
1488 // Optimize PearDB _extract_version_data and _extract_page_data.
1489 //
1490 // Revision 1.59  2004/11/27 14:39:05  rurban
1491 // simpified regex search architecture:
1492 //   no db specific node methods anymore,
1493 //   new sql() method for each node
1494 //   parallel to regexp() (which returns pcre)
1495 //   regex types bitmasked (op's not yet)
1496 // new regex=sql
1497 // clarified WikiDB::quote() backend methods:
1498 //   ->quote() adds surrounsing quotes
1499 //   ->qstr() (new method) assumes strings and adds no quotes! (in contrast to ADODB)
1500 //   pear and adodb have now unified quote methods for all generic queries.
1501 //
1502 // Revision 1.58  2004/11/26 18:39:02  rurban
1503 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1504 //
1505 // Revision 1.57  2004/11/25 17:20:51  rurban
1506 // and again a couple of more native db args: backlinks
1507 //
1508 // Revision 1.56  2004/11/23 13:35:48  rurban
1509 // add case_exact search
1510 //
1511 // Revision 1.55  2004/11/21 11:59:26  rurban
1512 // remove final \n to be ob_cache independent
1513 //
1514 // Revision 1.54  2004/11/20 17:49:39  rurban
1515 // add fast exclude support to SQL get_all_pages
1516 //
1517 // Revision 1.53  2004/11/20 17:35:58  rurban
1518 // improved WantedPages SQL backends
1519 // PageList::sortby new 3rd arg valid_fields (override db fields)
1520 // WantedPages sql pager inexact for performance reasons:
1521 //   assume 3 wantedfrom per page, to be correct, no getTotal()
1522 // support exclude argument for get_all_pages, new _sql_set()
1523 //
1524 // Revision 1.52  2004/11/17 20:07:17  rurban
1525 // just whitespace
1526 //
1527 // Revision 1.51  2004/11/15 15:57:37  rurban
1528 // silent cache warning
1529 //
1530 // Revision 1.50  2004/11/10 19:32:23  rurban
1531 // * optimize increaseHitCount, esp. for mysql.
1532 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
1533 // * Pear_DB version logic (awful but needed)
1534 // * fix broken ADODB quote
1535 // * _extract_page_data simplification
1536 //
1537 // Revision 1.49  2004/11/10 15:29:21  rurban
1538 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1539 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1540 // * WikiDB: moved SQL specific methods upwards
1541 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1542 //   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1543 //
1544 // Revision 1.48  2004/11/09 17:11:16  rurban
1545 // * revert to the wikidb ref passing. there's no memory abuse there.
1546 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1547 //   store page ids with getPageLinks (GleanDescription) of all existing pages, which
1548 //   are also needed at the rendering for linkExistingWikiWord().
1549 //   pass options to pageiterator.
1550 //   use this cache also for _get_pageid()
1551 //   This saves about 8 SELECT count per page (num all pagelinks).
1552 // * fix passing of all page fields to the pageiterator.
1553 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1554 //
1555 // Revision 1.47  2004/11/06 17:11:42  rurban
1556 // The optimized version doesn't query for pagedata anymore.
1557 //
1558 // Revision 1.46  2004/11/01 10:43:58  rurban
1559 // seperate PassUser methods into seperate dir (memory usage)
1560 // fix WikiUser (old) overlarge data session
1561 // remove wikidb arg from various page class methods, use global ->_dbi instead
1562 // ...
1563 //
1564 // Revision 1.45  2004/10/14 17:19:17  rurban
1565 // allow most_popular sortby arguments
1566 //
1567 // Revision 1.44  2004/09/06 08:33:09  rurban
1568 // force explicit mysql auto-incrementing, atomic version
1569 //
1570 // Revision 1.43  2004/07/10 08:50:24  rurban
1571 // applied patch by Philippe Vanhaesendonck:
1572 //   pass column list to iterators so we can FETCH_NUM in all cases.
1573 //   bind UPDATE pramas for huge pagedata.
1574 //   portable oracle backend
1575 //
1576 // Revision 1.42  2004/07/09 10:06:50  rurban
1577 // Use backend specific sortby and sortable_columns method, to be able to
1578 // select between native (Db backend) and custom (PageList) sorting.
1579 // Fixed PageList::AddPageList (missed the first)
1580 // Added the author/creator.. name to AllPagesBy...
1581 //   display no pages if none matched.
1582 // Improved dba and file sortby().
1583 // Use &$request reference
1584 //
1585 // Revision 1.41  2004/07/08 21:32:35  rurban
1586 // Prevent from more warnings, minor db and sort optimizations
1587 //
1588 // Revision 1.40  2004/07/08 16:56:16  rurban
1589 // use the backendType abstraction
1590 //
1591 // Revision 1.39  2004/07/05 13:56:22  rurban
1592 // sqlite autoincrement fix
1593 //
1594 // Revision 1.38  2004/07/05 12:57:54  rurban
1595 // add mysql timeout
1596 //
1597 // Revision 1.37  2004/07/04 10:24:43  rurban
1598 // forgot the expressions
1599 //
1600 // Revision 1.36  2004/07/03 16:51:06  rurban
1601 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1602 // added atomic mysql REPLACE for PearDB as in ADODB
1603 // fixed _lock_tables typo links => link
1604 // fixes unserialize ADODB bug in line 180
1605 //
1606 // Revision 1.35  2004/06/28 14:45:12  rurban
1607 // fix adodb_sqlite to have the same dsn syntax as pear, use pconnect if requested
1608 //
1609 // Revision 1.34  2004/06/28 14:17:38  rurban
1610 // updated DSN parser from Pear. esp. for sqlite
1611 //
1612 // Revision 1.33  2004/06/27 10:26:02  rurban
1613 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1614 //
1615 // Revision 1.32  2004/06/25 14:15:08  rurban
1616 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1617 //
1618 // Revision 1.31  2004/06/16 10:38:59  rurban
1619 // Disallow refernces in calls if the declaration is a reference
1620 // ("allow_call_time_pass_reference clean").
1621 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
1622 //   but several external libraries may not.
1623 //   In detail these libs look to be affected (not tested):
1624 //   * Pear_DB odbc
1625 //   * adodb oracle
1626 //
1627 // Revision 1.30  2004/06/07 19:31:31  rurban
1628 // fixed ADOOB upgrade: listOfFields()
1629 //
1630 // Revision 1.29  2004/05/12 10:49:55  rurban
1631 // require_once fix for those libs which are loaded before FileFinder and
1632 //   its automatic include_path fix, and where require_once doesn't grok
1633 //   dirname(__FILE__) != './lib'
1634 // upgrade fix with PearDB
1635 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1636 //
1637 // Revision 1.28  2004/05/06 19:26:16  rurban
1638 // improve stability, trying to find the InlineParser endless loop on sf.net
1639 //
1640 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1641 //
1642 // Revision 1.27  2004/05/06 17:30:38  rurban
1643 // CategoryGroup: oops, dos2unix eol
1644 // improved phpwiki_version:
1645 //   pre -= .0001 (1.3.10pre: 1030.099)
1646 //   -p1 += .001 (1.3.9-p1: 1030.091)
1647 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1648 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1649 //   backend->backendType(), backend->database(),
1650 //   backend->listOfFields(),
1651 //   backend->listOfTables(),
1652 //
1653 // Revision 1.26  2004/04/26 20:44:35  rurban
1654 // locking table specific for better databases
1655 //
1656 // Revision 1.25  2004/04/20 00:06:04  rurban
1657 // themable paging support
1658 //
1659 // Revision 1.24  2004/04/18 01:34:20  rurban
1660 // protect most_popular from sortby=mtime
1661 //
1662 // Revision 1.23  2004/04/16 14:19:39  rurban
1663 // updated ADODB notes
1664 //
1665
1666 // (c-file-style: "gnu")
1667 // Local Variables:
1668 // mode: php
1669 // tab-width: 8
1670 // c-basic-offset: 4
1671 // c-hanging-comment-ender-p: nil
1672 // indent-tabs-mode: nil
1673 // End:   
1674 ?>