2 rcs_id('$Id: ADODB.php,v 1.59 2004-11-27 14:39:05 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");
173 function increaseHitCount($pagename) {
175 // Hits is the only thing we can update in a fast manner.
176 // Note that this will fail silently if the page does not
177 // have a record in the page table. Since it's just the
178 // hit count, who cares?
179 $dbh->Execute(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename=%s LIMIT 1",
180 $this->_table_names['page_tbl'],
181 $dbh->qstr($pagename)));
186 * Read page information from database.
188 function get_pagedata($pagename) {
190 $row = $dbh->GetRow(sprintf("SELECT id,pagename,hits,pagedata FROM %s WHERE pagename=%s",
191 $this->_table_names['page_tbl'],
192 $dbh->qstr($pagename)));
193 return $row ? $this->_extract_page_data($row[3], $row[2]) : false;
196 function _extract_page_data($data, $hits) {
197 if (empty($data)) return array();
198 else return array_merge(array('hits' => $hits), $this->_unserialize($data));
201 function update_pagedata($pagename, $newdata) {
203 $page_tbl = $this->_table_names['page_tbl'];
205 // Hits is the only thing we can update in a fast manner.
206 if (count($newdata) == 1 && isset($newdata['hits'])) {
207 // Note that this will fail silently if the page does not
208 // have a record in the page table. Since it's just the
209 // hit count, who cares?
210 $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
211 $newdata['hits'], $dbh->qstr($pagename)));
214 $where = sprintf("pagename=%s",$dbh->qstr($pagename));
216 $dbh->RowLock($page_tbl,$where);
218 $data = $this->get_pagedata($pagename);
221 $this->_get_pageid($pagename, true); // Creates page record
224 @$hits = (int)$data['hits'];
225 unset($data['hits']);
227 foreach ($newdata as $key => $val) {
230 else if (empty($val))
235 if ($dbh->Execute("UPDATE $page_tbl"
236 . " SET hits=?, pagedata=?"
237 . " WHERE pagename=?",
238 array($hits, $this->_serialize($data),$pagename)))
239 $dbh->CommitTrans( );
241 $dbh->RollbackTrans( );
244 function _get_pageid($pagename, $create_if_missing = false) {
248 $cache =& $request->_dbi->_cache->_id_cache;
249 if (isset($cache[$pagename])) return $cache[$pagename];
252 $page_tbl = $this->_table_names['page_tbl'];
253 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
254 $dbh->qstr($pagename));
255 if (! $create_if_missing ) {
256 $row = $dbh->GetRow($query);
257 return $row ? $row[0] : false;
259 $row = $dbh->GetRow($query);
261 //mysql, mysqli or mysqlt
262 if (substr($dbh->databaseType,0,5) == 'mysql') {
263 // have auto-incrementing, atomic version
264 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
266 . " VALUES(NULL,%s)",
267 $dbh->qstr($pagename)));
268 $id = $dbh->_insertid();
270 //$id = $dbh->GenID($page_tbl . 'seq');
271 // Better generic version than with adodob::genID
272 //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1
273 $this->lock(array('page'));
275 $dbh->CommitLock($page_tbl);
276 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
278 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
279 . " (id,pagename,hits)"
280 . " VALUES (%d,%s,0)",
281 $id, $dbh->qstr($pagename)));
282 if ($rs) $dbh->CommitTrans( );
283 else $dbh->RollbackTrans( );
284 $this->unlock(array('page'));
292 function get_latest_version($pagename) {
294 extract($this->_table_names);
295 $row = $dbh->GetRow(sprintf("SELECT latestversion"
296 . " FROM $page_tbl, $recent_tbl"
297 . " WHERE $page_tbl.id=$recent_tbl.id"
298 . " AND pagename=%s",
299 $dbh->qstr($pagename)));
300 return $row ? (int)$row[0] : false;
303 function get_previous_version($pagename, $version) {
305 extract($this->_table_names);
306 // Use SELECTLIMIT for maximum portability
307 $rs = $dbh->SelectLimit(sprintf("SELECT version"
308 . " FROM $version_tbl, $page_tbl"
309 . " WHERE $version_tbl.id=$page_tbl.id"
311 . " AND version < %d"
312 . " ORDER BY version DESC"
313 ,$dbh->qstr($pagename),
316 return $rs->fields ? (int)$rs->fields[0] : false;
322 * @param $version int Which version to get.
324 * @return hash The version data, or false if specified version does not
327 function get_versiondata($pagename, $version, $want_content = false) {
329 extract($this->_table_names);
330 extract($this->_expressions);
332 assert(is_string($pagename) and $pagename != '');
333 assert($version > 0);
335 // FIXME: optimization: sometimes don't get page data?
337 $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
338 . ', ' . $this->version_tbl_fields;
340 $fields = $this->page_tbl_fields . ", '' AS pagedata"
341 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
342 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
343 . "$version_tbl.versiondata as versiondata";
345 $row = $dbh->GetRow(sprintf("SELECT $fields"
346 . " FROM $page_tbl, $version_tbl"
347 . " WHERE $page_tbl.id=$version_tbl.id"
350 $dbh->qstr($pagename), $version));
351 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
354 function _extract_version_data_num($row, $want_content) {
359 //$pagename &= $row[1];
360 $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
361 $data['mtime'] = $row[5];
362 $data['is_minor_edit'] = !empty($row[6]);
364 $data['%content'] = $row[7];
366 $data['%content'] = !empty($row[7]);
368 if (!empty($row[3])) {
369 $data['%pagedata'] = $this->_extract_page_data($row[3],$row[2]);
374 function _extract_version_data_assoc($row) {
379 $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
380 $data['mtime'] = $mtime;
381 $data['is_minor_edit'] = !empty($minor_edit);
383 $data['%content'] = $content;
384 elseif ($have_content)
385 $data['%content'] = true;
387 $data['%content'] = '';
388 if (!empty($pagedata)) {
389 $data['%pagedata'] = $this->_extract_page_data($pagedata,$hits);
395 * Create a new revision of a page.
397 function set_versiondata($pagename, $version, $data) {
399 $version_tbl = $this->_table_names['version_tbl'];
401 $minor_edit = (int) !empty($data['is_minor_edit']);
402 unset($data['is_minor_edit']);
404 $mtime = (int)$data['mtime'];
405 unset($data['mtime']);
406 assert(!empty($mtime));
408 @$content = (string) $data['%content'];
409 unset($data['%content']);
410 unset($data['%pagedata']);
412 $this->lock(array('page','recent','version','nonempty'));
414 $dbh->CommitLock($version_tbl);
415 $id = $this->_get_pageid($pagename, true);
416 $backend_type = $this->backendType();
417 // optimize: mysql can do this with one REPLACE INTO.
418 if (substr($backend_type,0,5) == 'mysql') {
419 $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl"
420 . " (id,version,mtime,minor_edit,content,versiondata)"
421 . " VALUES(%d,%d,%d,%d,%s,%s)",
422 $id, $version, $mtime, $minor_edit,
423 $dbh->qstr($content),
424 $dbh->qstr($this->_serialize($data))));
426 $dbh->Execute(sprintf("DELETE FROM $version_tbl"
427 . " WHERE id=%d AND version=%d",
429 $rs = $dbh->Execute("INSERT INTO $version_tbl"
430 . " (id,version,mtime,minor_edit,content,versiondata)"
431 . " VALUES(?,?,?,?,?,?)",
432 array($id, $version, $mtime, $minor_edit,
433 $content, $this->_serialize($data)));
435 $this->_update_recent_table($id);
436 $this->_update_nonempty_table($id);
437 if ($rs) $dbh->CommitTrans( );
438 else $dbh->RollbackTrans( );
439 $this->unlock(array('page','recent','version','nonempty'));
443 * Delete an old revision of a page.
445 function delete_versiondata($pagename, $version) {
447 extract($this->_table_names);
449 $this->lock(array('version'));
450 if ( ($id = $this->_get_pageid($pagename)) ) {
451 $dbh->Execute("DELETE FROM $version_tbl"
452 . " WHERE id=$id AND version=$version");
453 $this->_update_recent_table($id);
454 // This shouldn't be needed (as long as the latestversion
455 // never gets deleted.) But, let's be safe.
456 $this->_update_nonempty_table($id);
458 $this->unlock(array('version'));
462 * Delete page from the database.
464 function delete_page($pagename) {
466 extract($this->_table_names);
468 $this->lock(array('version','recent','nonempty','page','link'));
469 if ( ($id = $this->_get_pageid($pagename, false)) ) {
470 $dbh->Execute("DELETE FROM $version_tbl WHERE id=$id");
471 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id");
472 $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
473 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$id");
474 $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
475 if ($row and $row[0]) {
476 // We're still in the link table (dangling link) so we can't delete this
478 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
481 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
483 $this->_update_recent_table();
484 $this->_update_nonempty_table();
486 $this->unlock(array('version','recent','nonempty','page','link'));
490 // The only thing we might be interested in updating which we can
491 // do fast in the flags (minor_edit). I think the default
492 // update_versiondata will work fine...
493 //function update_versiondata($pagename, $version, $data) {
496 function set_links($pagename, $links) {
497 // Update link table.
498 // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
501 extract($this->_table_names);
503 $this->lock(array('link'));
504 $pageid = $this->_get_pageid($pagename, true);
506 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
509 foreach($links as $link) {
510 if (isset($linkseen[$link]))
512 $linkseen[$link] = true;
513 $linkid = $this->_get_pageid($link, true);
514 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
515 . " VALUES ($pageid, $linkid)");
518 $this->unlock(array('link'));
522 * Find pages which link to or are linked from a page.
524 * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
525 * (linkExistingWikiWord or linkUnknownWikiWord)
526 * This is called on every page header GleanDescription, so we can store all the existing links.
528 function get_links($pagename, $reversed=true, $include_empty=false,
529 $sortby=false, $limit=false, $exclude='') {
531 extract($this->_table_names);
534 list($have,$want) = array('linkee', 'linker');
536 list($have,$want) = array('linker', 'linkee');
537 $orderby = $this->sortby($sortby, 'db', array('pagename'));
538 if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
539 if ($exclude) // array of pagenames
540 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
544 $qpagename = $dbh->qstr($pagename);
545 // removed ref to FETCH_MODE in next line
546 $result = $dbh->Execute("SELECT $want.id AS id, $want.pagename AS pagename,"
547 . " $want.hits AS hits"
548 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
549 . (!$include_empty ? ", $nonempty_tbl" : '')
550 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
551 . " AND $have.pagename=$qpagename"
552 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
553 //. " GROUP BY $want.id"
556 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
559 function get_all_pages($include_empty=false, $sortby=false, $limit=false, $exclude='') {
561 extract($this->_table_names);
562 $orderby = $this->sortby($sortby, 'db');
563 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
564 if ($exclude) // array of pagenames
565 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
569 //$dbh->SetFetchMode(ADODB_FETCH_ASSOC);
570 if (strstr($orderby, 'mtime ')) { // was ' mtime'
571 if ($include_empty) {
573 . $this->page_tbl_fields
574 ." FROM $page_tbl, $recent_tbl, $version_tbl"
575 . " WHERE $page_tbl.id=$recent_tbl.id"
576 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
582 . $this->page_tbl_fields
583 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
584 . " WHERE $nonempty_tbl.id=$page_tbl.id"
585 . " AND $page_tbl.id=$recent_tbl.id"
586 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
591 if ($include_empty) {
593 . $this->page_tbl_fields
595 . $exclude ? " WHERE $exclude" : ''
599 . $this->page_tbl_fields
600 . " FROM $nonempty_tbl, $page_tbl"
601 . " WHERE $nonempty_tbl.id=$page_tbl.id"
607 // extract from,count from limit
608 list($offset,$count) = $this->limit($limit);
609 $result = $dbh->SelectLimit($sql, $count, $offset);
611 $result = $dbh->Execute($sql);
613 //$dbh->SetFetchMode(ADODB_FETCH_NUM);
614 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
620 function text_search($search, $fullsearch=false) {
622 extract($this->_table_names);
624 $table = "$nonempty_tbl, $page_tbl";
625 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
626 $fields = $this->page_tbl_fields;
627 $field_list = $this->page_tbl_field_list;
628 $searchobj = new WikiDB_backend_ADODB_search($search, $dbh);
631 $table .= ", $recent_tbl";
632 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
634 $table .= ", $version_tbl";
635 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
637 $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
638 $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
639 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
641 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
644 $search_clause = $search->makeSqlClauseObj($callback);
645 $result = $dbh->Execute("SELECT $fields FROM $table"
646 . " WHERE $join_clause"
647 . " AND ($search_clause)"
648 . " ORDER BY pagename");
649 return new WikiDB_backend_ADODB_iter($this, $result, $field_list);
652 function _sql_match_clause($word) {
653 //not sure if we need this. ADODB may do it for us
654 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
656 // (we need it for at least % and _ --- they're the wildcard characters
657 // for the LIKE operator, and we need to quote them if we're searching
658 // for literal '%'s or '_'s. --- I'm not sure about \, but it seems to
660 $word = $this->_dbh->qstr("%".strtolower($word)."%");
661 $page_tbl = $this->_table_names['page_tbl'];
662 return "LOWER($page_tbl.pagename) LIKE $word";
664 function _fullsearch_sql_match_clause($word) {
665 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); //not sure if we need this
667 $word = $this->_dbh->qstr("%".strtolower($word)."%");
668 $page_tbl = $this->_table_names['page_tbl'];
669 return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
674 * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
675 * not sets. See above, but the above methods find too much.
676 * This is only for already resolved wildcards:
677 * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
679 function _sql_set(&$pagenames) {
681 foreach ($pagenames as $p) {
682 $s .= ($this->_dbh->qstr($p).",");
684 return substr($s,0,-1).")";
688 * Find highest or lowest hit counts.
690 function most_popular($limit=0, $sortby='-hits') {
692 extract($this->_table_names);
699 $where = " AND hits > 0";
701 if ($sortby != '-hits') {
702 if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order;
705 $orderby = " ORDER BY hits $order";
706 $limit = $limit ? $limit : -1;
708 $result = $dbh->SelectLimit("SELECT "
709 . $this->page_tbl_fields
710 . " FROM $nonempty_tbl, $page_tbl"
711 . " WHERE $nonempty_tbl.id=$page_tbl.id"
714 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
718 * Find recent changes.
720 function most_recent($params) {
723 $include_minor_revisions = false;
724 $exclude_major_revisions = false;
725 $include_all_revisions = false;
729 extract($this->_table_names);
733 $pick[] = "mtime >= $since";
735 if ($include_all_revisions) {
736 // Include all revisions of each page.
737 $table = "$page_tbl, $version_tbl";
738 $join_clause = "$page_tbl.id=$version_tbl.id";
740 if ($exclude_major_revisions) {
741 // Include only minor revisions
742 $pick[] = "minor_edit <> 0";
744 elseif (!$include_minor_revisions) {
745 // Include only major revisions
746 $pick[] = "minor_edit = 0";
750 $table = "$page_tbl, $recent_tbl";
751 $join_clause = "$page_tbl.id=$recent_tbl.id";
752 $table .= ", $version_tbl";
753 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
755 if ($exclude_major_revisions) {
756 // Include only most recent minor revision
757 $pick[] = 'version=latestminor';
759 elseif (!$include_minor_revisions) {
760 // Include only most recent major revision
761 $pick[] = 'version=latestmajor';
764 // Include only the latest revision (whether major or minor).
765 $pick[] ='version=latestversion';
773 $limit = $limit ? $limit : -1;
774 $where_clause = $join_clause;
776 $where_clause .= " AND " . join(" AND ", $pick);
778 // FIXME: use SQL_BUFFER_RESULT for mysql?
779 // Use SELECTLIMIT for portability
780 $result = $dbh->SelectLimit("SELECT "
781 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
783 . " WHERE $where_clause"
784 . " ORDER BY mtime $order",
786 //$result->fields['version'] = $result->fields[6];
787 return new WikiDB_backend_ADODB_iter($this, $result,
788 array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
792 * Find referenced empty pages.
794 function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
796 extract($this->_table_names);
797 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
798 $orderby = 'ORDER BY ' . $orderby;
800 if ($exclude_from) // array of pagenames
801 $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
802 if ($exclude) // array of pagenames
803 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
805 $limit = $limit ? $limit : -1;
807 all empty pages, independent of linkstatus:
808 select pagename as empty from page left join nonempty using(id) where isnull(nonempty.id);
809 only all empty pages, which have a linkto:
810 select page.pagename, linked.pagename as wantedfrom from link, page as linked
811 left join page on(link.linkto=page.id) left join nonempty on(link.linkto=nonempty.id)
812 where isnull(nonempty.id) and linked.id=link.linkfrom;
814 $sql = "SELECT $page_tbl.pagename,linked.pagename as wantedfrom"
815 . " FROM $link_tbl,$page_tbl as linked "
816 . " LEFT JOIN $page_tbl ON($link_tbl.linkto=$page_tbl.id)"
817 . " LEFT JOIN $nonempty_tbl ON($link_tbl.linkto=$nonempty_tbl.id)"
818 . " WHERE ISNULL($nonempty_tbl.id) AND linked.id=$link_tbl.linkfrom"
822 $result = $dbh->SelectLimit($sql, $limit);
823 return new WikiDB_backend_ADODB_iter($this, $result, array('pagename','wantedfrom'));
827 * Rename page in the database.
829 function rename_page($pagename, $to) {
831 extract($this->_table_names);
833 $this->lock(array('page'));
834 if ( ($id = $this->_get_pageid($pagename, false)) ) {
835 if ($new = $this->_get_pageid($to, false)) {
837 //this page does not exist (already verified before), but exists in the page table.
838 //so we delete this page.
839 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
842 $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
845 $this->unlock(array('page'));
849 function _update_recent_table($pageid = false) {
851 extract($this->_table_names);
852 extract($this->_expressions);
854 $pageid = (int)$pageid;
856 // optimize: mysql can do this with one REPLACE INTO.
857 $backend_type = $this->backendType();
858 if (substr($backend_type,0,5) == 'mysql') {
859 $dbh->Execute("REPLACE INTO $recent_tbl"
860 . " (id, latestversion, latestmajor, latestminor)"
861 . " SELECT id, $maxversion, $maxmajor, $maxminor"
862 . " FROM $version_tbl"
863 . ( $pageid ? " WHERE id=$pageid" : "")
866 $this->lock(array('recent'));
867 $dbh->Execute("DELETE FROM $recent_tbl"
868 . ( $pageid ? " WHERE id=$pageid" : ""));
869 $dbh->Execute( "INSERT INTO $recent_tbl"
870 . " (id, latestversion, latestmajor, latestminor)"
871 . " SELECT id, $maxversion, $maxmajor, $maxminor"
872 . " FROM $version_tbl"
873 . ( $pageid ? " WHERE id=$pageid" : "")
875 $this->unlock(array('recent'));
879 function _update_nonempty_table($pageid = false) {
881 extract($this->_table_names);
882 extract($this->_expressions);
884 $pageid = (int)$pageid;
886 // Optimize: mysql can do this with one REPLACE INTO.
887 // FIXME: This treally should be moved into ADODB_mysql.php but
888 // then it must be duplicated for mysqli and mysqlt also.
889 $backend_type = $this->backendType();
890 if (substr($backend_type,0,5) == 'mysql') {
891 $dbh->Execute("REPLACE INTO $nonempty_tbl (id)"
892 . " SELECT $recent_tbl.id"
893 . " FROM $recent_tbl, $version_tbl"
894 . " WHERE $recent_tbl.id=$version_tbl.id"
895 . " AND version=latestversion"
896 // We have some specifics here (Oracle)
897 // . " AND content<>''"
898 . " AND content $notempty"
899 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
901 extract($this->_expressions);
902 $this->lock(array('nonempty'));
903 $dbh->Execute("DELETE FROM $nonempty_tbl"
904 . ( $pageid ? " WHERE id=$pageid" : ""));
905 $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
906 . " SELECT $recent_tbl.id"
907 . " FROM $recent_tbl, $version_tbl"
908 . " WHERE $recent_tbl.id=$version_tbl.id"
909 . " AND version=latestversion"
910 // We have some specifics here (Oracle)
911 //. " AND content<>''"
912 . " AND content $notempty"
913 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
914 $this->unlock(array('nonempty'));
920 * Grab a write lock on the tables in the SQL database.
922 * Calls can be nested. The tables won't be unlocked until
923 * _unlock_database() is called as many times as _lock_database().
927 function lock($tables, $write_lock = true) {
928 $this->_dbh->StartTrans();
929 if ($this->_lock_count++ == 0) {
930 $this->_current_lock = $tables;
931 $this->_lock_tables($tables, $write_lock);
936 * Overridden by non-transaction safe backends.
938 function _lock_tables($tables, $write_lock) {
939 return $this->_current_lock;
943 * Release a write lock on the tables in the SQL database.
947 * @param $force boolean Unlock even if not every call to lock() has been matched
948 * by a call to unlock().
950 * @see _lock_database
952 function unlock($tables = false, $force = false) {
953 if ($this->_lock_count == 0) {
954 $this->_dbh->CompleteTrans(! $force);
955 $this->_current_lock = false;
958 if (--$this->_lock_count <= 0 || $force) {
959 $this->_unlock_tables($tables);
960 $this->_current_lock = false;
961 $this->_lock_count = 0;
963 $this->_dbh->CompleteTrans(! $force);
967 * overridden by non-transaction safe backends
969 function _unlock_tables($tables, $write_lock) {
976 function _serialize($data) {
979 assert(is_array($data));
980 return serialize($data);
986 function _unserialize($data) {
987 return empty($data) ? array() : unserialize($data);
990 /* some variables and functions for DB backend abstraction (action=upgrade) */
991 function database () {
992 return $this->_dbh->database;
994 function backendType() {
995 return $this->_dbh->databaseType;
997 function connection() {
998 return $this->_dbh->_connectionID;
1001 function listOfTables() {
1002 return $this->_dbh->MetaTables();
1004 function listOfFields($database,$table) {
1005 $field_list = array();
1006 foreach ($this->_dbh->MetaColumns($table,false) as $field) {
1007 $field_list[] = $field->name;
1014 class WikiDB_backend_ADODB_generic_iter
1015 extends WikiDB_backend_iterator
1017 function WikiDB_backend_ADODB_generic_iter($backend, $query_result, $field_list = NULL) {
1018 $this->_backend = &$backend;
1019 $this->_result = $query_result;
1021 if (is_null($field_list)) {
1022 // No field list passed, retrieve from DB
1023 // WikiLens is using the iterator behind the scene
1024 $field_list = array();
1025 $fields = $query_result->FieldCount();
1026 for ($i = 0; $i < $fields ; $i++) {
1027 $field_info = $query_result->FetchField($i);
1028 array_push($field_list, $field_info->name);
1032 $this->_fields = $field_list;
1036 if (!$this->_result) {
1039 $count = $this->_result->numRows();
1040 //$this->_result->Close();
1045 $result = &$this->_result;
1046 $backend = &$this->_backend;
1047 if (!$result || $result->EOF) {
1052 // Convert array to hash
1054 $rec_num = $result->fields;
1055 foreach ($this->_fields as $field) {
1056 $rec_assoc[$field] = $rec_num[$i++];
1058 // check if the cache can be populated here?
1060 $result->MoveNext();
1065 if ($this->_result) {
1066 /* call mysql_free_result($this->_queryID) */
1067 $this->_result->Close();
1068 $this->_result = false;
1073 class WikiDB_backend_ADODB_iter
1074 extends WikiDB_backend_ADODB_generic_iter
1077 $result = &$this->_result;
1078 $backend = &$this->_backend;
1079 if (!$result || $result->EOF) {
1084 // Convert array to hash
1086 $rec_num = $result->fields;
1087 foreach ($this->_fields as $field) {
1088 $rec_assoc[$field] = $rec_num[$i++];
1091 $result->MoveNext();
1092 if (isset($rec_assoc['pagedata']))
1093 $rec_assoc['pagedata'] = $backend->_extract_page_data($rec_assoc['pagedata'], $rec_assoc['hits']);
1094 if (!empty($rec_assoc['version'])) {
1095 $rec_assoc['versiondata'] = $backend->_extract_version_data_assoc($rec_assoc);
1101 class WikiDB_backend_ADODB_search
1102 extends WikiDB_backend_search
1104 function WikiDB_backend_ADODB_search(&$search, &$dbh) {
1105 $this->_dbh =& $dbh;
1106 $this->_case_exact = $search->_case_exact;
1108 function _pagename_match_clause($node) {
1109 $word = $node->sql($word);
1110 return $this->_case_exact
1111 ? "pagename LIKE '$word'"
1112 : "LOWER(pagename) LIKE '$word'";
1114 function _fulltext_match_clause($node) {
1115 $word = $node->sql($word);
1116 return $this->_case_exact
1117 ? "pagename LIKE '$word' OR content LIKE '$word'"
1118 : "LOWER(pagename) LIKE '$word' OR content LIKE '$word'";
1122 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1123 // Eventually, change index.php to provide the relevant information
1126 * Parse a data source name.
1128 * Additional keys can be added by appending a URI query string to the
1131 * The format of the supplied DSN is in its fullest form:
1133 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1136 * Most variations are allowed:
1138 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1139 * phptype://username:password@hostspec/database_name
1140 * phptype://username:password@hostspec
1141 * phptype://username@hostspec
1142 * phptype://hostspec/database
1143 * phptype://hostspec
1148 * @param string $dsn Data Source Name to be parsed
1150 * @return array an associative array with the following keys:
1151 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1152 * + dbsyntax: Database used with regards to SQL syntax etc.
1153 * + protocol: Communication protocol to use (tcp, unix etc.)
1154 * + hostspec: Host specification (hostname[:port])
1155 * + database: Database to use on the DBMS server
1156 * + username: User name for login
1157 * + password: Password for login
1159 * @author Tomas V.V.Cox <cox@idecnet.com>
1161 function parseDSN($dsn)
1165 'dbsyntax' => false,
1166 'username' => false,
1167 'password' => false,
1168 'protocol' => false,
1169 'hostspec' => false,
1172 'database' => false,
1175 if (is_array($dsn)) {
1176 $dsn = array_merge($parsed, $dsn);
1177 if (!$dsn['dbsyntax']) {
1178 $dsn['dbsyntax'] = $dsn['phptype'];
1183 // Find phptype and dbsyntax
1184 if (($pos = strpos($dsn, '://')) !== false) {
1185 $str = substr($dsn, 0, $pos);
1186 $dsn = substr($dsn, $pos + 3);
1192 // Get phptype and dbsyntax
1193 // $str => phptype(dbsyntax)
1194 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1195 $parsed['phptype'] = $arr[1];
1196 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1198 $parsed['phptype'] = $str;
1199 $parsed['dbsyntax'] = $str;
1206 // Get (if found): username and password
1207 // $dsn => username:password@protocol+hostspec/database
1208 if (($at = strrpos($dsn,'@')) !== false) {
1209 $str = substr($dsn, 0, $at);
1210 $dsn = substr($dsn, $at + 1);
1211 if (($pos = strpos($str, ':')) !== false) {
1212 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1213 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1215 $parsed['username'] = rawurldecode($str);
1219 // Find protocol and hostspec
1221 // $dsn => proto(proto_opts)/database
1222 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1224 $proto_opts = $match[2] ? $match[2] : false;
1227 // $dsn => protocol+hostspec/database (old format)
1229 if (strpos($dsn, '+') !== false) {
1230 list($proto, $dsn) = explode('+', $dsn, 2);
1232 if (strpos($dsn, '/') !== false) {
1233 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1240 // process the different protocol options
1241 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1242 $proto_opts = rawurldecode($proto_opts);
1243 if ($parsed['protocol'] == 'tcp') {
1244 if (strpos($proto_opts, ':') !== false) {
1245 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1247 $parsed['hostspec'] = $proto_opts;
1249 } elseif ($parsed['protocol'] == 'unix') {
1250 $parsed['socket'] = $proto_opts;
1253 // Get dabase if any
1257 if (($pos = strpos($dsn, '?')) === false) {
1258 $parsed['database'] = $dsn;
1259 // /database?param1=value1¶m2=value2
1261 $parsed['database'] = substr($dsn, 0, $pos);
1262 $dsn = substr($dsn, $pos + 1);
1263 if (strpos($dsn, '&') !== false) {
1264 $opts = explode('&', $dsn);
1265 } else { // database?param1=value1
1266 $opts = array($dsn);
1268 foreach ($opts as $opt) {
1269 list($key, $value) = explode('=', $opt);
1270 if (!isset($parsed[$key])) {
1271 // don't allow params overwrite
1272 $parsed[$key] = rawurldecode($value);
1281 // $Log: not supported by cvs2svn $
1282 // Revision 1.58 2004/11/26 18:39:02 rurban
1283 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1285 // Revision 1.57 2004/11/25 17:20:51 rurban
1286 // and again a couple of more native db args: backlinks
1288 // Revision 1.56 2004/11/23 13:35:48 rurban
1289 // add case_exact search
1291 // Revision 1.55 2004/11/21 11:59:26 rurban
1292 // remove final \n to be ob_cache independent
1294 // Revision 1.54 2004/11/20 17:49:39 rurban
1295 // add fast exclude support to SQL get_all_pages
1297 // Revision 1.53 2004/11/20 17:35:58 rurban
1298 // improved WantedPages SQL backends
1299 // PageList::sortby new 3rd arg valid_fields (override db fields)
1300 // WantedPages sql pager inexact for performance reasons:
1301 // assume 3 wantedfrom per page, to be correct, no getTotal()
1302 // support exclude argument for get_all_pages, new _sql_set()
1304 // Revision 1.52 2004/11/17 20:07:17 rurban
1307 // Revision 1.51 2004/11/15 15:57:37 rurban
1308 // silent cache warning
1310 // Revision 1.50 2004/11/10 19:32:23 rurban
1311 // * optimize increaseHitCount, esp. for mysql.
1312 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
1313 // * Pear_DB version logic (awful but needed)
1314 // * fix broken ADODB quote
1315 // * _extract_page_data simplification
1317 // Revision 1.49 2004/11/10 15:29:21 rurban
1318 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1319 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1320 // * WikiDB: moved SQL specific methods upwards
1321 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1322 // fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1324 // Revision 1.48 2004/11/09 17:11:16 rurban
1325 // * revert to the wikidb ref passing. there's no memory abuse there.
1326 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1327 // store page ids with getPageLinks (GleanDescription) of all existing pages, which
1328 // are also needed at the rendering for linkExistingWikiWord().
1329 // pass options to pageiterator.
1330 // use this cache also for _get_pageid()
1331 // This saves about 8 SELECT count per page (num all pagelinks).
1332 // * fix passing of all page fields to the pageiterator.
1333 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1335 // Revision 1.47 2004/11/06 17:11:42 rurban
1336 // The optimized version doesn't query for pagedata anymore.
1338 // Revision 1.46 2004/11/01 10:43:58 rurban
1339 // seperate PassUser methods into seperate dir (memory usage)
1340 // fix WikiUser (old) overlarge data session
1341 // remove wikidb arg from various page class methods, use global ->_dbi instead
1344 // Revision 1.45 2004/10/14 17:19:17 rurban
1345 // allow most_popular sortby arguments
1347 // Revision 1.44 2004/09/06 08:33:09 rurban
1348 // force explicit mysql auto-incrementing, atomic version
1350 // Revision 1.43 2004/07/10 08:50:24 rurban
1351 // applied patch by Philippe Vanhaesendonck:
1352 // pass column list to iterators so we can FETCH_NUM in all cases.
1353 // bind UPDATE pramas for huge pagedata.
1354 // portable oracle backend
1356 // Revision 1.42 2004/07/09 10:06:50 rurban
1357 // Use backend specific sortby and sortable_columns method, to be able to
1358 // select between native (Db backend) and custom (PageList) sorting.
1359 // Fixed PageList::AddPageList (missed the first)
1360 // Added the author/creator.. name to AllPagesBy...
1361 // display no pages if none matched.
1362 // Improved dba and file sortby().
1363 // Use &$request reference
1365 // Revision 1.41 2004/07/08 21:32:35 rurban
1366 // Prevent from more warnings, minor db and sort optimizations
1368 // Revision 1.40 2004/07/08 16:56:16 rurban
1369 // use the backendType abstraction
1371 // Revision 1.39 2004/07/05 13:56:22 rurban
1372 // sqlite autoincrement fix
1374 // Revision 1.38 2004/07/05 12:57:54 rurban
1375 // add mysql timeout
1377 // Revision 1.37 2004/07/04 10:24:43 rurban
1378 // forgot the expressions
1380 // Revision 1.36 2004/07/03 16:51:06 rurban
1381 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1382 // added atomic mysql REPLACE for PearDB as in ADODB
1383 // fixed _lock_tables typo links => link
1384 // fixes unserialize ADODB bug in line 180
1386 // Revision 1.35 2004/06/28 14:45:12 rurban
1387 // fix adodb_sqlite to have the same dsn syntax as pear, use pconnect if requested
1389 // Revision 1.34 2004/06/28 14:17:38 rurban
1390 // updated DSN parser from Pear. esp. for sqlite
1392 // Revision 1.33 2004/06/27 10:26:02 rurban
1393 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1395 // Revision 1.32 2004/06/25 14:15:08 rurban
1396 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1398 // Revision 1.31 2004/06/16 10:38:59 rurban
1399 // Disallow refernces in calls if the declaration is a reference
1400 // ("allow_call_time_pass_reference clean").
1401 // PhpWiki is now allow_call_time_pass_reference = Off clean,
1402 // but several external libraries may not.
1403 // In detail these libs look to be affected (not tested):
1407 // Revision 1.30 2004/06/07 19:31:31 rurban
1408 // fixed ADOOB upgrade: listOfFields()
1410 // Revision 1.29 2004/05/12 10:49:55 rurban
1411 // require_once fix for those libs which are loaded before FileFinder and
1412 // its automatic include_path fix, and where require_once doesn't grok
1413 // dirname(__FILE__) != './lib'
1414 // upgrade fix with PearDB
1415 // navbar.tmpl: remove spaces for IE button alignment
1417 // Revision 1.28 2004/05/06 19:26:16 rurban
1418 // improve stability, trying to find the InlineParser endless loop on sf.net
1420 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1422 // Revision 1.27 2004/05/06 17:30:38 rurban
1423 // CategoryGroup: oops, dos2unix eol
1424 // improved phpwiki_version:
1425 // pre -= .0001 (1.3.10pre: 1030.099)
1426 // -p1 += .001 (1.3.9-p1: 1030.091)
1427 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1428 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1429 // backend->backendType(), backend->database(),
1430 // backend->listOfFields(),
1431 // backend->listOfTables(),
1433 // Revision 1.26 2004/04/26 20:44:35 rurban
1434 // locking table specific for better databases
1436 // Revision 1.25 2004/04/20 00:06:04 rurban
1437 // themable paging support
1439 // Revision 1.24 2004/04/18 01:34:20 rurban
1440 // protect most_popular from sortby=mtime
1442 // Revision 1.23 2004/04/16 14:19:39 rurban
1443 // updated ADODB notes
1446 // (c-file-style: "gnu")
1450 // c-basic-offset: 4
1451 // c-hanging-comment-ender-p: nil
1452 // indent-tabs-mode: nil