]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/ADODB.php
include [all] Include and file path should be devided with single space. File path...
[SourceForge/phpwiki.git] / lib / WikiDB / backend / ADODB.php
1 <?php // -*-php-*-
2
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     // The only thing we might be interested in updating which we can
570     // do fast in the flags (minor_edit).   I think the default
571     // update_versiondata will work fine...
572     //function update_versiondata($pagename, $version, $data) {
573     //}
574
575     /*
576      * Update link table.
577      * on DEBUG: delete old, deleted links from page
578      */
579     function set_links($pagename, $links) {
580         // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
581
582         $dbh = &$this->_dbh;
583         extract($this->_table_names);
584
585         $this->lock(array('link'));
586         $pageid = $this->_get_pageid($pagename, true);
587
588         $oldlinks = $dbh->getAssoc("SELECT $link_tbl.linkto as id, page.pagename FROM $link_tbl"
589                                   ." JOIN page ON ($link_tbl.linkto = page.id)"
590                                   ." WHERE linkfrom=$pageid");
591         // Delete current links,
592         $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
593         // and insert new links. Faster than checking for all single links
594         if ($links) {
595             foreach ($links as $link) {
596                 $linkto = $link['linkto'];
597                 if (isset($link['relation']))
598                     $relation = $this->_get_pageid($link['relation'], true);
599                 else
600                     $relation = 0;
601                 if ($linkto === "") { // ignore attributes
602                     continue;
603                 }
604                 // avoid duplicates
605                 if (isset($linkseen[$linkto]) and !$relation) {
606                     continue;
607                 }
608                 if (!$relation) {
609                     $linkseen[$linkto] = true;
610                 }
611                 $linkid = $this->_get_pageid($linkto, true);
612                 assert($linkid);
613                 if ($relation) {
614                     $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
615                                   . " VALUES ($pageid, $linkid, $relation)");
616                 } else {
617                     $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
618                                   . " VALUES ($pageid, $linkid)");
619                 }
620                 if ($oldlinks and array_key_exists($linkid, $oldlinks)) {
621                     // This was also in the previous page
622                     unset($oldlinks[$linkid]);
623                 }
624             }
625         }
626         // purge page table: delete all non-referenced pages
627         // for all previously linked pages, which have no other linkto links
628         if (DEBUG and $oldlinks) {
629             // trigger_error("purge page table: delete all non-referenced pages...", E_USER_NOTICE);
630             foreach ($oldlinks as $id => $name) {
631                 // ...check if the page is empty and has no version
632                 $result = $dbh->getRow("SELECT $page_tbl.id FROM $page_tbl"
633                                      . " LEFT JOIN $nonempty_tbl USING (id) "
634                                      . " LEFT JOIN $version_tbl USING (id)"
635                                      . " WHERE $nonempty_tbl.id is NULL"
636                                      . " AND $version_tbl.id is NULL"
637                                      . " AND $page_tbl.id=$id");
638                 $linkto = $dbh->getRow("SELECT linkfrom FROM $link_tbl WHERE linkto=$id");
639                 if ($result and empty($linkto))
640                 {
641                     trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE);
642                     $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
643                 $dbh->Execute("DELETE FROM $link_tbl WHERE linkto=$id");
644                     $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");   // this purges the link
645                 }
646             }
647         }
648         $this->unlock(array('link'));
649         return true;
650     }
651
652     /* get all oldlinks in hash => id, relation
653        check for all new links
654      */
655     function set_links1($pagename, $links) {
656
657         $dbh = &$this->_dbh;
658         extract($this->_table_names);
659
660         $this->lock(array('link'));
661         $pageid = $this->_get_pageid($pagename, true);
662
663         $oldlinks = $dbh->getAssoc("SELECT $link_tbl.linkto as linkto, $link_tbl.relation, page.pagename"
664                                   ." FROM $link_tbl"
665                                   ." JOIN page ON ($link_tbl.linkto = page.id)"
666                                   ." WHERE linkfrom=$pageid");
667         /*      old                  new
668          *      X => [1,0 2,0 1,1]   X => [1,1 3,0]
669          * => delete 1,0 2,0 + insert 3,0
670          */
671         if ($links) {
672             foreach ($links as $link) {
673                 $linkto = $link['linkto'];
674                 if ($link['relation'])
675                     $relation = $this->_get_pageid($link['relation'], true);
676                 else
677                     $relation = 0;
678                 // avoid duplicates
679                 if (isset($linkseen[$linkto]) and !$relation) {
680                     continue;
681                 }
682                 if (!$relation) {
683                     $linkseen[$linkto] = true;
684                 }
685                 $linkid = $this->_get_pageid($linkto, true);
686                 assert($linkid);
687                 $skip = 0;
688                 // find linkfrom,linkto,relation triple in oldlinks
689                 foreach ($oldlinks as $l) {
690                     if ($relation) { // relation NOT NULL
691                         if ($l['linkto'] == $linkid and $l['relation'] == $relation) {
692                             // found and skip
693                             $skip = 1;
694                         }
695                     }
696                 }
697                 if (! $skip ) {
698                     if ($update) {
699                     }
700                     if ($relation) {
701                         $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
702                                       . " VALUES ($pageid, $linkid, $relation)");
703                     } else {
704                         $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
705                                       . " VALUES ($pageid, $linkid)");
706                     }
707                 }
708
709                 if (array_key_exists($linkid, $oldlinks)) {
710                     // This was also in the previous page
711                     unset($oldlinks[$linkid]);
712                 }
713             }
714         }
715         // purge page table: delete all non-referenced pages
716         // for all previously linked pages...
717         if (DEBUG and $oldlinks) {
718             // trigger_error("purge page table: delete all non-referenced pages...", E_USER_NOTICE);
719             foreach ($oldlinks as $id => $name) {
720                 // ...check if the page is empty and has no version
721                 if ($dbh->getRow("SELECT $page_tbl.id FROM $page_tbl"
722                                      . " LEFT JOIN $nonempty_tbl USING (id) "
723                                      . " LEFT JOIN $version_tbl USING (id)"
724                                      . " WHERE $nonempty_tbl.id is NULL"
725                                      . " AND $version_tbl.id is NULL"
726                                      . " AND $page_tbl.id=$id"))
727                 {
728                         trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE);
729                         $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");   // this purges the link
730                         $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
731                 }
732             }
733         }
734         $this->unlock(array('link'));
735         return true;
736     }
737
738     /**
739      * Find pages which link to or are linked from a page.
740      *
741      * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
742      * (linkExistingWikiWord or linkUnknownWikiWord)
743      * This is called on every page header GleanDescription, so we can store all the
744      * existing links.
745      *
746      * relations: $backend->get_links is responsible to add the relation to the pagehash
747      * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
748      *   if (isset($next['linkrelation']))
749      */
750     function get_links($pagename, $reversed=true,   $include_empty=false,
751                        $sortby='', $limit='', $exclude='',
752                        $want_relations = false)
753     {
754         $dbh = &$this->_dbh;
755         extract($this->_table_names);
756
757         if ($reversed)
758             list($have,$want) = array('linkee', 'linker');
759         else
760             list($have,$want) = array('linker', 'linkee');
761         $orderby = $this->sortby($sortby, 'db', array('pagename'));
762         if ($orderby) $orderby = " ORDER BY $want." . $orderby;
763         if ($exclude) // array of pagenames
764             $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
765         else
766             $exclude='';
767
768         $qpagename = $dbh->qstr($pagename);
769         // removed ref to FETCH_MODE in next line
770         $sql = "SELECT $want.id AS id, $want.pagename AS pagename, "
771             . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
772             . " FROM "
773             . (!$include_empty ? "$nonempty_tbl, " : '')
774             . " $page_tbl linkee, $page_tbl linker, $link_tbl "
775             . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
776             . " WHERE linkfrom=linker.id AND linkto=linkee.id"
777             . " AND $have.pagename=$qpagename"
778             . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
779             //. " GROUP BY $want.id"
780             . $exclude
781             . $orderby;
782 /*
783   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
784 id      pagename        linkrelation
785 2268    California      located_in
786 */
787         if ($limit) {
788             // extract from,count from limit
789             list($offset,$count) = $this->limit($limit);
790             $result = $dbh->SelectLimit($sql, $count, $offset);
791         } else {
792             $result = $dbh->Execute($sql);
793         }
794         $fields = $this->links_field_list;
795         if ($want_relations) // instead of hits
796             $fields[2] = 'linkrelation';
797         return new WikiDB_backend_ADODB_iter($this, $result, $fields);
798     }
799
800     /**
801      * Find if a page links to another page
802      */
803     function exists_link($pagename, $link, $reversed=false) {
804         $dbh = &$this->_dbh;
805         extract($this->_table_names);
806
807         if ($reversed)
808             list($have, $want) = array('linkee', 'linker');
809         else
810             list($have, $want) = array('linker', 'linkee');
811         $qpagename = $dbh->qstr($pagename);
812         $qlink = $dbh->qstr($link);
813         $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename=$qlink THEN 1 ELSE 0 END"
814                             . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
815                             . " WHERE linkfrom=linker.id AND linkto=linkee.id"
816                             . " AND $have.pagename=$qpagename"
817                             . " AND $want.pagename=$qlink");
818         return $row[0];
819     }
820
821     /*
822      *
823      */
824     function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') {
825         $dbh = &$this->_dbh;
826         extract($this->_table_names);
827         $orderby = $this->sortby($sortby, 'db');
828         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
829         $and = '';
830         if ($exclude) {// array of pagenames
831             $and = ' AND ';
832             $exclude = " $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
833         } else {
834             $exclude='';
835         }
836
837         //$dbh->SetFetchMode(ADODB_FETCH_ASSOC);
838         if (strstr($orderby, 'mtime ')) { // was ' mtime'
839             if ($include_empty) {
840                 $sql = "SELECT "
841                     . $this->page_tbl_fields
842                     ." FROM $page_tbl, $recent_tbl, $version_tbl"
843                     . " WHERE $page_tbl.id=$recent_tbl.id"
844                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
845                     . " $and$exclude"
846                     . $orderby;
847             }
848             else {
849                 $sql = "SELECT "
850                     . $this->page_tbl_fields
851                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
852                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
853                     . " AND $page_tbl.id=$recent_tbl.id"
854                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
855                     . " $and$exclude"
856                     . $orderby;
857             }
858         } else {
859             if ($include_empty) {
860                 $sql = "SELECT "
861                     . $this->page_tbl_fields
862                     . " FROM $page_tbl"
863                     . ($exclude ? " WHERE $exclude" : '')
864                     . $orderby;
865             } else {
866                 $sql = "SELECT "
867                     . $this->page_tbl_fields
868                     . " FROM $nonempty_tbl, $page_tbl"
869                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
870                     . " $and$exclude"
871                     . $orderby;
872             }
873         }
874         if ($limit) {
875             // extract from,count from limit
876             list($offset,$count) = $this->limit($limit);
877             $result = $dbh->SelectLimit($sql, $count, $offset);
878         } else {
879             $result = $dbh->Execute($sql);
880         }
881         //$dbh->SetFetchMode(ADODB_FETCH_NUM);
882         return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
883     }
884
885     /**
886      * Title and fulltext search.
887      */
888     function text_search($search, $fullsearch=false,
889                          $sortby='', $limit='', $exclude='')
890     {
891         $dbh = &$this->_dbh;
892         extract($this->_table_names);
893         $orderby = $this->sortby($sortby, 'db');
894         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
895
896         $table = "$nonempty_tbl, $page_tbl";
897         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
898         $fields = $this->page_tbl_fields;
899         $field_list = $this->page_tbl_field_list;
900         $searchobj = new WikiDB_backend_ADODB_search($search, $dbh);
901
902         if ($fullsearch) {
903             $table .= ", $recent_tbl";
904             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
905
906             $table .= ", $version_tbl";
907             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
908
909             $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
910             $field_list = array_merge($field_list, array('pagedata'),
911                                       $this->version_tbl_field_list);
912             $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
913         } else {
914             $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
915         }
916
917         $search_clause = $search->makeSqlClauseObj($callback);
918         $sql = "SELECT $fields FROM $table"
919             . " WHERE $join_clause"
920             . " AND ($search_clause)"
921             . $orderby;
922         if ($limit) {
923             // extract from,count from limit
924             list($offset,$count) = $this->limit($limit);
925             $result = $dbh->SelectLimit($sql, $count, $offset);
926         } else {
927             $result = $dbh->Execute($sql);
928         }
929         $iter = new WikiDB_backend_ADODB_iter($this, $result, $field_list);
930         if ($fullsearch)
931             $iter->stoplisted = $searchobj->stoplisted;
932         return $iter;
933     }
934
935     /*
936      * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
937      *       not sets. See above, but the above methods find too much.
938      * This is only for already resolved wildcards:
939      * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
940      */
941     function _sql_set(&$pagenames) {
942         $s = '(';
943         foreach ($pagenames as $p) {
944             $s .= ($this->_dbh->qstr($p).",");
945         }
946         return substr($s,0,-1).")";
947     }
948
949     /**
950      * Find highest or lowest hit counts.
951      */
952     function most_popular($limit=20, $sortby='-hits') {
953         $dbh = &$this->_dbh;
954         extract($this->_table_names);
955         $order = "DESC";
956         if ($limit < 0){
957             $order = "ASC";
958             $limit = -$limit;
959             $where = "";
960         } else {
961             $where = " AND hits > 0";
962         }
963         if ($sortby != '-hits') {
964             if ($order = $this->sortby($sortby, 'db'))  $orderby = " ORDER BY " . $order;
965             else $orderby = "";
966         } else
967             $orderby = " ORDER BY hits $order";
968         $sql = "SELECT "
969             . $this->page_tbl_fields
970             . " FROM $nonempty_tbl, $page_tbl"
971             . " WHERE $nonempty_tbl.id=$page_tbl.id"
972             . $where
973             . $orderby;
974         if ($limit) {
975             // extract from,count from limit
976             list($offset,$count) = $this->limit($limit);
977             $result = $dbh->SelectLimit($sql, $count, $offset);
978         } else {
979             $result = $dbh->Execute($sql);
980         }
981         return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
982     }
983
984     /**
985      * Find recent changes.
986      */
987     function most_recent($params) {
988         $limit = 0;
989         $since = 0;
990         $include_minor_revisions = false;
991         $exclude_major_revisions = false;
992         $include_all_revisions = false;
993         extract($params);
994
995         $dbh = &$this->_dbh;
996         extract($this->_table_names);
997
998         $pick = array();
999         if ($since)
1000             $pick[] = "mtime >= $since";
1001
1002         if ($include_all_revisions) {
1003             // Include all revisions of each page.
1004             $table = "$page_tbl, $version_tbl";
1005             $join_clause = "$page_tbl.id=$version_tbl.id";
1006
1007             if ($exclude_major_revisions) {
1008                 // Include only minor revisions
1009                 $pick[] = "minor_edit <> 0";
1010             }
1011             elseif (!$include_minor_revisions) {
1012                 // Include only major revisions
1013                 $pick[] = "minor_edit = 0";
1014             }
1015         }
1016         else {
1017             $table = "$page_tbl, $recent_tbl";
1018             $join_clause = "$page_tbl.id=$recent_tbl.id";
1019             $table .= ", $version_tbl";
1020             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
1021
1022             if ($exclude_major_revisions) {
1023                 // Include only most recent minor revision
1024                 $pick[] = 'version=latestminor';
1025             }
1026             elseif (!$include_minor_revisions) {
1027                 // Include only most recent major revision
1028                 $pick[] = 'version=latestmajor';
1029             }
1030             else {
1031                 // Include only the latest revision (whether major or minor).
1032                 $pick[] ='version=latestversion';
1033             }
1034         }
1035         $order = "DESC";
1036         if($limit < 0){
1037             $order = "ASC";
1038             $limit = -$limit;
1039         }
1040         $where_clause = $join_clause;
1041         if ($pick)
1042             $where_clause .= " AND " . join(" AND ", $pick);
1043         $sql = "SELECT "
1044             . $this->page_tbl_fields . ", " . $this->version_tbl_fields
1045             . " FROM $table"
1046             . " WHERE $where_clause"
1047             . " ORDER BY mtime $order";
1048         // FIXME: use SQL_BUFFER_RESULT for mysql?
1049         if ($limit) {
1050             // extract from,count from limit
1051             list($offset,$count) = $this->limit($limit);
1052             $result = $dbh->SelectLimit($sql, $count, $offset);
1053         } else {
1054             $result = $dbh->Execute($sql);
1055         }
1056         //$result->fields['version'] = $result->fields[6];
1057         return new WikiDB_backend_ADODB_iter($this, $result,
1058             array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
1059     }
1060
1061     /**
1062      * Find referenced empty pages.
1063      */
1064     function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') {
1065         $dbh = &$this->_dbh;
1066         extract($this->_table_names);
1067         if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
1068             $orderby = 'ORDER BY ' . $orderby;
1069
1070         if ($exclude_from) // array of pagenames
1071             $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from);
1072         if ($exclude) // array of pagenames
1073             $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude);
1074
1075         /*
1076          all empty pages, independent of linkstatus:
1077            select pagename as empty from page left join nonempty using(id) where is null(nonempty.id);
1078          only all empty pages, which have a linkto:
1079             select page.pagename, linked.pagename as wantedfrom from link, page linked
1080               left join page on link.linkto=page.id left join nonempty on link.linkto=nonempty.id
1081               where nonempty.id is null and linked.id=link.linkfrom;
1082         */
1083         $sql = "SELECT p.pagename, pp.pagename as wantedfrom"
1084             . " FROM $page_tbl p, $link_tbl linked"
1085             .   " LEFT JOIN $page_tbl pp ON (linked.linkto = pp.id)"
1086             .   " LEFT JOIN $nonempty_tbl ne ON (linked.linkto = ne.id)"
1087             . " WHERE ne.id is NULL"
1088             .       " AND (p.id = linked.linkfrom)"
1089             . $exclude_from
1090             . $exclude
1091             . $orderby;
1092         if ($limit) {
1093             // extract from,count from limit
1094             list($offset,$count) = $this->limit($limit);
1095             $result = $dbh->SelectLimit($sql, $count, $offset);
1096         } else {
1097             $result = $dbh->Execute($sql);
1098         }
1099         return new WikiDB_backend_ADODB_iter($this, $result, array('pagename','wantedfrom'));
1100     }
1101
1102     /**
1103      * Rename page in the database.
1104      */
1105     function rename_page($pagename, $to) {
1106         $dbh = &$this->_dbh;
1107         extract($this->_table_names);
1108
1109         $this->lock(array('page','version','recent','nonempty','link'));
1110         if ( ($id = $this->_get_pageid($pagename, false)) ) {
1111             if ($new = $this->_get_pageid($to, false)) {
1112                 // Cludge Alert!
1113                 // This page does not exist (already verified before), but exists in the page table.
1114                 // So we delete this page.
1115                 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
1116                 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
1117                 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
1118                 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
1119                 // We have to fix all referring tables to the old id
1120                 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
1121                 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
1122             }
1123             $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
1124                                 $dbh->qstr($to)));
1125         }
1126         $this->unlock(array('page'));
1127         return $id;
1128     }
1129
1130     function _update_recent_table($pageid = false) {
1131         $dbh = &$this->_dbh;
1132         extract($this->_table_names);
1133         extract($this->_expressions);
1134
1135         $pageid = (int)$pageid;
1136
1137         // optimize: mysql can do this with one REPLACE INTO.
1138         $backend_type = $this->backendType();
1139         if (substr($backend_type,0,5) == 'mysql') {
1140             $dbh->Execute("REPLACE INTO $recent_tbl"
1141                           . " (id, latestversion, latestmajor, latestminor)"
1142                           . " SELECT id, $maxversion, $maxmajor, $maxminor"
1143                           . " FROM $version_tbl"
1144                           . ( $pageid ? " WHERE id=$pageid" : "")
1145                           . " GROUP BY id" );
1146         } else {
1147             $this->lock(array('recent'));
1148             $dbh->Execute("DELETE FROM $recent_tbl"
1149                       . ( $pageid ? " WHERE id=$pageid" : ""));
1150             $dbh->Execute( "INSERT INTO $recent_tbl"
1151                            . " (id, latestversion, latestmajor, latestminor)"
1152                            . " SELECT id, $maxversion, $maxmajor, $maxminor"
1153                            . " FROM $version_tbl"
1154                            . ( $pageid ? " WHERE id=$pageid" : "")
1155                            . " GROUP BY id" );
1156             $this->unlock(array('recent'));
1157         }
1158     }
1159
1160     function _update_nonempty_table($pageid = false) {
1161         $dbh = &$this->_dbh;
1162         extract($this->_table_names);
1163         extract($this->_expressions);
1164
1165         $pageid = (int)$pageid;
1166
1167         extract($this->_expressions);
1168         $this->lock(array('nonempty'));
1169         $dbh->Execute("DELETE FROM $nonempty_tbl"
1170                       . ( $pageid ? " WHERE id=$pageid" : ""));
1171         $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
1172                       . " SELECT $recent_tbl.id"
1173                       . " FROM $recent_tbl, $version_tbl"
1174                       . " WHERE $recent_tbl.id=$version_tbl.id"
1175                       .       " AND version=latestversion"
1176                       // We have some specifics here (Oracle)
1177                       //. "  AND content<>''"
1178                       . "  AND content $notempty" // On Oracle not just "<>''"
1179                       . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
1180         $this->unlock(array('nonempty'));
1181     }
1182
1183     /**
1184      * Grab a write lock on the tables in the SQL database.
1185      *
1186      * Calls can be nested.  The tables won't be unlocked until
1187      * _unlock_database() is called as many times as _lock_database().
1188      *
1189      * @access protected
1190      */
1191     function lock($tables, $write_lock = true) {
1192     $this->_dbh->StartTrans();
1193         if ($this->_lock_count++ == 0) {
1194             $this->_current_lock = $tables;
1195             $this->_lock_tables($tables, $write_lock);
1196         }
1197     }
1198
1199     /**
1200      * Overridden by non-transaction safe backends.
1201      */
1202     function _lock_tables($tables, $write_lock) {
1203         return $this->_current_lock;
1204     }
1205
1206     /**
1207      * Release a write lock on the tables in the SQL database.
1208      *
1209      * @access protected
1210      *
1211      * @param $force boolean Unlock even if not every call to lock() has been matched
1212      * by a call to unlock().
1213      *
1214      * @see _lock_database
1215      */
1216     function unlock($tables = false, $force = false) {
1217         if ($this->_lock_count == 0) {
1218             $this->_current_lock = false;
1219             return;
1220         }
1221         if (--$this->_lock_count <= 0 || $force) {
1222             $this->_unlock_tables($tables, $force);
1223             $this->_current_lock = false;
1224             $this->_lock_count = 0;
1225         }
1226             $this->_dbh->CompleteTrans(! $force);
1227     }
1228
1229     /**
1230      * overridden by non-transaction safe backends
1231      */
1232     function _unlock_tables($tables, $write_lock=false) {
1233         return;
1234     }
1235
1236     /**
1237      * Serialize data
1238      */
1239     function _serialize($data) {
1240         if (empty($data))
1241             return '';
1242         assert(is_array($data));
1243         return serialize($data);
1244     }
1245
1246     /**
1247      * Unserialize data
1248      */
1249     function _unserialize($data) {
1250         return empty($data) ? array() : unserialize($data);
1251     }
1252
1253     /* some variables and functions for DB backend abstraction (action=upgrade) */
1254     function database () {
1255         return $this->_dbh->database;
1256     }
1257     function backendType() {
1258         return $this->_dbh->databaseType;
1259     }
1260     function connection() {
1261         return $this->_dbh->_connectionID;
1262     }
1263     function getRow($query) {
1264         return $this->_dbh->getRow($query);
1265     }
1266
1267     function listOfTables() {
1268         return $this->_dbh->MetaTables();
1269     }
1270
1271     // other database needs another connection and other privileges.
1272     function listOfFields($database, $table) {
1273         $field_list = array();
1274         $old_db = $this->database();
1275         if ($database != $old_db) {
1276             $conn = $this->_dbh->Connect($this->_parsedDSN['hostspec'],
1277                              DBADMIN_USER ? DBADMIN_USER : $this->_parsedDSN['username'],
1278                                          DBADMIN_PASSWD ? DBADMIN_PASSWD : $this->_parsedDSN['password'],
1279                                          $database);
1280         }
1281         foreach ($this->_dbh->MetaColumns($table, false) as $field) {
1282             $field_list[] = $field->name;
1283         }
1284         if ($database != $old_db) {
1285             $this->_dbh->close();
1286             $conn = $this->_dbh->Connect($this->_parsedDSN['hostspec'],
1287                              $this->_parsedDSN['username'],
1288                                          $this->_parsedDSN['password'],
1289                                          $old_db);
1290         }
1291         return $field_list;
1292     }
1293
1294 };
1295
1296 class WikiDB_backend_ADODB_generic_iter
1297 extends WikiDB_backend_iterator
1298 {
1299     function WikiDB_backend_ADODB_generic_iter($backend, $query_result, $field_list = NULL) {
1300         $this->_backend = &$backend;
1301         $this->_result = $query_result;
1302
1303         if (is_null($field_list)) {
1304             // No field list passed, retrieve from DB
1305             // WikiLens is using the iterator behind the scene
1306             $field_list = array();
1307             $fields = $query_result->FieldCount();
1308             for ($i = 0; $i < $fields ; $i++) {
1309                 $field_info = $query_result->FetchField($i);
1310                 array_push($field_list, $field_info->name);
1311             }
1312         }
1313
1314         $this->_fields = $field_list;
1315     }
1316
1317     function count() {
1318         if (!$this->_result) {
1319             return false;
1320         }
1321         $count = $this->_result->numRows();
1322         //$this->_result->Close();
1323         return $count;
1324     }
1325
1326     function next() {
1327         $result = &$this->_result;
1328         $backend = &$this->_backend;
1329         if (!$result || $result->EOF) {
1330             $this->free();
1331             return false;
1332         }
1333
1334         // Convert array to hash
1335         $i = 0;
1336         $rec_num = $result->fields;
1337         foreach ($this->_fields as $field) {
1338             $rec_assoc[$field] = $rec_num[$i++];
1339         }
1340         // check if the cache can be populated here?
1341
1342         $result->MoveNext();
1343         return $rec_assoc;
1344     }
1345
1346     function reset () {
1347         if ($this->_result) {
1348             $this->_result->MoveFirst();
1349         }
1350     }
1351     function asArray () {
1352         $result = array();
1353         while ($page = $this->next())
1354             $result[] = $page;
1355         return $result;
1356     }
1357
1358     function free () {
1359         if ($this->_result) {
1360             /* call mysql_free_result($this->_queryID) */
1361             $this->_result->Close();
1362             $this->_result = false;
1363         }
1364     }
1365 }
1366
1367 class WikiDB_backend_ADODB_iter
1368 extends WikiDB_backend_ADODB_generic_iter
1369 {
1370     function next() {
1371         $result = &$this->_result;
1372         $backend = &$this->_backend;
1373         if (!$result || $result->EOF) {
1374             $this->free();
1375             return false;
1376         }
1377
1378         // Convert array to hash
1379         $i = 0;
1380         $rec_num = $result->fields;
1381         foreach ($this->_fields as $field) {
1382             $rec_assoc[$field] = $rec_num[$i++];
1383         }
1384
1385         $result->MoveNext();
1386         if (isset($rec_assoc['pagedata']))
1387             $rec_assoc['pagedata'] = $backend->_extract_page_data($rec_assoc['pagedata'], $rec_assoc['hits']);
1388         if (!empty($rec_assoc['version'])) {
1389             $rec_assoc['versiondata'] = $backend->_extract_version_data_assoc($rec_assoc);
1390         }
1391         if (!empty($rec_assoc['linkrelation'])) {
1392             $rec_assoc['linkrelation'] = $rec_assoc['linkrelation']; // pagename enough?
1393         }
1394         return $rec_assoc;
1395     }
1396 }
1397
1398 class WikiDB_backend_ADODB_search extends WikiDB_backend_search_sql
1399 {
1400     // no surrounding quotes because we know it's a string
1401     // function _quote($word) { return $this->_dbh->escapeSimple($word); }
1402 }
1403
1404 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1405 // Eventually, change index.php to provide the relevant information
1406 // directly?
1407     /**
1408      * Parse a data source name.
1409      *
1410      * Additional keys can be added by appending a URI query string to the
1411      * end of the DSN.
1412      *
1413      * The format of the supplied DSN is in its fullest form:
1414      * <code>
1415      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1416      * </code>
1417      *
1418      * Most variations are allowed:
1419      * <code>
1420      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1421      *  phptype://username:password@hostspec/database_name
1422      *  phptype://username:password@hostspec
1423      *  phptype://username@hostspec
1424      *  phptype://hostspec/database
1425      *  phptype://hostspec
1426      *  phptype(dbsyntax)
1427      *  phptype
1428      * </code>
1429      *
1430      * @param string $dsn Data Source Name to be parsed
1431      *
1432      * @return array an associative array with the following keys:
1433      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
1434      *  + dbsyntax: Database used with regards to SQL syntax etc.
1435      *  + protocol: Communication protocol to use (tcp, unix etc.)
1436      *  + hostspec: Host specification (hostname[:port])
1437      *  + database: Database to use on the DBMS server
1438      *  + username: User name for login
1439      *  + password: Password for login
1440      *
1441      * @author Tomas V.V.Cox <cox@idecnet.com>
1442      */
1443     function parseDSN($dsn)
1444     {
1445         $parsed = array(
1446             'phptype'  => false,
1447             'dbsyntax' => false,
1448             'username' => false,
1449             'password' => false,
1450             'protocol' => false,
1451             'hostspec' => false,
1452             'port'     => false,
1453             'socket'   => false,
1454             'database' => false,
1455         );
1456
1457         if (is_array($dsn)) {
1458             $dsn = array_merge($parsed, $dsn);
1459             if (!$dsn['dbsyntax']) {
1460                 $dsn['dbsyntax'] = $dsn['phptype'];
1461             }
1462             return $dsn;
1463         }
1464
1465         // Find phptype and dbsyntax
1466         if (($pos = strpos($dsn, '://')) !== false) {
1467             $str = substr($dsn, 0, $pos);
1468             $dsn = substr($dsn, $pos + 3);
1469         } else {
1470             $str = $dsn;
1471             $dsn = null;
1472         }
1473
1474         // Get phptype and dbsyntax
1475         // $str => phptype(dbsyntax)
1476         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1477             $parsed['phptype']  = $arr[1];
1478             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1479         } else {
1480             $parsed['phptype']  = $str;
1481             $parsed['dbsyntax'] = $str;
1482         }
1483
1484         if (!count($dsn)) {
1485             return $parsed;
1486         }
1487
1488         // Get (if found): username and password
1489         // $dsn => username:password@protocol+hostspec/database
1490         if (($at = strrpos($dsn,'@')) !== false) {
1491             $str = substr($dsn, 0, $at);
1492             $dsn = substr($dsn, $at + 1);
1493             if (($pos = strpos($str, ':')) !== false) {
1494                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1495                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1496             } else {
1497                 $parsed['username'] = rawurldecode($str);
1498             }
1499         }
1500
1501         // Find protocol and hostspec
1502
1503         // $dsn => proto(proto_opts)/database
1504         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1505             $proto       = $match[1];
1506             $proto_opts  = $match[2] ? $match[2] : false;
1507             $dsn         = $match[3];
1508
1509         // $dsn => protocol+hostspec/database (old format)
1510         } else {
1511             if (strpos($dsn, '+') !== false) {
1512                 list($proto, $dsn) = explode('+', $dsn, 2);
1513             }
1514             if (strpos($dsn, '/') !== false) {
1515                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1516             } else {
1517                 $proto_opts = $dsn;
1518                 $dsn = null;
1519             }
1520         }
1521
1522         // process the different protocol options
1523         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1524         $proto_opts = rawurldecode($proto_opts);
1525         if ($parsed['protocol'] == 'tcp') {
1526             if (strpos($proto_opts, ':') !== false) {
1527                 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1528             } else {
1529                 $parsed['hostspec'] = $proto_opts;
1530             }
1531         } elseif ($parsed['protocol'] == 'unix') {
1532             $parsed['socket'] = $proto_opts;
1533         }
1534
1535         // Get dabase if any
1536         // $dsn => database
1537         if ($dsn) {
1538             // /database
1539             if (($pos = strpos($dsn, '?')) === false) {
1540                 $parsed['database'] = $dsn;
1541             // /database?param1=value1&param2=value2
1542             } else {
1543                 $parsed['database'] = substr($dsn, 0, $pos);
1544                 $dsn = substr($dsn, $pos + 1);
1545                 if (strpos($dsn, '&') !== false) {
1546                     $opts = explode('&', $dsn);
1547                 } else { // database?param1=value1
1548                     $opts = array($dsn);
1549                 }
1550                 foreach ($opts as $opt) {
1551                     list($key, $value) = explode('=', $opt);
1552                     if (!isset($parsed[$key])) {
1553                         // don't allow params overwrite
1554                         $parsed[$key] = rawurldecode($value);
1555                     }
1556                 }
1557             }
1558         }
1559
1560         return $parsed;
1561     }
1562
1563 // Local Variables:
1564 // mode: php
1565 // tab-width: 8
1566 // c-basic-offset: 4
1567 // c-hanging-comment-ender-p: nil
1568 // indent-tabs-mode: nil
1569 // End: