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