]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PearDB.php
var --> public
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PearDB.php
1 <?php
2
3 require_once 'lib/WikiDB/backend.php';
4
5 class WikiDB_backend_PearDB
6     extends WikiDB_backend
7 {
8     public $_dbh;
9
10     function WikiDB_backend_PearDB($dbparams)
11     {
12         // Find and include PEAR's DB.php. maybe we should force our private version again...
13         // if DB would have exported its version number, it would be easier.
14         @require_once('DB/common.php'); // Either our local pear copy or the system one
15         $name = "escapeSimple";
16         // TODO: apparently some Pear::Db version adds LIMIT 1,0 to getOne(),
17         // which is invalid for "select version()"
18         if (!in_array($name, get_class_methods("DB_common"))) {
19             $finder = new FileFinder;
20             $dir = dirname(__FILE__) . "/../../pear";
21             $finder->_prepend_to_include_path($dir);
22             include_once("$dir/DB/common.php"); // use our version instead.
23             if (!in_array($name, get_class_methods("DB_common"))) {
24                 $pearFinder = new PearFileFinder("lib/pear");
25                 $pearFinder->includeOnce('DB.php');
26             } else {
27                 include_once("$dir/DB.php");
28             }
29         } else {
30             include_once 'DB.php';
31         }
32
33         // Install filter to handle bogus error notices from buggy DB.php's.
34         // TODO: check the Pear_DB version, but how?
35         if (DEBUG) {
36             global $ErrorManager;
37             $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
38             $this->_pearerrhandler = true;
39         }
40
41         // Open connection to database
42         $this->_dsn = $dbparams['dsn'];
43         $this->_dbparams = $dbparams;
44         $this->_lock_count = 0;
45
46         // persistent is usually a DSN option: we override it with a config value.
47         //   phptype://username:password@hostspec/database?persistent=false
48         $dboptions = array('persistent' => DATABASE_PERSISTENT,
49             'debug' => 2);
50         //if (preg_match('/^pgsql/', $this->_dsn)) $dboptions['persistent'] = false;
51         $this->_dbh = DB::connect($this->_dsn, $dboptions);
52         $dbh = &$this->_dbh;
53         if (DB::isError($dbh)) {
54             trigger_error(sprintf("Can't connect to database: %s",
55                     $this->_pear_error_message($dbh)),
56                 isset($dbparams['_tryroot_from_upgrade']) // hack!
57                     ? E_USER_WARNING : E_USER_ERROR);
58             if (isset($dbparams['_tryroot_from_upgrade']))
59                 return;
60         }
61         $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
62             array($this, '_pear_error_callback'));
63         $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
64
65         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
66         $this->_table_names
67             = array('page_tbl' => $prefix . 'page',
68             'version_tbl' => $prefix . 'version',
69             'link_tbl' => $prefix . 'link',
70             'recent_tbl' => $prefix . 'recent',
71             'nonempty_tbl' => $prefix . 'nonempty');
72         $page_tbl = $this->_table_names['page_tbl'];
73         $version_tbl = $this->_table_names['version_tbl'];
74         $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, $page_tbl.hits AS hits";
75         $this->version_tbl_fields = "$version_tbl.version AS version, $version_tbl.mtime AS mtime, " .
76             "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, $version_tbl.versiondata AS versiondata";
77
78         $this->_expressions
79             = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
80             'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
81             'maxversion' => "MAX(version)",
82             'notempty' => "<>''",
83             'iscontent' => "content<>''");
84
85     }
86
87     /**
88      * Close database connection.
89      */
90     function close()
91     {
92         if (!$this->_dbh)
93             return;
94         if ($this->_lock_count) {
95             trigger_error("WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
96                 E_USER_WARNING);
97         }
98         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
99         $this->unlock('force');
100
101         $this->_dbh->disconnect();
102
103         if (!empty($this->_pearerrhandler)) {
104             $GLOBALS['ErrorManager']->popErrorHandler();
105         }
106     }
107
108     /*
109      * Test fast wikipage.
110      */
111     function is_wiki_page($pagename)
112     {
113         $dbh = &$this->_dbh;
114         extract($this->_table_names);
115         return $dbh->getOne(sprintf("SELECT $page_tbl.id as id"
116                 . " FROM $nonempty_tbl, $page_tbl"
117                 . " WHERE $nonempty_tbl.id=$page_tbl.id"
118                 . "   AND pagename='%s'",
119             $dbh->escapeSimple($pagename)));
120     }
121
122     function get_all_pagenames()
123     {
124         $dbh = &$this->_dbh;
125         extract($this->_table_names);
126         return $dbh->getCol("SELECT pagename"
127             . " FROM $nonempty_tbl, $page_tbl"
128             . " WHERE $nonempty_tbl.id=$page_tbl.id");
129     }
130
131     function numPages($filter = false, $exclude = '')
132     {
133         $dbh = &$this->_dbh;
134         extract($this->_table_names);
135         return $dbh->getOne("SELECT count(*)"
136             . " FROM $nonempty_tbl, $page_tbl"
137             . " WHERE $nonempty_tbl.id=$page_tbl.id");
138     }
139
140     function increaseHitCount($pagename)
141     {
142         $dbh = &$this->_dbh;
143         // Hits is the only thing we can update in a fast manner.
144         // Note that this will fail silently if the page does not
145         // have a record in the page table.  Since it's just the
146         // hit count, who cares?
147         $dbh->query(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename='%s'",
148             $this->_table_names['page_tbl'],
149             $dbh->escapeSimple($pagename)));
150         return;
151     }
152
153     /**
154      * Read page information from database.
155      */
156     function get_pagedata($pagename)
157     {
158         $dbh = &$this->_dbh;
159         //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
160         $result = $dbh->getRow(sprintf("SELECT hits,pagedata FROM %s WHERE pagename='%s'",
161                 $this->_table_names['page_tbl'],
162                 $dbh->escapeSimple($pagename)),
163             DB_FETCHMODE_ASSOC);
164         return $result ? $this->_extract_page_data($result) : false;
165     }
166
167     function  _extract_page_data($data)
168     {
169         if (empty($data)) return array();
170         elseif (empty($data['pagedata'])) return $data; else {
171             $data = array_merge($data, $this->_unserialize($data['pagedata']));
172             unset($data['pagedata']);
173             return $data;
174         }
175     }
176
177     function update_pagedata($pagename, $newdata)
178     {
179         $dbh = &$this->_dbh;
180         $page_tbl = $this->_table_names['page_tbl'];
181
182         // Hits is the only thing we can update in a fast manner.
183         if (count($newdata) == 1 && isset($newdata['hits'])) {
184             // Note that this will fail silently if the page does not
185             // have a record in the page table.  Since it's just the
186             // hit count, who cares?
187             $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
188                 $newdata['hits'], $dbh->escapeSimple($pagename)));
189             return;
190         }
191
192         $this->lock(array($page_tbl), true);
193         $data = $this->get_pagedata($pagename);
194         if (!$data) {
195             $data = array();
196             $this->_get_pageid($pagename, true); // Creates page record
197         }
198
199         $hits = !empty($data['hits']) ? (int)$data['hits'] : 0;
200         unset($data['hits']);
201
202         foreach ($newdata as $key => $val) {
203             if ($key == 'hits')
204                 $hits = (int)$val;
205             else if (empty($val))
206                 unset($data[$key]);
207             else
208                 $data[$key] = $val;
209         }
210
211         /* Portability issue -- not all DBMS supports huge strings
212          * so we need to 'bind' instead of building a simple SQL statment.
213          * Note that we do not need to escapeSimple when we bind
214         $dbh->query(sprintf("UPDATE $page_tbl"
215                             . " SET hits=%d, pagedata='%s'"
216                             . " WHERE pagename='%s'",
217                             $hits,
218                             $dbh->escapeSimple($this->_serialize($data)),
219                             $dbh->escapeSimple($pagename)));
220         */
221         $dbh->query("UPDATE $page_tbl"
222                 . " SET hits=?, pagedata=?"
223                 . " WHERE pagename=?",
224             array($hits, $this->_serialize($data), $pagename));
225         $this->unlock(array($page_tbl));
226     }
227
228     function get_cached_html($pagename)
229     {
230         $dbh = &$this->_dbh;
231         $page_tbl = $this->_table_names['page_tbl'];
232         return $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename='%s'",
233             $dbh->escapeSimple($pagename)));
234     }
235
236     function set_cached_html($pagename, $data)
237     {
238         $dbh = &$this->_dbh;
239         $page_tbl = $this->_table_names['page_tbl'];
240         $dbh->query("UPDATE $page_tbl"
241                 . " SET cached_html=?"
242                 . " WHERE pagename=?",
243             array($data, $pagename));
244     }
245
246     function _get_pageid($pagename, $create_if_missing = false)
247     {
248
249         // check id_cache
250         global $request;
251         $cache =& $request->_dbi->_cache->_id_cache;
252         if (isset($cache[$pagename])) {
253             if ($cache[$pagename] or !$create_if_missing) {
254                 return $cache[$pagename];
255             }
256         }
257
258         // attributes play this game.
259         if ($pagename === '') return 0;
260
261         $dbh = &$this->_dbh;
262         $page_tbl = $this->_table_names['page_tbl'];
263
264         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
265             $dbh->escapeSimple($pagename));
266
267         if (!$create_if_missing)
268             return $dbh->getOne($query);
269
270         $id = $dbh->getOne($query);
271         if (empty($id)) {
272             $this->lock(array($page_tbl), true); // write lock
273             $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
274             $id = $max_id + 1;
275             // requires createSequence and on mysql lock the interim table ->getSequenceName
276             //$id = $dbh->nextId($page_tbl . "_id");
277             $dbh->query(sprintf("INSERT INTO $page_tbl"
278                     . " (id,pagename,hits)"
279                     . " VALUES (%d,'%s',0)",
280                 $id, $dbh->escapeSimple($pagename)));
281             $this->unlock(array($page_tbl));
282         }
283         return $id;
284     }
285
286     function get_latest_version($pagename)
287     {
288         $dbh = &$this->_dbh;
289         extract($this->_table_names);
290         return
291             (int)$dbh->getOne(sprintf("SELECT latestversion"
292                     . " FROM $page_tbl, $recent_tbl"
293                     . " WHERE $page_tbl.id=$recent_tbl.id"
294                     . "  AND pagename='%s'",
295                 $dbh->escapeSimple($pagename)));
296     }
297
298     function get_previous_version($pagename, $version)
299     {
300         $dbh = &$this->_dbh;
301         extract($this->_table_names);
302
303         return
304             (int)$dbh->getOne(sprintf("SELECT version"
305                     . " FROM $version_tbl, $page_tbl"
306                     . " WHERE $version_tbl.id=$page_tbl.id"
307                     . "  AND pagename='%s'"
308                     . "  AND version < %d"
309                     . " ORDER BY version DESC",
310                 /* Non portable and useless anyway with getOne
311                 . " LIMIT 1",
312                 */
313                 $dbh->escapeSimple($pagename),
314                 $version));
315     }
316
317     /**
318      * Get version data.
319      *
320      * @param $version int Which version to get.
321      *
322      * @return hash The version data, or false if specified version does not
323      *              exist.
324      */
325     function get_versiondata($pagename, $version, $want_content = false)
326     {
327         $dbh = &$this->_dbh;
328         extract($this->_table_names);
329         extract($this->_expressions);
330
331         assert(is_string($pagename) and $pagename != "");
332         assert($version > 0);
333
334         //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
335         // FIXME: optimization: sometimes don't get page data?
336         if ($want_content) {
337             $fields = $this->page_tbl_fields
338                 . ",$page_tbl.pagedata as pagedata,"
339                 . $this->version_tbl_fields;
340         } else {
341             $fields = $this->page_tbl_fields . ","
342                 . "mtime, minor_edit, versiondata,"
343                 . "$iscontent AS have_content";
344         }
345
346         $result = $dbh->getRow(sprintf("SELECT $fields"
347                     . " FROM $page_tbl, $version_tbl"
348                     . " WHERE $page_tbl.id=$version_tbl.id"
349                     . "  AND pagename='%s'"
350                     . "  AND version=%d",
351                 $dbh->escapeSimple($pagename), $version),
352             DB_FETCHMODE_ASSOC);
353
354         return $this->_extract_version_data($result);
355     }
356
357     function _extract_version_data($query_result)
358     {
359         if (!$query_result)
360             return false;
361
362         /* Earlier versions (<= 1.3.7) stored the version data in base64.
363            This could be done here or in upgrade.
364         */
365         if (!strstr($query_result['versiondata'], ":")) {
366             $query_result['versiondata'] =
367                 base64_decode($query_result['versiondata']);
368         }
369         $data = $this->_unserialize($query_result['versiondata']);
370
371         $data['mtime'] = $query_result['mtime'];
372         $data['is_minor_edit'] = !empty($query_result['minor_edit']);
373
374         if (isset($query_result['content']))
375             $data['%content'] = $query_result['content'];
376         elseif ($query_result['have_content'])
377             $data['%content'] = true; else
378             $data['%content'] = '';
379
380         // FIXME: this is ugly.
381         if (isset($query_result['pagedata'])) {
382             // Query also includes page data.
383             // We might as well send that back too...
384             unset($query_result['versiondata']);
385             $data['%pagedata'] = $this->_extract_page_data($query_result);
386         }
387
388         return $data;
389     }
390
391
392     /**
393      * Create a new revision of a page.
394      */
395     function set_versiondata($pagename, $version, $data)
396     {
397         $dbh = &$this->_dbh;
398         $version_tbl = $this->_table_names['version_tbl'];
399
400         $minor_edit = (int)!empty($data['is_minor_edit']);
401         unset($data['is_minor_edit']);
402
403         $mtime = (int)$data['mtime'];
404         unset($data['mtime']);
405         assert(!empty($mtime));
406
407         $content = isset($data['%content']) ? (string)$data['%content'] : '';
408         unset($data['%content']);
409
410         unset($data['%pagedata']);
411
412         $this->lock();
413         $id = $this->_get_pageid($pagename, true);
414
415         $dbh->query(sprintf("DELETE FROM $version_tbl"
416                 . " WHERE id=%d AND version=%d",
417             $id, $version));
418         // generic slow PearDB bind eh quoting.
419         $dbh->query("INSERT INTO $version_tbl"
420                 . " (id,version,mtime,minor_edit,content,versiondata)"
421                 . " VALUES(?, ?, ?, ?, ?, ?)",
422             array($id, $version, $mtime, $minor_edit, $content,
423                 $this->_serialize($data)));
424
425         $this->_update_recent_table($id);
426         $this->_update_nonempty_table($id);
427
428         $this->unlock();
429     }
430
431     /**
432      * Delete an old revision of a page.
433      */
434     function delete_versiondata($pagename, $version)
435     {
436         $dbh = &$this->_dbh;
437         extract($this->_table_names);
438
439         $this->lock();
440         if (($id = $this->_get_pageid($pagename))) {
441             $dbh->query("DELETE FROM $version_tbl"
442                 . " WHERE id=$id AND version=$version");
443
444             $this->_update_recent_table($id);
445             // This shouldn't be needed (as long as the latestversion
446             // never gets deleted.)  But, let's be safe.
447             $this->_update_nonempty_table($id);
448         }
449         $this->unlock();
450     }
451
452     /**
453      * Delete page from the database with backup possibility.
454      * i.e save_page('') and DELETE nonempty id
455      * Can be undone and is seen in RecentChanges.
456      */
457     /* // see parent backend.php
458     function delete_page($pagename) {
459         $mtime = time();
460         $user =& $GLOBALS['request']->_user;
461         $vdata = array('author' => $user->getId(),
462                        'author_id' => $user->getAuthenticatedId(),
463                        'mtime' => $mtime);
464
465         $this->lock();
466         $version = $this->get_latest_version($pagename);
467         $this->set_versiondata($pagename, $version+1, $vdata);
468         $this->set_links($pagename, false);
469         $pagedata = get_pagedata($pagename);
470         $this->update_pagedata($pagename, array('hits' => $pagedata['hits']));
471         $this->unlock();
472     }
473     */
474
475     /**
476      * Delete page completely from the database.
477      * I'm not sure if this is what we want. Maybe just delete the revisions
478      */
479     function purge_page($pagename)
480     {
481         $dbh = &$this->_dbh;
482         extract($this->_table_names);
483
484         $this->lock();
485         if (($id = $this->_get_pageid($pagename, false))) {
486             $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
487             $dbh->query("DELETE FROM $recent_tbl   WHERE id=$id");
488             $dbh->query("DELETE FROM $version_tbl  WHERE id=$id");
489             $dbh->query("DELETE FROM $link_tbl     WHERE linkfrom=$id");
490             $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
491             if ($nlinks) {
492                 // We're still in the link table (dangling link) so we can't delete this
493                 // altogether.
494                 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
495                 $result = 0;
496             } else {
497                 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
498                 $result = 1;
499             }
500             $this->_update_recent_table();
501             $this->_update_nonempty_table();
502         } else {
503             $result = -1; // already purged or not existing
504         }
505         $this->unlock();
506         return $result;
507     }
508
509     // The only thing we might be interested in updating which we can
510     // do fast in the flags (minor_edit).   I think the default
511     // update_versiondata will work fine...
512     //function update_versiondata($pagename, $version, $data) {
513     //}
514
515     function set_links($pagename, $links)
516     {
517         // Update link table.
518         // FIXME: optimize: mysql can do this all in one big INSERT.
519
520         $dbh = &$this->_dbh;
521         extract($this->_table_names);
522
523         $this->lock();
524         $pageid = $this->_get_pageid($pagename, true);
525
526         $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
527         if ($links) {
528             $linkseen = array();
529             foreach ($links as $link) {
530                 $linkto = $link['linkto'];
531                 if ($linkto === "") { // ignore attributes
532                     continue;
533                 }
534                 if (isset($link['relation']))
535                     $relation = $this->_get_pageid($link['relation'], true);
536                 else
537                     $relation = 0;
538                 // avoid duplicates
539                 if (isset($linkseen[$linkto]) and !$relation)
540                     continue;
541                 if (!$relation)
542                     $linkseen[$linkto] = true;
543                 $linkid = $this->_get_pageid($linkto, true);
544                 if (!$linkid) {
545                     echo("No link for $linkto on page $pagename");
546                     //printSimpleTrace(debug_backtrace());
547                     trigger_error("No link for $linkto on page $pagename");
548                 }
549                 assert($linkid);
550                 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
551                     . " VALUES ($pageid, $linkid, $relation)");
552             }
553             unset($linkseen);
554         }
555         $this->unlock();
556     }
557
558     /**
559      * Find pages which link to or are linked from a page.
560      *
561      * TESTME relations: get_links is responsible to add the relation to the pagehash
562      * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
563      *   if (isset($next['linkrelation']))
564      */
565     function get_links($pagename, $reversed = true, $include_empty = false,
566                        $sortby = '', $limit = '', $exclude = '',
567                        $want_relations = false)
568     {
569         $dbh = &$this->_dbh;
570         extract($this->_table_names);
571
572         if ($reversed)
573             list($have, $want) = array('linkee', 'linker');
574         else
575             list($have, $want) = array('linker', 'linkee');
576         $orderby = $this->sortby($sortby, 'db', array('pagename'));
577         if ($orderby) $orderby = " ORDER BY $want." . $orderby;
578         if ($exclude) // array of pagenames
579             $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude);
580         else
581             $exclude = '';
582
583         $qpagename = $dbh->escapeSimple($pagename);
584         $sql = "SELECT $want.id AS id, $want.pagename AS pagename, "
585             . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
586             . " FROM "
587             . (!$include_empty ? "$nonempty_tbl, " : '')
588             . " $page_tbl linkee, $page_tbl linker, $link_tbl "
589             . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
590             . " WHERE linkfrom=linker.id AND linkto=linkee.id"
591             . " AND $have.pagename='$qpagename'"
592             . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
593             //. " GROUP BY $want.id"
594             . $exclude
595             . $orderby;
596         if ($limit) {
597             // extract from,count from limit
598             list($from, $count) = $this->limit($limit);
599             $result = $dbh->limitQuery($sql, $from, $count);
600         } else {
601             $result = $dbh->query($sql);
602         }
603
604         return new WikiDB_backend_PearDB_iter($this, $result);
605     }
606
607     /**
608      * Find if a page links to another page
609      */
610     function exists_link($pagename, $link, $reversed = false)
611     {
612         $dbh = &$this->_dbh;
613         extract($this->_table_names);
614
615         if ($reversed)
616             list($have, $want) = array('linkee', 'linker');
617         else
618             list($have, $want) = array('linker', 'linkee');
619         $qpagename = $dbh->escapeSimple($pagename);
620         $qlink = $dbh->escapeSimple($link);
621         $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename='$qlink' THEN 1 ELSE 0 END as result"
622             . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
623             . " WHERE linkfrom=linker.id AND linkto=linkee.id"
624             . " AND $have.pagename='$qpagename'"
625             . " AND $want.pagename='$qlink'");
626         return $row['result'];
627     }
628
629     function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
630     {
631         $dbh = &$this->_dbh;
632         extract($this->_table_names);
633         $orderby = $this->sortby($sortby, 'db');
634         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
635         if ($exclude) // array of pagenames
636             $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude);
637         else
638             $exclude = '';
639
640         if (strstr($orderby, 'mtime ')) { // multiple columns possible
641             if ($include_empty) {
642                 $sql = "SELECT "
643                     . $this->page_tbl_fields
644                     . " FROM $page_tbl, $recent_tbl, $version_tbl"
645                     . " WHERE $page_tbl.id=$recent_tbl.id"
646                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
647                     . $exclude
648                     . $orderby;
649             } else {
650                 $sql = "SELECT "
651                     . $this->page_tbl_fields
652                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
653                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
654                     . " AND $page_tbl.id=$recent_tbl.id"
655                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
656                     . $exclude
657                     . $orderby;
658             }
659         } else {
660             if ($include_empty) {
661                 $sql = "SELECT "
662                     . $this->page_tbl_fields
663                     . " FROM $page_tbl"
664                     . ($exclude ? " WHERE $exclude" : '')
665                     . $orderby;
666             } else {
667                 $sql = "SELECT "
668                     . $this->page_tbl_fields
669                     . " FROM $nonempty_tbl, $page_tbl"
670                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
671                     . $exclude
672                     . $orderby;
673             }
674         }
675         if ($limit && $orderby) {
676             // extract from,count from limit
677             list($from, $count) = $this->limit($limit);
678             $result = $dbh->limitQuery($sql, $from, $count);
679             $options = array('limit_by_db' => 1);
680         } else {
681             $result = $dbh->query($sql);
682             $options = array('limit_by_db' => 0);
683         }
684         return new WikiDB_backend_PearDB_iter($this, $result, $options);
685     }
686
687     /**
688      * Title search.
689      * Todo: exclude
690      */
691     function text_search($search, $fulltext = false, $sortby = '', $limit = '',
692                          $exclude = '')
693     {
694         $dbh = &$this->_dbh;
695         extract($this->_table_names);
696         $orderby = $this->sortby($sortby, 'db');
697         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
698         //else " ORDER BY rank($field, to_tsquery('$searchon')) DESC";
699
700         $searchclass = get_class($this) . "_search";
701         // no need to define it everywhere and then fallback. memory!
702         if (!class_exists($searchclass))
703             $searchclass = "WikiDB_backend_PearDB_search";
704         $searchobj = new $searchclass($search, $dbh);
705
706         $table = "$nonempty_tbl, $page_tbl";
707         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
708         $fields = $this->page_tbl_fields;
709
710         if ($fulltext) {
711             $table .= ", $recent_tbl";
712             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
713
714             $table .= ", $version_tbl";
715             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
716
717             $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
718             $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
719         } else {
720             $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
721         }
722         $search_clause = $search->makeSqlClauseObj($callback);
723
724         $sql = "SELECT $fields FROM $table"
725             . " WHERE $join_clause"
726             . "  AND ($search_clause)"
727             . $orderby;
728         if ($limit) {
729             list($from, $count) = $this->limit($limit);
730             $result = $dbh->limitQuery($sql, $from, $count);
731         } else {
732             $result = $dbh->query($sql);
733         }
734
735         $iter = new WikiDB_backend_PearDB_iter($this, $result);
736         $iter->stoplisted = @$searchobj->stoplisted;
737         return $iter;
738     }
739
740     //Todo: check if the better Mysql MATCH operator is supported,
741     // (ranked search) and also google like expressions.
742     function _sql_match_clause($word)
743     {
744         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
745         $word = $this->_dbh->escapeSimple($word);
746         //$page_tbl = $this->_table_names['page_tbl'];
747         //Note: Mysql 4.1.0 has a bug which fails with binary fields.
748         //      e.g. if word is lowercased.
749         // http://bugs.mysql.com/bug.php?id=1491
750         return "LOWER(pagename) LIKE '%$word%'";
751     }
752
753     function _sql_casematch_clause($word)
754     {
755         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
756         $word = $this->_dbh->escapeSimple($word);
757         return "pagename LIKE '%$word%'";
758     }
759
760     function _fullsearch_sql_match_clause($word)
761     {
762         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
763         $word = $this->_dbh->escapeSimple($word);
764         //$page_tbl = $this->_table_names['page_tbl'];
765         //Mysql 4.1.1 has a bug which fails here if word is lowercased.
766         return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
767     }
768
769     function _fullsearch_sql_casematch_clause($word)
770     {
771         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
772         $word = $this->_dbh->escapeSimple($word);
773         return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
774     }
775
776     /**
777      * Find highest or lowest hit counts.
778      */
779     function most_popular($limit = 20, $sortby = '-hits')
780     {
781         $dbh = &$this->_dbh;
782         extract($this->_table_names);
783         if ($limit < 0) {
784             $order = "hits ASC";
785             $limit = -$limit;
786             $where = "";
787         } else {
788             $order = "hits DESC";
789             $where = " AND hits > 0";
790         }
791         $orderby = '';
792         if ($sortby != '-hits') {
793             if ($order = $this->sortby($sortby, 'db'))
794                 $orderby = " ORDER BY " . $order;
795         } else {
796             $orderby = " ORDER BY $order";
797         }
798         //$limitclause = $limit ? " LIMIT $limit" : '';
799         $sql = "SELECT "
800             . $this->page_tbl_fields
801             . " FROM $nonempty_tbl, $page_tbl"
802             . " WHERE $nonempty_tbl.id=$page_tbl.id"
803             . $where
804             . $orderby;
805         if ($limit) {
806             list($from, $count) = $this->limit($limit);
807             $result = $dbh->limitQuery($sql, $from, $count);
808         } else {
809             $result = $dbh->query($sql);
810         }
811
812         return new WikiDB_backend_PearDB_iter($this, $result);
813     }
814
815     /**
816      * Find recent changes.
817      */
818     function most_recent($params)
819     {
820         $limit = 0;
821         $since = 0;
822         $include_minor_revisions = false;
823         $exclude_major_revisions = false;
824         $include_all_revisions = false;
825         extract($params);
826
827         $dbh = &$this->_dbh;
828         extract($this->_table_names);
829
830         $pick = array();
831         if ($since)
832             $pick[] = "mtime >= $since";
833
834         if ($include_all_revisions) {
835             // Include all revisions of each page.
836             $table = "$page_tbl, $version_tbl";
837             $join_clause = "$page_tbl.id=$version_tbl.id";
838
839             if ($exclude_major_revisions) {
840                 // Include only minor revisions
841                 $pick[] = "minor_edit <> 0";
842             } elseif (!$include_minor_revisions) {
843                 // Include only major revisions
844                 $pick[] = "minor_edit = 0";
845             }
846         } else {
847             $table = "$page_tbl, $recent_tbl";
848             $join_clause = "$page_tbl.id=$recent_tbl.id";
849             $table .= ", $version_tbl";
850             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
851
852             if ($exclude_major_revisions) {
853                 // Include only most recent minor revision
854                 $pick[] = 'version=latestminor';
855             } elseif (!$include_minor_revisions) {
856                 // Include only most recent major revision
857                 $pick[] = 'version=latestmajor';
858             } else {
859                 // Include only the latest revision (whether major or minor).
860                 $pick[] = 'version=latestversion';
861             }
862         }
863         $order = "DESC";
864         if ($limit < 0) {
865             $order = "ASC";
866             $limit = -$limit;
867         }
868         // $limitclause = $limit ? " LIMIT $limit" : '';
869         $where_clause = $join_clause;
870         if ($pick)
871             $where_clause .= " AND " . join(" AND ", $pick);
872
873         // FIXME: use SQL_BUFFER_RESULT for mysql?
874         $sql = "SELECT "
875             . $this->page_tbl_fields . ", " . $this->version_tbl_fields
876             . " FROM $table"
877             . " WHERE $where_clause"
878             . " ORDER BY mtime $order";
879         if ($limit) {
880             list($from, $count) = $this->limit($limit);
881             $result = $dbh->limitQuery($sql, $from, $count);
882         } else {
883             $result = $dbh->query($sql);
884         }
885         return new WikiDB_backend_PearDB_iter($this, $result);
886     }
887
888     /**
889      * Find referenced empty pages.
890      */
891     function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
892     {
893         $dbh = &$this->_dbh;
894         extract($this->_table_names);
895         if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom')))
896             $orderby = 'ORDER BY ' . $orderby;
897
898         if ($exclude_from) // array of pagenames
899             $exclude_from = " AND pp.pagename NOT IN " . $this->_sql_set($exclude_from);
900         if ($exclude) // array of pagenames
901             $exclude = " AND p.pagename NOT IN " . $this->_sql_set($exclude);
902         $sql = "SELECT p.pagename, pp.pagename AS wantedfrom"
903             . " FROM $page_tbl p, $link_tbl linked"
904             . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
905             . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
906             . " WHERE ne.id IS NULL"
907             . " AND p.id = linked.linkfrom"
908             . $exclude_from
909             . $exclude
910             . $orderby;
911         if ($limit) {
912             // oci8 error: WHERE NULL = NULL appended
913             list($from, $count) = $this->limit($limit);
914             $result = $dbh->limitQuery($sql, $from, $count * 3);
915         } else {
916             $result = $dbh->query($sql);
917         }
918         return new WikiDB_backend_PearDB_generic_iter($this, $result);
919     }
920
921     function _sql_set(&$pagenames)
922     {
923         $s = '(';
924         foreach ($pagenames as $p) {
925             $s .= ("'" . $this->_dbh->escapeSimple($p) . "',");
926         }
927         return substr($s, 0, -1) . ")";
928     }
929
930     /**
931      * Rename page in the database.
932      */
933     function rename_page($pagename, $to)
934     {
935         $dbh = &$this->_dbh;
936         extract($this->_table_names);
937
938         $this->lock();
939         if (($id = $this->_get_pageid($pagename, false))) {
940             if ($new = $this->_get_pageid($to, false)) {
941                 // Cludge Alert!
942                 // This page does not exist (already verified before), but exists in the page table.
943                 // So we delete this page.
944                 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
945                 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
946                 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
947                 // We have to fix all referring tables to the old id
948                 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
949                 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
950                 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
951             }
952             $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
953                 $dbh->escapeSimple($to)));
954         }
955         $this->unlock();
956         return $id;
957     }
958
959     function _update_recent_table($pageid = false)
960     {
961         $dbh = &$this->_dbh;
962         extract($this->_table_names);
963         extract($this->_expressions);
964
965         $pageid = (int)$pageid;
966
967         $this->lock();
968         $dbh->query("DELETE FROM $recent_tbl"
969             . ($pageid ? " WHERE id=$pageid" : ""));
970         $dbh->query("INSERT INTO $recent_tbl"
971             . " (id, latestversion, latestmajor, latestminor)"
972             . " SELECT id, $maxversion, $maxmajor, $maxminor"
973             . " FROM $version_tbl"
974             . ($pageid ? " WHERE id=$pageid" : "")
975             . " GROUP BY id");
976         $this->unlock();
977     }
978
979     function _update_nonempty_table($pageid = false)
980     {
981         $dbh = &$this->_dbh;
982         extract($this->_table_names);
983
984         $pageid = (int)$pageid;
985
986         extract($this->_expressions);
987         $this->lock();
988         $dbh->query("DELETE FROM $nonempty_tbl"
989             . ($pageid ? " WHERE id=$pageid" : ""));
990         $dbh->query("INSERT INTO $nonempty_tbl (id)"
991             . " SELECT $recent_tbl.id"
992             . " FROM $recent_tbl, $version_tbl"
993             . " WHERE $recent_tbl.id=$version_tbl.id"
994             . "       AND version=latestversion"
995             // We have some specifics here (Oracle)
996             //. "  AND content<>''"
997             . "  AND content $notempty"
998             . ($pageid ? " AND $recent_tbl.id=$pageid" : ""));
999
1000         $this->unlock();
1001     }
1002
1003     /**
1004      * Grab a write lock on the tables in the SQL database.
1005      *
1006      * Calls can be nested.  The tables won't be unlocked until
1007      * _unlock_database() is called as many times as _lock_database().
1008      *
1009      * @access protected
1010      */
1011     function lock($tables = false, $write_lock = true)
1012     {
1013         if ($this->_lock_count++ == 0)
1014             $this->_lock_tables($write_lock);
1015     }
1016
1017     /**
1018      * Actually lock the required tables.
1019      */
1020     function _lock_tables($write_lock)
1021     {
1022         trigger_error("virtual", E_USER_ERROR);
1023     }
1024
1025     /**
1026      * Release a write lock on the tables in the SQL database.
1027      *
1028      * @access protected
1029      *
1030      * @param $force boolean Unlock even if not every call to lock() has been matched
1031      * by a call to unlock().
1032      *
1033      * @see _lock_database
1034      */
1035     function unlock($tables = false, $force = false)
1036     {
1037         if ($this->_lock_count == 0)
1038             return;
1039         if (--$this->_lock_count <= 0 || $force) {
1040             $this->_unlock_tables();
1041             $this->_lock_count = 0;
1042         }
1043     }
1044
1045     /**
1046      * Actually unlock the required tables.
1047      */
1048     function _unlock_tables($write_lock)
1049     {
1050         trigger_error("virtual", E_USER_ERROR);
1051     }
1052
1053
1054     /**
1055      * Serialize data
1056      */
1057     function _serialize($data)
1058     {
1059         if (empty($data))
1060             return '';
1061         assert(is_array($data));
1062         return serialize($data);
1063     }
1064
1065     /**
1066      * Unserialize data
1067      */
1068     function _unserialize($data)
1069     {
1070         return empty($data) ? array() : unserialize($data);
1071     }
1072
1073     /**
1074      * Callback for PEAR (DB) errors.
1075      *
1076      * @access protected
1077      *
1078      * @param A PEAR_error object.
1079      */
1080     function _pear_error_callback($error)
1081     {
1082         if ($this->_is_false_error($error))
1083             return;
1084
1085         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
1086         $this->close();
1087         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
1088     }
1089
1090     /**
1091      * Detect false errors messages from PEAR DB.
1092      *
1093      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
1094      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
1095      * return any data.  (So when a "LOCK" command doesn't return any data,
1096      * DB reports it as an error, when in fact, it's not.)
1097      *
1098      * @access private
1099      * @return bool True iff error is not really an error.
1100      */
1101     function _is_false_error($error)
1102     {
1103         if ($error->getCode() != DB_ERROR)
1104             return false;
1105
1106         $query = $this->_dbh->last_query;
1107
1108         if (!preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
1109             . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)
1110         ) {
1111             // Last query was not of the sort which doesn't return any data.
1112             //" <--kludge for brain-dead syntax coloring
1113             return false;
1114         }
1115
1116         if (!in_array('ismanip', get_class_methods('DB'))) {
1117             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
1118             // does not have the DB::isManip method.
1119             return true;
1120         }
1121
1122         if (DB::isManip($query)) {
1123             // If Pear thinks it's an isManip then it wouldn't have thrown
1124             // the error we're testing for....
1125             return false;
1126         }
1127
1128         return true;
1129     }
1130
1131     function _pear_error_message($error)
1132     {
1133         $class = get_class($this);
1134         $message = "$class: fatal database error\n"
1135             . "\t" . $error->getMessage() . "\n"
1136             . "\t(" . $error->getDebugInfo() . ")\n";
1137
1138         // Prevent password from being exposed during a connection error
1139         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
1140             '\\1:XXXXXXXX', $this->_dsn);
1141         return str_replace($this->_dsn, $safe_dsn, $message);
1142     }
1143
1144     /**
1145      * Filter PHP errors notices from PEAR DB code.
1146      *
1147      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
1148      * errors and notices.  This is an error callback (for use with
1149      * ErrorManager which will filter out those spurious messages.)
1150      * @see _is_false_error, ErrorManager
1151      * @access private
1152      */
1153     function _pear_notice_filter($err)
1154     {
1155         return ($err->isNotice()
1156             && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
1157             && $err->errline == 126
1158             && preg_match('/Undefined offset: +0\b/', $err->errstr));
1159     }
1160
1161     /* some variables and functions for DB backend abstraction (action=upgrade) */
1162     function database()
1163     {
1164         return $this->_dbh->dsn['database'];
1165     }
1166
1167     function backendType()
1168     {
1169         return $this->_dbh->phptype;
1170     }
1171
1172     function connection()
1173     {
1174         return $this->_dbh->connection;
1175     }
1176
1177     function getRow($query)
1178     {
1179         return $this->_dbh->getRow($query);
1180     }
1181
1182     function listOfTables()
1183     {
1184         return $this->_dbh->getListOf('tables');
1185     }
1186
1187     function listOfFields($database, $table)
1188     {
1189         if ($this->backendType() == 'mysql') {
1190             $fields = array();
1191             assert(!empty($database));
1192             assert(!empty($table));
1193             $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
1194                 trigger_error(__FILE__ . ':' . __LINE__ . ' ' . mysql_error(), E_USER_WARNING);
1195             if (!$result) return array();
1196             $columns = mysql_num_fields($result);
1197             for ($i = 0; $i < $columns; $i++) {
1198                 $fields[] = mysql_field_name($result, $i);
1199             }
1200             mysql_free_result($result);
1201             return $fields;
1202         } else {
1203             // TODO: try ADODB version?
1204             trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1205             return false;
1206         }
1207     }
1208 }
1209
1210 /**
1211  * This class is a generic iterator.
1212  *
1213  * WikiDB_backend_PearDB_iter only iterates over things that have
1214  * 'pagename', 'pagedata', etc. etc.
1215  *
1216  * Probably WikiDB_backend_PearDB_iter and this class should be merged
1217  * (most of the code is cut-and-paste :-( ), but I am trying to make
1218  * changes that could be merged easily.
1219  *
1220  * @author: Dan Frankowski
1221  */
1222 class WikiDB_backend_PearDB_generic_iter
1223     extends WikiDB_backend_iterator
1224 {
1225     function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL)
1226     {
1227         if (DB::isError($query_result)) {
1228             // This shouldn't happen, I thought.
1229             $backend->_pear_error_callback($query_result);
1230         }
1231
1232         $this->_backend = &$backend;
1233         $this->_result = $query_result;
1234         $this->_options = $field_list;
1235     }
1236
1237     function count()
1238     {
1239         if (!$this->_result)
1240             return false;
1241         return $this->_result->numRows();
1242     }
1243
1244     function next()
1245     {
1246         if (!$this->_result)
1247             return false;
1248
1249         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1250         if (!$record) {
1251             $this->free();
1252             return false;
1253         }
1254
1255         return $record;
1256     }
1257
1258     function reset()
1259     {
1260         if ($this->_result) {
1261             $this->_result->MoveFirst();
1262         }
1263     }
1264
1265     function free()
1266     {
1267         if ($this->_result) {
1268             $this->_result->free();
1269             $this->_result = false;
1270         }
1271     }
1272
1273     function asArray()
1274     {
1275         $result = array();
1276         while ($page = $this->next())
1277             $result[] = $page;
1278         return $result;
1279     }
1280 }
1281
1282 class WikiDB_backend_PearDB_iter
1283     extends WikiDB_backend_PearDB_generic_iter
1284 {
1285
1286     function next()
1287     {
1288         $backend = &$this->_backend;
1289         if (!$this->_result) {
1290             return false;
1291         }
1292
1293         if (!is_object($this->_result)) {
1294             return false;
1295         }
1296
1297         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1298         if (!$record) {
1299             $this->free();
1300             return false;
1301         }
1302
1303         $pagedata = $backend->_extract_page_data($record);
1304         $rec = array('pagename' => $record['pagename'],
1305             'pagedata' => $pagedata);
1306
1307         if (!empty($record['version'])) {
1308             $rec['versiondata'] = $backend->_extract_version_data($record);
1309             $rec['version'] = $record['version'];
1310         }
1311
1312         return $rec;
1313     }
1314 }
1315
1316 class WikiDB_backend_PearDB_search extends WikiDB_backend_search_sql
1317 {
1318     // no surrounding quotes because we know it's a string
1319     // function _quote($word) { return $this->_dbh->addq($word); }
1320 }
1321
1322 // Local Variables:
1323 // mode: php
1324 // tab-width: 8
1325 // c-basic-offset: 4
1326 // c-hanging-comment-ender-p: nil
1327 // indent-tabs-mode: nil
1328 // End: