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