]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PearDB.php
add native asArray methods to generic iters (for DebugInfo)
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PearDB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PearDB.php,v 1.108 2007-06-07 21:37:39 rurban Exp $');
3
4 require_once('lib/WikiDB/backend.php');
5 //require_once('lib/FileFinder.php');
6 //require_once('lib/ErrorManager.php');
7
8 class WikiDB_backend_PearDB
9 extends WikiDB_backend
10 {
11     var $_dbh;
12
13     function WikiDB_backend_PearDB ($dbparams) {
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         if (!$this->_dbh)
95             return;
96         if ($this->_lock_count) {
97             trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
98                           E_USER_WARNING);
99         }
100         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
101         $this->unlock('force');
102
103         $this->_dbh->disconnect();
104
105         if (!empty($this->_pearerrhandler)) {
106             $GLOBALS['ErrorManager']->popErrorHandler();
107         }
108     }
109
110
111     /*
112      * Test fast wikipage.
113      */
114     function is_wiki_page($pagename) {
115         $dbh = &$this->_dbh;
116         extract($this->_table_names);
117         return $dbh->getOne(sprintf("SELECT $page_tbl.id as id"
118                                     . " FROM $nonempty_tbl, $page_tbl"
119                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
120                                     . "   AND pagename='%s'",
121                                     $dbh->escapeSimple($pagename)));
122     }
123         
124     function get_all_pagenames() {
125         $dbh = &$this->_dbh;
126         extract($this->_table_names);
127         return $dbh->getCol("SELECT pagename"
128                             . " FROM $nonempty_tbl, $page_tbl"
129                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
130     }
131
132     function numPages($filter=false, $exclude='') {
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         $dbh = &$this->_dbh;
142         // Hits is the only thing we can update in a fast manner.
143         // Note that this will fail silently if the page does not
144         // have a record in the page table.  Since it's just the
145         // hit count, who cares?
146         $dbh->query(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename='%s'",
147                             $this->_table_names['page_tbl'],
148                             $dbh->escapeSimple($pagename)));
149         return;
150     }
151
152     /**
153      * Read page information from database.
154      */
155     function get_pagedata($pagename) {
156         $dbh = &$this->_dbh;
157         //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
158         $result = $dbh->getRow(sprintf("SELECT hits,pagedata FROM %s WHERE pagename='%s'",
159                                        $this->_table_names['page_tbl'],
160                                        $dbh->escapeSimple($pagename)),
161                                DB_FETCHMODE_ASSOC);
162         return $result ? $this->_extract_page_data($result) : false;
163     }
164
165     function  _extract_page_data($data) {
166         if (empty($data)) return array();
167         elseif (empty($data['pagedata'])) return $data;
168         else {
169             $data = array_merge($data, $this->_unserialize($data['pagedata']));
170             unset($data['pagedata']);
171             return $data;
172         }
173     }
174
175     function update_pagedata($pagename, $newdata) {
176         $dbh = &$this->_dbh;
177         $page_tbl = $this->_table_names['page_tbl'];
178
179         // Hits is the only thing we can update in a fast manner.
180         if (count($newdata) == 1 && isset($newdata['hits'])) {
181             // Note that this will fail silently if the page does not
182             // have a record in the page table.  Since it's just the
183             // hit count, who cares?
184             $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
185                                 $newdata['hits'], $dbh->escapeSimple($pagename)));
186             return;
187         }
188
189         $this->lock(array($page_tbl), true);
190         $data = $this->get_pagedata($pagename);
191         if (!$data) {
192             $data = array();
193             $this->_get_pageid($pagename, true); // Creates page record
194         }
195         
196         @$hits = (int)$data['hits'];
197         unset($data['hits']);
198
199         foreach ($newdata as $key => $val) {
200             if ($key == 'hits')
201                 $hits = (int)$val;
202             else if (empty($val))
203                 unset($data[$key]);
204             else
205                 $data[$key] = $val;
206         }
207
208         /* Portability issue -- not all DBMS supports huge strings 
209          * so we need to 'bind' instead of building a simple SQL statment.
210          * Note that we do not need to escapeSimple when we bind
211         $dbh->query(sprintf("UPDATE $page_tbl"
212                             . " SET hits=%d, pagedata='%s'"
213                             . " WHERE pagename='%s'",
214                             $hits,
215                             $dbh->escapeSimple($this->_serialize($data)),
216                             $dbh->escapeSimple($pagename)));
217         */
218         $dbh->query("UPDATE $page_tbl"
219                     . " SET hits=?, pagedata=?"
220                     . " WHERE pagename=?",
221                     array($hits, $this->_serialize($data), $pagename));
222         $this->unlock(array($page_tbl));
223     }
224
225     function get_cached_html($pagename) {
226         $dbh = &$this->_dbh;
227         $page_tbl = $this->_table_names['page_tbl'];
228         return $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename='%s'",
229                                     $dbh->escapeSimple($pagename)));
230     }
231
232     function set_cached_html($pagename, $data) {
233         $dbh = &$this->_dbh;
234         $page_tbl = $this->_table_names['page_tbl'];
235         $dbh->query("UPDATE $page_tbl"
236                     . " SET cached_html=?"
237                     . " WHERE pagename=?",
238                     array($data, $pagename));
239     }
240
241     function _get_pageid($pagename, $create_if_missing = false) {
242         
243         // check id_cache
244         global $request;
245         $cache =& $request->_dbi->_cache->_id_cache;
246         if (isset($cache[$pagename])) {
247             if ($cache[$pagename] or !$create_if_missing) {
248                 return $cache[$pagename];
249             }
250         }
251
252         // attributes play this game.
253         if ($pagename === '') return 0;
254
255         $dbh = &$this->_dbh;
256         $page_tbl = $this->_table_names['page_tbl'];
257         
258         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
259                          $dbh->escapeSimple($pagename));
260
261         if (!$create_if_missing)
262             return $dbh->getOne($query);
263
264         $id = $dbh->getOne($query);
265         if (empty($id)) {
266             $this->lock(array($page_tbl), true); // write lock
267             $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
268             $id = $max_id + 1;
269             // requires createSequence and on mysql lock the interim table ->getSequenceName
270             //$id = $dbh->nextId($page_tbl . "_id");
271             $dbh->query(sprintf("INSERT INTO $page_tbl"
272                                 . " (id,pagename,hits)"
273                                 . " VALUES (%d,'%s',0)",
274                                 $id, $dbh->escapeSimple($pagename)));
275             $this->unlock(array($page_tbl));
276         }
277         return $id;
278     }
279
280     function get_latest_version($pagename) {
281         $dbh = &$this->_dbh;
282         extract($this->_table_names);
283         return
284             (int)$dbh->getOne(sprintf("SELECT latestversion"
285                                       . " FROM $page_tbl, $recent_tbl"
286                                       . " WHERE $page_tbl.id=$recent_tbl.id"
287                                       . "  AND pagename='%s'",
288                                       $dbh->escapeSimple($pagename)));
289     }
290
291     function get_previous_version($pagename, $version) {
292         $dbh = &$this->_dbh;
293         extract($this->_table_names);
294         
295         return
296             (int)$dbh->getOne(sprintf("SELECT version"
297                                       . " FROM $version_tbl, $page_tbl"
298                                       . " WHERE $version_tbl.id=$page_tbl.id"
299                                       . "  AND pagename='%s'"
300                                       . "  AND version < %d"
301                                       . " ORDER BY version DESC",
302                                       /* Non portable and useless anyway with getOne
303                                       . " LIMIT 1",
304                                       */
305                                       $dbh->escapeSimple($pagename),
306                                       $version));
307     }
308     
309     /**
310      * Get version data.
311      *
312      * @param $version int Which version to get.
313      *
314      * @return hash The version data, or false if specified version does not
315      *              exist.
316      */
317     function get_versiondata($pagename, $version, $want_content = false) {
318         $dbh = &$this->_dbh;
319         extract($this->_table_names);
320         extract($this->_expressions);
321
322         assert(is_string($pagename) and $pagename != "");
323         assert($version > 0);
324         
325         //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
326         // FIXME: optimization: sometimes don't get page data?
327         if ($want_content) {
328             $fields = $this->page_tbl_fields 
329                 . ",$page_tbl.pagedata as pagedata," 
330                 . $this->version_tbl_fields;
331         }
332         else {
333             $fields = $this->page_tbl_fields . ","
334                 . "mtime, minor_edit, versiondata,"
335                 . "$iscontent AS have_content";
336         }
337
338         $result = $dbh->getRow(sprintf("SELECT $fields"
339                                        . " FROM $page_tbl, $version_tbl"
340                                        . " WHERE $page_tbl.id=$version_tbl.id"
341                                        . "  AND pagename='%s'"
342                                        . "  AND version=%d",
343                                        $dbh->escapeSimple($pagename), $version),
344                                DB_FETCHMODE_ASSOC);
345
346         return $this->_extract_version_data($result);
347     }
348
349     function _extract_version_data($query_result) {
350         if (!$query_result)
351             return false;
352
353         /* Earlier versions (<= 1.3.7) stored the version data in base64.
354            This could be done here or in upgrade.
355         */
356         if (!strstr($query_result['versiondata'], ":")) {
357             $query_result['versiondata'] = 
358                 base64_decode($query_result['versiondata']);
359         }
360         $data = $this->_unserialize($query_result['versiondata']);
361         
362         $data['mtime'] = $query_result['mtime'];
363         $data['is_minor_edit'] = !empty($query_result['minor_edit']);
364         
365         if (isset($query_result['content']))
366             $data['%content'] = $query_result['content'];
367         elseif ($query_result['have_content'])
368             $data['%content'] = true;
369         else
370             $data['%content'] = '';
371
372         // FIXME: this is ugly.
373         if (isset($query_result['pagedata'])) {
374             // Query also includes page data.
375             // We might as well send that back too...
376             unset($query_result['versiondata']);
377             $data['%pagedata'] = $this->_extract_page_data($query_result);
378         }
379
380         return $data;
381     }
382
383
384     /**
385      * Create a new revision of a page.
386      */
387     function set_versiondata($pagename, $version, $data) {
388         $dbh = &$this->_dbh;
389         $version_tbl = $this->_table_names['version_tbl'];
390         
391         $minor_edit = (int) !empty($data['is_minor_edit']);
392         unset($data['is_minor_edit']);
393         
394         $mtime = (int)$data['mtime'];
395         unset($data['mtime']);
396         assert(!empty($mtime));
397
398         @$content = (string) $data['%content'];
399         unset($data['%content']);
400
401         unset($data['%pagedata']);
402         
403         $this->lock();
404         $id = $this->_get_pageid($pagename, true);
405
406         $dbh->query(sprintf("DELETE FROM $version_tbl"
407                             . " WHERE id=%d AND version=%d",
408                             $id, $version));
409         // generic slow PearDB bind eh quoting.
410         $dbh->query("INSERT INTO $version_tbl"
411                     . " (id,version,mtime,minor_edit,content,versiondata)"
412                     . " VALUES(?, ?, ?, ?, ?, ?)",
413                     array($id, $version, $mtime, $minor_edit, $content,
414                     $this->_serialize($data)));
415
416         $this->_update_recent_table($id);
417         $this->_update_nonempty_table($id);
418         
419         $this->unlock();
420     }
421     
422     /**
423      * Delete an old revision of a page.
424      */
425     function delete_versiondata($pagename, $version) {
426         $dbh = &$this->_dbh;
427         extract($this->_table_names);
428
429         $this->lock();
430         if ( ($id = $this->_get_pageid($pagename)) ) {
431             $dbh->query("DELETE FROM $version_tbl"
432                         . " WHERE id=$id AND version=$version");
433
434             $this->_update_recent_table($id);
435             // This shouldn't be needed (as long as the latestversion
436             // never gets deleted.)  But, let's be safe.
437             $this->_update_nonempty_table($id);
438         }
439         $this->unlock();
440     }
441
442     /**
443      * Delete page from the database with backup possibility.
444      * i.e save_page('') and DELETE nonempty id
445      * Can be undone and is seen in RecentChanges.
446      */
447     /* // see parent backend.php
448     function delete_page($pagename) {
449         $mtime = time();
450         $user =& $GLOBALS['request']->_user;
451         $vdata = array('author' => $user->getId(),
452                        'author_id' => $user->getAuthenticatedId(),
453                        'mtime' => $mtime);
454
455         $this->lock();
456         $version = $this->get_latest_version($pagename);
457         $this->set_versiondata($pagename, $version+1, $vdata);
458         $this->set_links($pagename, false);
459         $pagedata = get_pagedata($pagename);
460         $this->update_pagedata($pagename, array('hits' => $pagedata['hits']));
461         $this->unlock();
462     }
463     */
464
465     /**
466      * Delete page completely from the database.
467      * I'm not sure if this is what we want. Maybe just delete the revisions
468      */
469     function purge_page($pagename) {
470         $dbh = &$this->_dbh;
471         extract($this->_table_names);
472         
473         $this->lock();
474         if ( ($id = $this->_get_pageid($pagename, false)) ) {
475             $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
476             $dbh->query("DELETE FROM $recent_tbl   WHERE id=$id");
477             $dbh->query("DELETE FROM $version_tbl  WHERE id=$id");
478             $dbh->query("DELETE FROM $link_tbl     WHERE linkfrom=$id");
479             $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
480             if ($nlinks) {
481                 // We're still in the link table (dangling link) so we can't delete this
482                 // altogether.
483                 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
484                 $result = 0;
485             }
486             else {
487                 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
488                 $result = 1;
489             }
490             $this->_update_recent_table();
491             $this->_update_nonempty_table();
492         } else {
493             $result = -1; // already purged or not existing
494         }
495         $this->unlock();
496         return $result;
497     }
498
499     // The only thing we might be interested in updating which we can
500     // do fast in the flags (minor_edit).   I think the default
501     // update_versiondata will work fine...
502     //function update_versiondata($pagename, $version, $data) {
503     //}
504
505     function set_links($pagename, $links) {
506         // Update link table.
507         // FIXME: optimize: mysql can do this all in one big INSERT.
508
509         $dbh = &$this->_dbh;
510         extract($this->_table_names);
511
512         $this->lock();
513         $pageid = $this->_get_pageid($pagename, true);
514
515         $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
516         if ($links) {
517             $linkseen = array();
518             foreach ($links as $link) {
519                 $linkto = $link['linkto'];
520                 if ($linkto === "") { // ignore attributes
521                     continue;
522                 }
523                 if ($link['relation'])
524                     $relation = $this->_get_pageid($link['relation'], true);
525                 else 
526                     $relation = 0;
527                 // avoid duplicates
528                 if (isset($linkseen[$linkto]) and !$relation)
529                     continue;
530                 if (!$relation)
531                     $linkseen[$linkto] = true;
532                 $linkid = $this->_get_pageid($linkto, true);
533                 if (!$linkid) {
534                     echo("No link for $linkto on page $pagename");
535                     //printSimpleTrace(debug_backtrace());
536                     trigger_error("No link for $linkto on page $pagename");
537                 }
538                 assert($linkid);
539                 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
540                             . " VALUES ($pageid, $linkid, $relation)");
541             }
542             unset($linkseen);
543         }
544         $this->unlock();
545     }
546     
547     /**
548      * Find pages which link to or are linked from a page.
549      *
550      * TESTME relations: get_links is responsible to add the relation to the pagehash 
551      * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next 
552      *   if (isset($next['linkrelation']))
553      */
554     function get_links($pagename, $reversed=true, $include_empty=false,
555                        $sortby='', $limit='', $exclude='', 
556                        $want_relations = false)
557     {
558         $dbh = &$this->_dbh;
559         extract($this->_table_names);
560
561         if ($reversed)
562             list($have,$want) = array('linkee', 'linker');
563         else
564             list($have,$want) = array('linker', 'linkee');
565         $orderby = $this->sortby($sortby, 'db', array('pagename'));
566         if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
567         if ($exclude) // array of pagenames
568             $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
569         else 
570             $exclude='';
571
572         $qpagename = $dbh->escapeSimple($pagename);
573         $sql = "SELECT $want.id AS id, $want.pagename AS pagename, "
574             . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
575             . " FROM "
576             . (!$include_empty ? "$nonempty_tbl, " : '')
577             . " $page_tbl linkee, $page_tbl linker, $link_tbl "
578             . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
579             . " WHERE linkfrom=linker.id AND linkto=linkee.id"
580             . " AND $have.pagename='$qpagename'"
581             . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
582             //. " GROUP BY $want.id"
583             . $exclude
584             . $orderby;
585         if ($limit) {
586             // extract from,count from limit
587             list($from,$count) = $this->limit($limit);
588             $result = $dbh->limitQuery($sql, $from, $count);
589         } else {
590             $result = $dbh->query($sql);
591         }
592         
593         return new WikiDB_backend_PearDB_iter($this, $result);
594     }
595
596     /**
597      * Find if a page links to another page
598      */
599     function exists_link($pagename, $link, $reversed=false) {
600         $dbh = &$this->_dbh;
601         extract($this->_table_names);
602
603         if ($reversed)
604             list($have, $want) = array('linkee', 'linker');
605         else
606             list($have, $want) = array('linker', 'linkee');
607         $qpagename = $dbh->escapeSimple($pagename);
608         $qlink = $dbh->escapeSimple($link);
609         $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename='$qlink' THEN 1 ELSE 0 END as result"
610                             . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
611                             . " WHERE linkfrom=linker.id AND linkto=linkee.id"
612                             . " AND $have.pagename='$qpagename'"
613                             . " AND $want.pagename='$qlink'");
614         return $row['result'];
615     }
616
617     function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') {
618         $dbh = &$this->_dbh;
619         extract($this->_table_names);
620         $orderby = $this->sortby($sortby, 'db');
621         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
622         if ($exclude) // array of pagenames
623             $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
624         else 
625             $exclude='';
626
627         if (strstr($orderby, 'mtime ')) { // multiple columns possible
628             if ($include_empty) {
629                 $sql = "SELECT "
630                     . $this->page_tbl_fields
631                     . " FROM $page_tbl, $recent_tbl, $version_tbl"
632                     . " WHERE $page_tbl.id=$recent_tbl.id"
633                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
634                     . $exclude
635                     . $orderby;
636             }
637             else {
638                 $sql = "SELECT "
639                     . $this->page_tbl_fields
640                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
641                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
642                     . " AND $page_tbl.id=$recent_tbl.id"
643                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
644                     . $exclude
645                     . $orderby;
646             }
647         } else {
648             if ($include_empty) {
649                 $sql = "SELECT "
650                     . $this->page_tbl_fields 
651                     ." FROM $page_tbl"
652                     . ($exclude ? " WHERE $exclude" : '')
653                     . $orderby;
654             }
655             else {
656                 $sql = "SELECT "
657                     . $this->page_tbl_fields
658                     . " FROM $nonempty_tbl, $page_tbl"
659                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
660                     . $exclude
661                     . $orderby;
662             }
663         }
664         if ($limit) {
665             // extract from,count from limit
666             list($from,$count) = $this->limit($limit);
667             $result = $dbh->limitQuery($sql, $from, $count);
668         } else {
669             $result = $dbh->query($sql);
670         }
671         return new WikiDB_backend_PearDB_iter($this, $result);
672     }
673         
674     /**
675      * Title search.
676      * Todo: exclude
677      */
678     function text_search($search, $fulltext=false, $sortby='', $limit='', 
679                          $exclude='') 
680     {
681         $dbh = &$this->_dbh;
682         extract($this->_table_names);
683         $orderby = $this->sortby($sortby, 'db');
684         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
685         //else " ORDER BY rank($field, to_tsquery('$searchon')) DESC";
686
687         $searchclass = get_class($this)."_search";
688         // no need to define it everywhere and then fallback. memory!
689         if (!class_exists($searchclass))
690             $searchclass = "WikiDB_backend_PearDB_search";
691         $searchobj = new $searchclass($search, $dbh);
692         
693         $table = "$nonempty_tbl, $page_tbl";
694         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
695         $fields = $this->page_tbl_fields;
696
697         if ($fulltext) {
698             $table .= ", $recent_tbl";
699             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
700
701             $table .= ", $version_tbl";
702             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
703
704             $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
705             $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
706         } else {
707             $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
708         }
709         $search_clause = $search->makeSqlClauseObj($callback);
710         
711         $sql = "SELECT $fields FROM $table"
712             . " WHERE $join_clause"
713             . "  AND ($search_clause)"
714             . $orderby;
715          if ($limit) {
716              list($from, $count) = $this->limit($limit);
717              $result = $dbh->limitQuery($sql, $from, $count);
718          } else {
719              $result = $dbh->query($sql);
720          }
721         
722         $iter = new WikiDB_backend_PearDB_iter($this, $result);
723         $iter->stoplisted = @$searchobj->stoplisted;
724         return $iter;
725     }
726
727     //Todo: check if the better Mysql MATCH operator is supported,
728     // (ranked search) and also google like expressions.
729     function _sql_match_clause($word) {
730         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
731         $word = $this->_dbh->escapeSimple($word);
732         //$page_tbl = $this->_table_names['page_tbl'];
733         //Note: Mysql 4.1.0 has a bug which fails with binary fields.
734         //      e.g. if word is lowercased.
735         // http://bugs.mysql.com/bug.php?id=1491
736         return "LOWER(pagename) LIKE '%$word%'";
737     }
738     function _sql_casematch_clause($word) {
739         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
740         $word = $this->_dbh->escapeSimple($word);
741         return "pagename LIKE '%$word%'";
742     }
743     function _fullsearch_sql_match_clause($word) {
744         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
745         $word = $this->_dbh->escapeSimple($word);
746         //$page_tbl = $this->_table_names['page_tbl'];
747         //Mysql 4.1.1 has a bug which fails here if word is lowercased.
748         return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
749     }
750     function _fullsearch_sql_casematch_clause($word) {
751         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
752         $word = $this->_dbh->escapeSimple($word);
753         return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
754     }
755
756     /**
757      * Find highest or lowest hit counts.
758      */
759     function most_popular($limit=20, $sortby='-hits') {
760         $dbh = &$this->_dbh;
761         extract($this->_table_names);
762         if ($limit < 0){ 
763             $order = "hits ASC";
764             $limit = -$limit;
765             $where = ""; 
766         } else {
767             $order = "hits DESC";
768             $where = " AND hits > 0";
769         }
770         $orderby = '';
771         if ($sortby != '-hits') {
772             if ($order = $this->sortby($sortby, 'db'))
773                 $orderby = " ORDER BY " . $order;
774         } else {
775             $orderby = " ORDER BY $order";
776         }
777         //$limitclause = $limit ? " LIMIT $limit" : '';
778         $sql = "SELECT "
779             . $this->page_tbl_fields
780             . " FROM $nonempty_tbl, $page_tbl"
781             . " WHERE $nonempty_tbl.id=$page_tbl.id" 
782             . $where
783             . $orderby;
784          if ($limit) {
785              list($from, $count) = $this->limit($limit);
786              $result = $dbh->limitQuery($sql, $from, $count);
787          } else {
788              $result = $dbh->query($sql);
789          }
790
791         return new WikiDB_backend_PearDB_iter($this, $result);
792     }
793
794     /**
795      * Find recent changes.
796      */
797     function most_recent($params) {
798         $limit = 0;
799         $since = 0;
800         $include_minor_revisions = false;
801         $exclude_major_revisions = false;
802         $include_all_revisions = false;
803         extract($params);
804
805         $dbh = &$this->_dbh;
806         extract($this->_table_names);
807
808         $pick = array();
809         if ($since)
810             $pick[] = "mtime >= $since";
811                         
812         
813         if ($include_all_revisions) {
814             // Include all revisions of each page.
815             $table = "$page_tbl, $version_tbl";
816             $join_clause = "$page_tbl.id=$version_tbl.id";
817
818             if ($exclude_major_revisions) {
819                 // Include only minor revisions
820                 $pick[] = "minor_edit <> 0";
821             }
822             elseif (!$include_minor_revisions) {
823                 // Include only major revisions
824                 $pick[] = "minor_edit = 0";
825             }
826         }
827         else {
828             $table = "$page_tbl, $recent_tbl";
829             $join_clause = "$page_tbl.id=$recent_tbl.id";
830             $table .= ", $version_tbl";
831             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
832             
833             if ($exclude_major_revisions) {
834                 // Include only most recent minor revision
835                 $pick[] = 'version=latestminor';
836             }
837             elseif (!$include_minor_revisions) {
838                 // Include only most recent major revision
839                 $pick[] = 'version=latestmajor';
840             }
841             else {
842                 // Include only the latest revision (whether major or minor).
843                 $pick[] ='version=latestversion';
844             }
845         }
846         $order = "DESC";
847         if($limit < 0){
848             $order = "ASC";
849             $limit = -$limit;
850         }
851         // $limitclause = $limit ? " LIMIT $limit" : '';
852         $where_clause = $join_clause;
853         if ($pick)
854             $where_clause .= " AND " . join(" AND ", $pick);
855
856         // FIXME: use SQL_BUFFER_RESULT for mysql?
857         $sql = "SELECT " 
858                . $this->page_tbl_fields . ", " . $this->version_tbl_fields
859                . " FROM $table"
860                . " WHERE $where_clause"
861                . " ORDER BY mtime $order";
862         if ($limit) {
863              list($from, $count) = $this->limit($limit);
864              $result = $dbh->limitQuery($sql, $from, $count);
865         } else {
866             $result = $dbh->query($sql);
867         }
868         return new WikiDB_backend_PearDB_iter($this, $result);
869     }
870
871     /**
872      * Find referenced empty pages.
873      */
874     function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') {
875         $dbh = &$this->_dbh;
876         extract($this->_table_names);
877         if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
878             $orderby = 'ORDER BY ' . $orderby;
879
880         if ($exclude_from) // array of pagenames
881             $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from);
882         if ($exclude) // array of pagenames
883             $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude);
884         $sql = "SELECT p.pagename, pp.pagename AS wantedfrom"
885             . " FROM $page_tbl p, $link_tbl linked"
886             .   " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
887             .   " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
888             . " WHERE ne.id IS NULL"
889             .       " AND p.id = linked.linkfrom"
890             . $exclude_from
891             . $exclude
892             . $orderby;
893         if ($limit) {
894             // oci8 error: WHERE NULL = NULL appended
895             list($from, $count) = $this->limit($limit);
896             $result = $dbh->limitQuery($sql, $from, $count * 3);
897         } else {
898             $result = $dbh->query($sql);
899         }
900         return new WikiDB_backend_PearDB_generic_iter($this, $result);
901     }
902
903     function _sql_set(&$pagenames) {
904         $s = '(';
905         foreach ($pagenames as $p) {
906             $s .= ("'".$this->_dbh->escapeSimple($p)."',");
907         }
908         return substr($s,0,-1).")";
909     }
910
911     /**
912      * Rename page in the database.
913      */
914     function rename_page ($pagename, $to) {
915         $dbh = &$this->_dbh;
916         extract($this->_table_names);
917         
918         $this->lock();
919         if (($id = $this->_get_pageid($pagename, false)) ) {
920             if ($new = $this->_get_pageid($to, false)) {
921                 // Cludge Alert!
922                 // This page does not exist (already verified before), but exists in the page table.
923                 // So we delete this page.
924                 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
925                 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
926                 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
927                 // We have to fix all referring tables to the old id
928                 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
929                 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
930                 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
931             }
932             $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
933                                 $dbh->escapeSimple($to)));
934         }
935         $this->unlock();
936         return $id;
937     }
938
939     function _update_recent_table($pageid = false) {
940         $dbh = &$this->_dbh;
941         extract($this->_table_names);
942         extract($this->_expressions);
943
944         $pageid = (int)$pageid;
945
946         $this->lock();
947         $dbh->query("DELETE FROM $recent_tbl"
948                     . ( $pageid ? " WHERE id=$pageid" : ""));
949         $dbh->query( "INSERT INTO $recent_tbl"
950                      . " (id, latestversion, latestmajor, latestminor)"
951                      . " SELECT id, $maxversion, $maxmajor, $maxminor"
952                      . " FROM $version_tbl"
953                      . ( $pageid ? " WHERE id=$pageid" : "")
954                      . " GROUP BY id" );
955         $this->unlock();
956     }
957
958     function _update_nonempty_table($pageid = false) {
959         $dbh = &$this->_dbh;
960         extract($this->_table_names);
961
962         $pageid = (int)$pageid;
963
964         extract($this->_expressions);
965         $this->lock();
966         $dbh->query("DELETE FROM $nonempty_tbl"
967                     . ( $pageid ? " WHERE id=$pageid" : ""));
968         $dbh->query("INSERT INTO $nonempty_tbl (id)"
969                     . " SELECT $recent_tbl.id"
970                     . " FROM $recent_tbl, $version_tbl"
971                     . " WHERE $recent_tbl.id=$version_tbl.id"
972                     . "       AND version=latestversion"
973                     // We have some specifics here (Oracle)
974                     //. "  AND content<>''"
975                     . "  AND content $notempty"
976                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
977         
978         $this->unlock();
979     }
980
981
982     /**
983      * Grab a write lock on the tables in the SQL database.
984      *
985      * Calls can be nested.  The tables won't be unlocked until
986      * _unlock_database() is called as many times as _lock_database().
987      *
988      * @access protected
989      */
990     function lock($tables = false, $write_lock = true) {
991         if ($this->_lock_count++ == 0)
992             $this->_lock_tables($write_lock);
993     }
994
995     /**
996      * Actually lock the required tables.
997      */
998     function _lock_tables($write_lock) {
999         trigger_error("virtual", E_USER_ERROR);
1000     }
1001     
1002     /**
1003      * Release a write lock on the tables in the SQL database.
1004      *
1005      * @access protected
1006      *
1007      * @param $force boolean Unlock even if not every call to lock() has been matched
1008      * by a call to unlock().
1009      *
1010      * @see _lock_database
1011      */
1012     function unlock($tables = false, $force = false) {
1013         if ($this->_lock_count == 0)
1014             return;
1015         if (--$this->_lock_count <= 0 || $force) {
1016             $this->_unlock_tables();
1017             $this->_lock_count = 0;
1018         }
1019     }
1020
1021     /**
1022      * Actually unlock the required tables.
1023      */
1024     function _unlock_tables($write_lock) {
1025         trigger_error("virtual", E_USER_ERROR);
1026     }
1027
1028
1029     /**
1030      * Serialize data
1031      */
1032     function _serialize($data) {
1033         if (empty($data))
1034             return '';
1035         assert(is_array($data));
1036         return serialize($data);
1037     }
1038
1039     /**
1040      * Unserialize data
1041      */
1042     function _unserialize($data) {
1043         return empty($data) ? array() : unserialize($data);
1044     }
1045     
1046     /**
1047      * Callback for PEAR (DB) errors.
1048      *
1049      * @access protected
1050      *
1051      * @param A PEAR_error object.
1052      */
1053     function _pear_error_callback($error) {
1054         if ($this->_is_false_error($error))
1055             return;
1056         
1057         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
1058         $this->close();
1059         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
1060     }
1061
1062     /**
1063      * Detect false errors messages from PEAR DB.
1064      *
1065      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
1066      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
1067      * return any data.  (So when a "LOCK" command doesn't return any data,
1068      * DB reports it as an error, when in fact, it's not.)
1069      *
1070      * @access private
1071      * @return bool True iff error is not really an error.
1072      */
1073     function _is_false_error($error) {
1074         if ($error->getCode() != DB_ERROR)
1075             return false;
1076
1077         $query = $this->_dbh->last_query;
1078
1079         if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
1080                          . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
1081             // Last query was not of the sort which doesn't return any data.
1082             //" <--kludge for brain-dead syntax coloring
1083             return false;
1084         }
1085         
1086         if (! in_array('ismanip', get_class_methods('DB'))) {
1087             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
1088             // does not have the DB::isManip method.
1089             return true;
1090         }
1091         
1092         if (DB::isManip($query)) {
1093             // If Pear thinks it's an isManip then it wouldn't have thrown
1094             // the error we're testing for....
1095             return false;
1096         }
1097
1098         return true;
1099     }
1100
1101     function _pear_error_message($error) {
1102         $class = get_class($this);
1103         $message = "$class: fatal database error\n"
1104              . "\t" . $error->getMessage() . "\n"
1105              . "\t(" . $error->getDebugInfo() . ")\n";
1106
1107         // Prevent password from being exposed during a connection error
1108         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
1109                                  '\\1:XXXXXXXX', $this->_dsn);
1110         return str_replace($this->_dsn, $safe_dsn, $message);
1111     }
1112
1113     /**
1114      * Filter PHP errors notices from PEAR DB code.
1115      *
1116      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
1117      * errors and notices.  This is an error callback (for use with
1118      * ErrorManager which will filter out those spurious messages.)
1119      * @see _is_false_error, ErrorManager
1120      * @access private
1121      */
1122     function _pear_notice_filter($err) {
1123         return ( $err->isNotice()
1124                  && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
1125                  && $err->errline == 126
1126                  && preg_match('/Undefined offset: +0\b/', $err->errstr) );
1127     }
1128
1129     /* some variables and functions for DB backend abstraction (action=upgrade) */
1130     function database () {
1131         return $this->_dbh->dsn['database'];
1132     }
1133     function backendType() {
1134         return $this->_dbh->phptype;
1135     }
1136     function connection() {
1137         return $this->_dbh->connection;
1138     }
1139     function getRow($query) {
1140         return $this->_dbh->getRow($query);
1141     }
1142
1143     function listOfTables() {
1144         return $this->_dbh->getListOf('tables');
1145     }
1146     function listOfFields($database,$table) {
1147         if ($this->backendType() == 'mysql') {
1148             $fields = array();
1149             assert(!empty($database));
1150             assert(!empty($table));
1151             $result = mysql_list_fields($database, $table, $this->_dbh->connection) or 
1152                 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
1153             if (!$result) return array();
1154               $columns = mysql_num_fields($result);
1155             for ($i = 0; $i < $columns; $i++) {
1156                 $fields[] = mysql_field_name($result, $i);
1157             }
1158             mysql_free_result($result);
1159             return $fields;
1160         } else {
1161             // TODO: try ADODB version?
1162             trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1163             return false;
1164         }
1165     }
1166 };
1167
1168 /**
1169  * This class is a generic iterator.
1170  *
1171  * WikiDB_backend_PearDB_iter only iterates over things that have
1172  * 'pagename', 'pagedata', etc. etc.
1173  *
1174  * Probably WikiDB_backend_PearDB_iter and this class should be merged
1175  * (most of the code is cut-and-paste :-( ), but I am trying to make
1176  * changes that could be merged easily.
1177  *
1178  * @author: Dan Frankowski
1179  */
1180 class WikiDB_backend_PearDB_generic_iter
1181 extends WikiDB_backend_iterator
1182 {
1183     function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
1184         if (DB::isError($query_result)) {
1185             // This shouldn't happen, I thought.
1186             $backend->_pear_error_callback($query_result);
1187         }
1188         
1189         $this->_backend = &$backend;
1190         $this->_result = $query_result;
1191     }
1192
1193     function count() {
1194         if (!$this->_result)
1195             return false;
1196         return $this->_result->numRows();
1197     }
1198     
1199     function next() {
1200         if (!$this->_result)
1201             return false;
1202
1203         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1204         if (!$record) {
1205             $this->free();
1206             return false;
1207         }
1208         
1209         return $record;
1210     }
1211
1212     function free () {
1213         if ($this->_result) {
1214             $this->_result->free();
1215             $this->_result = false;
1216         }
1217     }
1218
1219     function asArray () {
1220         $result = array();
1221         while ($page = $this->next())
1222             $result[] = $page;
1223         return $result;
1224     }
1225 }
1226
1227 class WikiDB_backend_PearDB_iter
1228 extends WikiDB_backend_PearDB_generic_iter
1229 {
1230
1231     function next() {
1232         $backend = &$this->_backend;
1233         if (!$this->_result)
1234             return false;
1235
1236         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1237         if (!$record) {
1238             $this->free();
1239             return false;
1240         }
1241         
1242         $pagedata = $backend->_extract_page_data($record);
1243         $rec = array('pagename' => $record['pagename'],
1244                      'pagedata' => $pagedata);
1245
1246         if (!empty($record['version'])) {
1247             $rec['versiondata'] = $backend->_extract_version_data($record);
1248             $rec['version'] = $record['version'];
1249         }
1250         
1251         return $rec;
1252     }
1253 }
1254
1255 class WikiDB_backend_PearDB_search extends WikiDB_backend_search_sql 
1256 {
1257     // no surrounding quotes because we know it's a string
1258     // function _quote($word) { return $this->_dbh->addq($word); }
1259 }
1260
1261 // $Log: not supported by cvs2svn $
1262 // Revision 1.107  2007/05/28 20:13:46  rurban
1263 // Overwrite all attributes at once at page->save to delete dangling meta
1264 //
1265 // Revision 1.106  2007/01/04 16:57:32  rurban
1266 // Clarify API: sortby,limit and exclude are strings. fix upgrade test connection
1267 //
1268 // Revision 1.105  2006/12/23 13:03:32  rurban
1269 // reorder deletion
1270 //
1271 // Revision 1.104  2006/12/23 11:44:56  rurban
1272 // deal with strict references and the order of deletion
1273 //
1274 // Revision 1.103  2006/12/03 17:11:53  rurban
1275 // #1535832 by matt brown: Check for base 64 encoded version data
1276 //
1277 // Revision 1.102  2006/12/02 21:57:27  rurban
1278 // fix WantedPages SQL: no JOIN
1279 // clarify first condition in CASE WHEN
1280 //
1281 // Revision 1.101  2006/11/29 19:49:05  rurban
1282 // fix CASE WHEN SQL syntax error from previous commit
1283 //
1284 // Revision 1.100  2006/11/19 13:59:11  rurban
1285 // Replace IF by CASE in exists_link()
1286 //
1287 // Revision 1.99  2006/10/08 12:40:51  rurban
1288 // minor cleanup: remove unused vars
1289 //
1290 // Revision 1.98  2006/06/03 08:50:41  rurban
1291 // revert wrong pear DB nextID() usage, our old is easier
1292 //
1293 // Revision 1.97  2006/05/14 12:28:03  rurban
1294 // mysql 5.x fix for wantedpages join
1295 //
1296 // Revision 1.96  2006/04/15 12:28:53  rurban
1297 // use pear nextID
1298 //
1299 // Revision 1.95  2006/02/22 21:52:28  rurban
1300 // whitespace only
1301 //
1302 // Revision 1.94  2005/11/14 22:24:33  rurban
1303 // fix fulltext search,
1304 // Eliminate stoplist words,
1305 // don't extract %pagedate twice in ADODB,
1306 // add SemanticWeb support: link(relation),
1307 // major postgresql update: stored procedures, tsearch2 for fulltext
1308 //
1309 // Revision 1.93  2005/10/10 19:42:15  rurban
1310 // fix wanted_pages SQL syntax
1311 //
1312 // Revision 1.92  2005/09/14 06:04:43  rurban
1313 // optimize searching for ALL (ie %), use the stoplist on PDO
1314 //
1315 // Revision 1.91  2005/09/11 14:55:05  rurban
1316 // implement fulltext stoplist
1317 //
1318 // Revision 1.90  2005/09/11 13:25:12  rurban
1319 // enhance LIMIT support
1320 //
1321 // Revision 1.89  2005/09/10 21:30:16  rurban
1322 // enhance titleSearch
1323 //
1324 // Revision 1.88  2005/08/06 13:20:05  rurban
1325 // add comments
1326 //
1327 // Revision 1.87  2005/02/10 19:04:24  rurban
1328 // move getRow up one level to our backend class
1329 //
1330 // Revision 1.86  2005/01/29 19:51:02  rurban
1331 // Bugs item #1077769 fixed by frugal.
1332 // Deleted the wrong page. Fix all other tables also.
1333 //
1334 // Revision 1.85  2005/01/25 08:03:35  rurban
1335 // support DATABASE_PERSISTENT besides dsn database?persistent=false; move lock_count up (per Charles Corrigan)
1336 //
1337 // Revision 1.84  2005/01/18 20:55:47  rurban
1338 // reformatting and two bug fixes: adding missing parens
1339 //
1340 // Revision 1.83  2005/01/18 10:11:29  rurban
1341 // Oops. Again thanks to Charles Corrigan
1342 //
1343 // Revision 1.82  2005/01/18 08:55:51  rurban
1344 // fix quoting
1345 //
1346 // Revision 1.81  2005/01/17 08:53:09  rurban
1347 // pagedata fix by Charles Corrigan
1348 //
1349 // Revision 1.80  2004/12/22 18:33:31  rurban
1350 // fix page _id_cache logic for _get_pageid create_if_missing
1351 //
1352 // Revision 1.79  2004/12/10 02:45:27  rurban
1353 // SQL optimization:
1354 //   put _cached_html from pagedata into a new seperate blob, not huge serialized string.
1355 //   it is only rarelely needed: for current page only, if-not-modified
1356 //   but was extracted for every simple page iteration.
1357 //
1358 // Revision 1.78  2004/12/08 12:55:51  rurban
1359 // support new non-destructive delete_page via generic backend method
1360 //
1361 // Revision 1.77  2004/12/06 19:50:04  rurban
1362 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
1363 // renamed delete_page to purge_page.
1364 // enable action=edit&version=-1 to force creation of a new version.
1365 // added BABYCART_PATH config
1366 // fixed magiqc in adodb.inc.php
1367 // and some more docs
1368 //
1369 // Revision 1.76  2004/11/30 17:45:53  rurban
1370 // exists_links backend implementation
1371 //
1372 // Revision 1.75  2004/11/28 20:42:33  rurban
1373 // Optimize PearDB _extract_version_data and _extract_page_data.
1374 //
1375 // Revision 1.74  2004/11/27 14:39:05  rurban
1376 // simpified regex search architecture:
1377 //   no db specific node methods anymore,
1378 //   new sql() method for each node
1379 //   parallel to regexp() (which returns pcre)
1380 //   regex types bitmasked (op's not yet)
1381 // new regex=sql
1382 // clarified WikiDB::quote() backend methods:
1383 //   ->quote() adds surrounsing quotes
1384 //   ->qstr() (new method) assumes strings and adds no quotes! (in contrast to ADODB)
1385 //   pear and adodb have now unified quote methods for all generic queries.
1386 //
1387 // Revision 1.73  2004/11/26 18:39:02  rurban
1388 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1389 //
1390 // Revision 1.72  2004/11/25 17:20:51  rurban
1391 // and again a couple of more native db args: backlinks
1392 //
1393 // Revision 1.71  2004/11/23 13:35:48  rurban
1394 // add case_exact search
1395 //
1396 // Revision 1.70  2004/11/21 11:59:26  rurban
1397 // remove final \n to be ob_cache independent
1398 //
1399 // Revision 1.69  2004/11/20 17:49:39  rurban
1400 // add fast exclude support to SQL get_all_pages
1401 //
1402 // Revision 1.68  2004/11/20 17:35:58  rurban
1403 // improved WantedPages SQL backends
1404 // PageList::sortby new 3rd arg valid_fields (override db fields)
1405 // WantedPages sql pager inexact for performance reasons:
1406 //   assume 3 wantedfrom per page, to be correct, no getTotal()
1407 // support exclude argument for get_all_pages, new _sql_set()
1408 //
1409 // Revision 1.67  2004/11/10 19:32:24  rurban
1410 // * optimize increaseHitCount, esp. for mysql.
1411 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
1412 // * Pear_DB version logic (awful but needed)
1413 // * fix broken ADODB quote
1414 // * _extract_page_data simplification
1415 //
1416 // Revision 1.66  2004/11/10 15:29:21  rurban
1417 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1418 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1419 // * WikiDB: moved SQL specific methods upwards
1420 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1421 //   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1422 //
1423 // Revision 1.65  2004/11/09 17:11:17  rurban
1424 // * revert to the wikidb ref passing. there's no memory abuse there.
1425 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1426 //   store page ids with getPageLinks (GleanDescription) of all existing pages, which
1427 //   are also needed at the rendering for linkExistingWikiWord().
1428 //   pass options to pageiterator.
1429 //   use this cache also for _get_pageid()
1430 //   This saves about 8 SELECT count per page (num all pagelinks).
1431 // * fix passing of all page fields to the pageiterator.
1432 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1433 //
1434 // Revision 1.64  2004/11/07 16:02:52  rurban
1435 // new sql access log (for spam prevention), and restructured access log class
1436 // dbh->quote (generic)
1437 // pear_db: mysql specific parts seperated (using replace)
1438 //
1439 // Revision 1.63  2004/11/01 10:43:58  rurban
1440 // seperate PassUser methods into seperate dir (memory usage)
1441 // fix WikiUser (old) overlarge data session
1442 // remove wikidb arg from various page class methods, use global ->_dbi instead
1443 // ...
1444 //
1445 // Revision 1.62  2004/10/14 19:19:34  rurban
1446 // loadsave: check if the dumped file will be accessible from outside.
1447 // and some other minor fixes. (cvsclient native not yet ready)
1448 //
1449 // Revision 1.61  2004/10/14 17:19:17  rurban
1450 // allow most_popular sortby arguments
1451 //
1452 // Revision 1.60  2004/07/09 10:06:50  rurban
1453 // Use backend specific sortby and sortable_columns method, to be able to
1454 // select between native (Db backend) and custom (PageList) sorting.
1455 // Fixed PageList::AddPageList (missed the first)
1456 // Added the author/creator.. name to AllPagesBy...
1457 //   display no pages if none matched.
1458 // Improved dba and file sortby().
1459 // Use &$request reference
1460 //
1461 // Revision 1.59  2004/07/08 21:32:36  rurban
1462 // Prevent from more warnings, minor db and sort optimizations
1463 //
1464 // Revision 1.58  2004/07/08 16:56:16  rurban
1465 // use the backendType abstraction
1466 //
1467 // Revision 1.57  2004/07/05 12:57:54  rurban
1468 // add mysql timeout
1469 //
1470 // Revision 1.56  2004/07/04 10:24:43  rurban
1471 // forgot the expressions
1472 //
1473 // Revision 1.55  2004/07/03 16:51:06  rurban
1474 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1475 // added atomic mysql REPLACE for PearDB as in ADODB
1476 // fixed _lock_tables typo links => link
1477 // fixes unserialize ADODB bug in line 180
1478 //
1479 // Revision 1.54  2004/06/29 08:52:24  rurban
1480 // Use ...version() $need_content argument in WikiDB also:
1481 // To reduce the memory footprint for larger sets of pagelists,
1482 // we don't cache the content (only true or false) and
1483 // we purge the pagedata (_cached_html) also.
1484 // _cached_html is only cached for the current pagename.
1485 // => Vastly improved page existance check, ACL check, ...
1486 //
1487 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1488 //
1489 // Revision 1.53  2004/06/27 10:26:03  rurban
1490 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1491 //
1492 // Revision 1.52  2004/06/25 14:15:08  rurban
1493 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1494 //
1495 // Revision 1.51  2004/05/12 10:49:55  rurban
1496 // require_once fix for those libs which are loaded before FileFinder and
1497 //   its automatic include_path fix, and where require_once doesn't grok
1498 //   dirname(__FILE__) != './lib'
1499 // upgrade fix with PearDB
1500 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1501 //
1502 // Revision 1.50  2004/05/06 17:30:39  rurban
1503 // CategoryGroup: oops, dos2unix eol
1504 // improved phpwiki_version:
1505 //   pre -= .0001 (1.3.10pre: 1030.099)
1506 //   -p1 += .001 (1.3.9-p1: 1030.091)
1507 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1508 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1509 //   backend->backendType(), backend->database(),
1510 //   backend->listOfFields(),
1511 //   backend->listOfTables(),
1512 //
1513 // Revision 1.49  2004/05/03 21:35:30  rurban
1514 // don't use persistent connections with postgres
1515 //
1516 // Revision 1.48  2004/04/26 20:44:35  rurban
1517 // locking table specific for better databases
1518 //
1519 // Revision 1.47  2004/04/20 00:06:04  rurban
1520 // themable paging support
1521 //
1522 // Revision 1.46  2004/04/19 21:51:41  rurban
1523 // php5 compatibility: it works!
1524 //
1525 // Revision 1.45  2004/04/16 14:19:39  rurban
1526 // updated ADODB notes
1527 //
1528
1529 // (c-file-style: "gnu")
1530 // Local Variables:
1531 // mode: php
1532 // tab-width: 8
1533 // c-basic-offset: 4
1534 // c-hanging-comment-ender-p: nil
1535 // indent-tabs-mode: nil
1536 // End:   
1537 ?>