]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PearDB.php
Jeff's hacks II.
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PearDB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PearDB.php,v 1.1 2001-09-18 19:16:23 dairiki Exp $');
3
4 require_once('DB.php');
5 require_once('lib/WikiDB/backend.php');
6
7 class WikiDB_backend_PearDB
8 extends WikiDB_backend
9 {
10     function WikiDB_backend_PearDB ($dbparams) {
11         // Open connection to database
12         $dsn = $dbparams['dsn'];
13         $this->_dbh = DB::connect($dsn, true); //FIXME: true -> persistent connection
14         $dbh = &$this->_dbh;
15         if (DB::isError($dbh)) {
16             trigger_error("Can't connect to database: "
17                           . $this->_pear_error_message($dbh),
18                           E_USER_ERROR);
19         }
20         $this->_dbh = $dbh;
21         $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
22                                array($this, '_pear_error_callback'));
23         $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
24
25         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
26
27         $this->_table_names
28             = array('page_tbl'     => $prefix . 'page',
29                     'version_tbl'  => $prefix . 'version',
30                     'link_tbl'     => $prefix . 'link',
31                     'recent_tbl'   => $prefix . 'recent',
32                     'nonempty_tbl' => $prefix . 'nonempty');
33
34         $this->_lock_count = 0;
35     }
36     
37     /**
38      * Close database connection.
39      */
40     function close () {
41         if (!$this->_dbh)
42             return;
43         if ($this->_lock_count) {
44             trigger_error("WARNING: database still locked"
45                           . " (lock_count = $this->_lock_count)\n<br>",
46                           E_USER_WARNING);
47         }
48         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
49         $this->unlock('force');
50
51         $this->_dbh->disconnect();
52         $this->_dbh = false;
53     }
54
55
56     /*
57      * Test fast wikipage.
58      */
59     function is_wiki_page($pagename) {
60         $dbh = &$this->_dbh;
61         extract($this->_table_names);
62         return $dbh->getOne(sprintf("SELECT $page_tbl.id"
63                                     . " FROM $nonempty_tbl INNER JOIN $page_tbl USING(id)"
64                                     . " WHERE pagename='%s'",
65                                     $dbh->quoteString($pagename)));
66     }
67         
68     function get_all_pagenames() {
69         $dbh = &$this->_dbh;
70         extract($this->_table_names);
71         return $dbh->getCol("SELECT pagename"
72                             . " FROM $nonempty_tbl INNER JOIN $page_tbl USING(id)");
73     }
74             
75     /**
76      * Read page information from database.
77      */
78     function get_pagedata($pagename) {
79         $dbh = &$this->_dbh;
80         $page_tbl = $this->_table_names['page_tbl'];
81
82         //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
83
84         $result = $dbh->getRow(sprintf("SELECT * FROM $page_tbl WHERE pagename='%s'",
85                                        $dbh->quoteString($pagename)),
86                                DB_FETCHMODE_ASSOC);
87         if (!$result)
88             return false;
89         return $this->_extract_page_data($result);
90     }
91
92     function  _extract_page_data(&$query_result) {
93         extract($query_result);
94         $data = empty($pagedata) ? array() : unserialize($pagedata);
95         $data['hits'] = $hits;
96         return $data;
97     }
98
99     function update_pagedata($pagename, $newdata) {
100         $dbh = &$this->_dbh;
101         $page_tbl = $this->_table_names['page_tbl'];
102
103         // Hits is the only thing we can update in a fast manner.
104         if (count($newdata) == 1 && isset($newdata['hits'])) {
105             // Note that this will fail silently if the page does not
106             // have a record in the page table.  Since it's just the
107             // hit count, who cares?
108             $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
109                                 $newdata['hits'], $dbh->quoteString($pagename)));
110             return;
111         }
112
113         $this->lock();
114         $data = $this->get_pagedata($pagename);
115         if (!$data) {
116             $data = array();
117             $this->_get_pageid($pagename, true); // Creates page record
118         }
119         
120         @$hits = (int)$data['hits'];
121         unset($data['hits']);
122
123         foreach ($newdata as $key => $val) {
124             if ($key == 'hits')
125                 $hits = (int)$val;
126             else if (empty($val))
127                 unset($data[$key]);
128             else
129                 $data[$key] = $val;
130         }
131
132         $dbh->query(sprintf("UPDATE $page_tbl"
133                             . " SET hits=%d, pagedata='%s'"
134                             . " WHERE pagename='%s'",
135                             $hits,
136                             $dbh->quoteString(serialize($data)),
137                             $dbh->quoteString($pagename)));
138
139         $this->unlock();
140     }
141
142     function _get_pageid($pagename, $create_if_missing = false) {
143         
144         $dbh = &$this->_dbh;
145         $page_tbl = $this->_table_names['page_tbl'];
146         
147         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
148                          $dbh->quoteString($pagename));
149
150         if (!$create_if_missing)
151             return $dbh->getOne($query);
152
153         $this->lock();
154         $id = $dbh->getOne($query);
155         if (empty($id)) {
156             $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
157             $id = $max_id + 1;
158             $dbh->query(sprintf("INSERT INTO $page_tbl"
159                                 . " (id,pagename,hits)"
160                                 . " VALUES (%d,'%s',0)",
161                                 $id, $dbh->quoteString($pagename)));
162         }
163         $this->unlock();
164         return $id;
165     }
166
167     function get_latest_version($pagename) {
168         $dbh = &$this->_dbh;
169         extract($this->_table_names);
170         return
171             (int)$dbh->getOne(sprintf("SELECT latestversion"
172                                       . " FROM $page_tbl"
173                                       . "  INNER JOIN $recent_tbl USING(id)"
174                                       . " WHERE pagename='%s'",
175                                       $dbh->quoteString($pagename)));
176     }
177
178     function get_previous_version($pagename, $version) {
179         $dbh = &$this->_dbh;
180         extract($this->_table_names);
181         
182         return
183             (int)$dbh->getOne(sprintf("SELECT version"
184                                       . " FROM $version_tbl"
185                                       . "  INNER JOIN $page_tbl USING(id)"
186                                       . " WHERE pagename='%s'"
187                                       . "  AND version < %d"
188                                       . " ORDER BY version DESC"
189                                       . " LIMIT 1",
190                                       $dbh->quoteString($pagename),
191                                       $version));
192     }
193     
194     /**
195      * Get version data.
196      *
197      * @param $version int Which version to get.
198      *
199      * @return hash The version data, or false if specified version does not
200      *              exist.
201      */
202     function get_versiondata($pagename, $version, $want_content = false) {
203         $dbh = &$this->_dbh;
204         extract($this->_table_names);
205                 
206         assert(!empty($pagename));
207         assert($version > 0);
208         
209         //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
210         // FIXME: optimization: sometimes don't get page data?
211
212         if ($want_content) {
213             $fields = "*";
214         }
215         else {
216             $fields = ("$page_tbl.*,"
217                        . "mtime,minor_edit,versiondata,"
218                        . "content<>'' AS have_content");
219         }
220
221         $result = $dbh->getRow(sprintf("SELECT $fields"
222                                        . " FROM $page_tbl"
223                                        . "  INNER JOIN $version_tbl USING(id)"
224                                        . " WHERE pagename='%s' AND version=%d",
225                                        $dbh->quoteString($pagename), $version),
226                                DB_FETCHMODE_ASSOC);
227
228         return $this->_extract_version_data($result);
229     }
230
231     function _extract_version_data(&$query_result) {
232         if (!$query_result)
233             return false;
234
235         extract($query_result);
236         $data = empty($versiondata) ? array() : unserialize($versiondata);
237
238         $data['mtime'] = $mtime;
239         $data['is_minor_edit'] = !empty($minor_edit);
240         
241         if (isset($content))
242             $data['%content'] = $content;
243         elseif ($have_content)
244             $data['%content'] = true;
245         else
246             $data['%content'] = '';
247
248         // FIXME: this is ugly.
249         if (isset($pagename)) {
250             // Query also includes page data.
251             // We might as well send that back too...
252             $data['%pagedata'] = $this->_extract_page_data($query_result);
253         }
254
255         return $data;
256     }
257
258
259     /**
260      * Create a new revision of a page.
261      */
262     function set_versiondata($pagename, $version, $data) {
263         $dbh = &$this->_dbh;
264         $version_tbl = $this->_table_names['version_tbl'];
265         
266         $minor_edit = (int) !empty($data['is_minor_edit']);
267         unset($data['is_minor_edit']);
268         
269         $mtime = (int)$data['mtime'];
270         unset($data['mtime']);
271         assert(!empty($mtime));
272
273         @$content = (string) $data['%content'];
274         unset($data['%content']);
275
276         unset($data['%pagedata']);
277         
278         $this->lock();
279         $id = $this->_get_pageid($pagename, true);
280
281         // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
282         $dbh->query(sprintf("DELETE FROM $version_tbl"
283                             . " WHERE id=%d AND version=%d",
284                             $id, $version));
285
286         $dbh->query(sprintf("INSERT INTO $version_tbl"
287                             . " (id,version,mtime,minor_edit,content,versiondata)"
288                             . " VALUES(%d,%d,%d,%d,'%s','%s')",
289                             $id, $version, $mtime, $minor_edit,
290                             $dbh->quoteString($content),
291                             $dbh->quoteString(serialize($data))));
292
293         $this->_update_recent_table($id);
294         $this->_update_nonempty_table($id);
295         
296         $this->unlock();
297     }
298     
299     /**
300      * Delete an old revision of a page.
301      */
302     function delete_versiondata($pagename, $version) {
303         $dbh = &$this->_dbh;
304         extract($this->_table_names);
305
306         $this->lock();
307         if ( ($id = $this->_get_pageid($pagename)) ) {
308             $dbh->query("DELETE FROM $version_tbl"
309                         . " WHERE id=$id AND version=$version");
310             $this->_update_recent_table($id);
311             // This shouldn't be needed (as long as the latestversion
312             // never gets deleted.)  But, let's be safe.
313             $this->_update_nonempty_table($id);
314         }
315         $this->unlock();
316     }
317
318     /**
319      * Delete page from the database.
320      */
321     function delete_page($pagename) {
322         $dbh = &$this->_dbh;
323         extract($this->_table_names);
324         
325         $this->lock();
326         if ( ($id = $this->_get_pageid($pagename, 'id')) ) {
327             $dbh->query("DELETE FROM $version_tbl  WHERE id=$id");
328             $dbh->query("DELETE FROM $recent_tbl   WHERE id=$id");
329             $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
330             $dbh->query("DELETE FROM $link_tbl     WHERE linkfrom=$id");
331             $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
332             if ($nlinks) {
333                 // We're still in the link table (dangling link) so we can't delete this
334                 // altogether.
335                 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
336             }
337             else {
338                 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
339             }
340             $this->_update_recent_table();
341             $this->_update_nonempty_table();
342         }
343         $this->unlock();
344     }
345             
346
347     // The only thing we might be interested in updating which we can
348     // do fast in the flags (minor_edit).   I think the default
349     // update_versiondata will work fine...
350     //function update_versiondata($pagename, $version, $data) {
351     //}
352
353     function set_links($pagename, $links) {
354         // Update link table.
355         // FIXME: optimize: mysql can do this all in one big INSERT.
356
357         $dbh = &$this->_dbh;
358         extract($this->_table_names);
359
360         $this->lock();
361         $pageid = $this->_get_pageid($pagename, true);
362
363         $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
364
365         foreach($links as $link) {
366             if (isset($linkseen[$link]))
367                 continue;
368             $linkseen[$link] = true;
369             $linkid = $this->_get_pageid($link, true);
370             $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
371                         . " VALUES ($pageid, $linkid)");
372         }
373         $this->unlock();
374     }
375     
376     /**
377      * Find pages which link to or are linked from a page.
378      */
379     function get_links($pagename, $reversed = true) {
380         $dbh = &$this->_dbh;
381         extract($this->_table_names);
382
383         if ($reversed)
384             list($have,$want) = array('linkee', 'linker');
385         else
386             list($have,$want) = array('linker', 'linkee');
387
388         $qpagename = $dbh->quoteString($pagename);
389         
390         $result = $dbh->query("SELECT $want.*"
391                               . " FROM $link_tbl"
392                               . "  INNER JOIN $page_tbl AS linker ON linkfrom=linker.id"
393                               . "  INNER JOIN $page_tbl AS linkee ON linkto=linkee.id"
394                               . " WHERE $have.pagename='$qpagename'"
395                               //. " GROUP BY $want.id"
396                               . " ORDER BY $want.pagename",
397                               DB_FETCHMODE_ASSOC);
398         
399         return new WikiDB_backend_PearDB_iter($this, $result);
400     }
401
402     function get_all_pages($include_deleted) {
403         $dbh = &$this->_dbh;
404         extract($this->_table_names);
405
406         if ($include_deleted) {
407             $result = $dbh->query("SELECT * FROM $page_tbl ORDER BY pagename");
408         }
409         else {
410             $result = $dbh->query("SELECT $page_tbl.*"
411                                   . " FROM $nonempty_tbl INNER JOIN $page_tbl USING(id)"
412                                   . " ORDER BY pagename");
413         }
414
415         return new WikiDB_backend_PearDB_iter($this, $result);
416     }
417         
418     /**
419      * Title search.
420      */
421     function text_search($search = '', $fullsearch = false) {
422         $dbh = &$this->_dbh;
423         extract($this->_table_names);
424         
425         $table = "$nonempty_tbl INNER JOIN $page_tbl USING(id)";
426         $fields = "$page_tbl.*";
427         $callback = '_sql_match_clause';
428         
429         if ($fullsearch) {
430             $table .= (" INNER JOIN $recent_tbl ON $page_tbl.id=$recent_tbl.id"
431                        . " INNER JOIN $version_tbl"
432                        . "   ON $page_tbl.id=$version_tbl.id"
433                        . "   AND latestversion=version" );
434             $fields .= ",$version_tbl.*";
435             $callback = '_fullsearch_sql_match_clause';
436         }
437
438         
439         $search_clause = $search->makeSqlClause(array($this, $callback));
440         
441         $result = $dbh->query("SELECT $fields FROM $table"
442                               . " WHERE $search_clause"
443                               . " ORDER BY pagename");
444         
445         return new WikiDB_backend_PearDB_iter($this, $result);
446     }
447
448     function _sql_match_clause($word) {
449         $word = $this->_dbh->quoteString($word);
450         return "LOWER(pagename) LIKE '%$word%'";
451     }
452
453     function _fullsearch_sql_match_clause($word) {
454         $word = $this->_dbh->quoteString($word);
455         return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
456     }
457
458     /**
459      * Find highest hit counts.
460      */
461     function most_popular($limit) {
462         $dbh = &$this->_dbh;
463         extract($this->_table_names);
464
465         $limitclause = $limit ? " LIMIT $limit" : '';
466         $result = $dbh->query("SELECT $page_tbl.*"
467                               . " FROM $nonempty_tbl INNER JOIN $page_tbl USING(id)"
468                               . " ORDER BY hits DESC"
469                               . " $limitclause");
470
471         return new WikiDB_backend_PearDB_iter($this, $result);
472     }
473
474     /**
475      * Find recent changes.
476      */
477     function most_recent($params) {
478         $limit = 0;
479         $since = 0;
480         $include_minor_revisions = false;
481         $exclude_major_revisions = false;
482         $include_all_revisions = false;
483         extract($params);
484
485         $dbh = &$this->_dbh;
486         extract($this->_table_names);
487
488         $pick = array();
489         if ($since)
490             $pick[] = "mtime >= $since";
491         
492         if ($include_all_revisions) {
493             // Include all revisions of each page.
494             $table = "$page_tbl INNER JOIN $version_tbl USING(id)";
495
496             if ($exclude_major_revisions) {
497                 // Include only minor revisions
498                 $pick[] = "minor_edit <> 0";
499             }
500             elseif (!$include_minor_revisions) {
501                 // Include only major revisions
502                 $pick[] = "minor_edit = 0";
503             }
504         }
505         else {
506             $table = ( "$page_tbl INNER JOIN $recent_tbl USING(id)"
507                        . " INNER JOIN $version_tbl ON $version_tbl.id=$page_tbl.id");
508                 
509             if ($exclude_major_revisions) {
510                 // Include only most recent minor revision
511                 $pick[] = 'version=latestminor';
512             }
513             elseif (!$include_minor_revisions) {
514                 // Include only most recent major revision
515                 $pick[] = 'version=latestmajor';
516             }
517             else {
518                 // Include only the latest revision (whether major or minor).
519                 $pick[] ='version=latestversion';
520             }
521         }
522
523         $limitclause = $limit ? " LIMIT $limit" : '';
524         $whereclause = $pick ? " WHERE " . join(" AND ", $pick) : '';
525
526         // FIXME: use SQL_BUFFER_RESULT for mysql?
527         $result = $dbh->query("SELECT $page_tbl.*,$version_tbl.*"
528                               . " FROM $table"
529                               . $whereclause
530                               . " ORDER BY mtime DESC"
531                               . $limitclause);
532
533         return new WikiDB_backend_PearDB_iter($this, $result);
534     }
535
536     function _update_recent_table($pageid = false) {
537         $dbh = &$this->_dbh;
538         extract($this->_table_names);
539
540         $maxmajor = "MAX(CASE WHEN minor_edit=0 THEN version END)";
541         $maxminor = "MAX(CASE WHEN minor_edit<>0 THEN version END)";
542         $maxversion = "MAX(version)";
543
544         $pageid = (int)$pageid;
545
546         $this->lock();
547
548         $dbh->query("DELETE FROM $recent_tbl"
549                     . ( $pageid ? " WHERE id=$pageid" : ""));
550         
551         $dbh->query( "INSERT INTO $recent_tbl"
552                      . " (id, latestversion, latestmajor, latestminor)"
553                      . " SELECT id, $maxversion, $maxmajor, $maxminor"
554                      . " FROM $version_tbl"
555                      . ( $pageid ? " WHERE id=$pageid" : "")
556                      . " GROUP BY id" );
557         $this->unlock();
558     }
559
560     function _update_nonempty_table($pageid = false) {
561         $dbh = &$this->_dbh;
562         extract($this->_table_names);
563
564         $pageid = (int)$pageid;
565
566         $this->lock();
567
568         $dbh->query("DELETE FROM $nonempty_tbl"
569                     . ( $pageid ? " WHERE id=$pageid" : ""));
570
571         $dbh->query("INSERT INTO $nonempty_tbl (id)"
572                     . " SELECT $recent_tbl.id"
573                     . " FROM $recent_tbl INNER JOIN $version_tbl"
574                     . "               ON $recent_tbl.id=$version_tbl.id"
575                     . "                  AND version=latestversion"
576                     . "  WHERE content<>''"
577                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
578
579         $this->unlock();
580     }
581
582
583     /**
584      * Grab a write lock on the tables in the SQL database.
585      *
586      * Calls can be nested.  The tables won't be unlocked until
587      * _unlock_database() is called as many times as _lock_database().
588      *
589      * @access protected
590      */
591     function lock($write_lock = true) {
592         if ($this->_lock_count++ == 0)
593             $this->_lock_tables($write_lock);
594     }
595
596     /**
597      * Actually lock the required tables.
598      */
599     function _lock_tables($write_lock) {
600         trigger_error("virtual", E_USER_ERROR);
601     }
602     
603     /**
604      * Release a write lock on the tables in the SQL database.
605      *
606      * @access protected
607      *
608      * @param $force boolean Unlock even if not every call to lock() has been matched
609      * by a call to unlock().
610      *
611      * @see _lock_database
612      */
613     function unlock($force = false) {
614         if ($this->_lock_count == 0)
615             return;
616         if (--$this->_lock_count <= 0 || $force) {
617             $this->_unlock_tables();
618             $this->_lock_count = 0;
619         }
620     }
621
622     /**
623      * Actually unlock the required tables.
624      */
625     function _unlock_tables($write_lock) {
626         trigger_error("virtual", E_USER_ERROR);
627     }
628     
629     /**
630      * Callback for PEAR (DB) errors.
631      *
632      * @access protected
633      *
634      * @param A PEAR_error object.
635      */
636     function _pear_error_callback($error) {
637         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
638         $this->close();
639         //trigger_error($this->_pear_error_message($error), E_USER_WARNING);
640         ExitWiki($this->_pear_error_message($error));
641     }
642
643     function _pear_error_message($error) {
644         $class = get_class($this);
645         $message = "$class: fatal database error\n"
646              . "\t" . $error->getMessage() . "\n"
647              . "\t(" . $error->getDebugInfo() . ")\n";
648
649         return $message;
650     }
651 };
652
653 class WikiDB_backend_PearDB_iter
654 extends WikiDB_backend_iterator
655 {
656     function WikiDB_backend_PearDB_iter(&$backend, &$query_result) {
657         if (DB::isError($query_result)) {
658             // This shouldn't happen, I thought.
659             $backend->_pear_error_callback($query_result);
660         }
661         
662         $this->_backend = &$backend;
663         $this->_result = $query_result;
664     }
665     
666     function next() {
667         $backend = &$this->_backend;
668         if (!$this->_result)
669             return false;
670
671         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
672         if (!$record) {
673             $this->free();
674             return false;
675         }
676         
677         $pagedata = $backend->_extract_page_data($record);
678         $rec = array('pagename' => $record['pagename'],
679                      'pagedata' => $pagedata);
680
681         if (!empty($record['version'])) {
682             $rec['versiondata'] = $backend->_extract_version_data($record);
683             $rec['version'] = $record['version'];
684         }
685         
686         return $rec;
687     }
688
689     function free () {
690         if ($this->_result) {
691             $this->_result->free();
692             $this->_result = false;
693         }
694     }
695 }
696
697 // (c-file-style: "gnu")
698 // Local Variables:
699 // mode: php
700 // tab-width: 8
701 // c-basic-offset: 4
702 // c-hanging-comment-ender-p: nil
703 // indent-tabs-mode: nil
704 // End:   
705 ?>