2 rcs_id('$Id: ADODB.php,v 1.48 2004-11-09 17:11:16 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 if (DEBUG & _DEBUG_SQL) {
79 $this->_dbh->debug = true;
80 $GLOBALS['ADODB_OUTP'] = '_sql_debuglog';
82 $this->_dsn = $parsed;
83 if (!empty($parsed['persistent']))
84 $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'],
85 $parsed['password'], $parsed['database']);
87 $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
88 $parsed['password'], $parsed['database']);
90 // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
91 // with some ASSOC based recordsets.
92 $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
93 $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
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->page_tbl_field_list = array('id', 'pagename', 'hits');
108 $this->version_tbl_fields = "$version_tbl.version AS version, "
109 . "$version_tbl.mtime AS mtime, "
110 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
111 . "$version_tbl.versiondata AS versiondata";
112 $this->version_tbl_field_list = array('version', 'mtime', 'minor_edit', 'content',
116 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
117 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
118 'maxversion' => "MAX(version)",
119 'notempty' => "<>''",
120 'iscontent' => "$version_tbl.content<>''");
121 $this->_lock_count = 0;
125 * Close database connection.
130 if ($this->_lock_count) {
131 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
134 // $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
135 $this->unlock(false,'force');
137 $this->_dbh->close();
142 * Fast test for wikipage.
144 function is_wiki_page($pagename) {
146 extract($this->_table_names);
147 $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
148 . " FROM $nonempty_tbl, $page_tbl"
149 . " WHERE $nonempty_tbl.id=$page_tbl.id"
150 . " AND pagename=%s",
151 $dbh->qstr($pagename)));
152 return $row ? $row[0] : false;
155 function get_all_pagenames() {
157 extract($this->_table_names);
158 $result = $dbh->Execute("SELECT pagename"
159 . " FROM $nonempty_tbl, $page_tbl"
160 . " WHERE $nonempty_tbl.id=$page_tbl.id");
161 return $result->GetArray();
164 function numPages($filter=false, $exclude='') {
166 extract($this->_table_names);
167 $result = $dbh->getRow("SELECT count(*)"
168 . " FROM $nonempty_tbl, $page_tbl"
169 . " WHERE $nonempty_tbl.id=$page_tbl.id");
174 * Read page information from database.
176 function get_pagedata($pagename) {
178 $page_tbl = $this->_table_names['page_tbl'];
179 $row = $dbh->GetRow(sprintf("SELECT hits, pagedata FROM $page_tbl WHERE pagename=%s",
180 $dbh->qstr($pagename)));
181 return $row ? $this->_extract_page_data($row[1],$row[0]) : false;
184 function _extract_page_data($data, $hits) {
185 $pagedata = empty($data) ? array() : $this->_unserialize($data);
186 $pagedata['hits'] = $hits;
190 function update_pagedata($pagename, $newdata) {
192 $page_tbl = $this->_table_names['page_tbl'];
194 // Hits is the only thing we can update in a fast manner.
195 if (count($newdata) == 1 && isset($newdata['hits'])) {
196 // Note that this will fail silently if the page does not
197 // have a record in the page table. Since it's just the
198 // hit count, who cares?
199 $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
200 $newdata['hits'], $dbh->qstr($pagename)));
203 $where = sprintf("pagename=%s",$dbh->qstr($pagename));
205 $dbh->RowLock($page_tbl,$where);
207 $data = $this->get_pagedata($pagename);
210 $this->_get_pageid($pagename, true); // Creates page record
213 @$hits = (int)$data['hits'];
214 unset($data['hits']);
216 foreach ($newdata as $key => $val) {
219 else if (empty($val))
224 if ($dbh->Execute("UPDATE $page_tbl"
225 . " SET hits=?, pagedata=?"
226 . " WHERE pagename=?",
227 array($hits, $this->_serialize($data),$pagename)))
228 $dbh->CommitTrans( );
230 $dbh->RollbackTrans( );
233 function _get_pageid($pagename, $create_if_missing = false) {
237 $cache =& $request->_dbi->_cache->_id_cache;
238 if ($cache[$pagename]) return $cache[$pagename];
241 $page_tbl = $this->_table_names['page_tbl'];
242 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
243 $dbh->qstr($pagename));
244 if (! $create_if_missing ) {
245 $row = $dbh->GetRow($query);
246 return $row ? $row[0] : false;
248 $row = $dbh->GetRow($query);
250 //mysql, mysqli or mysqlt
251 if (substr($dbh->databaseType,0,5) == 'mysql') {
252 // have auto-incrementing, atomic version
253 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
255 . " VALUES(NULL,%s)",
256 $dbh->qstr($pagename)));
257 $id = $dbh->_insertid();
259 //$id = $dbh->GenID($page_tbl . 'seq');
260 // Better generic version than with adodob::genID
261 //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1
262 $this->lock(array('page'));
264 $dbh->CommitLock($page_tbl);
265 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
267 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
268 . " (id,pagename,hits)"
269 . " VALUES (%d,%s,0)",
270 $id, $dbh->qstr($pagename)));
271 if ($rs) $dbh->CommitTrans( );
272 else $dbh->RollbackTrans( );
273 $this->unlock(array('page'));
281 function get_latest_version($pagename) {
283 extract($this->_table_names);
284 $row = $dbh->GetRow(sprintf("SELECT latestversion"
285 . " FROM $page_tbl, $recent_tbl"
286 . " WHERE $page_tbl.id=$recent_tbl.id"
287 . " AND pagename=%s",
288 $dbh->qstr($pagename)));
289 return $row ? (int)$row[0] : false;
292 function get_previous_version($pagename, $version) {
294 extract($this->_table_names);
295 // Use SELECTLIMIT for maximum portability
296 $rs = $dbh->SelectLimit(sprintf("SELECT version"
297 . " FROM $version_tbl, $page_tbl"
298 . " WHERE $version_tbl.id=$page_tbl.id"
300 . " AND version < %d"
301 . " ORDER BY version DESC"
302 ,$dbh->qstr($pagename),
305 return $rs->fields ? (int)$rs->fields[0] : false;
311 * @param $version int Which version to get.
313 * @return hash The version data, or false if specified version does not
316 function get_versiondata($pagename, $version, $want_content = false) {
318 extract($this->_table_names);
319 extract($this->_expressions);
321 assert(is_string($pagename) and $pagename != '');
322 assert($version > 0);
324 // FIXME: optimization: sometimes don't get page data?
326 $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
327 . ', ' . $this->version_tbl_fields;
329 $fields = $this->page_tbl_fields . ", '' AS pagedata"
330 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
331 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
332 . "$version_tbl.versiondata as versiondata";
334 $row = $dbh->GetRow(sprintf("SELECT $fields"
335 . " FROM $page_tbl, $version_tbl"
336 . " WHERE $page_tbl.id=$version_tbl.id"
339 $dbh->qstr($pagename), $version));
340 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
343 function _extract_version_data_num($row, $want_content) {
348 //$pagename &= $row[1];
349 $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
350 $data['mtime'] = $row[5];
351 $data['is_minor_edit'] = !empty($row[6]);
353 $data['%content'] = $row[7];
355 $data['%content'] = !empty($row[7]);
357 if (!empty($row[3])) {
358 $data['%pagedata'] = $this->_extract_page_data($row[3],$row[2]);
363 function _extract_version_data_assoc($row) {
368 $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
369 $data['mtime'] = $mtime;
370 $data['is_minor_edit'] = !empty($minor_edit);
372 $data['%content'] = $content;
373 elseif ($have_content)
374 $data['%content'] = true;
376 $data['%content'] = '';
377 if (!empty($pagedata)) {
378 $data['%pagedata'] = $this->_extract_page_data($pagedata,$hits);
384 * Create a new revision of a page.
386 function set_versiondata($pagename, $version, $data) {
388 $version_tbl = $this->_table_names['version_tbl'];
390 $minor_edit = (int) !empty($data['is_minor_edit']);
391 unset($data['is_minor_edit']);
393 $mtime = (int)$data['mtime'];
394 unset($data['mtime']);
395 assert(!empty($mtime));
397 @$content = (string) $data['%content'];
398 unset($data['%content']);
399 unset($data['%pagedata']);
401 $this->lock(array('page','recent','version','nonempty'));
403 $dbh->CommitLock($version_tbl);
404 $id = $this->_get_pageid($pagename, true);
405 $backend_type = $this->backendType();
406 // optimize: mysql can do this with one REPLACE INTO.
407 if (substr($backend_type,0,5) == 'mysql') {
408 $rs = $dbh->Execute(sprintf("REPLACE 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($this->_serialize($data))));
415 $dbh->Execute(sprintf("DELETE FROM $version_tbl"
416 . " WHERE id=%d AND version=%d",
418 $rs = $dbh->Execute("INSERT INTO $version_tbl"
419 . " (id,version,mtime,minor_edit,content,versiondata)"
420 . " VALUES(?,?,?,?,?,?)",
421 array($id, $version, $mtime, $minor_edit,
422 $content, $this->_serialize($data)));
424 $this->_update_recent_table($id);
425 $this->_update_nonempty_table($id);
426 if ($rs) $dbh->CommitTrans( );
427 else $dbh->RollbackTrans( );
428 $this->unlock(array('page','recent','version','nonempty'));
432 * Delete an old revision of a page.
434 function delete_versiondata($pagename, $version) {
436 extract($this->_table_names);
438 $this->lock(array('version'));
439 if ( ($id = $this->_get_pageid($pagename)) ) {
440 $dbh->Execute("DELETE FROM $version_tbl"
441 . " WHERE id=$id AND version=$version");
442 $this->_update_recent_table($id);
443 // This shouldn't be needed (as long as the latestversion
444 // never gets deleted.) But, let's be safe.
445 $this->_update_nonempty_table($id);
447 $this->unlock(array('version'));
451 * Delete page from the database.
453 function delete_page($pagename) {
455 extract($this->_table_names);
457 $this->lock(array('version','recent','nonempty','page','link'));
458 if ( ($id = $this->_get_pageid($pagename, false)) ) {
459 $dbh->Execute("DELETE FROM $version_tbl WHERE id=$id");
460 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id");
461 $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
462 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$id");
463 $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
464 if ($row and $row[0]) {
465 // We're still in the link table (dangling link) so we can't delete this
467 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
470 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
472 $this->_update_recent_table();
473 $this->_update_nonempty_table();
475 $this->unlock(array('version','recent','nonempty','page','link'));
479 // The only thing we might be interested in updating which we can
480 // do fast in the flags (minor_edit). I think the default
481 // update_versiondata will work fine...
482 //function update_versiondata($pagename, $version, $data) {
485 function set_links($pagename, $links) {
486 // Update link table.
487 // FIXME: optimize: mysql can do this all in one big INSERT.
490 extract($this->_table_names);
492 $this->lock(array('link'));
493 $pageid = $this->_get_pageid($pagename, true);
495 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
498 foreach($links as $link) {
499 if (isset($linkseen[$link]))
501 $linkseen[$link] = true;
502 $linkid = $this->_get_pageid($link, true);
503 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
504 . " VALUES ($pageid, $linkid)");
507 $this->unlock(array('link'));
511 * Find pages which link to or are linked from a page.
513 * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
514 * (linkExistingWikiWord or linkUnknownWikiWord)
515 * This is called on every page header GleanDescription, so we can store all the existing links.
517 function get_links($pagename, $reversed=true, $include_empty=false) {
519 extract($this->_table_names);
522 list($have,$want) = array('linkee', 'linker');
524 list($have,$want) = array('linker', 'linkee');
526 $qpagename = $dbh->qstr($pagename);
527 // removed ref to FETCH_MODE in next line
528 $result = $dbh->Execute("SELECT $want.id AS id, $want.pagename AS pagename,"
529 . " $want.hits AS hits"
530 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
531 . (!$include_empty ? ", $nonempty_tbl" : '')
532 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
533 . " AND $have.pagename=$qpagename"
534 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
535 //. " GROUP BY $want.id"
536 . " ORDER BY $want.pagename");
537 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
540 function get_all_pages($include_empty=false, $sortby=false, $limit=false) {
542 extract($this->_table_names);
543 $orderby = $this->sortby($sortby, 'db');
544 if ($orderby) $orderby = 'ORDER BY ' . $orderby;
545 //$dbh->SetFetchMode(ADODB_FETCH_ASSOC);
546 if (strstr($orderby, 'mtime ')) { // was ' mtime'
547 if ($include_empty) {
549 . $this->page_tbl_fields
550 ." FROM $page_tbl, $recent_tbl, $version_tbl"
551 . " WHERE $page_tbl.id=$recent_tbl.id"
552 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
557 . $this->page_tbl_fields
558 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
559 . " WHERE $nonempty_tbl.id=$page_tbl.id"
560 . " AND $page_tbl.id=$recent_tbl.id"
561 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
565 if ($include_empty) {
567 . $this->page_tbl_fields
568 . " FROM $page_tbl $orderby";
571 . $this->page_tbl_fields
572 . " FROM $nonempty_tbl, $page_tbl"
573 . " WHERE $nonempty_tbl.id=$page_tbl.id"
578 // extract from,count from limit
579 list($offset,$count) = $this->limit($limit);
580 $result = $dbh->SelectLimit($sql, $count, $offset);
582 $result = $dbh->Execute($sql);
584 //$dbh->SetFetchMode(ADODB_FETCH_NUM);
585 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
591 function text_search($search = '', $fullsearch = false) {
593 extract($this->_table_names);
595 $table = "$nonempty_tbl, $page_tbl";
596 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
597 $fields = $this->page_tbl_fields;
598 $field_list = $this->page_tbl_field_list;
599 $callback = new WikiMethodCb($this, '_sql_match_clause');
602 $table .= ", $recent_tbl";
603 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
605 $table .= ", $version_tbl";
606 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
608 $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
609 $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
610 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
613 $search_clause = $search->makeSqlClause($callback);
614 $result = $dbh->Execute("SELECT $fields FROM $table"
615 . " WHERE $join_clause"
616 . " AND ($search_clause)"
617 . " ORDER BY pagename");
619 return new WikiDB_backend_ADODB_iter($this, $result, $field_list);
622 function _sql_match_clause($word) {
623 //not sure if we need this. ADODB may do it for us
624 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
626 // (we need it for at least % and _ --- they're the wildcard characters
627 // for the LIKE operator, and we need to quote them if we're searching
628 // for literal '%'s or '_'s. --- I'm not sure about \, but it seems to
630 $word = $this->_dbh->qstr("%".strtolower($word)."%");
631 $page_tbl = $this->_table_names['page_tbl'];
632 return "LOWER($page_tbl.pagename) LIKE $word";
635 function _fullsearch_sql_match_clause($word) {
636 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); //not sure if we need this
638 $word = $this->_dbh->qstr("%".strtolower($word)."%");
639 $page_tbl = $this->_table_names['page_tbl'];
640 return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
644 * Find highest or lowest hit counts.
646 function most_popular($limit=0, $sortby='-hits') {
648 extract($this->_table_names);
655 $where = " AND hits > 0";
657 if ($sortby != '-hits')
658 $orderby = " ORDER BY " . $this->sortby($sortby, 'db');
660 $orderby = " ORDER BY hits $order";
661 $limit = $limit ? $limit : -1;
663 $result = $dbh->SelectLimit("SELECT "
664 . $this->page_tbl_fields
665 . " FROM $nonempty_tbl, $page_tbl"
666 . " WHERE $nonempty_tbl.id=$page_tbl.id"
669 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
673 * Find recent changes.
675 function most_recent($params) {
678 $include_minor_revisions = false;
679 $exclude_major_revisions = false;
680 $include_all_revisions = false;
684 extract($this->_table_names);
688 $pick[] = "mtime >= $since";
690 if ($include_all_revisions) {
691 // Include all revisions of each page.
692 $table = "$page_tbl, $version_tbl";
693 $join_clause = "$page_tbl.id=$version_tbl.id";
695 if ($exclude_major_revisions) {
696 // Include only minor revisions
697 $pick[] = "minor_edit <> 0";
699 elseif (!$include_minor_revisions) {
700 // Include only major revisions
701 $pick[] = "minor_edit = 0";
705 $table = "$page_tbl, $recent_tbl";
706 $join_clause = "$page_tbl.id=$recent_tbl.id";
707 $table .= ", $version_tbl";
708 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
710 if ($exclude_major_revisions) {
711 // Include only most recent minor revision
712 $pick[] = 'version=latestminor';
714 elseif (!$include_minor_revisions) {
715 // Include only most recent major revision
716 $pick[] = 'version=latestmajor';
719 // Include only the latest revision (whether major or minor).
720 $pick[] ='version=latestversion';
728 $limit = $limit ? $limit : -1;
729 $where_clause = $join_clause;
731 $where_clause .= " AND " . join(" AND ", $pick);
733 // FIXME: use SQL_BUFFER_RESULT for mysql?
734 // Use SELECTLIMIT for portability
735 $result = $dbh->SelectLimit("SELECT "
736 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
738 . " WHERE $where_clause"
739 . " ORDER BY mtime $order",
741 //$result->fields['version'] = $result->fields[6];
742 return new WikiDB_backend_ADODB_iter($this, $result,
743 array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
747 * Rename page in the database.
749 function rename_page($pagename, $to) {
751 extract($this->_table_names);
753 $this->lock(array('page'));
754 if ( ($id = $this->_get_pageid($pagename, false)) ) {
755 if ($new = $this->_get_pageid($to, false)) {
757 //this page does not exist (already verified before), but exists in the page table.
758 //so we delete this page.
759 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
762 $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
765 $this->unlock(array('page'));
769 function _update_recent_table($pageid = false) {
771 extract($this->_table_names);
772 extract($this->_expressions);
774 $pageid = (int)$pageid;
776 // optimize: mysql can do this with one REPLACE INTO.
777 $backend_type = $this->backendType();
778 if (substr($backend_type,0,5) == 'mysql') {
779 $dbh->Execute("REPLACE INTO $recent_tbl"
780 . " (id, latestversion, latestmajor, latestminor)"
781 . " SELECT id, $maxversion, $maxmajor, $maxminor"
782 . " FROM $version_tbl"
783 . ( $pageid ? " WHERE id=$pageid" : "")
786 $this->lock(array('recent'));
787 $dbh->Execute("DELETE FROM $recent_tbl"
788 . ( $pageid ? " WHERE id=$pageid" : ""));
789 $dbh->Execute( "INSERT INTO $recent_tbl"
790 . " (id, latestversion, latestmajor, latestminor)"
791 . " SELECT id, $maxversion, $maxmajor, $maxminor"
792 . " FROM $version_tbl"
793 . ( $pageid ? " WHERE id=$pageid" : "")
795 $this->unlock(array('recent'));
799 function _update_nonempty_table($pageid = false) {
801 extract($this->_table_names);
802 extract($this->_expressions);
804 $pageid = (int)$pageid;
806 // Optimize: mysql can do this with one REPLACE INTO.
807 // FIXME: This treally should be moved into ADODB_mysql.php but
808 // then it must be duplicated for mysqli and mysqlt also.
809 $backend_type = $this->backendType();
810 if (substr($backend_type,0,5) == 'mysql') {
811 $dbh->Execute("REPLACE INTO $nonempty_tbl (id)"
812 . " SELECT $recent_tbl.id"
813 . " FROM $recent_tbl, $version_tbl"
814 . " WHERE $recent_tbl.id=$version_tbl.id"
815 . " AND version=latestversion"
816 // We have some specifics here (Oracle)
817 // . " AND content<>''"
818 . " AND content $notempty"
819 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
821 extract($this->_expressions);
822 $this->lock(array('nonempty'));
823 $dbh->Execute("DELETE FROM $nonempty_tbl"
824 . ( $pageid ? " WHERE id=$pageid" : ""));
825 $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
826 . " SELECT $recent_tbl.id"
827 . " FROM $recent_tbl, $version_tbl"
828 . " WHERE $recent_tbl.id=$version_tbl.id"
829 . " AND version=latestversion"
830 // We have some specifics here (Oracle)
831 //. " AND content<>''"
832 . " AND content $notempty"
833 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
834 $this->unlock(array('nonempty'));
840 * Grab a write lock on the tables in the SQL database.
842 * Calls can be nested. The tables won't be unlocked until
843 * _unlock_database() is called as many times as _lock_database().
847 function lock($tables, $write_lock = true) {
848 $this->_dbh->StartTrans();
849 if ($this->_lock_count++ == 0) {
850 $this->_current_lock = $tables;
851 $this->_lock_tables($tables, $write_lock);
856 * Overridden by non-transaction safe backends.
858 function _lock_tables($tables, $write_lock) {
859 return $this->_current_lock;
863 * Release a write lock on the tables in the SQL database.
867 * @param $force boolean Unlock even if not every call to lock() has been matched
868 * by a call to unlock().
870 * @see _lock_database
872 function unlock($tables = false, $force = false) {
873 if ($this->_lock_count == 0) {
874 $this->_dbh->CompleteTrans(! $force);
875 $this->_current_lock = false;
878 if (--$this->_lock_count <= 0 || $force) {
879 $this->_unlock_tables($tables);
880 $this->_current_lock = false;
881 $this->_lock_count = 0;
883 $this->_dbh->CompleteTrans(! $force);
887 * overridden by non-transaction safe backends
889 function _unlock_tables($tables, $write_lock) {
896 function _serialize($data) {
899 assert(is_array($data));
900 return serialize($data);
906 function _unserialize($data) {
907 return empty($data) ? array() : unserialize($data);
910 /* some variables and functions for DB backend abstraction (action=upgrade) */
911 function database () {
912 return $this->_dbh->database;
914 function backendType() {
915 return $this->_dbh->databaseType;
917 function connection() {
918 return $this->_dbh->_connectionID;
921 function listOfTables() {
922 return $this->_dbh->MetaTables();
924 function listOfFields($database,$table) {
925 $field_list = array();
926 foreach ($this->_dbh->MetaColumns($table,false) as $field) {
927 $field_list[] = $field->name;
934 class WikiDB_backend_ADODB_generic_iter
935 extends WikiDB_backend_iterator
937 function WikiDB_backend_ADODB_generic_iter($backend, $query_result, $field_list = NULL) {
938 $this->_backend = &$backend;
939 $this->_result = $query_result;
941 if (is_null($field_list)) {
942 // No field list passed, retrieve from DB
943 // WikiLens is using the iterator behind the scene
944 $field_list = array();
945 $fields = $query_result->FieldCount();
946 for ($i = 0; $i < $fields ; $i++) {
947 $field_info = $query_result->FetchField($i);
948 array_push($field_list, $field_info->name);
952 $this->_fields = $field_list;
956 if (!$this->_result) {
959 $count = $this->_result->numRows();
960 //$this->_result->Close();
965 $result = &$this->_result;
966 $backend = &$this->_backend;
967 if (!$result || $result->EOF) {
972 // Convert array to hash
974 $rec_num = $result->fields;
975 foreach ($this->_fields as $field) {
976 $rec_assoc[$field] = $rec_num[$i++];
978 // check if the cache can be populated here?
985 if ($this->_result) {
986 /* call mysql_free_result($this->_queryID) */
987 $this->_result->Close();
988 $this->_result = false;
993 class WikiDB_backend_ADODB_iter
994 extends WikiDB_backend_ADODB_generic_iter
997 $result = &$this->_result;
998 $backend = &$this->_backend;
999 if (!$result || $result->EOF) {
1004 // Convert array to hash
1006 $rec_num = $result->fields;
1007 foreach ($this->_fields as $field) {
1008 $rec_assoc[$field] = $rec_num[$i++];
1011 $result->MoveNext();
1012 if (isset($rec_assoc['pagedata']))
1013 $rec_assoc['pagedata'] = $backend->_extract_page_data($rec_assoc['pagedata'], $rec_assoc['hits']);
1014 if (!empty($rec_assoc['version'])) {
1015 $rec_assoc['versiondata'] = $backend->_extract_version_data_assoc($rec_assoc);
1021 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1022 // Eventually, change index.php to provide the relevant information
1025 * Parse a data source name.
1027 * Additional keys can be added by appending a URI query string to the
1030 * The format of the supplied DSN is in its fullest form:
1032 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1035 * Most variations are allowed:
1037 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1038 * phptype://username:password@hostspec/database_name
1039 * phptype://username:password@hostspec
1040 * phptype://username@hostspec
1041 * phptype://hostspec/database
1042 * phptype://hostspec
1047 * @param string $dsn Data Source Name to be parsed
1049 * @return array an associative array with the following keys:
1050 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1051 * + dbsyntax: Database used with regards to SQL syntax etc.
1052 * + protocol: Communication protocol to use (tcp, unix etc.)
1053 * + hostspec: Host specification (hostname[:port])
1054 * + database: Database to use on the DBMS server
1055 * + username: User name for login
1056 * + password: Password for login
1058 * @author Tomas V.V.Cox <cox@idecnet.com>
1060 function parseDSN($dsn)
1064 'dbsyntax' => false,
1065 'username' => false,
1066 'password' => false,
1067 'protocol' => false,
1068 'hostspec' => false,
1071 'database' => false,
1074 if (is_array($dsn)) {
1075 $dsn = array_merge($parsed, $dsn);
1076 if (!$dsn['dbsyntax']) {
1077 $dsn['dbsyntax'] = $dsn['phptype'];
1082 // Find phptype and dbsyntax
1083 if (($pos = strpos($dsn, '://')) !== false) {
1084 $str = substr($dsn, 0, $pos);
1085 $dsn = substr($dsn, $pos + 3);
1091 // Get phptype and dbsyntax
1092 // $str => phptype(dbsyntax)
1093 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1094 $parsed['phptype'] = $arr[1];
1095 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1097 $parsed['phptype'] = $str;
1098 $parsed['dbsyntax'] = $str;
1105 // Get (if found): username and password
1106 // $dsn => username:password@protocol+hostspec/database
1107 if (($at = strrpos($dsn,'@')) !== false) {
1108 $str = substr($dsn, 0, $at);
1109 $dsn = substr($dsn, $at + 1);
1110 if (($pos = strpos($str, ':')) !== false) {
1111 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1112 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1114 $parsed['username'] = rawurldecode($str);
1118 // Find protocol and hostspec
1120 // $dsn => proto(proto_opts)/database
1121 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1123 $proto_opts = $match[2] ? $match[2] : false;
1126 // $dsn => protocol+hostspec/database (old format)
1128 if (strpos($dsn, '+') !== false) {
1129 list($proto, $dsn) = explode('+', $dsn, 2);
1131 if (strpos($dsn, '/') !== false) {
1132 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1139 // process the different protocol options
1140 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1141 $proto_opts = rawurldecode($proto_opts);
1142 if ($parsed['protocol'] == 'tcp') {
1143 if (strpos($proto_opts, ':') !== false) {
1144 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1146 $parsed['hostspec'] = $proto_opts;
1148 } elseif ($parsed['protocol'] == 'unix') {
1149 $parsed['socket'] = $proto_opts;
1152 // Get dabase if any
1156 if (($pos = strpos($dsn, '?')) === false) {
1157 $parsed['database'] = $dsn;
1158 // /database?param1=value1¶m2=value2
1160 $parsed['database'] = substr($dsn, 0, $pos);
1161 $dsn = substr($dsn, $pos + 1);
1162 if (strpos($dsn, '&') !== false) {
1163 $opts = explode('&', $dsn);
1164 } else { // database?param1=value1
1165 $opts = array($dsn);
1167 foreach ($opts as $opt) {
1168 list($key, $value) = explode('=', $opt);
1169 if (!isset($parsed[$key])) {
1170 // don't allow params overwrite
1171 $parsed[$key] = rawurldecode($value);
1180 // $Log: not supported by cvs2svn $
1181 // Revision 1.47 2004/11/06 17:11:42 rurban
1182 // The optimized version doesn't query for pagedata anymore.
1184 // Revision 1.46 2004/11/01 10:43:58 rurban
1185 // seperate PassUser methods into seperate dir (memory usage)
1186 // fix WikiUser (old) overlarge data session
1187 // remove wikidb arg from various page class methods, use global ->_dbi instead
1190 // Revision 1.45 2004/10/14 17:19:17 rurban
1191 // allow most_popular sortby arguments
1193 // Revision 1.44 2004/09/06 08:33:09 rurban
1194 // force explicit mysql auto-incrementing, atomic version
1196 // Revision 1.43 2004/07/10 08:50:24 rurban
1197 // applied patch by Philippe Vanhaesendonck:
1198 // pass column list to iterators so we can FETCH_NUM in all cases.
1199 // bind UPDATE pramas for huge pagedata.
1200 // portable oracle backend
1202 // Revision 1.42 2004/07/09 10:06:50 rurban
1203 // Use backend specific sortby and sortable_columns method, to be able to
1204 // select between native (Db backend) and custom (PageList) sorting.
1205 // Fixed PageList::AddPageList (missed the first)
1206 // Added the author/creator.. name to AllPagesBy...
1207 // display no pages if none matched.
1208 // Improved dba and file sortby().
1209 // Use &$request reference
1211 // Revision 1.41 2004/07/08 21:32:35 rurban
1212 // Prevent from more warnings, minor db and sort optimizations
1214 // Revision 1.40 2004/07/08 16:56:16 rurban
1215 // use the backendType abstraction
1217 // Revision 1.39 2004/07/05 13:56:22 rurban
1218 // sqlite autoincrement fix
1220 // Revision 1.38 2004/07/05 12:57:54 rurban
1221 // add mysql timeout
1223 // Revision 1.37 2004/07/04 10:24:43 rurban
1224 // forgot the expressions
1226 // Revision 1.36 2004/07/03 16:51:06 rurban
1227 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1228 // added atomic mysql REPLACE for PearDB as in ADODB
1229 // fixed _lock_tables typo links => link
1230 // fixes unserialize ADODB bug in line 180
1232 // Revision 1.35 2004/06/28 14:45:12 rurban
1233 // fix adodb_sqlite to have the same dsn syntax as pear, use pconnect if requested
1235 // Revision 1.34 2004/06/28 14:17:38 rurban
1236 // updated DSN parser from Pear. esp. for sqlite
1238 // Revision 1.33 2004/06/27 10:26:02 rurban
1239 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1241 // Revision 1.32 2004/06/25 14:15:08 rurban
1242 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1244 // Revision 1.31 2004/06/16 10:38:59 rurban
1245 // Disallow refernces in calls if the declaration is a reference
1246 // ("allow_call_time_pass_reference clean").
1247 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1248 // but several external libraries may not.
1249 // In detail these libs look to be affected (not tested):
1253 // Revision 1.30 2004/06/07 19:31:31 rurban
1254 // fixed ADOOB upgrade: listOfFields()
1256 // Revision 1.29 2004/05/12 10:49:55 rurban
1257 // require_once fix for those libs which are loaded before FileFinder and
1258 // its automatic include_path fix, and where require_once doesn't grok
1259 // dirname(__FILE__) != './lib'
1260 // upgrade fix with PearDB
1261 // navbar.tmpl: remove spaces for IE button alignment
1263 // Revision 1.28 2004/05/06 19:26:16 rurban
1264 // improve stability, trying to find the InlineParser endless loop on sf.net
1266 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1268 // Revision 1.27 2004/05/06 17:30:38 rurban
1269 // CategoryGroup: oops, dos2unix eol
1270 // improved phpwiki_version:
1271 // pre -= .0001 (1.3.10pre: 1030.099)
1272 // -p1 += .001 (1.3.9-p1: 1030.091)
1273 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1274 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1275 // backend->backendType(), backend->database(),
1276 // backend->listOfFields(),
1277 // backend->listOfTables(),
1279 // Revision 1.26 2004/04/26 20:44:35 rurban
1280 // locking table specific for better databases
1282 // Revision 1.25 2004/04/20 00:06:04 rurban
1283 // themable paging support
1285 // Revision 1.24 2004/04/18 01:34:20 rurban
1286 // protect most_popular from sortby=mtime
1288 // Revision 1.23 2004/04/16 14:19:39 rurban
1289 // updated ADODB notes
1292 // (c-file-style: "gnu")
1296 // c-basic-offset: 4
1297 // c-hanging-comment-ender-p: nil
1298 // indent-tabs-mode: nil