2 // $Id: PearDB_ffpgsql.php 7957 2011-03-03 17:38:22Z vargenau $
5 * Copyright (C) 2001-2009 $ThePhpWikiProgrammingTeam
6 * Copyright (C) 2010 Alain Peyrat, Alcatel-Lucent
8 * This file is part of PhpWiki.
10 * PhpWiki is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * PhpWiki is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * Standard Alcatel-Lucent disclaimer for contributing to open source
28 * "The Fusionforge backend ("Contribution") has not been tested and/or
29 * validated for release as or in products, combinations with products or
30 * other commercial use. Any use of the Contribution is entirely made at
31 * the user's own responsibility and the user can not rely on any features,
32 * functionalities or performances Alcatel-Lucent has attributed to the
35 * THE CONTRIBUTION BY ALCATEL-LUCENT IS PROVIDED AS IS, WITHOUT WARRANTY
36 * OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
37 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, COMPLIANCE,
38 * NON-INTERFERENCE AND/OR INTERWORKING WITH THE SOFTWARE TO WHICH THE
39 * CONTRIBUTION HAS BEEN MADE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
40 * ALCATEL-LUCENT BE LIABLE FOR ANY DAMAGES OR OTHER LIABLITY, WHETHER IN
41 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
42 * CONTRIBUTION OR THE USE OR OTHER DEALINGS IN THE CONTRIBUTION, WHETHER
43 * TOGETHER WITH THE SOFTWARE TO WHICH THE CONTRIBUTION RELATES OR ON A STAND
48 require_once('lib/ErrorManager.php');
49 require_once('lib/WikiDB/backend/PearDB_pgsql.php');
51 class WikiDB_backend_PearDB_ffpgsql
52 extends WikiDB_backend_PearDB_pgsql
54 function WikiDB_backend_PearDB_ffpgsql($dbparams) {
55 $dbparams['dsn'] = str_replace('ffpgsql:', 'pgsql:', $dbparams['dsn']);
56 parent::WikiDB_backend_PearDB_pgsql($dbparams);
58 $p = strlen(PAGE_PREFIX)+1;
59 $page_tbl = $this->_table_names['page_tbl'];
60 $this->page_tbl_fields = "$page_tbl.id AS id, substring($page_tbl.pagename from $p) AS pagename, $page_tbl.hits AS hits";
62 pg_set_client_encoding("iso-8859-1");
65 function get_all_pagenames() {
67 extract($this->_table_names);
70 return $dbh->getCol("SELECT substring(pagename from $p)"
71 . " FROM $nonempty_tbl, $page_tbl"
72 . " WHERE $nonempty_tbl.id=$page_tbl.id"
73 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'");
76 function numPages($filter=false, $exclude='') {
78 extract($this->_table_names);
81 return $dbh->getOne("SELECT count(*)"
82 . " FROM $nonempty_tbl, $page_tbl"
83 . " WHERE $nonempty_tbl.id=$page_tbl.id"
84 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'");
87 function get_pagedata($pagename) {
88 return parent::get_pagedata(PAGE_PREFIX.$pagename);
91 function update_pagedata($pagename, $newdata) {
93 $page_tbl = $this->_table_names['page_tbl'];
95 // Hits is the only thing we can update in a fast manner.
96 if (count($newdata) == 1 && isset($newdata['hits'])) {
97 // Note that this will fail silently if the page does not
98 // have a record in the page table. Since it's just the
99 // hit count, who cares?
100 $pagename = PAGE_PREFIX.$pagename;
101 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
102 $newdata['hits'], $dbh->escapeSimple($pagename)));
106 $this->lock(array($page_tbl), true);
107 $data = $this->get_pagedata($pagename);
110 $this->_get_pageid($pagename, true); // Creates page record
113 @$hits = (int)$data['hits'];
114 unset($data['hits']);
116 foreach ($newdata as $key => $val) {
119 else if (empty($val))
125 /* Portability issue -- not all DBMS supports huge strings
126 * so we need to 'bind' instead of building a simple SQL statment.
127 * Note that we do not need to escapeSimple when we bind
128 $dbh->query(sprintf("UPDATE $page_tbl"
129 . " SET hits=%d, pagedata='%s'"
130 . " WHERE pagename='%s'",
132 $dbh->escapeSimple($this->_serialize($data)),
133 $dbh->escapeSimple($pagename)));
135 $pagename = PAGE_PREFIX.$pagename;
136 $dbh->query("UPDATE $page_tbl"
137 . " SET hits=?, pagedata=?"
138 . " WHERE pagename=?",
139 array($hits, $this->_serialize($data), $pagename));
140 $this->unlock(array($page_tbl));
143 function get_latest_version($pagename) {
144 return parent::get_latest_version(PAGE_PREFIX.$pagename);
147 function get_previous_version($pagename, $version) {
148 return parent::get_previous_version(PAGE_PREFIX.$pagename, $version);
151 function get_versiondata($pagename, $version, $want_content = false) {
153 extract($this->_table_names);
154 extract($this->_expressions);
156 // assert(is_string($pagename) and $pagename != "");
157 // assert($version > 0);
159 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
160 // FIXME: optimization: sometimes don't get page data?
162 $fields = $this->page_tbl_fields
163 . ",$page_tbl.pagedata as pagedata,"
164 . $this->version_tbl_fields;
167 $fields = $this->page_tbl_fields . ","
168 . "mtime, minor_edit, versiondata,"
169 . "$iscontent AS have_content";
172 $pagename = PAGE_PREFIX.$pagename;
173 $result = $dbh->getRow(sprintf("SELECT $fields"
174 . " FROM $page_tbl, $version_tbl"
175 . " WHERE $page_tbl.id=$version_tbl.id"
176 . " AND pagename='%s'"
178 $dbh->escapeSimple($pagename), $version),
181 return $this->_extract_version_data($result);
184 function get_cached_html($pagename) {
185 return parent::get_cached_html(PAGE_PREFIX.$pagename);
188 function set_cached_html($pagename, $data) {
189 return parent::set_cached_html(PAGE_PREFIX.$pagename, $data);
192 function _get_pageid($pagename, $create_if_missing = false) {
196 $cache =& $request->_dbi->_cache->_id_cache;
197 if (isset($cache[$pagename])) {
198 if ($cache[$pagename] or !$create_if_missing) {
199 return $cache[$pagename];
203 // attributes play this game.
204 if ($pagename === '') return 0;
207 $page_tbl = $this->_table_names['page_tbl'];
208 $pagename = PAGE_PREFIX.$pagename;
210 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
211 $dbh->escapeSimple($pagename));
213 if (!$create_if_missing)
214 return $dbh->getOne($query);
216 $id = $dbh->getOne($query);
218 $this->lock(array($page_tbl), true); // write lock
219 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
221 // requires createSequence and on mysql lock the interim table ->getSequenceName
222 //$id = $dbh->nextId($page_tbl . "_id");
223 $dbh->query(sprintf("INSERT INTO $page_tbl"
224 . " (id,pagename,hits)"
225 . " VALUES (%d,'%s',0)",
226 $id, $dbh->escapeSimple($pagename)));
227 $this->unlock(array($page_tbl));
232 function purge_page($pagename) {
234 extract($this->_table_names);
237 if ( ($id = $this->_get_pageid($pagename, false)) ) {
238 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
239 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
240 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
241 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
242 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
244 // We're still in the link table (dangling link) so we can't delete this
246 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
250 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
254 $result = -1; // already purged or not existing
260 function get_links($pagename, $reversed=true, $include_empty=false,
261 $sortby='', $limit='', $exclude='',
262 $want_relations = false)
265 extract($this->_table_names);
268 list($have,$want) = array('linkee', 'linker');
270 list($have,$want) = array('linker', 'linkee');
271 $orderby = $this->sortby($sortby, 'db', array('pagename'));
272 if ($orderby) $orderby = " ORDER BY $want." . $orderby;
273 if ($exclude) // array of pagenames
274 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
281 $qpagename = $dbh->escapeSimple($pagename);
282 // MeV+APe 2007-11-14
283 // added "dummyname" so that database accepts "ORDER BY"
284 $sql = "SELECT DISTINCT $want.id AS id, substring($want.pagename from $p) AS pagename, $want.pagename AS dummyname,"
285 . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
287 . (!$include_empty ? "$nonempty_tbl, " : '')
288 . " $page_tbl linkee, $page_tbl linker, $link_tbl "
289 . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
290 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
291 . " AND $have.pagename='$pat$qpagename'"
292 . " AND substring($want.pagename from 0 for $p) = '$pat'"
293 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
294 //. " GROUP BY $want.id"
298 // extract from,count from limit
299 list($from,$count) = $this->limit($limit);
300 $result = $dbh->limitQuery($sql, $from, $count);
302 $result = $dbh->query($sql);
305 return new WikiDB_backend_PearDB_iter($this, $result);
308 function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') {
310 extract($this->_table_names);
315 $orderby = $this->sortby($sortby, 'db');
316 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
317 if ($exclude) // array of pagenames
318 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
323 $include_empty=false;
325 if (strstr($orderby, 'mtime ')) { // multiple columns possible
326 if ($include_empty) {
328 . $this->page_tbl_fields
329 . " FROM $page_tbl, $recent_tbl, $version_tbl"
330 . " WHERE $page_tbl.id=$recent_tbl.id"
331 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
332 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"
338 . $this->page_tbl_fields
339 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
340 . " WHERE $nonempty_tbl.id=$page_tbl.id"
341 . " AND $page_tbl.id=$recent_tbl.id"
342 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
343 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"
348 if ($include_empty) {
350 . $this->page_tbl_fields
352 . ($exclude ? " WHERE $exclude" : '')
353 . ($exclude ? " AND " : " WHERE ")
354 . " substring($page_tbl.pagename from 0 for $p) = '$pat'"
359 . $this->page_tbl_fields
360 . " FROM $nonempty_tbl, $page_tbl"
361 . " WHERE $nonempty_tbl.id=$page_tbl.id"
362 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"
367 if ($limit && $orderby) {
368 // extract from,count from limit
369 list($from,$count) = $this->limit($limit);
370 $result = $dbh->limitQuery($sql, $from, $count);
371 $options = array('limit_by_db' => 1);
373 $result = $dbh->query($sql);
374 $options = array('limit_by_db' => 0);
376 return new WikiDB_backend_PearDB_iter($this, $result, $options);
379 function most_popular($limit=20, $sortby='-hits') {
381 extract($this->_table_names);
389 $order = "hits DESC";
390 $where = " AND hits > 0";
393 if ($sortby != '-hits') {
394 if ($order = $this->sortby($sortby, 'db'))
395 $orderby = " ORDER BY " . $order;
397 $orderby = " ORDER BY $order";
399 //$limitclause = $limit ? " LIMIT $limit" : '';
401 . $this->page_tbl_fields
402 . " FROM $nonempty_tbl, $page_tbl"
403 . " WHERE $nonempty_tbl.id=$page_tbl.id"
404 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"
408 list($from, $count) = $this->limit($limit);
409 $result = $dbh->limitQuery($sql, $from, $count);
411 $result = $dbh->query($sql);
414 return new WikiDB_backend_PearDB_iter($this, $result);
417 function most_recent($params) {
420 $include_minor_revisions = false;
421 $exclude_major_revisions = false;
422 $include_all_revisions = false;
426 extract($this->_table_names);
430 $pick[] = "mtime >= $since";
433 if ($include_all_revisions) {
434 // Include all revisions of each page.
435 $table = "$page_tbl, $version_tbl";
436 $join_clause = "$page_tbl.id=$version_tbl.id";
438 if ($exclude_major_revisions) {
439 // Include only minor revisions
440 $pick[] = "minor_edit <> 0";
442 elseif (!$include_minor_revisions) {
443 // Include only major revisions
444 $pick[] = "minor_edit = 0";
448 $table = "$page_tbl, $recent_tbl";
449 $join_clause = "$page_tbl.id=$recent_tbl.id";
450 $table .= ", $version_tbl";
451 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
453 if ($exclude_major_revisions) {
454 // Include only most recent minor revision
455 $pick[] = 'version=latestminor';
457 elseif (!$include_minor_revisions) {
458 // Include only most recent major revision
459 $pick[] = 'version=latestmajor';
462 // Include only the latest revision (whether major or minor).
463 $pick[] ='version=latestversion';
471 // $limitclause = $limit ? " LIMIT $limit" : '';
472 $where_clause = $join_clause;
474 $where_clause .= " AND " . join(" AND ", $pick);
479 // FIXME: use SQL_BUFFER_RESULT for mysql?
481 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
483 . " WHERE $where_clause"
484 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"
485 . " ORDER BY mtime $order";
487 list($from, $count) = $this->limit($limit);
488 $result = $dbh->limitQuery($sql, $from, $count);
490 $result = $dbh->query($sql);
492 return new WikiDB_backend_PearDB_iter($this, $result);
495 function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') {
497 extract($this->_table_names);
500 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
501 $orderby = 'ORDER BY ' . $orderby;
503 if ($exclude_from) // array of pagenames
504 $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from);
505 if ($exclude) // array of pagenames
506 $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude);
508 $p = strlen(PAGE_PREFIX)+1;
509 $sql = "SELECT substring(p.pagename from $p) AS wantedfrom, substring(pp.pagename from $p) AS pagename"
510 . " FROM $page_tbl p, $link_tbl linked"
511 . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
512 . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
513 . " WHERE ne.id IS NULL"
514 . " AND p.id = linked.linkfrom"
515 . " AND substring(p.pagename from 0 for $p) = '$pat'"
516 . " AND substring(pp.pagename from 0 for $p) = '$pat'"
521 // oci8 error: WHERE NULL = NULL appended
522 list($from, $count) = $this->limit($limit);
523 $result = $dbh->limitQuery($sql, $from, $count * 3);
525 $result = $dbh->query($sql);
527 return new WikiDB_backend_PearDB_generic_iter($this, $result);
530 function rename_page ($pagename, $to) {
532 extract($this->_table_names);
535 if (($id = $this->_get_pageid($pagename, false)) ) {
536 if ($new = $this->_get_pageid($to, false)) {
538 // This page does not exist (already verified before), but exists in the page table.
539 // So we delete this page.
540 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
541 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
542 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
543 // We have to fix all referring tables to the old id
544 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
545 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
546 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
548 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
549 $dbh->escapeSimple(PAGE_PREFIX.$to)));
555 function is_wiki_page($pagename) {
556 return parent::is_wiki_page(PAGE_PREFIX.$pagename);
559 function increaseHitCount($pagename) {
560 return parent::increaseHitCount(PAGE_PREFIX.$pagename);
563 function _serialize($data) {
564 return WikiDB_backend_PearDB::_serialize($data);
569 * NOTE: Disable vacuum, wikiuser is not the table owner
571 function optimize() {
578 function text_search($search, $fulltext=false, $sortby='', $limit='',
582 extract($this->_table_names);
584 $len = strlen($pat)+1;
585 $orderby = $this->sortby($sortby, 'db');
586 if ($sortby and $orderby) $orderby = ' ORDER BY ' . $orderby;
588 $searchclass = get_class($this)."_search";
589 // no need to define it everywhere and then fallback. memory!
590 if (!class_exists($searchclass))
591 $searchclass = "WikiDB_backend_PearDB_search";
592 $searchobj = new $searchclass($search, $dbh);
594 $table = "$nonempty_tbl, $page_tbl";
595 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
596 $fields = $this->page_tbl_fields;
599 $table .= ", $recent_tbl";
600 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
602 $table .= ", $version_tbl";
603 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
605 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
606 // TODO: title still ignored, need better rank and subselect
607 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
608 $search_string = $search->makeTsearch2SqlClauseObj($callback);
609 $search_string = str_replace(array("%"," "), array("","&"), $search_string);
610 $search_clause = "substring(plugin_wiki_page.pagename from 0 for $len) = '$pat') AND (";
612 $search_clause .= "idxFTI @@ to_tsquery('$search_string')";
614 $orderby = " ORDER BY ts_rank(idxFTI, to_tsquery('$search_string')) DESC";
616 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
617 $search_clause = "substring(plugin_wiki_page.pagename from 0 for $len) = '$pat') AND (";
618 $search_clause .= $search->makeSqlClauseObj($callback);
621 $sql = "SELECT $fields FROM $table"
622 . " WHERE $join_clause"
623 . " AND ($search_clause)"
626 list($from, $count) = $this->limit($limit);
627 $result = $dbh->limitQuery($sql, $from, $count);
629 $result = $dbh->query($sql);
632 $iter = new WikiDB_backend_PearDB_iter($this, $result);
633 $iter->stoplisted = @$searchobj->stoplisted;
637 function exists_link($pagename, $link, $reversed=false) {
639 extract($this->_table_names);
642 list($have, $want) = array('linkee', 'linker');
644 list($have, $want) = array('linker', 'linkee');
645 $qpagename = $dbh->escapeSimple($pagename);
646 $qlink = $dbh->escapeSimple($link);
647 $row = $dbh->GetRow("SELECT $want.pagename as result"
648 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
649 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
650 . " AND $have.pagename='$qpagename'"
651 . " AND $want.pagename='$qlink'"
653 return $row['result'] ? 1 : 0;
657 class WikiDB_backend_PearDB_ffpgsql_search
658 extends WikiDB_backend_PearDB_pgsql_search
660 function _pagename_match_clause($node) {
661 $word = $node->sql();
662 // @alu: use _quote maybe instead of direct pg_escape_string
663 $word = pg_escape_string($word);
664 $len = strlen(PAGE_PREFIX)+1;
665 if ($node->op == 'REGEX') { // posix regex extensions
666 return ($this->_case_exact
667 ? "substring(pagename from $len) ~* '$word'"
668 : "substring(pagename from $len) ~ '$word'");
670 return ($this->_case_exact
671 ? "substring(pagename from $len) LIKE '$word'"
672 : "substring(pagename from $len) ILIKE '$word'");
677 * use tsearch2. See schemas/psql-tsearch2.sql and /usr/share/postgresql/contrib/tsearch2.sql
678 * TODO: don't parse the words into nodes. rather replace "[ +]" with & and "-" with "!" and " or " with "|"
679 * tsearch2 query language: @@ "word | word", "word & word", ! word
680 * ~* '.*something that does not exist.*'
683 phrase search for "history lesson":
685 SELECT id FROM tab WHERE ts_idx_col @@ to_tsquery('history&lesson')
686 AND text_col ~* '.*history\\s+lesson.*';
688 The full-text index will still be used, and the regex will be used to
689 prune the results afterwards.
691 function _fulltext_match_clause($node) {
692 $word = strtolower($node->word);
693 $word = str_replace(" ", "&", $word); // phrase fix
695 // @alu: use _quote maybe instead of direct pg_escape_string
696 $word = pg_escape_string($word);
706 // c-hanging-comment-ender-p: nil
707 // indent-tabs-mode: nil