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 PhpWiki; 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
47 require_once 'lib/ErrorManager.php';
48 require_once 'lib/WikiDB/backend/PearDB_pgsql.php';
50 class WikiDB_backend_PearDB_ffpgsql
51 extends WikiDB_backend_PearDB_pgsql
53 function WikiDB_backend_PearDB_ffpgsql($dbparams) {
54 $dbparams['dsn'] = str_replace('ffpgsql:', 'pgsql:', $dbparams['dsn']);
55 parent::WikiDB_backend_PearDB_pgsql($dbparams);
57 $p = strlen(PAGE_PREFIX)+1;
58 $page_tbl = $this->_table_names['page_tbl'];
59 $this->page_tbl_fields = "$page_tbl.id AS id, substring($page_tbl.pagename from $p) AS pagename, $page_tbl.hits AS hits";
61 pg_set_client_encoding("iso-8859-1");
64 function get_all_pagenames() {
66 extract($this->_table_names);
69 return $dbh->getCol("SELECT substring(pagename from $p)"
70 . " FROM $nonempty_tbl, $page_tbl"
71 . " WHERE $nonempty_tbl.id=$page_tbl.id"
72 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'");
75 function numPages($filter=false, $exclude='') {
77 extract($this->_table_names);
80 return $dbh->getOne("SELECT count(*)"
81 . " FROM $nonempty_tbl, $page_tbl"
82 . " WHERE $nonempty_tbl.id=$page_tbl.id"
83 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'");
86 function get_pagedata($pagename) {
87 return parent::get_pagedata(PAGE_PREFIX.$pagename);
90 function update_pagedata($pagename, $newdata) {
92 $page_tbl = $this->_table_names['page_tbl'];
94 // Hits is the only thing we can update in a fast manner.
95 if (count($newdata) == 1 && isset($newdata['hits'])) {
96 // Note that this will fail silently if the page does not
97 // have a record in the page table. Since it's just the
98 // hit count, who cares?
99 $pagename = PAGE_PREFIX.$pagename;
100 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
101 $newdata['hits'], $dbh->escapeSimple($pagename)));
105 $this->lock(array($page_tbl), true);
106 $data = $this->get_pagedata($pagename);
109 $this->_get_pageid($pagename, true); // Creates page record
112 if (isset($data['hits'])) {
113 $hits = (int)$data['hits'];
114 unset($data['hits']);
119 foreach ($newdata as $key => $val) {
122 else if (empty($val))
128 /* Portability issue -- not all DBMS supports huge strings
129 * so we need to 'bind' instead of building a simple SQL statment.
130 * Note that we do not need to escapeSimple when we bind
131 $dbh->query(sprintf("UPDATE $page_tbl"
132 . " SET hits=%d, pagedata='%s'"
133 . " WHERE pagename='%s'",
135 $dbh->escapeSimple($this->_serialize($data)),
136 $dbh->escapeSimple($pagename)));
138 $pagename = PAGE_PREFIX.$pagename;
139 $dbh->query("UPDATE $page_tbl"
140 . " SET hits=?, pagedata=?"
141 . " WHERE pagename=?",
142 array($hits, $this->_serialize($data), $pagename));
143 $this->unlock(array($page_tbl));
146 function get_latest_version($pagename) {
147 return parent::get_latest_version(PAGE_PREFIX.$pagename);
150 function get_previous_version($pagename, $version) {
151 return parent::get_previous_version(PAGE_PREFIX.$pagename, $version);
154 function get_versiondata($pagename, $version, $want_content = false) {
156 extract($this->_table_names);
157 extract($this->_expressions);
159 // assert(is_string($pagename) and $pagename != "");
160 // assert($version > 0);
162 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
163 // FIXME: optimization: sometimes don't get page data?
165 $fields = $this->page_tbl_fields
166 . ",$page_tbl.pagedata as pagedata,"
167 . $this->version_tbl_fields;
170 $fields = $this->page_tbl_fields . ","
171 . "mtime, minor_edit, versiondata,"
172 . "$iscontent AS have_content";
175 $pagename = PAGE_PREFIX.$pagename;
176 $result = $dbh->getRow(sprintf("SELECT $fields"
177 . " FROM $page_tbl, $version_tbl"
178 . " WHERE $page_tbl.id=$version_tbl.id"
179 . " AND pagename='%s'"
181 $dbh->escapeSimple($pagename), $version),
184 return $this->_extract_version_data($result);
187 function get_cached_html($pagename) {
188 return parent::get_cached_html(PAGE_PREFIX.$pagename);
191 function set_cached_html($pagename, $data) {
192 return parent::set_cached_html(PAGE_PREFIX.$pagename, $data);
195 function _get_pageid($pagename, $create_if_missing = false) {
199 $cache =& $request->_dbi->_cache->_id_cache;
200 if (isset($cache[$pagename])) {
201 if ($cache[$pagename] or !$create_if_missing) {
202 return $cache[$pagename];
206 // attributes play this game.
207 if ($pagename === '') return 0;
210 $page_tbl = $this->_table_names['page_tbl'];
211 $pagename = PAGE_PREFIX.$pagename;
213 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
214 $dbh->escapeSimple($pagename));
216 if (!$create_if_missing)
217 return $dbh->getOne($query);
219 $id = $dbh->getOne($query);
221 $this->lock(array($page_tbl), true); // write lock
222 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
224 // requires createSequence and on mysql lock the interim table ->getSequenceName
225 //$id = $dbh->nextId($page_tbl . "_id");
226 $dbh->query(sprintf("INSERT INTO $page_tbl"
227 . " (id,pagename,hits)"
228 . " VALUES (%d,'%s',0)",
229 $id, $dbh->escapeSimple($pagename)));
230 $this->unlock(array($page_tbl));
235 function purge_page($pagename) {
237 extract($this->_table_names);
240 if ( ($id = $this->_get_pageid($pagename, false)) ) {
241 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
242 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
243 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
244 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
245 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
247 // We're still in the link table (dangling link) so we can't delete this
249 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
253 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
257 $result = -1; // already purged or not existing
263 function get_links($pagename, $reversed=true, $include_empty=false,
264 $sortby='', $limit='', $exclude='',
265 $want_relations = false)
268 extract($this->_table_names);
271 list($have,$want) = array('linkee', 'linker');
273 list($have,$want) = array('linker', 'linkee');
274 $orderby = $this->sortby($sortby, 'db', array('pagename'));
275 if ($orderby) $orderby = " ORDER BY $want." . $orderby;
276 if ($exclude) // array of pagenames
277 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
284 $qpagename = $dbh->escapeSimple($pagename);
285 // MeV+APe 2007-11-14
286 // added "dummyname" so that database accepts "ORDER BY"
287 $sql = "SELECT DISTINCT $want.id AS id, substring($want.pagename from $p) AS pagename, $want.pagename AS dummyname,"
288 . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
290 . (!$include_empty ? "$nonempty_tbl, " : '')
291 . " $page_tbl linkee, $page_tbl linker, $link_tbl "
292 . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
293 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
294 . " AND $have.pagename='$pat$qpagename'"
295 . " AND substring($want.pagename from 0 for $p) = '$pat'"
296 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
297 //. " GROUP BY $want.id"
301 // extract from,count from limit
302 list($from,$count) = $this->limit($limit);
303 $result = $dbh->limitQuery($sql, $from, $count);
305 $result = $dbh->query($sql);
308 return new WikiDB_backend_PearDB_iter($this, $result);
311 function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') {
313 extract($this->_table_names);
318 $orderby = $this->sortby($sortby, 'db');
319 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
320 if ($exclude) // array of pagenames
321 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
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";
432 if ($include_all_revisions) {
433 // Include all revisions of each page.
434 $table = "$page_tbl, $version_tbl";
435 $join_clause = "$page_tbl.id=$version_tbl.id";
437 if ($exclude_major_revisions) {
438 // Include only minor revisions
439 $pick[] = "minor_edit <> 0";
441 elseif (!$include_minor_revisions) {
442 // Include only major revisions
443 $pick[] = "minor_edit = 0";
447 $table = "$page_tbl, $recent_tbl";
448 $join_clause = "$page_tbl.id=$recent_tbl.id";
449 $table .= ", $version_tbl";
450 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
452 if ($exclude_major_revisions) {
453 // Include only most recent minor revision
454 $pick[] = 'version=latestminor';
456 elseif (!$include_minor_revisions) {
457 // Include only most recent major revision
458 $pick[] = 'version=latestmajor';
461 // Include only the latest revision (whether major or minor).
462 $pick[] ='version=latestversion';
470 // $limitclause = $limit ? " LIMIT $limit" : '';
471 $where_clause = $join_clause;
473 $where_clause .= " AND " . join(" AND ", $pick);
478 // FIXME: use SQL_BUFFER_RESULT for mysql?
480 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
482 . " WHERE $where_clause"
483 . " AND substring($page_tbl.pagename from 0 for $p) = '$pat'"
484 . " ORDER BY mtime $order";
486 list($from, $count) = $this->limit($limit);
487 $result = $dbh->limitQuery($sql, $from, $count);
489 $result = $dbh->query($sql);
491 return new WikiDB_backend_PearDB_iter($this, $result);
494 function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') {
496 extract($this->_table_names);
499 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
500 $orderby = 'ORDER BY ' . $orderby;
502 if ($exclude_from) // array of pagenames
503 $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from);
504 if ($exclude) // array of pagenames
505 $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude);
507 $p = strlen(PAGE_PREFIX)+1;
508 $sql = "SELECT substring(p.pagename from $p) AS wantedfrom, substring(pp.pagename from $p) AS pagename"
509 . " FROM $page_tbl p, $link_tbl linked"
510 . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
511 . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
512 . " WHERE ne.id IS NULL"
513 . " AND p.id = linked.linkfrom"
514 . " AND substring(p.pagename from 0 for $p) = '$pat'"
515 . " AND substring(pp.pagename from 0 for $p) = '$pat'"
520 // oci8 error: WHERE NULL = NULL appended
521 list($from, $count) = $this->limit($limit);
522 $result = $dbh->limitQuery($sql, $from, $count * 3);
524 $result = $dbh->query($sql);
526 return new WikiDB_backend_PearDB_generic_iter($this, $result);
529 function rename_page ($pagename, $to) {
531 extract($this->_table_names);
534 if (($id = $this->_get_pageid($pagename, false)) ) {
535 if ($new = $this->_get_pageid($to, false)) {
537 // This page does not exist (already verified before), but exists in the page table.
538 // So we delete this page.
539 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
540 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
541 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
542 // We have to fix all referring tables to the old id
543 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
544 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
545 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
547 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
548 $dbh->escapeSimple(PAGE_PREFIX.$to)));
554 function is_wiki_page($pagename) {
555 return parent::is_wiki_page(PAGE_PREFIX.$pagename);
558 function increaseHitCount($pagename) {
559 return parent::increaseHitCount(PAGE_PREFIX.$pagename);
562 function _serialize($data) {
563 return WikiDB_backend_PearDB::_serialize($data);
568 * NOTE: Disable vacuum, wikiuser is not the table owner
570 function optimize() {
577 function text_search($search, $fulltext=false, $sortby='', $limit='',
581 extract($this->_table_names);
583 $len = strlen($pat)+1;
584 $orderby = $this->sortby($sortby, 'db');
585 if ($sortby and $orderby) $orderby = ' ORDER BY ' . $orderby;
587 $searchclass = get_class($this)."_search";
588 // no need to define it everywhere and then fallback. memory!
589 if (!class_exists($searchclass))
590 $searchclass = "WikiDB_backend_PearDB_search";
591 $searchobj = new $searchclass($search, $dbh);
593 $table = "$nonempty_tbl, $page_tbl";
594 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
595 $fields = $this->page_tbl_fields;
598 $table .= ", $recent_tbl";
599 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
601 $table .= ", $version_tbl";
602 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
604 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
605 // TODO: title still ignored, need better rank and subselect
606 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
607 $search_string = $search->makeTsearch2SqlClauseObj($callback);
608 $search_string = str_replace('%', '', $search_string);
609 $search_clause = "substring(plugin_wiki_page.pagename from 0 for $len) = '$pat') AND (";
611 $search_clause .= "idxFTI @@ to_tsquery('$search_string')";
613 $orderby = " ORDER BY ts_rank(idxFTI, to_tsquery('$search_string')) DESC";
615 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
616 $search_clause = "substring(plugin_wiki_page.pagename from 0 for $len) = '$pat') AND (";
617 $search_clause .= $search->makeSqlClauseObj($callback);
620 $sql = "SELECT $fields FROM $table"
621 . " WHERE $join_clause"
622 . " AND ($search_clause)"
625 list($from, $count) = $this->limit($limit);
626 $result = $dbh->limitQuery($sql, $from, $count);
628 $result = $dbh->query($sql);
631 $iter = new WikiDB_backend_PearDB_iter($this, $result);
632 $iter->stoplisted = @$searchobj->stoplisted;
636 function exists_link($pagename, $link, $reversed=false) {
638 extract($this->_table_names);
641 list($have, $want) = array('linkee', 'linker');
643 list($have, $want) = array('linker', 'linkee');
644 $qpagename = $dbh->escapeSimple($pagename);
645 $qlink = $dbh->escapeSimple($link);
646 $row = $dbh->GetRow("SELECT $want.pagename as result"
647 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
648 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
649 . " AND $have.pagename='$qpagename'"
650 . " AND $want.pagename='$qlink'"
652 return $row['result'] ? 1 : 0;
656 class WikiDB_backend_PearDB_ffpgsql_search
657 extends WikiDB_backend_PearDB_pgsql_search
659 function _pagename_match_clause($node) {
660 $word = $node->sql();
661 // @alu: use _quote maybe instead of direct pg_escape_string
662 $word = pg_escape_string($word);
663 $len = strlen(PAGE_PREFIX)+1;
664 if ($node->op == 'REGEX') { // posix regex extensions
665 return ($this->_case_exact
666 ? "substring(pagename from $len) ~* '$word'"
667 : "substring(pagename from $len) ~ '$word'");
669 return ($this->_case_exact
670 ? "substring(pagename from $len) LIKE '$word'"
671 : "substring(pagename from $len) ILIKE '$word'");
676 * use tsearch2. See schemas/psql-tsearch2.sql and /usr/share/postgresql/contrib/tsearch2.sql
677 * TODO: don't parse the words into nodes. rather replace "[ +]" with & and "-" with "!" and " or " with "|"
678 * tsearch2 query language: @@ "word | word", "word & word", ! word
679 * ~* '.*something that does not exist.*'
682 phrase search for "history lesson":
684 SELECT id FROM tab WHERE ts_idx_col @@ to_tsquery('history&lesson')
685 AND text_col ~* '.*history\\s+lesson.*';
687 The full-text index will still be used, and the regex will be used to
688 prune the results afterwards.
690 function _fulltext_match_clause($node) {
691 $word = strtolower($node->word);
692 // $word = str_replace(" ", "&", $word); // phrase fix
694 // @alu: use _quote maybe instead of direct pg_escape_string
695 $word = pg_escape_string($word);
705 // c-hanging-comment-ender-p: nil
706 // indent-tabs-mode: nil