2 rcs_id('$Id: ADODB.php,v 1.42 2004-07-09 10:06:50 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->_dbparams = $dbparams;
74 $this->_dbh = &ADONewConnection($parsed['phptype']);
75 $this->_dsn = $parsed;
76 if (!empty($parsed['persistent']))
77 $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'],
78 $parsed['password'], $parsed['database']);
80 $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
81 $parsed['password'], $parsed['database']);
83 //$this->_dbh->debug = true;
85 // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
86 // with some ASSOC based recordsets.
87 $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
88 $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
91 // With ADODB_COUNTRECS false it should speed up queries, but:
92 // 1) It only works with PHP >= 4.0.6; and
93 // 2) At the moment, I haven't figured out why the wrong results are returned'
94 $GLOBALS['ADODB_COUNTRECS'] = false;
96 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
98 = array('page_tbl' => $prefix . 'page',
99 'version_tbl' => $prefix . 'version',
100 'link_tbl' => $prefix . 'link',
101 'recent_tbl' => $prefix . 'recent',
102 'nonempty_tbl' => $prefix . 'nonempty');
103 $page_tbl = $this->_table_names['page_tbl'];
104 $version_tbl = $this->_table_names['version_tbl'];
105 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
106 . "$page_tbl.hits hits";
107 $this->version_tbl_fields = "$version_tbl.version AS version, "
108 . "$version_tbl.mtime AS mtime, "
109 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
110 . "$version_tbl.versiondata AS versiondata";
113 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
114 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
115 'maxversion' => "MAX(version)",
116 'notempty' => "<>''",
117 'iscontent' => "content<>''");
118 $this->_lock_count = 0;
122 * Close database connection.
127 if ($this->_lock_count) {
128 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
131 // $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
132 $this->unlock(false,'force');
134 $this->_dbh->close();
139 * Fast test for wikipage.
141 function is_wiki_page($pagename) {
143 extract($this->_table_names);
144 $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
145 . " FROM $nonempty_tbl, $page_tbl"
146 . " WHERE $nonempty_tbl.id=$page_tbl.id"
147 . " AND pagename=%s",
148 $dbh->qstr($pagename)));
149 return $row ? $row[0] : false;
152 function get_all_pagenames() {
154 extract($this->_table_names);
155 $result = $dbh->Execute("SELECT pagename"
156 . " FROM $nonempty_tbl, $page_tbl"
157 . " WHERE $nonempty_tbl.id=$page_tbl.id");
158 return $result->GetArray();
161 function numPages($filter=false, $exclude='') {
163 extract($this->_table_names);
164 $result = $dbh->getRow("SELECT count(*)"
165 . " FROM $nonempty_tbl, $page_tbl"
166 . " WHERE $nonempty_tbl.id=$page_tbl.id");
171 * Read page information from database.
173 function get_pagedata($pagename) {
175 $page_tbl = $this->_table_names['page_tbl'];
176 $row = $dbh->GetRow(sprintf("SELECT hits, pagedata FROM $page_tbl WHERE pagename=%s",
177 $dbh->qstr($pagename)));
178 return $row ? $this->_extract_page_data($row[1],$row[0]) : false;
181 function _extract_page_data(&$data, $hits) {
182 $pagedata = empty($data) ? array() : unserialize($data);
183 $pagedata['hits'] = $hits;
187 function update_pagedata($pagename, $newdata) {
189 $page_tbl = $this->_table_names['page_tbl'];
191 // Hits is the only thing we can update in a fast manner.
192 if (count($newdata) == 1 && isset($newdata['hits'])) {
193 // Note that this will fail silently if the page does not
194 // have a record in the page table. Since it's just the
195 // hit count, who cares?
196 $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
197 $newdata['hits'], $dbh->qstr($pagename)));
200 $where = sprintf("pagename=%s",$dbh->qstr($pagename));
202 $dbh->RowLock($page_tbl,$where);
204 $data = $this->get_pagedata($pagename);
207 $this->_get_pageid($pagename, true); // Creates page record
210 @$hits = (int)$data['hits'];
211 unset($data['hits']);
213 foreach ($newdata as $key => $val) {
216 else if (empty($val))
221 // FIXME: some DBMs dont support huge strings (pagedata), so we have to bind it.
222 if ($dbh->Execute(sprintf("UPDATE $page_tbl"
223 . " SET hits=%d, pagedata=%s"
224 . " WHERE pagename=%s",
226 $dbh->qstr(serialize($data)),
227 $dbh->qstr($pagename))))
228 $dbh->CommitTrans( );
230 $dbh->RollbackTrans( );
233 function _get_pageid($pagename, $create_if_missing = false) {
236 $page_tbl = $this->_table_names['page_tbl'];
237 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
238 $dbh->qstr($pagename));
239 if (! $create_if_missing ) {
240 $row = $dbh->GetRow($query);
241 return $row ? $row[0] : false;
243 $row = $dbh->GetRow($query);
245 //mysql, mysqli or mysqlt
246 if (substr($dbh->databaseType,0,5) == 'mysql') {
247 // have auto-incrementing, atomic version
248 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
251 $dbh->qstr($pagename)));
252 $id = $dbh->_insertid();
254 //$id = $dbh->GenID($page_tbl . 'seq');
255 // Better generic version than with adodob::genID
256 //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1
257 $this->lock(array('page'));
259 $dbh->CommitLock($page_tbl);
260 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
262 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
263 . " (id,pagename,hits)"
264 . " VALUES (%d,%s,0)",
265 $id, $dbh->qstr($pagename)));
266 if ($rs) $dbh->CommitTrans( );
267 else $dbh->RollbackTrans( );
268 $this->unlock(array('page'));
276 function get_latest_version($pagename) {
278 extract($this->_table_names);
279 $row = $dbh->GetRow(sprintf("SELECT latestversion"
280 . " FROM $page_tbl, $recent_tbl"
281 . " WHERE $page_tbl.id=$recent_tbl.id"
282 . " AND pagename=%s",
283 $dbh->qstr($pagename)));
284 return $row ? (int)$row[0] : false;
287 function get_previous_version($pagename, $version) {
289 extract($this->_table_names);
290 // Use SELECTLIMIT for maximum portability
291 $rs = $dbh->SelectLimit(sprintf("SELECT version"
292 . " FROM $version_tbl, $page_tbl"
293 . " WHERE $version_tbl.id=$page_tbl.id"
295 . " AND version < %d"
296 . " ORDER BY version DESC"
297 ,$dbh->qstr($pagename),
300 return $rs->fields[0] ? (int)$rs->fields[0] : false;
306 * @param $version int Which version to get.
308 * @return hash The version data, or false if specified version does not
311 function get_versiondata($pagename, $version, $want_content = false) {
313 extract($this->_table_names);
315 assert(is_string($pagename) and $pagename != '');
316 assert($version > 0);
318 // FIXME: optimization: sometimes don't get page data?
320 $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
321 . ', ' . $this->version_tbl_fields;
323 $fields = $this->page_tbl_fields . ", ''"
324 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
325 . "$version_tbl.minor_edit AS minor_edit, ". $this->_expressions['iscontent']. " as have_content, "
326 . "$version_tbl.versiondata as versiondata";
328 $row = $dbh->GetRow(sprintf("SELECT $fields"
329 . " FROM $page_tbl, $version_tbl"
330 . " WHERE $page_tbl.id=$version_tbl.id"
333 $dbh->qstr($pagename), $version));
334 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
337 function _extract_version_data_num(&$row, $want_content) {
342 //$pagename &= $row[1];
343 $data = empty($row[8]) ? array() : unserialize($row[8]);
344 $data['mtime'] = $row[5];
345 $data['is_minor_edit'] = !empty($row[6]);
347 $data['%content'] = $row[7];
349 $data['%content'] = !empty($row[7]);
351 if (!empty($row[3])) {
352 $data['%pagedata'] = $this->_extract_page_data($row[3],$row[2]);
357 function _extract_version_data_assoc(&$row) {
362 $data = empty($versiondata) ? array() : unserialize($versiondata);
363 $data['mtime'] = $mtime;
364 $data['is_minor_edit'] = !empty($minor_edit);
366 $data['%content'] = $content;
367 elseif ($have_content)
368 $data['%content'] = true;
370 $data['%content'] = '';
371 if (!empty($pagedata)) {
372 $data['%pagedata'] = $this->_extract_page_data($pagedata,$hits);
378 * Create a new revision of a page.
380 function set_versiondata($pagename, $version, $data) {
382 $version_tbl = $this->_table_names['version_tbl'];
384 $minor_edit = (int) !empty($data['is_minor_edit']);
385 unset($data['is_minor_edit']);
387 $mtime = (int)$data['mtime'];
388 unset($data['mtime']);
389 assert(!empty($mtime));
391 @$content = (string) $data['%content'];
392 unset($data['%content']);
393 unset($data['%pagedata']);
395 $this->lock(array('page','recent','version','nonempty'));
397 $dbh->CommitLock($version_tbl);
398 $id = $this->_get_pageid($pagename, true);
399 $backend_type = $this->backendType();
400 // optimize: mysql can do this with one REPLACE INTO.
401 if (substr($backend_type,0,5) == 'mysql') {
402 $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl"
403 . " (id,version,mtime,minor_edit,content,versiondata)"
404 . " VALUES(%d,%d,%d,%d,%s,%s)",
405 $id, $version, $mtime, $minor_edit,
406 $dbh->qstr($content),
407 $dbh->qstr(serialize($data))));
409 $dbh->Execute(sprintf("DELETE FROM $version_tbl"
410 . " WHERE id=%d AND version=%d",
412 $rs = $dbh->Execute(sprintf("INSERT INTO $version_tbl"
413 . " (id,version,mtime,minor_edit,content,versiondata)"
414 . " VALUES(%d,%d,%d,%d,%s,%s)",
415 $id, $version, $mtime, $minor_edit,
416 $dbh->qstr($content),
417 $dbh->qstr(serialize($data))));
419 $this->_update_recent_table($id);
420 $this->_update_nonempty_table($id);
421 if ($rs) $dbh->CommitTrans( );
422 else $dbh->RollbackTrans( );
423 $this->unlock(array('page','recent','version','nonempty'));
427 * Delete an old revision of a page.
429 function delete_versiondata($pagename, $version) {
431 extract($this->_table_names);
433 $this->lock(array('version'));
434 if ( ($id = $this->_get_pageid($pagename)) ) {
435 $dbh->Execute("DELETE FROM $version_tbl"
436 . " WHERE id=$id AND version=$version");
437 $this->_update_recent_table($id);
438 // This shouldn't be needed (as long as the latestversion
439 // never gets deleted.) But, let's be safe.
440 $this->_update_nonempty_table($id);
442 $this->unlock(array('version'));
446 * Delete page from the database.
448 function delete_page($pagename) {
450 extract($this->_table_names);
452 $this->lock(array('version','recent','nonempty','page','link'));
453 if ( ($id = $this->_get_pageid($pagename, false)) ) {
454 $dbh->Execute("DELETE FROM $version_tbl WHERE id=$id");
455 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id");
456 $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
457 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$id");
458 $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
459 if ($row and $row[0]) {
460 // We're still in the link table (dangling link) so we can't delete this
462 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
465 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
467 $this->_update_recent_table();
468 $this->_update_nonempty_table();
470 $this->unlock(array('version','recent','nonempty','page','link'));
474 // The only thing we might be interested in updating which we can
475 // do fast in the flags (minor_edit). I think the default
476 // update_versiondata will work fine...
477 //function update_versiondata($pagename, $version, $data) {
480 function set_links($pagename, $links) {
481 // Update link table.
482 // FIXME: optimize: mysql can do this all in one big INSERT.
485 extract($this->_table_names);
487 $this->lock(array('link'));
488 $pageid = $this->_get_pageid($pagename, true);
490 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
493 foreach($links as $link) {
494 if (isset($linkseen[$link]))
496 $linkseen[$link] = true;
497 $linkid = $this->_get_pageid($link, true);
498 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
499 . " VALUES ($pageid, $linkid)");
502 $this->unlock(array('link'));
506 * Find pages which link to or are linked from a page.
508 function get_links($pagename, $reversed = true) {
510 extract($this->_table_names);
513 list($have,$want) = array('linkee', 'linker');
515 list($have,$want) = array('linker', 'linkee');
517 $qpagename = $dbh->qstr($pagename);
518 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
519 // removed ref to FETCH_MODE in next line
520 $result = $dbh->Execute("SELECT $want.id AS id, $want.pagename AS pagename,"
521 . " $want.hits AS hits"
522 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
523 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
524 . " AND $have.pagename=$qpagename"
525 //. " GROUP BY $want.id"
526 . " ORDER BY $want.pagename");
527 $dbh->SetFetchMode(ADODB_FETCH_NUM);
528 return new WikiDB_backend_ADODB_iter($this, $result);
531 function get_all_pages($include_deleted=false, $sortby=false, $limit=false) {
533 extract($this->_table_names);
534 //if ($limit) $limit = "LIMIT $limit";
536 $orderby = $this->sortby($sortby, 'db');
537 if ($orderby) $orderby = 'ORDER BY ' . $orderby;
538 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
539 if (strstr($orderby, 'mtime')) { // was ' mtime'
540 if ($include_deleted) {
542 . $this->page_tbl_fields
543 ." FROM $page_tbl, $recent_tbl, $version_tbl"
544 . " WHERE $page_tbl.id=$recent_tbl.id"
545 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
550 . $this->page_tbl_fields
551 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
552 . " WHERE $nonempty_tbl.id=$page_tbl.id"
553 . " AND $page_tbl.id=$recent_tbl.id"
554 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
558 if ($include_deleted) {
560 . $this->page_tbl_fields
561 . " FROM $page_tbl $orderby";
564 . $this->page_tbl_fields
565 . " FROM $nonempty_tbl, $page_tbl"
566 . " WHERE $nonempty_tbl.id=$page_tbl.id"
571 // extract from,count from limit
572 list($offset,$count) = $this->limit($limit);
573 $result = $dbh->SelectLimit($sql, $count, $offset);
575 $result = $dbh->Execute($sql);
577 $dbh->SetFetchMode(ADODB_FETCH_NUM);
578 return new WikiDB_backend_ADODB_iter($this, $result);
584 function text_search($search = '', $fullsearch = false) {
586 extract($this->_table_names);
588 $table = "$nonempty_tbl, $page_tbl";
589 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
590 $fields = $this->page_tbl_fields;
591 $callback = new WikiMethodCb($this, '_sql_match_clause');
594 $table .= ", $recent_tbl";
595 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
597 $table .= ", $version_tbl";
598 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
600 $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
601 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
604 $search_clause = $search->makeSqlClause($callback);
605 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
606 $result = $dbh->Execute("SELECT $fields FROM $table"
607 . " WHERE $join_clause"
608 . " AND ($search_clause)"
609 . " ORDER BY pagename");
611 $dbh->SetFetchMode(ADODB_FETCH_NUM);
612 return new WikiDB_backend_ADODB_iter($this, $result);
615 function _sql_match_clause($word) {
616 //not sure if we need this. ADODB may do it for us
617 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
619 // (we need it for at least % and _ --- they're the wildcard characters
620 // for the LIKE operator, and we need to quote them if we're searching
621 // for literal '%'s or '_'s. --- I'm not sure about \, but it seems to
623 $word = $this->_dbh->qstr("%".strtolower($word)."%");
624 $page_tbl = $this->_table_names['page_tbl'];
625 return "LOWER($page_tbl.pagename) LIKE $word";
628 function _fullsearch_sql_match_clause($word) {
629 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); //not sure if we need this
631 $word = $this->_dbh->qstr("%".strtolower($word)."%");
632 $page_tbl = $this->_table_names['page_tbl'];
633 return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
637 * Find highest or lowest hit counts.
639 function most_popular($limit=0, $sortby = '') {
641 extract($this->_table_names);
648 $where = " AND hits > 0";
650 if ($sortby) $orderby = " ORDER BY " . $this->sortby($sortby, 'db');
651 else $orderby = " ORDER BY hits $order";
652 $limit = $limit ? $limit : -1;
654 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
655 $result = $dbh->SelectLimit("SELECT "
656 . $this->page_tbl_fields
657 . " FROM $nonempty_tbl, $page_tbl"
658 . " WHERE $nonempty_tbl.id=$page_tbl.id"
661 $dbh->SetFetchMode(ADODB_FETCH_NUM);
662 return new WikiDB_backend_ADODB_iter($this, $result);
666 * Find recent changes.
668 function most_recent($params) {
671 $include_minor_revisions = false;
672 $exclude_major_revisions = false;
673 $include_all_revisions = false;
677 extract($this->_table_names);
681 $pick[] = "mtime >= $since";
683 if ($include_all_revisions) {
684 // Include all revisions of each page.
685 $table = "$page_tbl, $version_tbl";
686 $join_clause = "$page_tbl.id=$version_tbl.id";
688 if ($exclude_major_revisions) {
689 // Include only minor revisions
690 $pick[] = "minor_edit <> 0";
692 elseif (!$include_minor_revisions) {
693 // Include only major revisions
694 $pick[] = "minor_edit = 0";
698 $table = "$page_tbl, $recent_tbl";
699 $join_clause = "$page_tbl.id=$recent_tbl.id";
700 $table .= ", $version_tbl";
701 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
703 if ($exclude_major_revisions) {
704 // Include only most recent minor revision
705 $pick[] = 'version=latestminor';
707 elseif (!$include_minor_revisions) {
708 // Include only most recent major revision
709 $pick[] = 'version=latestmajor';
712 // Include only the latest revision (whether major or minor).
713 $pick[] ='version=latestversion';
721 $limit = $limit ? $limit : -1;
722 $where_clause = $join_clause;
724 $where_clause .= " AND " . join(" AND ", $pick);
726 // FIXME: use SQL_BUFFER_RESULT for mysql?
727 // Use SELECTLIMIT for portability
728 $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
729 $result = $dbh->SelectLimit("SELECT "
730 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
732 . " WHERE $where_clause"
733 . " ORDER BY mtime $order",
735 $dbh->SetFetchMode(ADODB_FETCH_NUM);
736 //$result->fields['version'] = $result->fields[6];
737 return new WikiDB_backend_ADODB_iter($this, $result);
741 * Rename page in the database.
743 function rename_page($pagename, $to) {
745 extract($this->_table_names);
747 $this->lock(array('page'));
748 if ( ($id = $this->_get_pageid($pagename, false)) ) {
749 if ($new = $this->_get_pageid($to, false)) {
751 //this page does not exist (already verified before), but exists in the page table.
752 //so we delete this page.
753 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
756 $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
759 $this->unlock(array('page'));
763 function _update_recent_table($pageid = false) {
765 extract($this->_table_names);
766 extract($this->_expressions);
768 $pageid = (int)$pageid;
770 // optimize: mysql can do this with one REPLACE INTO.
771 $backend_type = $this->backendType();
772 if (substr($backend_type,0,5) == 'mysql') {
773 $dbh->Execute("REPLACE INTO $recent_tbl"
774 . " (id, latestversion, latestmajor, latestminor)"
775 . " SELECT id, $maxversion, $maxmajor, $maxminor"
776 . " FROM $version_tbl"
777 . ( $pageid ? " WHERE id=$pageid" : "")
780 $this->lock(array('recent'));
781 $dbh->Execute("DELETE FROM $recent_tbl"
782 . ( $pageid ? " WHERE id=$pageid" : ""));
783 $dbh->Execute( "INSERT INTO $recent_tbl"
784 . " (id, latestversion, latestmajor, latestminor)"
785 . " SELECT id, $maxversion, $maxmajor, $maxminor"
786 . " FROM $version_tbl"
787 . ( $pageid ? " WHERE id=$pageid" : "")
789 $this->unlock(array('recent'));
793 function _update_nonempty_table($pageid = false) {
795 extract($this->_table_names);
797 $pageid = (int)$pageid;
799 // Optimize: mysql can do this with one REPLACE INTO.
800 // FIXME: This treally should be moved into ADODB_mysql.php but
801 // then it must be duplicated for mysqli and mysqlt also.
802 $backend_type = $this->backendType();
803 if (substr($backend_type,0,5) == 'mysql') {
804 $dbh->Execute("REPLACE INTO $nonempty_tbl (id)"
805 . " SELECT $recent_tbl.id"
806 . " FROM $recent_tbl, $version_tbl"
807 . " WHERE $recent_tbl.id=$version_tbl.id"
808 . " AND version=latestversion"
810 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
812 extract($this->_expressions);
813 $this->lock(array('nonempty'));
814 $dbh->Execute("DELETE FROM $nonempty_tbl"
815 . ( $pageid ? " WHERE id=$pageid" : ""));
816 $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
817 . " SELECT $recent_tbl.id"
818 . " FROM $recent_tbl, $version_tbl"
819 . " WHERE $recent_tbl.id=$version_tbl.id"
820 . " AND version=latestversion"
821 // We have some specifics here (Oracle)
822 //. " AND content<>''"
823 . " AND content $notempty"
824 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
825 $this->unlock(array('nonempty'));
831 * Grab a write lock on the tables in the SQL database.
833 * Calls can be nested. The tables won't be unlocked until
834 * _unlock_database() is called as many times as _lock_database().
838 function lock($tables, $write_lock = true) {
839 $this->_dbh->StartTrans();
840 if ($this->_lock_count++ == 0) {
841 $this->_current_lock = $tables;
842 $this->_lock_tables($tables, $write_lock);
847 * Overridden by non-transaction safe backends.
849 function _lock_tables($tables, $write_lock) {
850 return $this->_current_lock;
854 * Release a write lock on the tables in the SQL database.
858 * @param $force boolean Unlock even if not every call to lock() has been matched
859 * by a call to unlock().
861 * @see _lock_database
863 function unlock($tables = false, $force = false) {
864 if ($this->_lock_count == 0) {
865 $this->_dbh->CompleteTrans(! $force);
866 $this->_current_lock = false;
869 if (--$this->_lock_count <= 0 || $force) {
870 $this->_unlock_tables($tables);
871 $this->_current_lock = false;
872 $this->_lock_count = 0;
874 $this->_dbh->CompleteTrans(! $force);
878 * overridden by non-transaction safe backends
880 function _unlock_tables($tables, $write_lock) {
884 /* some variables and functions for DB backend abstraction (action=upgrade) */
885 function database () {
886 return $this->_dbh->database;
888 function backendType() {
889 return $this->_dbh->databaseType;
891 function connection() {
892 return $this->_dbh->_connectionID;
895 function listOfTables() {
896 return $this->_dbh->MetaTables();
898 function listOfFields($database,$table) {
899 $field_list = array();
900 foreach ($this->_dbh->MetaColumns($table,false) as $field) {
901 $field_list[] = $field->name;
908 class WikiDB_backend_ADODB_generic_iter
909 extends WikiDB_backend_iterator
911 function WikiDB_backend_ADODB_generic_iter(&$backend, &$query_result) {
912 $this->_backend = &$backend;
913 $this->_result = $query_result;
917 if (!$this->_result) {
920 return $this->_result->numRows();
924 $result = &$this->_result;
925 $backend = &$this->_backend;
926 if (!$result || $result->EOF) {
930 if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
931 $result->fetchMode = 1;
933 $result->fetchMode = 2;
934 $record = $result->fields;
935 if (isset($record[0])) {
936 $record = $result->GetRowAssoc(2);
938 $record = $result->fields;
945 if ($this->_result) {
946 $this->_result->Close();
947 $this->_result = false;
952 class WikiDB_backend_ADODB_iter
953 extends WikiDB_backend_ADODB_generic_iter
956 $result = &$this->_result;
957 $backend = &$this->_backend;
958 if (!$result || $result->EOF) {
962 if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
963 $result->fetchMode = 1;
965 $result->fetchMode = 2;
966 $record = $result->fields;
967 if (isset($record[0])) {
968 $record = $result->GetRowAssoc(2);
970 $record = $result->fields;
974 $pagedata = $backend->_extract_page_data($record['pagedata'], $record['hits']);
975 $rec = array('pagename' => $record['pagename'],
976 'pagedata' => $pagedata);
977 if (!empty($record['version'])) {
978 $rec['versiondata'] = $backend->_extract_version_data_assoc($record);
979 $rec['version'] = $record['version'];
985 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
986 // Eventually, change index.php to provide the relevant information
989 * Parse a data source name.
991 * Additional keys can be added by appending a URI query string to the
994 * The format of the supplied DSN is in its fullest form:
996 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
999 * Most variations are allowed:
1001 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1002 * phptype://username:password@hostspec/database_name
1003 * phptype://username:password@hostspec
1004 * phptype://username@hostspec
1005 * phptype://hostspec/database
1006 * phptype://hostspec
1011 * @param string $dsn Data Source Name to be parsed
1013 * @return array an associative array with the following keys:
1014 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1015 * + dbsyntax: Database used with regards to SQL syntax etc.
1016 * + protocol: Communication protocol to use (tcp, unix etc.)
1017 * + hostspec: Host specification (hostname[:port])
1018 * + database: Database to use on the DBMS server
1019 * + username: User name for login
1020 * + password: Password for login
1022 * @author Tomas V.V.Cox <cox@idecnet.com>
1024 function parseDSN($dsn)
1028 'dbsyntax' => false,
1029 'username' => false,
1030 'password' => false,
1031 'protocol' => false,
1032 'hostspec' => false,
1035 'database' => false,
1038 if (is_array($dsn)) {
1039 $dsn = array_merge($parsed, $dsn);
1040 if (!$dsn['dbsyntax']) {
1041 $dsn['dbsyntax'] = $dsn['phptype'];
1046 // Find phptype and dbsyntax
1047 if (($pos = strpos($dsn, '://')) !== false) {
1048 $str = substr($dsn, 0, $pos);
1049 $dsn = substr($dsn, $pos + 3);
1055 // Get phptype and dbsyntax
1056 // $str => phptype(dbsyntax)
1057 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1058 $parsed['phptype'] = $arr[1];
1059 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1061 $parsed['phptype'] = $str;
1062 $parsed['dbsyntax'] = $str;
1069 // Get (if found): username and password
1070 // $dsn => username:password@protocol+hostspec/database
1071 if (($at = strrpos($dsn,'@')) !== false) {
1072 $str = substr($dsn, 0, $at);
1073 $dsn = substr($dsn, $at + 1);
1074 if (($pos = strpos($str, ':')) !== false) {
1075 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1076 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1078 $parsed['username'] = rawurldecode($str);
1082 // Find protocol and hostspec
1084 // $dsn => proto(proto_opts)/database
1085 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1087 $proto_opts = $match[2] ? $match[2] : false;
1090 // $dsn => protocol+hostspec/database (old format)
1092 if (strpos($dsn, '+') !== false) {
1093 list($proto, $dsn) = explode('+', $dsn, 2);
1095 if (strpos($dsn, '/') !== false) {
1096 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1103 // process the different protocol options
1104 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1105 $proto_opts = rawurldecode($proto_opts);
1106 if ($parsed['protocol'] == 'tcp') {
1107 if (strpos($proto_opts, ':') !== false) {
1108 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1110 $parsed['hostspec'] = $proto_opts;
1112 } elseif ($parsed['protocol'] == 'unix') {
1113 $parsed['socket'] = $proto_opts;
1116 // Get dabase if any
1120 if (($pos = strpos($dsn, '?')) === false) {
1121 $parsed['database'] = $dsn;
1122 // /database?param1=value1¶m2=value2
1124 $parsed['database'] = substr($dsn, 0, $pos);
1125 $dsn = substr($dsn, $pos + 1);
1126 if (strpos($dsn, '&') !== false) {
1127 $opts = explode('&', $dsn);
1128 } else { // database?param1=value1
1129 $opts = array($dsn);
1131 foreach ($opts as $opt) {
1132 list($key, $value) = explode('=', $opt);
1133 if (!isset($parsed[$key])) {
1134 // don't allow params overwrite
1135 $parsed[$key] = rawurldecode($value);
1144 // $Log: not supported by cvs2svn $
1145 // Revision 1.41 2004/07/08 21:32:35 rurban
1146 // Prevent from more warnings, minor db and sort optimizations
1148 // Revision 1.40 2004/07/08 16:56:16 rurban
1149 // use the backendType abstraction
1151 // Revision 1.39 2004/07/05 13:56:22 rurban
1152 // sqlite autoincrement fix
1154 // Revision 1.38 2004/07/05 12:57:54 rurban
1155 // add mysql timeout
1157 // Revision 1.37 2004/07/04 10:24:43 rurban
1158 // forgot the expressions
1160 // Revision 1.36 2004/07/03 16:51:06 rurban
1161 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1162 // added atomic mysql REPLACE for PearDB as in ADODB
1163 // fixed _lock_tables typo links => link
1164 // fixes unserialize ADODB bug in line 180
1166 // Revision 1.35 2004/06/28 14:45:12 rurban
1167 // fix adodb_sqlite to have the same dsn syntax as pear, use pconnect if requested
1169 // Revision 1.34 2004/06/28 14:17:38 rurban
1170 // updated DSN parser from Pear. esp. for sqlite
1172 // Revision 1.33 2004/06/27 10:26:02 rurban
1173 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1175 // Revision 1.32 2004/06/25 14:15:08 rurban
1176 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1178 // Revision 1.31 2004/06/16 10:38:59 rurban
1179 // Disallow refernces in calls if the declaration is a reference
1180 // ("allow_call_time_pass_reference clean").
1181 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1182 // but several external libraries may not.
1183 // In detail these libs look to be affected (not tested):
1187 // Revision 1.30 2004/06/07 19:31:31 rurban
1188 // fixed ADOOB upgrade: listOfFields()
1190 // Revision 1.29 2004/05/12 10:49:55 rurban
1191 // require_once fix for those libs which are loaded before FileFinder and
1192 // its automatic include_path fix, and where require_once doesn't grok
1193 // dirname(__FILE__) != './lib'
1194 // upgrade fix with PearDB
1195 // navbar.tmpl: remove spaces for IE button alignment
1197 // Revision 1.28 2004/05/06 19:26:16 rurban
1198 // improve stability, trying to find the InlineParser endless loop on sf.net
1200 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1202 // Revision 1.27 2004/05/06 17:30:38 rurban
1203 // CategoryGroup: oops, dos2unix eol
1204 // improved phpwiki_version:
1205 // pre -= .0001 (1.3.10pre: 1030.099)
1206 // -p1 += .001 (1.3.9-p1: 1030.091)
1207 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1208 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1209 // backend->backendType(), backend->database(),
1210 // backend->listOfFields(),
1211 // backend->listOfTables(),
1213 // Revision 1.26 2004/04/26 20:44:35 rurban
1214 // locking table specific for better databases
1216 // Revision 1.25 2004/04/20 00:06:04 rurban
1217 // themable paging support
1219 // Revision 1.24 2004/04/18 01:34:20 rurban
1220 // protect most_popular from sortby=mtime
1222 // Revision 1.23 2004/04/16 14:19:39 rurban
1223 // updated ADODB notes
1226 // (c-file-style: "gnu")
1230 // c-basic-offset: 4
1231 // c-hanging-comment-ender-p: nil
1232 // indent-tabs-mode: nil