2 rcs_id('$Id: ADODB.php,v 1.43 2004-07-10 08:50:24 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 * phpwiki-1.3.11, by Philippe Vanhaesendonck
40 * - pass column list to iterators so we can FETCH_NUM in all cases
42 * ADODB basic differences to PearDB: It pre-fetches the first row into fields,
43 * is dirtier in style, layout and more low-level ("worse is better").
44 * It has less needed basic features (modifyQuery, locks, ...), but some more
45 * unneeded features included: paging, monitoring and sessions, and much more drivers.
46 * No locking (which PearDB supports in some backends), and sequences are very
47 * bad compared to PearDB.
49 * Old Comments, by Lawrence Akka:
50 * 1) ADODB's GetRow() is slightly different from that in PEAR. It does not
51 * accept a fetchmode parameter
52 * That doesn't matter too much here, since we only ever use FETCHMODE_ASSOC
53 * 2) No need for ''s around strings in sprintf arguments - qstr puts them
55 * 3) ADODB has a version of GetOne, but it is difficult to use it when
56 * FETCH_ASSOC is in effect.
57 * Instead, use $rs = Execute($query); $value = $rs->fields["$colname"]
58 * 4) No error handling yet - could use ADOConnection->raiseErrorFn
59 * 5) It used to be faster then PEAR/DB at the beginning of 2002.
60 * Now at August 2002 PEAR/DB with our own page cache added,
61 * performance is comparable.
64 require_once('lib/WikiDB/backend.php');
65 // Error handling - calls trigger_error. NB - does not close the connection. Does it need to?
66 include_once('lib/WikiDB/adodb/adodb-errorhandler.inc.php');
67 // include the main adodb file
68 require_once('lib/WikiDB/adodb/adodb.inc.php');
70 class WikiDB_backend_ADODB
71 extends WikiDB_backend
74 function WikiDB_backend_ADODB ($dbparams) {
75 $parsed = parseDSN($dbparams['dsn']);
76 $this->_dbparams = $dbparams;
77 $this->_dbh = &ADONewConnection($parsed['phptype']);
78 $this->_dsn = $parsed;
79 if (!empty($parsed['persistent']))
80 $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'],
81 $parsed['password'], $parsed['database']);
83 $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
84 $parsed['password'], $parsed['database']);
86 //$this->_dbh->debug = true;
88 // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
89 // with some ASSOC based recordsets.
90 $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
91 $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
94 // With ADODB_COUNTRECS false it should speed up queries, but:
95 // 1) It only works with PHP >= 4.0.6; and
96 // 2) At the moment, I haven't figured out why the wrong results are returned'
97 $GLOBALS['ADODB_COUNTRECS'] = false;
99 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
101 = array('page_tbl' => $prefix . 'page',
102 'version_tbl' => $prefix . 'version',
103 'link_tbl' => $prefix . 'link',
104 'recent_tbl' => $prefix . 'recent',
105 'nonempty_tbl' => $prefix . 'nonempty');
106 $page_tbl = $this->_table_names['page_tbl'];
107 $version_tbl = $this->_table_names['version_tbl'];
108 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
109 . "$page_tbl.hits hits";
110 $this->page_tbl_field_list = array('id', 'pagename', 'hits');
111 $this->version_tbl_fields = "$version_tbl.version AS version, "
112 . "$version_tbl.mtime AS mtime, "
113 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
114 . "$version_tbl.versiondata AS versiondata";
115 $this->version_tbl_field_list = array('version', 'mtime', 'minor_edit', 'content',
119 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
120 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
121 'maxversion' => "MAX(version)",
122 'notempty' => "<>''",
123 'iscontent' => "$version_tbl.content<>''");
124 $this->_lock_count = 0;
128 * Close database connection.
133 if ($this->_lock_count) {
134 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
137 // $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
138 $this->unlock(false,'force');
140 $this->_dbh->close();
145 * Fast test for wikipage.
147 function is_wiki_page($pagename) {
149 extract($this->_table_names);
150 $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
151 . " FROM $nonempty_tbl, $page_tbl"
152 . " WHERE $nonempty_tbl.id=$page_tbl.id"
153 . " AND pagename=%s",
154 $dbh->qstr($pagename)));
155 return $row ? $row[0] : false;
158 function get_all_pagenames() {
160 extract($this->_table_names);
161 $result = $dbh->Execute("SELECT pagename"
162 . " FROM $nonempty_tbl, $page_tbl"
163 . " WHERE $nonempty_tbl.id=$page_tbl.id");
164 return $result->GetArray();
167 function numPages($filter=false, $exclude='') {
169 extract($this->_table_names);
170 $result = $dbh->getRow("SELECT count(*)"
171 . " FROM $nonempty_tbl, $page_tbl"
172 . " WHERE $nonempty_tbl.id=$page_tbl.id");
177 * Read page information from database.
179 function get_pagedata($pagename) {
181 $page_tbl = $this->_table_names['page_tbl'];
182 $row = $dbh->GetRow(sprintf("SELECT hits, pagedata FROM $page_tbl WHERE pagename=%s",
183 $dbh->qstr($pagename)));
184 return $row ? $this->_extract_page_data($row[1],$row[0]) : false;
187 function _extract_page_data(&$data, $hits) {
188 $pagedata = empty($data) ? array() : $this->_unserialize($data);
189 $pagedata['hits'] = $hits;
193 function update_pagedata($pagename, $newdata) {
195 $page_tbl = $this->_table_names['page_tbl'];
197 // Hits is the only thing we can update in a fast manner.
198 if (count($newdata) == 1 && isset($newdata['hits'])) {
199 // Note that this will fail silently if the page does not
200 // have a record in the page table. Since it's just the
201 // hit count, who cares?
202 $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
203 $newdata['hits'], $dbh->qstr($pagename)));
206 $where = sprintf("pagename=%s",$dbh->qstr($pagename));
208 $dbh->RowLock($page_tbl,$where);
210 $data = $this->get_pagedata($pagename);
213 $this->_get_pageid($pagename, true); // Creates page record
216 @$hits = (int)$data['hits'];
217 unset($data['hits']);
219 foreach ($newdata as $key => $val) {
222 else if (empty($val))
227 if ($dbh->Execute("UPDATE $page_tbl"
228 . " SET hits=?, pagedata=?"
229 . " WHERE pagename=?",
230 array($hits, $this->_serialize($data),$pagename)))
231 $dbh->CommitTrans( );
233 $dbh->RollbackTrans( );
236 function _get_pageid($pagename, $create_if_missing = false) {
239 $page_tbl = $this->_table_names['page_tbl'];
240 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
241 $dbh->qstr($pagename));
242 if (! $create_if_missing ) {
243 $row = $dbh->GetRow($query);
244 return $row ? $row[0] : false;
246 $row = $dbh->GetRow($query);
248 //mysql, mysqli or mysqlt
249 if (substr($dbh->databaseType,0,5) == 'mysql') {
250 // have auto-incrementing, atomic version
251 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
254 $dbh->qstr($pagename)));
255 $id = $dbh->_insertid();
257 //$id = $dbh->GenID($page_tbl . 'seq');
258 // Better generic version than with adodob::genID
259 //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1
260 $this->lock(array('page'));
262 $dbh->CommitLock($page_tbl);
263 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
265 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
266 . " (id,pagename,hits)"
267 . " VALUES (%d,%s,0)",
268 $id, $dbh->qstr($pagename)));
269 if ($rs) $dbh->CommitTrans( );
270 else $dbh->RollbackTrans( );
271 $this->unlock(array('page'));
279 function get_latest_version($pagename) {
281 extract($this->_table_names);
282 $row = $dbh->GetRow(sprintf("SELECT latestversion"
283 . " FROM $page_tbl, $recent_tbl"
284 . " WHERE $page_tbl.id=$recent_tbl.id"
285 . " AND pagename=%s",
286 $dbh->qstr($pagename)));
287 return $row ? (int)$row[0] : false;
290 function get_previous_version($pagename, $version) {
292 extract($this->_table_names);
293 // Use SELECTLIMIT for maximum portability
294 $rs = $dbh->SelectLimit(sprintf("SELECT version"
295 . " FROM $version_tbl, $page_tbl"
296 . " WHERE $version_tbl.id=$page_tbl.id"
298 . " AND version < %d"
299 . " ORDER BY version DESC"
300 ,$dbh->qstr($pagename),
303 return $rs->fields ? (int)$rs->fields[0] : false;
309 * @param $version int Which version to get.
311 * @return hash The version data, or false if specified version does not
314 function get_versiondata($pagename, $version, $want_content = false) {
316 extract($this->_table_names);
317 extract($this->_expressions);
319 assert(is_string($pagename) and $pagename != '');
320 assert($version > 0);
322 // FIXME: optimization: sometimes don't get page data?
324 $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
325 . ', ' . $this->version_tbl_fields;
327 $fields = $this->page_tbl_fields . ", '' AS pagedata"
328 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
329 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
330 . "$version_tbl.versiondata as versiondata";
332 $row = $dbh->GetRow(sprintf("SELECT $fields"
333 . " FROM $page_tbl, $version_tbl"
334 . " WHERE $page_tbl.id=$version_tbl.id"
337 $dbh->qstr($pagename), $version));
338 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
341 function _extract_version_data_num(&$row, $want_content) {
346 //$pagename &= $row[1];
347 $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
348 $data['mtime'] = $row[5];
349 $data['is_minor_edit'] = !empty($row[6]);
351 $data['%content'] = $row[7];
353 $data['%content'] = !empty($row[7]);
355 if (!empty($row[3])) {
356 $data['%pagedata'] = $this->_extract_page_data($row[3],$row[2]);
361 function _extract_version_data_assoc(&$row) {
366 $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
367 $data['mtime'] = $mtime;
368 $data['is_minor_edit'] = !empty($minor_edit);
370 $data['%content'] = $content;
371 elseif ($have_content)
372 $data['%content'] = true;
374 $data['%content'] = '';
375 if (!empty($pagedata)) {
376 $data['%pagedata'] = $this->_extract_page_data($pagedata,$hits);
382 * Create a new revision of a page.
384 function set_versiondata($pagename, $version, $data) {
386 $version_tbl = $this->_table_names['version_tbl'];
388 $minor_edit = (int) !empty($data['is_minor_edit']);
389 unset($data['is_minor_edit']);
391 $mtime = (int)$data['mtime'];
392 unset($data['mtime']);
393 assert(!empty($mtime));
395 @$content = (string) $data['%content'];
396 unset($data['%content']);
397 unset($data['%pagedata']);
399 $this->lock(array('page','recent','version','nonempty'));
401 $dbh->CommitLock($version_tbl);
402 $id = $this->_get_pageid($pagename, true);
403 $backend_type = $this->backendType();
404 // optimize: mysql can do this with one REPLACE INTO.
405 if (substr($backend_type,0,5) == 'mysql') {
406 $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl"
407 . " (id,version,mtime,minor_edit,content,versiondata)"
408 . " VALUES(%d,%d,%d,%d,%s,%s)",
409 $id, $version, $mtime, $minor_edit,
410 $dbh->qstr($content),
411 $dbh->qstr($this->_serialize($data))));
413 $dbh->Execute(sprintf("DELETE FROM $version_tbl"
414 . " WHERE id=%d AND version=%d",
416 $rs = $dbh->Execute("INSERT INTO $version_tbl"
417 . " (id,version,mtime,minor_edit,content,versiondata)"
418 . " VALUES(?,?,?,?,?,?)",
419 array($id, $version, $mtime, $minor_edit,
420 $content, $this->_serialize($data)));
422 $this->_update_recent_table($id);
423 $this->_update_nonempty_table($id);
424 if ($rs) $dbh->CommitTrans( );
425 else $dbh->RollbackTrans( );
426 $this->unlock(array('page','recent','version','nonempty'));
430 * Delete an old revision of a page.
432 function delete_versiondata($pagename, $version) {
434 extract($this->_table_names);
436 $this->lock(array('version'));
437 if ( ($id = $this->_get_pageid($pagename)) ) {
438 $dbh->Execute("DELETE FROM $version_tbl"
439 . " WHERE id=$id AND version=$version");
440 $this->_update_recent_table($id);
441 // This shouldn't be needed (as long as the latestversion
442 // never gets deleted.) But, let's be safe.
443 $this->_update_nonempty_table($id);
445 $this->unlock(array('version'));
449 * Delete page from the database.
451 function delete_page($pagename) {
453 extract($this->_table_names);
455 $this->lock(array('version','recent','nonempty','page','link'));
456 if ( ($id = $this->_get_pageid($pagename, false)) ) {
457 $dbh->Execute("DELETE FROM $version_tbl WHERE id=$id");
458 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id");
459 $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
460 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$id");
461 $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
462 if ($row and $row[0]) {
463 // We're still in the link table (dangling link) so we can't delete this
465 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
468 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
470 $this->_update_recent_table();
471 $this->_update_nonempty_table();
473 $this->unlock(array('version','recent','nonempty','page','link'));
477 // The only thing we might be interested in updating which we can
478 // do fast in the flags (minor_edit). I think the default
479 // update_versiondata will work fine...
480 //function update_versiondata($pagename, $version, $data) {
483 function set_links($pagename, $links) {
484 // Update link table.
485 // FIXME: optimize: mysql can do this all in one big INSERT.
488 extract($this->_table_names);
490 $this->lock(array('link'));
491 $pageid = $this->_get_pageid($pagename, true);
493 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
496 foreach($links as $link) {
497 if (isset($linkseen[$link]))
499 $linkseen[$link] = true;
500 $linkid = $this->_get_pageid($link, true);
501 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
502 . " VALUES ($pageid, $linkid)");
505 $this->unlock(array('link'));
509 * Find pages which link to or are linked from a page.
511 function get_links($pagename, $reversed = true) {
513 extract($this->_table_names);
516 list($have,$want) = array('linkee', 'linker');
518 list($have,$want) = array('linker', 'linkee');
520 $qpagename = $dbh->qstr($pagename);
521 // removed ref to FETCH_MODE in next line
522 $result = $dbh->Execute("SELECT $want.id AS id, $want.pagename AS pagename,"
523 . " $want.hits AS hits"
524 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
525 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
526 . " AND $have.pagename=$qpagename"
527 //. " GROUP BY $want.id"
528 . " ORDER BY $want.pagename");
529 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
532 function get_all_pages($include_deleted=false, $sortby=false, $limit=false) {
534 extract($this->_table_names);
535 $orderby = $this->sortby($sortby, 'db');
536 if ($orderby) $orderby = 'ORDER BY ' . $orderby;
537 //$dbh->SetFetchMode(ADODB_FETCH_ASSOC);
538 if (strstr($orderby, 'mtime ')) { // was ' mtime'
539 if ($include_deleted) {
541 . $this->page_tbl_fields
542 ." FROM $page_tbl, $recent_tbl, $version_tbl"
543 . " WHERE $page_tbl.id=$recent_tbl.id"
544 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
549 . $this->page_tbl_fields
550 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
551 . " WHERE $nonempty_tbl.id=$page_tbl.id"
552 . " AND $page_tbl.id=$recent_tbl.id"
553 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
557 if ($include_deleted) {
559 . $this->page_tbl_fields
560 . " FROM $page_tbl $orderby";
563 . $this->page_tbl_fields
564 . " FROM $nonempty_tbl, $page_tbl"
565 . " WHERE $nonempty_tbl.id=$page_tbl.id"
570 // extract from,count from limit
571 list($offset,$count) = $this->limit($limit);
572 $result = $dbh->SelectLimit($sql, $count, $offset);
574 $result = $dbh->Execute($sql);
576 //$dbh->SetFetchMode(ADODB_FETCH_NUM);
577 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
583 function text_search($search = '', $fullsearch = false) {
585 extract($this->_table_names);
587 $table = "$nonempty_tbl, $page_tbl";
588 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
589 $fields = $this->page_tbl_fields;
590 $field_list = $this->page_tbl_field_list;
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 $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
602 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
605 $search_clause = $search->makeSqlClause($callback);
606 $result = $dbh->Execute("SELECT $fields FROM $table"
607 . " WHERE $join_clause"
608 . " AND ($search_clause)"
609 . " ORDER BY pagename");
611 return new WikiDB_backend_ADODB_iter($this, $result, $field_list);
614 function _sql_match_clause($word) {
615 //not sure if we need this. ADODB may do it for us
616 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
618 // (we need it for at least % and _ --- they're the wildcard characters
619 // for the LIKE operator, and we need to quote them if we're searching
620 // for literal '%'s or '_'s. --- I'm not sure about \, but it seems to
622 $word = $this->_dbh->qstr("%".strtolower($word)."%");
623 $page_tbl = $this->_table_names['page_tbl'];
624 return "LOWER($page_tbl.pagename) LIKE $word";
627 function _fullsearch_sql_match_clause($word) {
628 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); //not sure if we need this
630 $word = $this->_dbh->qstr("%".strtolower($word)."%");
631 $page_tbl = $this->_table_names['page_tbl'];
632 return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
636 * Find highest or lowest hit counts.
638 function most_popular($limit=0, $sortby = '') {
640 extract($this->_table_names);
647 $where = " AND hits > 0";
649 if ($sortby) $orderby = " ORDER BY " . $this->sortby($sortby, 'db');
650 else $orderby = " ORDER BY hits $order";
651 $limit = $limit ? $limit : -1;
653 $result = $dbh->SelectLimit("SELECT "
654 . $this->page_tbl_fields
655 . " FROM $nonempty_tbl, $page_tbl"
656 . " WHERE $nonempty_tbl.id=$page_tbl.id"
659 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
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 $result = $dbh->SelectLimit("SELECT "
726 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
728 . " WHERE $where_clause"
729 . " ORDER BY mtime $order",
731 //$result->fields['version'] = $result->fields[6];
732 return new WikiDB_backend_ADODB_iter($this, $result,
733 array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
737 * Rename page in the database.
739 function rename_page($pagename, $to) {
741 extract($this->_table_names);
743 $this->lock(array('page'));
744 if ( ($id = $this->_get_pageid($pagename, false)) ) {
745 if ($new = $this->_get_pageid($to, false)) {
747 //this page does not exist (already verified before), but exists in the page table.
748 //so we delete this page.
749 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
752 $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
755 $this->unlock(array('page'));
759 function _update_recent_table($pageid = false) {
761 extract($this->_table_names);
762 extract($this->_expressions);
764 $pageid = (int)$pageid;
766 // optimize: mysql can do this with one REPLACE INTO.
767 $backend_type = $this->backendType();
768 if (substr($backend_type,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);
792 extract($this->_expressions);
794 $pageid = (int)$pageid;
796 // Optimize: mysql can do this with one REPLACE INTO.
797 // FIXME: This treally should be moved into ADODB_mysql.php but
798 // then it must be duplicated for mysqli and mysqlt also.
799 $backend_type = $this->backendType();
800 if (substr($backend_type,0,5) == 'mysql') {
801 $dbh->Execute("REPLACE INTO $nonempty_tbl (id)"
802 . " SELECT $recent_tbl.id"
803 . " FROM $recent_tbl, $version_tbl"
804 . " WHERE $recent_tbl.id=$version_tbl.id"
805 . " AND version=latestversion"
806 // We have some specifics here (Oracle)
807 // . " AND content<>''"
808 . " AND content $notempty"
809 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
811 extract($this->_expressions);
812 $this->lock(array('nonempty'));
813 $dbh->Execute("DELETE FROM $nonempty_tbl"
814 . ( $pageid ? " WHERE id=$pageid" : ""));
815 $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
816 . " SELECT $recent_tbl.id"
817 . " FROM $recent_tbl, $version_tbl"
818 . " WHERE $recent_tbl.id=$version_tbl.id"
819 . " AND version=latestversion"
820 // We have some specifics here (Oracle)
821 //. " AND content<>''"
822 . " AND content $notempty"
823 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
824 $this->unlock(array('nonempty'));
830 * Grab a write lock on the tables in the SQL database.
832 * Calls can be nested. The tables won't be unlocked until
833 * _unlock_database() is called as many times as _lock_database().
837 function lock($tables, $write_lock = true) {
838 $this->_dbh->StartTrans();
839 if ($this->_lock_count++ == 0) {
840 $this->_current_lock = $tables;
841 $this->_lock_tables($tables, $write_lock);
846 * Overridden by non-transaction safe backends.
848 function _lock_tables($tables, $write_lock) {
849 return $this->_current_lock;
853 * Release a write lock on the tables in the SQL database.
857 * @param $force boolean Unlock even if not every call to lock() has been matched
858 * by a call to unlock().
860 * @see _lock_database
862 function unlock($tables = false, $force = false) {
863 if ($this->_lock_count == 0) {
864 $this->_dbh->CompleteTrans(! $force);
865 $this->_current_lock = false;
868 if (--$this->_lock_count <= 0 || $force) {
869 $this->_unlock_tables($tables);
870 $this->_current_lock = false;
871 $this->_lock_count = 0;
873 $this->_dbh->CompleteTrans(! $force);
877 * overridden by non-transaction safe backends
879 function _unlock_tables($tables, $write_lock) {
886 function _serialize($data) {
889 assert(is_array($data));
890 return serialize($data);
896 function _unserialize($data) {
897 return empty($data) ? array() : unserialize($data);
900 /* some variables and functions for DB backend abstraction (action=upgrade) */
901 function database () {
902 return $this->_dbh->database;
904 function backendType() {
905 return $this->_dbh->databaseType;
907 function connection() {
908 return $this->_dbh->_connectionID;
911 function listOfTables() {
912 return $this->_dbh->MetaTables();
914 function listOfFields($database,$table) {
915 $field_list = array();
916 foreach ($this->_dbh->MetaColumns($table,false) as $field) {
917 $field_list[] = $field->name;
924 class WikiDB_backend_ADODB_generic_iter
925 extends WikiDB_backend_iterator
927 function WikiDB_backend_ADODB_generic_iter(&$backend, &$query_result, $field_list = NULL) {
928 $this->_backend = &$backend;
929 $this->_result = $query_result;
931 if (is_null($field_list)) {
932 // No field list passed, retrieve from DB
933 // WikiLiens is using the iterator behind the scene
934 $field_list = array();
935 $fields = $query_result->FieldCount();
936 for ($i = 0; $i < $fields ; $i++) {
937 $field_info = $query_result->FetchField($i);
938 array_push($field_list, $field_info->name);
942 $this->_fields = $field_list;
946 if (!$this->_result) {
949 return $this->_result->numRows();
953 $result = &$this->_result;
954 $backend = &$this->_backend;
955 if (!$result || $result->EOF) {
960 // Convert array to hash
962 $rec_num = $result->fields;
963 foreach ($this->_fields as $field) {
964 $rec_assoc[$field] = $rec_num[$i++];
972 if ($this->_result) {
973 $this->_result->Close();
974 $this->_result = false;
979 class WikiDB_backend_ADODB_iter
980 extends WikiDB_backend_ADODB_generic_iter
983 $result = &$this->_result;
984 $backend = &$this->_backend;
985 if (!$result || $result->EOF) {
990 // Convert array to hash
992 $rec_num = $result->fields;
993 foreach ($this->_fields as $field) {
994 $rec_assoc[$field] = $rec_num[$i++];
999 $pagedata = $backend->_extract_page_data($rec_assoc['pagedata'], $rec_assoc['hits']);
1000 $rec = array('pagename' => $rec_assoc['pagename'],
1001 'pagedata' => $pagedata);
1002 if (!empty($rec_assoc['version'])) {
1003 $rec['versiondata'] = $backend->_extract_version_data_assoc($rec_assoc);
1004 $rec['version'] = $rec_assoc['version'];
1010 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1011 // Eventually, change index.php to provide the relevant information
1014 * Parse a data source name.
1016 * Additional keys can be added by appending a URI query string to the
1019 * The format of the supplied DSN is in its fullest form:
1021 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1024 * Most variations are allowed:
1026 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1027 * phptype://username:password@hostspec/database_name
1028 * phptype://username:password@hostspec
1029 * phptype://username@hostspec
1030 * phptype://hostspec/database
1031 * phptype://hostspec
1036 * @param string $dsn Data Source Name to be parsed
1038 * @return array an associative array with the following keys:
1039 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1040 * + dbsyntax: Database used with regards to SQL syntax etc.
1041 * + protocol: Communication protocol to use (tcp, unix etc.)
1042 * + hostspec: Host specification (hostname[:port])
1043 * + database: Database to use on the DBMS server
1044 * + username: User name for login
1045 * + password: Password for login
1047 * @author Tomas V.V.Cox <cox@idecnet.com>
1049 function parseDSN($dsn)
1053 'dbsyntax' => false,
1054 'username' => false,
1055 'password' => false,
1056 'protocol' => false,
1057 'hostspec' => false,
1060 'database' => false,
1063 if (is_array($dsn)) {
1064 $dsn = array_merge($parsed, $dsn);
1065 if (!$dsn['dbsyntax']) {
1066 $dsn['dbsyntax'] = $dsn['phptype'];
1071 // Find phptype and dbsyntax
1072 if (($pos = strpos($dsn, '://')) !== false) {
1073 $str = substr($dsn, 0, $pos);
1074 $dsn = substr($dsn, $pos + 3);
1080 // Get phptype and dbsyntax
1081 // $str => phptype(dbsyntax)
1082 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1083 $parsed['phptype'] = $arr[1];
1084 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1086 $parsed['phptype'] = $str;
1087 $parsed['dbsyntax'] = $str;
1094 // Get (if found): username and password
1095 // $dsn => username:password@protocol+hostspec/database
1096 if (($at = strrpos($dsn,'@')) !== false) {
1097 $str = substr($dsn, 0, $at);
1098 $dsn = substr($dsn, $at + 1);
1099 if (($pos = strpos($str, ':')) !== false) {
1100 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1101 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1103 $parsed['username'] = rawurldecode($str);
1107 // Find protocol and hostspec
1109 // $dsn => proto(proto_opts)/database
1110 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1112 $proto_opts = $match[2] ? $match[2] : false;
1115 // $dsn => protocol+hostspec/database (old format)
1117 if (strpos($dsn, '+') !== false) {
1118 list($proto, $dsn) = explode('+', $dsn, 2);
1120 if (strpos($dsn, '/') !== false) {
1121 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1128 // process the different protocol options
1129 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1130 $proto_opts = rawurldecode($proto_opts);
1131 if ($parsed['protocol'] == 'tcp') {
1132 if (strpos($proto_opts, ':') !== false) {
1133 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1135 $parsed['hostspec'] = $proto_opts;
1137 } elseif ($parsed['protocol'] == 'unix') {
1138 $parsed['socket'] = $proto_opts;
1141 // Get dabase if any
1145 if (($pos = strpos($dsn, '?')) === false) {
1146 $parsed['database'] = $dsn;
1147 // /database?param1=value1¶m2=value2
1149 $parsed['database'] = substr($dsn, 0, $pos);
1150 $dsn = substr($dsn, $pos + 1);
1151 if (strpos($dsn, '&') !== false) {
1152 $opts = explode('&', $dsn);
1153 } else { // database?param1=value1
1154 $opts = array($dsn);
1156 foreach ($opts as $opt) {
1157 list($key, $value) = explode('=', $opt);
1158 if (!isset($parsed[$key])) {
1159 // don't allow params overwrite
1160 $parsed[$key] = rawurldecode($value);
1169 // $Log: not supported by cvs2svn $
1170 // Revision 1.42 2004/07/09 10:06:50 rurban
1171 // Use backend specific sortby and sortable_columns method, to be able to
1172 // select between native (Db backend) and custom (PageList) sorting.
1173 // Fixed PageList::AddPageList (missed the first)
1174 // Added the author/creator.. name to AllPagesBy...
1175 // display no pages if none matched.
1176 // Improved dba and file sortby().
1177 // Use &$request reference
1179 // Revision 1.41 2004/07/08 21:32:35 rurban
1180 // Prevent from more warnings, minor db and sort optimizations
1182 // Revision 1.40 2004/07/08 16:56:16 rurban
1183 // use the backendType abstraction
1185 // Revision 1.39 2004/07/05 13:56:22 rurban
1186 // sqlite autoincrement fix
1188 // Revision 1.38 2004/07/05 12:57:54 rurban
1189 // add mysql timeout
1191 // Revision 1.37 2004/07/04 10:24:43 rurban
1192 // forgot the expressions
1194 // Revision 1.36 2004/07/03 16:51:06 rurban
1195 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1196 // added atomic mysql REPLACE for PearDB as in ADODB
1197 // fixed _lock_tables typo links => link
1198 // fixes unserialize ADODB bug in line 180
1200 // Revision 1.35 2004/06/28 14:45:12 rurban
1201 // fix adodb_sqlite to have the same dsn syntax as pear, use pconnect if requested
1203 // Revision 1.34 2004/06/28 14:17:38 rurban
1204 // updated DSN parser from Pear. esp. for sqlite
1206 // Revision 1.33 2004/06/27 10:26:02 rurban
1207 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1209 // Revision 1.32 2004/06/25 14:15:08 rurban
1210 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1212 // Revision 1.31 2004/06/16 10:38:59 rurban
1213 // Disallow refernces in calls if the declaration is a reference
1214 // ("allow_call_time_pass_reference clean").
1215 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1216 // but several external libraries may not.
1217 // In detail these libs look to be affected (not tested):
1221 // Revision 1.30 2004/06/07 19:31:31 rurban
1222 // fixed ADOOB upgrade: listOfFields()
1224 // Revision 1.29 2004/05/12 10:49:55 rurban
1225 // require_once fix for those libs which are loaded before FileFinder and
1226 // its automatic include_path fix, and where require_once doesn't grok
1227 // dirname(__FILE__) != './lib'
1228 // upgrade fix with PearDB
1229 // navbar.tmpl: remove spaces for IE button alignment
1231 // Revision 1.28 2004/05/06 19:26:16 rurban
1232 // improve stability, trying to find the InlineParser endless loop on sf.net
1234 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1236 // Revision 1.27 2004/05/06 17:30:38 rurban
1237 // CategoryGroup: oops, dos2unix eol
1238 // improved phpwiki_version:
1239 // pre -= .0001 (1.3.10pre: 1030.099)
1240 // -p1 += .001 (1.3.9-p1: 1030.091)
1241 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1242 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1243 // backend->backendType(), backend->database(),
1244 // backend->listOfFields(),
1245 // backend->listOfTables(),
1247 // Revision 1.26 2004/04/26 20:44:35 rurban
1248 // locking table specific for better databases
1250 // Revision 1.25 2004/04/20 00:06:04 rurban
1251 // themable paging support
1253 // Revision 1.24 2004/04/18 01:34:20 rurban
1254 // protect most_popular from sortby=mtime
1256 // Revision 1.23 2004/04/16 14:19:39 rurban
1257 // updated ADODB notes
1260 // (c-file-style: "gnu")
1264 // c-basic-offset: 4
1265 // c-hanging-comment-ender-p: nil
1266 // indent-tabs-mode: nil