2 rcs_id('$Id: ADODB.php,v 1.35 2004-06-28 14:45:12 rurban Exp $');
5 Copyright 2002,2004 $ThePhpWikiProgrammingTeam
7 This file is part of PhpWiki.
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.
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.
19 You should have received a copy of the GNU General Public License
20 along with PhpWiki; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 * Based on PearDB.php.
27 * @author: Lawrence Akka, Reini Urban
29 * Now (phpwiki-1.3.10) with adodb-4.22, by Reini Urban:
30 * 1) Extended to use all available database backend, not only mysql.
31 * 2) It uses the ultra-fast binary adodb extension if loaded.
32 * 3) We use FETCH_NUM instead of FETCH_ASSOC (faster and more generic)
33 * 4) To support generic iterators which return ASSOC fields, and to support queries with
34 * variable columns, some trickery was needed to use recordset specific fetchMode.
35 * The first Execute uses the global fetchMode (ASSOC), then it's resetted back to NUM
36 * and the recordset fetchmode is set to ASSOC.
37 * 5) Transaction support, and locking as fallback.
39 * ADODB basic differences to PearDB: It pre-fetches the first row into fields,
40 * is dirtier in style, layout and more low-level ("worse is better").
41 * It has less needed basic features (modifyQuery, locks, ...), but some more
42 * unneeded features included: paging, monitoring and sessions, and much more drivers.
43 * No locking (which PearDB supports in some backends), and sequences are very
44 * bad compared to PearDB.
46 * Old Comments, by Lawrence Akka:
47 * 1) ADODB's GetRow() is slightly different from that in PEAR. It does not
48 * accept a fetchmode parameter
49 * That doesn't matter too much here, since we only ever use FETCHMODE_ASSOC
50 * 2) No need for ''s around strings in sprintf arguments - qstr puts them
52 * 3) ADODB has a version of GetOne, but it is difficult to use it when
53 * FETCH_ASSOC is in effect.
54 * Instead, use $rs = Execute($query); $value = $rs->fields["$colname"]
55 * 4) No error handling yet - could use ADOConnection->raiseErrorFn
56 * 5) It used to be faster then PEAR/DB at the beginning of 2002.
57 * Now at August 2002 PEAR/DB with our own page cache added,
58 * performance is comparable.
61 require_once('lib/WikiDB/backend.php');
62 // Error handling - calls trigger_error. NB - does not close the connection. Does it need to?
63 include_once('lib/WikiDB/adodb/adodb-errorhandler.inc.php');
64 // include the main adodb file
65 require_once('lib/WikiDB/adodb/adodb.inc.php');
67 class WikiDB_backend_ADODB
68 extends WikiDB_backend
71 function WikiDB_backend_ADODB ($dbparams) {
72 $parsed = parseDSN($dbparams['dsn']);
73 $this->_dbh = &ADONewConnection($parsed['phptype']);
74 if (!empty($parsed['persistent']))
75 $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'],
76 $parsed['password'], $parsed['database']);
78 $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
79 $parsed['password'], $parsed['database']);
81 //$this->_dbh->debug = true;
83 // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
84 // with some ASSOC based recordsets.
85 $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
86 $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
89 // With ADODB_COUNTRECS false it should speed up queries, but:
90 // 1) It only works with PHP >= 4.0.6; and
91 // 2) At the moment, I haven't figured out why the wrong results are returned'
92 $GLOBALS['ADODB_COUNTRECS'] = false;
94 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
96 = array('page_tbl' => $prefix . 'page',
97 'version_tbl' => $prefix . 'version',
98 'link_tbl' => $prefix . 'link',
99 'recent_tbl' => $prefix . 'recent',
100 'nonempty_tbl' => $prefix . 'nonempty');
101 $page_tbl = $this->_table_names['page_tbl'];
102 $version_tbl = $this->_table_names['version_tbl'];
103 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
104 . "$page_tbl.hits hits";
105 $this->version_tbl_fields = "$version_tbl.version AS version, "
106 . "$version_tbl.mtime AS mtime, "
107 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
108 . "$version_tbl.versiondata AS versiondata";
111 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
112 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
113 'maxversion' => "MAX(version)",
114 'notempty' => "<>''",
115 'iscontent' => "content<>''");
116 $this->_lock_count = 0;
120 * Close database connection.
125 if ($this->_lock_count) {
126 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
129 // $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
130 $this->unlock(false,'force');
132 $this->_dbh->close();
137 * Fast test for wikipage.
139 function is_wiki_page($pagename) {
141 extract($this->_table_names);
142 $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
143 . " FROM $nonempty_tbl, $page_tbl"
144 . " WHERE $nonempty_tbl.id=$page_tbl.id"
145 . " AND pagename=%s",
146 $dbh->qstr($pagename)));
147 return $row ? $row[0] : false;
150 function get_all_pagenames() {
152 extract($this->_table_names);
153 $result = $dbh->Execute("SELECT pagename"
154 . " FROM $nonempty_tbl, $page_tbl"
155 . " WHERE $nonempty_tbl.id=$page_tbl.id");
156 return $result->GetArray();
159 function numPages($filter=false, $exclude='') {
161 extract($this->_table_names);
162 $result = $dbh->getRow("SELECT count(*)"
163 . " FROM $nonempty_tbl, $page_tbl"
164 . " WHERE $nonempty_tbl.id=$page_tbl.id");
169 * Read page information from database.
171 function get_pagedata($pagename) {
173 $page_tbl = $this->_table_names['page_tbl'];
174 $row = $dbh->GetRow(sprintf("SELECT hits, pagedata FROM $page_tbl WHERE pagename=%s",
175 $dbh->qstr($pagename)));
176 return $row ? $this->_extract_page_data($row[1],$row[0]) : false;
179 function _extract_page_data(&$data, $hits) {
180 $pagedata = empty($data) ? array() : unserialize($data);
181 $pagedata['hits'] = $hits;
185 function update_pagedata($pagename, $newdata) {
187 $page_tbl = $this->_table_names['page_tbl'];
189 // Hits is the only thing we can update in a fast manner.
190 if (count($newdata) == 1 && isset($newdata['hits'])) {
191 // Note that this will fail silently if the page does not
192 // have a record in the page table. Since it's just the
193 // hit count, who cares?
194 $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
195 $newdata['hits'], $dbh->qstr($pagename)));
198 $where = sprintf("pagename=%s",$dbh->qstr($pagename));
200 $dbh->RowLock($page_tbl,$where);
202 $data = $this->get_pagedata($pagename);
205 $this->_get_pageid($pagename, true); // Creates page record
208 @$hits = (int)$data['hits'];
209 unset($data['hits']);
211 foreach ($newdata as $key => $val) {
214 else if (empty($val))
219 // FIXME: some DBMs dont support huge strings (pagedata), so we have to bind it.
220 if ($dbh->Execute(sprintf("UPDATE $page_tbl"
221 . " SET hits=%d, pagedata=%s"
222 . " WHERE pagename=%s",
224 $dbh->qstr(serialize($data)),
225 $dbh->qstr($pagename))))
226 $dbh->CommitTrans( );
228 $dbh->RollbackTrans( );
231 function _get_pageid($pagename, $create_if_missing = false) {
234 $page_tbl = $this->_table_names['page_tbl'];
235 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
236 $dbh->qstr($pagename));
237 if (! $create_if_missing ) {
238 $row = $dbh->GetRow($query);
239 return $row ? $row[0] : false;
241 $row = $dbh->GetRow($query);
243 if ((substr($dbh->databaseType,0,5) == 'mysql') or isa($dbh,'ADODB_sqlite')) {
244 // have auto-incrementing and atomic version
245 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
248 $dbh->qstr($pagename)));
249 $id = $dbh->_insertid();
251 //$id = $dbh->GenID($page_tbl . 'seq');
252 // Better generic version than with adodob::genID
253 $this->lock(array('page'));
255 $dbh->CommitLock($page_tbl);
256 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
258 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
259 . " (id,pagename,hits)"
260 . " VALUES (%d,%s,0)",
261 $id, $dbh->qstr($pagename)));
262 if ($rs) $dbh->CommitTrans( );
263 else $dbh->RollbackTrans( );
264 $this->unlock(array('page'));
272 function get_latest_version($pagename) {
274 extract($this->_table_names);
275 $row = $dbh->GetRow(sprintf("SELECT latestversion"
276 . " FROM $page_tbl, $recent_tbl"
277 . " WHERE $page_tbl.id=$recent_tbl.id"
278 . " AND pagename=%s",
279 $dbh->qstr($pagename)));
280 return $row ? (int)$row[0] : false;
283 function get_previous_version($pagename, $version) {
285 extract($this->_table_names);
286 // Use SELECTLIMIT for maximum portability
287 $rs = $dbh->SelectLimit(sprintf("SELECT version"
288 . " FROM $version_tbl, $page_tbl"
289 . " WHERE $version_tbl.id=$page_tbl.id"
291 . " AND version < %d"
292 . " ORDER BY version DESC"
293 ,$dbh->qstr($pagename),
296 return $rs->fields[0] ? (int)$rs->fields[0] : false;
302 * @param $version int Which version to get.
304 * @return hash The version data, or false if specified version does not
307 function get_versiondata($pagename, $version, $want_content = false) {
309 extract($this->_table_names);
311 assert(is_string($pagename) and $pagename != '');
312 assert($version > 0);
314 // FIXME: optimization: sometimes don't get page data?
316 $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
317 . ', ' . $this->version_tbl_fields;
319 $fields = $this->page_tbl_fields
320 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
321 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content<>'' as have_content, "
322 . "$version_tbl.versiondata as versiondata";
324 $row = $dbh->GetRow(sprintf("SELECT $fields"
325 . " FROM $page_tbl, $version_tbl"
326 . " WHERE $page_tbl.id=$version_tbl.id"
329 $dbh->qstr($pagename), $version));
330 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
333 function _extract_version_data_num(&$row, $want_content) {
338 //$pagename &= $row[1];
339 $data = empty($row[8]) ? array() : unserialize($row[8]);
340 $data['mtime'] = $row[5];
341 $data['is_minor_edit'] = !empty($row[6]);
343 $data['%content'] = $row[7];
345 $data['%content'] = !empty($row[7]);
347 if (!empty($row[3])) {
348 $data['%pagedata'] = $this->_extract_page_data($row[3],$row[2]);
353 function _extract_version_data_assoc(&$row) {
358 $data = empty($versiondata) ? array() : unserialize($versiondata);
359 $data['mtime'] = $mtime;
360 $data['is_minor_edit'] = !empty($minor_edit);
362 $data['%content'] = $content;
363 elseif ($have_content)
364 $data['%content'] = true;
366 $data['%content'] = '';
367 if (!empty($pagedata)) {
368 $data['%pagedata'] = $this->_extract_page_data($pagedata,$hits);
374 * Create a new revision of a page.
376 function set_versiondata($pagename, $version, $data) {
378 $version_tbl = $this->_table_names['version_tbl'];
380 $minor_edit = (int) !empty($data['is_minor_edit']);
381 unset($data['is_minor_edit']);
383 $mtime = (int)$data['mtime'];
384 unset($data['mtime']);
385 assert(!empty($mtime));
387 @$content = (string) $data['%content'];
388 unset($data['%content']);
389 unset($data['%pagedata']);
391 $this->lock(array('page','recent','version','nonempty'));
393 $dbh->CommitLock($version_tbl);
394 $id = $this->_get_pageid($pagename, true);
396 // optimize: mysql can do this with one REPLACE INTO.
397 if (substr($dbh->databaseType,0,5) == 'mysql') {
398 $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl"
399 . " (id,version,mtime,minor_edit,content,versiondata)"
400 . " VALUES(%d,%d,%d,%d,%s,%s)",
401 $id, $version, $mtime, $minor_edit,
402 $dbh->qstr($content),
403 $dbh->qstr(serialize($data))));
405 $dbh->Execute(sprintf("DELETE FROM $version_tbl"
406 . " WHERE id=%d AND version=%d",
408 $rs = $dbh->Execute(sprintf("INSERT INTO $version_tbl"
409 . " (id,version,mtime,minor_edit,content,versiondata)"
410 . " VALUES(%d,%d,%d,%d,%s,%s)",
411 $id, $version, $mtime, $minor_edit,
412 $dbh->qstr($content),
413 $dbh->qstr(serialize($data))));
415 $this->_update_recent_table($id);
416 $this->_update_nonempty_table($id);
417 if ($rs) $dbh->CommitTrans( );
418 else $dbh->RollbackTrans( );
419 $this->unlock(array('page','recent','version','nonempty'));
423 * Delete an old revision of a page.
425 function delete_versiondata($pagename, $version) {
427 extract($this->_table_names);
429 $this->lock(array('version'));
430 if ( ($id = $this->_get_pageid($pagename)) ) {
431 $dbh->Execute("DELETE FROM $version_tbl"
432 . " WHERE id=$id AND version=$version");
433 $this->_update_recent_table($id);
434 // This shouldn't be needed (as long as the latestversion
435 // never gets deleted.) But, let's be safe.
436 $this->_update_nonempty_table($id);
438 $this->unlock(array('version'));
442 * Delete page from the database.
444 function delete_page($pagename) {
446 extract($this->_table_names);
448 $this->lock(array('version','recent','nonempty','page','link'));
449 if ( ($id = $this->_get_pageid($pagename, false)) ) {
450 $dbh->Execute("DELETE FROM $version_tbl WHERE id=$id");
451 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id");
452 $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
453 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$id");
454 $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
455 if ($row and $row[0]) {
456 // We're still in the link table (dangling link) so we can't delete this
458 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
461 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
463 $this->_update_recent_table();
464 $this->_update_nonempty_table();
466 $this->unlock(array('version','recent','nonempty','page','link'));
470 // The only thing we might be interested in updating which we can
471 // do fast in the flags (minor_edit). I think the default
472 // update_versiondata will work fine...
473 //function update_versiondata($pagename, $version, $data) {
476 function set_links($pagename, $links) {
477 // Update link table.
478 // FIXME: optimize: mysql can do this all in one big INSERT.
481 extract($this->_table_names);
483 $this->lock(array('link'));
484 $pageid = $this->_get_pageid($pagename, true);
486 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
489 foreach($links as $link) {
490 if (isset($linkseen[$link]))
492 $linkseen[$link] = true;
493 $linkid = $this->_get_pageid($link, true);
494 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
495 . " VALUES ($pageid, $linkid)");
498 $this->unlock(array('link'));
502 * Find pages which link to or are linked from a page.
504 function get_links($pagename, $reversed = true) {
506 extract($this->_table_names);
509 list($have,$want) = array('linkee', 'linker');
511 list($have,$want) = array('linker', 'linkee');
513 $qpagename = $dbh->qstr($pagename);
514 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
515 // removed ref to FETCH_MODE in next line
516 $result = $dbh->Execute("SELECT $want.id AS id, $want.pagename AS pagename,"
517 . " $want.hits AS hits"
518 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
519 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
520 . " AND $have.pagename=$qpagename"
521 //. " GROUP BY $want.id"
522 . " ORDER BY $want.pagename");
523 $dbh->SetFetchMode(ADODB_FETCH_NUM);
524 return new WikiDB_backend_ADODB_iter($this, $result);
527 function get_all_pages($include_deleted=false,$sortby = false,$limit = false) {
529 extract($this->_table_names);
530 //if ($limit) $limit = "LIMIT $limit";
532 if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
534 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
535 if (strstr($orderby,' mtime')) {
536 if ($include_deleted) {
538 . $this->page_tbl_fields
539 ." FROM $page_tbl, $recent_tbl, $version_tbl"
540 . " WHERE $page_tbl.id=$recent_tbl.id"
541 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
546 . $this->page_tbl_fields
547 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
548 . " WHERE $nonempty_tbl.id=$page_tbl.id"
549 . " AND $page_tbl.id=$recent_tbl.id"
550 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
554 if ($include_deleted) {
556 . $this->page_tbl_fields
557 . " FROM $page_tbl $orderby";
560 . $this->page_tbl_fields
561 . " FROM $nonempty_tbl, $page_tbl"
562 . " WHERE $nonempty_tbl.id=$page_tbl.id"
567 // extract from,count from limit
568 require_once("lib/PageList.php");
569 list($offset,$count) = PageList::limit($limit);
570 $result = $dbh->SelectLimit($sql, $count, $offset);
572 $result = $dbh->Execute($sql);
574 $dbh->SetFetchMode(ADODB_FETCH_NUM);
575 return new WikiDB_backend_ADODB_iter($this, $result);
581 function text_search($search = '', $fullsearch = false) {
583 extract($this->_table_names);
585 $table = "$nonempty_tbl, $page_tbl";
586 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
587 $fields = $this->page_tbl_fields;
588 $callback = new WikiMethodCb($this, '_sql_match_clause');
591 $table .= ", $recent_tbl";
592 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
594 $table .= ", $version_tbl";
595 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
597 $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
598 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
601 $search_clause = $search->makeSqlClause($callback);
602 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
603 $result = $dbh->Execute("SELECT $fields FROM $table"
604 . " WHERE $join_clause"
605 . " AND ($search_clause)"
606 . " ORDER BY pagename");
608 $dbh->SetFetchMode(ADODB_FETCH_NUM);
609 return new WikiDB_backend_ADODB_iter($this, $result);
612 function _sql_match_clause($word) {
613 //not sure if we need this. ADODB may do it for us
614 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
616 // (we need it for at least % and _ --- they're the wildcard characters
617 // for the LIKE operator, and we need to quote them if we're searching
618 // for literal '%'s or '_'s. --- I'm not sure about \, but it seems to
620 $word = $this->_dbh->qstr("%$word%");
621 $page_tbl = $this->_table_names['page_tbl'];
622 return "LOWER($page_tbl.pagename) LIKE $word";
625 function _fullsearch_sql_match_clause($word) {
626 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); //not sure if we need this
628 $word = $this->_dbh->qstr("%$word%");
629 $page_tbl = $this->_table_names['page_tbl'];
630 return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
634 * Find highest or lowest hit counts.
636 function most_popular($limit=0, $sortby = '') {
638 extract($this->_table_names);
645 $where = " AND hits > 0";
647 if ($sortby) $orderby = " ORDER BY " . PageList::sortby($sortby,'db');
648 else $orderby = " ORDER BY hits $order";
649 $limit = $limit ? $limit : -1;
651 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
652 $result = $dbh->SelectLimit("SELECT "
653 . $this->page_tbl_fields
654 . " FROM $nonempty_tbl, $page_tbl"
655 . " WHERE $nonempty_tbl.id=$page_tbl.id"
658 $dbh->SetFetchMode(ADODB_FETCH_NUM);
659 return new WikiDB_backend_ADODB_iter($this, $result);
663 * Find recent changes.
665 function most_recent($params) {
668 $include_minor_revisions = false;
669 $exclude_major_revisions = false;
670 $include_all_revisions = false;
674 extract($this->_table_names);
678 $pick[] = "mtime >= $since";
680 if ($include_all_revisions) {
681 // Include all revisions of each page.
682 $table = "$page_tbl, $version_tbl";
683 $join_clause = "$page_tbl.id=$version_tbl.id";
685 if ($exclude_major_revisions) {
686 // Include only minor revisions
687 $pick[] = "minor_edit <> 0";
689 elseif (!$include_minor_revisions) {
690 // Include only major revisions
691 $pick[] = "minor_edit = 0";
695 $table = "$page_tbl, $recent_tbl";
696 $join_clause = "$page_tbl.id=$recent_tbl.id";
697 $table .= ", $version_tbl";
698 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
700 if ($exclude_major_revisions) {
701 // Include only most recent minor revision
702 $pick[] = 'version=latestminor';
704 elseif (!$include_minor_revisions) {
705 // Include only most recent major revision
706 $pick[] = 'version=latestmajor';
709 // Include only the latest revision (whether major or minor).
710 $pick[] ='version=latestversion';
718 $limit = $limit ? $limit : -1;
719 $where_clause = $join_clause;
721 $where_clause .= " AND " . join(" AND ", $pick);
723 // FIXME: use SQL_BUFFER_RESULT for mysql?
724 // Use SELECTLIMIT for portability
725 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
726 $result = $dbh->SelectLimit("SELECT "
727 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
729 . " WHERE $where_clause"
730 . " ORDER BY mtime $order",
732 $dbh->SetFetchMode(ADODB_FETCH_NUM);
733 //$result->fields['version'] = $result->fields[6];
734 return new WikiDB_backend_ADODB_iter($this, $result);
738 * Rename page in the database.
740 function rename_page($pagename, $to) {
742 extract($this->_table_names);
744 $this->lock(array('page'));
745 if ( ($id = $this->_get_pageid($pagename, false)) ) {
746 if ($new = $this->_get_pageid($to, false)) {
748 //this page does not exist (already verified before), but exists in the page table.
749 //so we delete this page.
750 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
753 $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
756 $this->unlock(array('page'));
760 function _update_recent_table($pageid = false) {
762 extract($this->_table_names);
763 extract($this->_expressions);
765 $pageid = (int)$pageid;
767 // optimize: mysql can do this with one REPLACE INTO.
768 if (substr($dbh->databaseType,0,5) == 'mysql') {
769 $dbh->Execute("REPLACE INTO $recent_tbl"
770 . " (id, latestversion, latestmajor, latestminor)"
771 . " SELECT id, $maxversion, $maxmajor, $maxminor"
772 . " FROM $version_tbl"
773 . ( $pageid ? " WHERE id=$pageid" : "")
776 $this->lock(array('recent'));
777 $dbh->Execute("DELETE FROM $recent_tbl"
778 . ( $pageid ? " WHERE id=$pageid" : ""));
779 $dbh->Execute( "INSERT INTO $recent_tbl"
780 . " (id, latestversion, latestmajor, latestminor)"
781 . " SELECT id, $maxversion, $maxmajor, $maxminor"
782 . " FROM $version_tbl"
783 . ( $pageid ? " WHERE id=$pageid" : "")
785 $this->unlock(array('recent'));
789 function _update_nonempty_table($pageid = false) {
791 extract($this->_table_names);
793 $pageid = (int)$pageid;
795 // optimize: mysql can do this with one REPLACE INTO.
796 if (substr($dbh->databaseType,0,5) == 'mysql') {
797 $dbh->Execute("REPLACE INTO $nonempty_tbl (id)"
798 . " SELECT $recent_tbl.id"
799 . " FROM $recent_tbl, $version_tbl"
800 . " WHERE $recent_tbl.id=$version_tbl.id"
801 . " AND version=latestversion"
803 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
805 $this->lock(array('nonempty'));
806 $dbh->Execute("DELETE FROM $nonempty_tbl"
807 . ( $pageid ? " WHERE id=$pageid" : ""));
808 $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
809 . " SELECT $recent_tbl.id"
810 . " FROM $recent_tbl, $version_tbl"
811 . " WHERE $recent_tbl.id=$version_tbl.id"
812 . " AND version=latestversion"
814 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
815 $this->unlock(array('nonempty'));
821 * Grab a write lock on the tables in the SQL database.
823 * Calls can be nested. The tables won't be unlocked until
824 * _unlock_database() is called as many times as _lock_database().
828 function lock($tables, $write_lock = true) {
829 $this->_dbh->StartTrans();
830 if ($this->_lock_count++ == 0) {
831 $this->_current_lock = $tables;
832 $this->_lock_tables($tables, $write_lock);
837 * Overridden by non-transaction safe backends.
839 function _lock_tables($tables, $write_lock) {
840 return $this->_current_lock;
844 * Release a write lock on the tables in the SQL database.
848 * @param $force boolean Unlock even if not every call to lock() has been matched
849 * by a call to unlock().
851 * @see _lock_database
853 function unlock($tables = false, $force = false) {
854 if ($this->_lock_count == 0) {
855 $this->_dbh->CompleteTrans(! $force);
856 $this->_current_lock = false;
859 if (--$this->_lock_count <= 0 || $force) {
860 $this->_unlock_tables($tables);
861 $this->_current_lock = false;
862 $this->_lock_count = 0;
864 $this->_dbh->CompleteTrans(! $force);
868 * overridden by non-transaction safe backends
870 function _unlock_tables($tables, $write_lock) {
874 /* some variables and functions for DB backend abstraction (action=upgrade) */
875 function database () {
876 return $this->_dbh->database;
878 function backendType() {
879 return $this->_dbh->databaseType;
881 function connection() {
882 return $this->_dbh->_connectionID;
885 function listOfTables() {
886 return $this->_dbh->MetaTables();
888 function listOfFields($database,$table) {
889 $field_list = array();
890 foreach ($this->_dbh->MetaColumns($table,false) as $field) {
891 $field_list[] = $field->name;
898 class WikiDB_backend_ADODB_generic_iter
899 extends WikiDB_backend_iterator
901 function WikiDB_backend_ADODB_generic_iter(&$backend, &$query_result) {
902 $this->_backend = &$backend;
903 $this->_result = $query_result;
907 if (!$this->_result) {
910 return $this->_result->numRows();
914 $result = &$this->_result;
915 $backend = &$this->_backend;
916 if (!$result || $result->EOF) {
920 if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
921 $result->fetchMode = 1;
923 $result->fetchMode = 2;
924 $record = $result->fields;
925 if (isset($record[0])) {
926 $record = $result->GetRowAssoc(2);
928 $record = $result->fields;
935 if ($this->_result) {
936 $this->_result->Close();
937 $this->_result = false;
942 class WikiDB_backend_ADODB_iter
943 extends WikiDB_backend_ADODB_generic_iter
946 $result = &$this->_result;
947 $backend = &$this->_backend;
948 if (!$result || $result->EOF) {
952 if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
953 $result->fetchMode = 1;
955 $result->fetchMode = 2;
956 $record = $result->fields;
957 if (isset($record[0])) {
958 $record = $result->GetRowAssoc(2);
960 $record = $result->fields;
964 $pagedata = $backend->_extract_page_data($record['pagedata'], $record['hits']);
965 $rec = array('pagename' => $record['pagename'],
966 'pagedata' => $pagedata);
967 if (!empty($record['version'])) {
968 $rec['versiondata'] = $backend->_extract_version_data_assoc($record);
969 $rec['version'] = $record['version'];
975 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
976 // Eventually, change index.php to provide the relevant information
979 * Parse a data source name.
981 * Additional keys can be added by appending a URI query string to the
984 * The format of the supplied DSN is in its fullest form:
986 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
989 * Most variations are allowed:
991 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
992 * phptype://username:password@hostspec/database_name
993 * phptype://username:password@hostspec
994 * phptype://username@hostspec
995 * phptype://hostspec/database
1001 * @param string $dsn Data Source Name to be parsed
1003 * @return array an associative array with the following keys:
1004 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1005 * + dbsyntax: Database used with regards to SQL syntax etc.
1006 * + protocol: Communication protocol to use (tcp, unix etc.)
1007 * + hostspec: Host specification (hostname[:port])
1008 * + database: Database to use on the DBMS server
1009 * + username: User name for login
1010 * + password: Password for login
1012 * @author Tomas V.V.Cox <cox@idecnet.com>
1014 function parseDSN($dsn)
1018 'dbsyntax' => false,
1019 'username' => false,
1020 'password' => false,
1021 'protocol' => false,
1022 'hostspec' => false,
1025 'database' => false,
1028 if (is_array($dsn)) {
1029 $dsn = array_merge($parsed, $dsn);
1030 if (!$dsn['dbsyntax']) {
1031 $dsn['dbsyntax'] = $dsn['phptype'];
1036 // Find phptype and dbsyntax
1037 if (($pos = strpos($dsn, '://')) !== false) {
1038 $str = substr($dsn, 0, $pos);
1039 $dsn = substr($dsn, $pos + 3);
1045 // Get phptype and dbsyntax
1046 // $str => phptype(dbsyntax)
1047 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1048 $parsed['phptype'] = $arr[1];
1049 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1051 $parsed['phptype'] = $str;
1052 $parsed['dbsyntax'] = $str;
1059 // Get (if found): username and password
1060 // $dsn => username:password@protocol+hostspec/database
1061 if (($at = strrpos($dsn,'@')) !== false) {
1062 $str = substr($dsn, 0, $at);
1063 $dsn = substr($dsn, $at + 1);
1064 if (($pos = strpos($str, ':')) !== false) {
1065 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1066 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1068 $parsed['username'] = rawurldecode($str);
1072 // Find protocol and hostspec
1074 // $dsn => proto(proto_opts)/database
1075 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1077 $proto_opts = $match[2] ? $match[2] : false;
1080 // $dsn => protocol+hostspec/database (old format)
1082 if (strpos($dsn, '+') !== false) {
1083 list($proto, $dsn) = explode('+', $dsn, 2);
1085 if (strpos($dsn, '/') !== false) {
1086 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1093 // process the different protocol options
1094 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1095 $proto_opts = rawurldecode($proto_opts);
1096 if ($parsed['protocol'] == 'tcp') {
1097 if (strpos($proto_opts, ':') !== false) {
1098 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1100 $parsed['hostspec'] = $proto_opts;
1102 } elseif ($parsed['protocol'] == 'unix') {
1103 $parsed['socket'] = $proto_opts;
1106 // Get dabase if any
1110 if (($pos = strpos($dsn, '?')) === false) {
1111 $parsed['database'] = $dsn;
1112 // /database?param1=value1¶m2=value2
1114 $parsed['database'] = substr($dsn, 0, $pos);
1115 $dsn = substr($dsn, $pos + 1);
1116 if (strpos($dsn, '&') !== false) {
1117 $opts = explode('&', $dsn);
1118 } else { // database?param1=value1
1119 $opts = array($dsn);
1121 foreach ($opts as $opt) {
1122 list($key, $value) = explode('=', $opt);
1123 if (!isset($parsed[$key])) {
1124 // don't allow params overwrite
1125 $parsed[$key] = rawurldecode($value);
1134 // $Log: not supported by cvs2svn $
1135 // Revision 1.34 2004/06/28 14:17:38 rurban
1136 // updated DSN parser from Pear. esp. for sqlite
1138 // Revision 1.33 2004/06/27 10:26:02 rurban
1139 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1141 // Revision 1.32 2004/06/25 14:15:08 rurban
1142 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1144 // Revision 1.31 2004/06/16 10:38:59 rurban
1145 // Disallow refernces in calls if the declaration is a reference
1146 // ("allow_call_time_pass_reference clean").
1147 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1148 // but several external libraries may not.
1149 // In detail these libs look to be affected (not tested):
1153 // Revision 1.30 2004/06/07 19:31:31 rurban
1154 // fixed ADOOB upgrade: listOfFields()
1156 // Revision 1.29 2004/05/12 10:49:55 rurban
1157 // require_once fix for those libs which are loaded before FileFinder and
1158 // its automatic include_path fix, and where require_once doesn't grok
1159 // dirname(__FILE__) != './lib'
1160 // upgrade fix with PearDB
1161 // navbar.tmpl: remove spaces for IE button alignment
1163 // Revision 1.28 2004/05/06 19:26:16 rurban
1164 // improve stability, trying to find the InlineParser endless loop on sf.net
1166 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1168 // Revision 1.27 2004/05/06 17:30:38 rurban
1169 // CategoryGroup: oops, dos2unix eol
1170 // improved phpwiki_version:
1171 // pre -= .0001 (1.3.10pre: 1030.099)
1172 // -p1 += .001 (1.3.9-p1: 1030.091)
1173 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1174 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1175 // backend->backendType(), backend->database(),
1176 // backend->listOfFields(),
1177 // backend->listOfTables(),
1179 // Revision 1.26 2004/04/26 20:44:35 rurban
1180 // locking table specific for better databases
1182 // Revision 1.25 2004/04/20 00:06:04 rurban
1183 // themable paging support
1185 // Revision 1.24 2004/04/18 01:34:20 rurban
1186 // protect most_popular from sortby=mtime
1188 // Revision 1.23 2004/04/16 14:19:39 rurban
1189 // updated ADODB notes
1192 // (c-file-style: "gnu")
1196 // c-basic-offset: 4
1197 // c-hanging-comment-ender-p: nil
1198 // indent-tabs-mode: nil