From e7779909e9bf05778613d201adf15d7ba860b349 Mon Sep 17 00:00:00 2001 From: vargenau Date: Sat, 5 Mar 2011 17:05:30 +0000 Subject: [PATCH] No tabs git-svn-id: svn://svn.code.sf.net/p/phpwiki/code/trunk@7964 96ab9672-09ca-45d6-a79d-3d69d39ca109 --- lib/AccessLog.php | 22 +- lib/ArchiveCleaner.php | 34 +- lib/AtomParser.php | 10 +- lib/BlockParser.php | 170 +-- lib/CachedMarkup.php | 482 ++++----- lib/Captcha.php | 56 +- lib/DbSession.php | 4 +- lib/DbaDatabase.php | 26 +- lib/DbaListSet.php | 8 +- lib/DbaPartition.php | 10 +- lib/EditToolbar.php | 90 +- lib/ErrorManager.php | 56 +- lib/ExternalReferrer.php | 4 +- lib/FileFinder.php | 62 +- lib/Google.php | 14 +- lib/HtmlElement.php | 34 +- lib/HtmlElement5.php | 34 +- lib/HtmlParser.php | 10 +- lib/HttpClient.php | 204 ++-- lib/InlineParser.php | 214 ++-- lib/MailNotify.php | 126 +-- lib/PageList.php | 46 +- lib/PagePerm.php | 76 +- lib/PageType.php | 128 +-- lib/RSSWriter091.php | 30 +- lib/Request.php | 172 +-- lib/RssParser.php | 18 +- lib/RssWriter.php | 142 +-- lib/RssWriter2.php | 30 +- lib/SemanticWeb.php | 228 ++-- lib/SpamBlocklist.php | 70 +- lib/Template.php | 70 +- lib/TextSearchQuery.php | 484 ++++----- lib/Units.php | 104 +- lib/WikiCallback.php | 4 +- lib/WikiDB.php | 466 ++++---- lib/WikiGroup.php | 94 +- lib/WikiPlugin.php | 54 +- lib/WikiPluginCached.php | 92 +- lib/WikiTheme.php | 440 ++++---- lib/WikiUser.php | 24 +- lib/WikiUserNew.php | 500 ++++----- lib/WysiwygEdit.php | 18 +- lib/XmlElement.php | 138 +-- lib/XmlParser.php | 8 +- lib/XmlRpcClient.php | 24 +- lib/XmlRpcServer.php | 142 +-- lib/config.php | 16 +- lib/diff3.php | 28 +- lib/difflib.php | 402 +++---- lib/display.php | 278 ++--- lib/editpage.php | 256 ++--- lib/fortune.php | 58 +- lib/fpdf.php | 1084 +++++++++---------- lib/gif.php | 72 +- lib/imagecache.php | 32 +- lib/imdb.php | 2 +- lib/install.php | 2 +- lib/loadsave.php | 506 ++++----- lib/main.php | 250 ++--- lib/pdf.php | 14 +- lib/prepend.php | 18 +- lib/spam_babycart.php | 14 +- lib/stdlib.php | 370 +++---- lib/upgrade.php | 1768 +++++++++++++++---------------- lib/ziplib.php | 238 ++--- tests/CompatInfo.php | 6 +- tests/unit_test_backend_cvs.php | 10 +- uploads/index.php | 6 +- 69 files changed, 5351 insertions(+), 5351 deletions(-) diff --git a/lib/AccessLog.php b/lib/AccessLog.php index 7c783f9ca..281286316 100644 --- a/lib/AccessLog.php +++ b/lib/AccessLog.php @@ -57,7 +57,7 @@ class Request_AccessLog { if (!$request->_dbi->isSQL()) { trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB or PDO"); } else { - global $DBParams; + global $DBParams; //$this->_dbi =& $request->_dbi; $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog"; } @@ -126,8 +126,8 @@ class Request_AccessLog { if ($this->logtable) { // mysql specific only: return $this->read_sql("request_host=".$this->_dbi->quote($host) - ." AND time_stamp > ". (time()-$since_minutes*60) - ." ORDER BY time_stamp DESC"); + ." AND time_stamp > ". (time()-$since_minutes*60) + ." ORDER BY time_stamp DESC"); } else { $iter = new WikiDB_Array_generic_iter(); $logs =& $iter->_array; @@ -160,7 +160,7 @@ class Request_AccessLog { $entry = new Request_AccessLogEntry($this); $re = '/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/'; if (preg_match($re, $s, $m)) { - list(,$entry->host, $entry->ident, $entry->user, $entry->time, + list(,$entry->host, $entry->ident, $entry->user, $entry->time, $entry->request, $entry->status, $entry->size, $entry->referer, $entry->user_agent) = $m; } @@ -176,8 +176,8 @@ class Request_AccessLog { return $this->sqliter->next(); } function _read_sql_query($where='') { - global $request; - $dbh =& $request->_dbi; + global $request; + $dbh =& $request->_dbi; $log_tbl =& $this->logtable; return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user," ."remote_host as host,agent as user_agent" @@ -187,8 +187,8 @@ class Request_AccessLog { /* done in request->finish() before the db is closed */ function write_sql() { - global $request; - $dbh =& $request->_dbi; + global $request; + $dbh =& $request->_dbi; if (isset($this->entries) and $dbh and $dbh->isOpen()) foreach ($this->entries as $entry) { $entry->write_sql(); @@ -236,7 +236,7 @@ class Request_AccessLogEntry $this->logfile = $accesslog->logfile; $this->time = time(); $this->status = 200; // see setStatus() - $this->size = 0; // see setSize() + $this->size = 0; // see setSize() } /** @@ -350,7 +350,7 @@ class Request_AccessLogEntry /* This is better been done by apache mod_log_sql */ /* If ACCESS_LOG_SQL & 2 we do write it by our own */ function write_sql() { - global $request; + global $request; $dbh =& $request->_dbi; if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) { @@ -365,7 +365,7 @@ class Request_AccessLogEntry if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = ''; $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used. } else { - $this->request_args = $request->get('QUERY_STRING'); + $this->request_args = $request->get('QUERY_STRING'); } $this->request_method = $request->get('REQUEST_METHOD'); $this->request_uri = $request->get('REQUEST_URI'); diff --git a/lib/ArchiveCleaner.php b/lib/ArchiveCleaner.php index 0910393cc..19f70caf2 100644 --- a/lib/ArchiveCleaner.php +++ b/lib/ArchiveCleaner.php @@ -1,19 +1,19 @@ - * * This file is part of PhpWiki. - * + * * PhpWiki is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. - * + * * PhpWiki is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with PhpWiki; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA @@ -24,7 +24,7 @@ class ArchiveCleaner function ArchiveCleaner ($expire_params) { $this->expire_params = $expire_params; } - + function isMergeable($revision) { if ( ! $revision->get('is_minor_edit') ) return false; @@ -43,20 +43,20 @@ class ArchiveCleaner while ($page = $iter->next()) $this->cleanPageRevisions($page); } - + function cleanPageRevisions($page) { $INFINITY = 0x7fffffff; $expire = &$this->expire_params; foreach (array('major', 'minor', 'author') as $class) $counter[$class] = new ArchiveCleaner_Counter($expire[$class]); - // shortcut to keep all - if (($counter['minor']->min_keep == $INFINITY) + // shortcut to keep all + if (($counter['minor']->min_keep == $INFINITY) and ($counter['major']->min_keep == $INFINITY)) return; $authors_seen = array(); - + $current = $page->getCurrentRevision(false); for ( $revision = $page->getRevisionBefore($current,false); @@ -117,11 +117,11 @@ class ArchiveCleaner_Counter if ($this->min_age > $this->max_age) $this->min_age = $this->max_age; - + $this->now = time(); $this->count = 0; $this->previous_supplanted = false; - + } function computeAge($revision) { @@ -148,14 +148,14 @@ class ArchiveCleaner_Counter $this->previous_supplanted = $supplanted; return ($this->now - $supplanted) / (24 * 3600); } - + function keep($revision) { - $INFINITY = 0x7fffffff; - if ($this->min_keep == $INFINITY) - return true; + $INFINITY = 0x7fffffff; + if ($this->min_keep == $INFINITY) + return true; $count = ++$this->count; $age = $this->computeAge($revision); - + if ($count > $this->max_keep) return false; if ($age <= $this->min_age || $count <= $this->min_keep) @@ -170,5 +170,5 @@ class ArchiveCleaner_Counter // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/AtomParser.php b/lib/AtomParser.php index c7257d299..511672d5c 100644 --- a/lib/AtomParser.php +++ b/lib/AtomParser.php @@ -23,7 +23,7 @@ * This class is a poor-man Atom parser, it does no validation of the feed. * The content of an entry ("payload") is not parsed but rather returned "as-is", * as its format can be text, html or xhtml. - * + * * @author: Sébastien Le Callonnec */ require_once('lib/XmlParser.php'); @@ -44,7 +44,7 @@ extends XmlParser var $icon = ''; var $rights = ''; var $logo = ''; - + var $categories = array(); var $authors = array(); @@ -64,7 +64,7 @@ extends XmlParser var $id = ''; var $links = array(); var $summary = ''; - + var $inside_content = false; var $content = ''; @@ -165,7 +165,7 @@ extends XmlParser function cdata($parser, $data) { global $current_tag, $current_attrs; - + if ($this->inside_content) { $this->content .= $data; } else { @@ -244,7 +244,7 @@ extends XmlParser return trim($element); } } - + function serialize_tag($tag_name, $attributes) { $tag = "<" . $tag_name; foreach ($attributes as $k => $v) { diff --git a/lib/BlockParser.php b/lib/BlockParser.php index 3d02b7fd6..ed24dac49 100644 --- a/lib/BlockParser.php +++ b/lib/BlockParser.php @@ -93,11 +93,11 @@ class AnchoredRegexpSet * @return object A RegexpSet_match object, or false if no match. */ function match ($text) { - if (!is_string($text)) return false; + if (!is_string($text)) return false; if (! preg_match($this->_re, $text, $m)) { return false; } - + $match = new AnchoredRegexpSet_match; $match->postmatch = substr($text, strlen($m[0])); $match->match = $m[1]; @@ -136,7 +136,7 @@ class AnchoredRegexpSet if (! preg_match($pat, $text, $m)) { return false; } - + $match = new AnchoredRegexpSet_match; $match->postmatch = substr($text, strlen($m[0])); $match->match = $m[1]; @@ -146,11 +146,11 @@ class AnchoredRegexpSet } - + class BlockParser_Input { function BlockParser_Input ($text) { - + // Expand leading tabs. // FIXME: do this better. // @@ -182,14 +182,14 @@ class BlockParser_Input { } return $this->_atSpace; } - + function currentLine () { if ($this->_pos >= count($this->_lines)) { return false; } return $this->_lines[$this->_pos]; } - + function nextLine () { $this->_atSpace = $this->_lines[$this->_pos++] === ''; if ($this->_pos >= count($this->_lines)) { @@ -202,7 +202,7 @@ class BlockParser_Input { $this->_atSpace = ($this->_lines[$this->_pos] === ''); $this->_pos++; } - + function getPos () { return array($this->_pos, $this->_atSpace); } @@ -225,7 +225,7 @@ class BlockParser_Input { else return ""; } - + function _debug ($tab, $msg) { //return ; $where = $this->where(); @@ -233,7 +233,7 @@ class BlockParser_Input { printXML(HTML::div("$tab $msg: at: '", HTML::tt($where), "'")); - flush(); + flush(); } } @@ -271,7 +271,7 @@ class BlockParser_InputSubBlock extends BlockParser_Input else return $this->_atSpace; } - + function currentLine () { return $this->_line; } @@ -296,7 +296,7 @@ class BlockParser_InputSubBlock extends BlockParser_Input function advance () { $this->nextLine(); } - + function getPos () { return array($this->_line, $this->_atSpace, $this->_input->getPos()); } @@ -306,7 +306,7 @@ class BlockParser_InputSubBlock extends BlockParser_Input $this->_atSpace = $pos[1]; $this->_input->setPos($pos[2]); } - + function getPrefix () { assert ($this->_line !== false); $line = $this->_input->currentLine(); @@ -322,7 +322,7 @@ class BlockParser_InputSubBlock extends BlockParser_Input return $this->_input->where(); } } - + class Block_HtmlElement extends HtmlElement { @@ -335,7 +335,7 @@ class Block_HtmlElement extends HtmlElement } class ParsedBlock extends Block_HtmlElement { - + function ParsedBlock (&$input, $tag = 'div', $attr = false) { $this->Block_HtmlElement($tag, $attr); $this->_initBlockTypes(); @@ -362,22 +362,22 @@ class ParsedBlock extends Block_HtmlElement { // FIXME: hackish. This should only be called once. function _initBlockTypes () { - // better static or global? - static $_regexpset, $_block_types; + // better static or global? + static $_regexpset, $_block_types; - if (!is_object($_regexpset)) { + if (!is_object($_regexpset)) { // nowiki_wikicreole must be before template_plugin - $Block_types = array - ('nowiki_wikicreole', 'template_plugin', 'placeholder', 'oldlists', 'list', 'dl', + $Block_types = array + ('nowiki_wikicreole', 'template_plugin', 'placeholder', 'oldlists', 'list', 'dl', 'table_dl', 'table_wikicreole', 'table_mediawiki', 'blockquote', 'heading', 'heading_wikicreole', 'hr', 'pre', 'email_blockquote', 'wikicreole_indented', - 'plugin', 'plugin_wikicreole', 'p'); + 'plugin', 'plugin_wikicreole', 'p'); // insert it before p! if (ENABLE_MARKUP_DIVSPAN) { - array_pop($Block_types); - $Block_types[] = 'divspan'; - $Block_types[] = 'p'; + array_pop($Block_types); + $Block_types[] = 'divspan'; + $Block_types[] = 'p'; } foreach ($Block_types as $type) { $class = "Block_$type"; @@ -389,7 +389,7 @@ class ParsedBlock extends Block_HtmlElement { $_regexpset = $this->_regexpset; $_block_types = $this->_block_types; unset($Block_types); - } else { + } else { $this->_regexpset = $_regexpset; $this->_block_types = $_block_types; } @@ -409,9 +409,9 @@ class ParsedBlock extends Block_HtmlElement { $block = clone($this->_block_types[$m->regexp_ind]); if (DEBUG & _DEBUG_PARSER) $input->_debug('>', get_class($block)); - + if ($block->_match($input, $m)) { - //$block->_text = $line; + //$block->_text = $line; if (DEBUG & _DEBUG_PARSER) $input->_debug('<', get_class($block)); $tight_bottom = ! $input->skipSpace(); @@ -500,12 +500,12 @@ class Block_blockquote extends BlockMarkup 'blockquote'); return true; } - + function merge ($nextBlock) { if (get_class($nextBlock) == get_class($this)) { assert ($nextBlock->_depth < $this->_depth); $nextBlock->_element->unshiftContent($this->_element); - if (!empty($this->_tight_top)) + if (!empty($this->_tight_top)) $nextBlock->_tight_top = $this->_tight_top; return $nextBlock; } @@ -535,7 +535,7 @@ class Block_list extends BlockMarkup if (preg_match('/[*#+-o]/', $input->getPrefix())) { return false; } - + $prefix = $m->match; $indent = sprintf("\\ {%d}", strlen($prefix)); @@ -619,13 +619,13 @@ class Block_table_dl_defn extends XmlContent { var $nrows; var $ncols; - + function Block_table_dl_defn ($term, $defn) { $this->XmlContent(); if (!is_array($defn)) $defn = $defn->getContent(); - $this->_next_tight_top = false; // value irrelevant - gets fixed later + $this->_next_tight_top = false; // value irrelevant - gets fixed later $this->_ncols = $this->_ComputeNcols($defn); $this->_nrows = 0; @@ -645,9 +645,9 @@ class Block_table_dl_defn extends XmlContent function setTightness($tight_top, $tight_bot) { $this->_tight_top = $tight_top; - $this->_tight_bot = $tight_bot; + $this->_tight_bot = $tight_bot; } - + function _addToRow ($item) { if (empty($this->_accum)) { $this->_accum = HTML::td(); @@ -663,7 +663,7 @@ class Block_table_dl_defn extends XmlContent $row->setTightness($this->_next_tight_top, $tight_bottom); $this->_next_tight_top = $tight_bottom; - + $this->pushContent($row); $this->_accum = false; $this->_nrows++; @@ -675,7 +675,7 @@ class Block_table_dl_defn extends XmlContent return; $this->_flushRow($table_rows[0]->_tight_top); - + foreach ($table_rows as $subdef) { $this->pushContent($subdef); $this->_nrows += $subdef->nrows(); @@ -690,7 +690,7 @@ class Block_table_dl_defn extends XmlContent else $first_row->unshiftContent($th); } - + function _ComputeNcols ($defn) { $ncols = 2; foreach ($defn as $item) { @@ -722,17 +722,17 @@ class Block_table_dl_defn extends XmlContent } function & firstTR() { - $first = &$this->_content[0]; - if (isa($first, 'Block_table_dl_defn')) - return $first->firstTR(); - return $first; + $first = &$this->_content[0]; + if (isa($first, 'Block_table_dl_defn')) + return $first->firstTR(); + return $first; } function & lastTR() { - $last = &$this->_content[$this->_nrows - 1]; - if (isa($last, 'Block_table_dl_defn')) - return $last->lastTR(); - return $last; + $last = &$this->_content[$this->_nrows - 1]; + if (isa($last, 'Block_table_dl_defn')) + return $last->lastTR(); + return $last; } function setWidth ($ncols) { @@ -774,7 +774,7 @@ class Block_table_dl extends Block_dl function _setTightness($top, $bot) { $this->_content[0]->setTightness($top, $bot); } - + function finish () { $defs = &$this->_content; @@ -782,7 +782,7 @@ class Block_table_dl extends Block_dl $ncols = 0; foreach ($defs as $defn) $ncols = max($ncols, $defn->ncols()); - + foreach ($defs as $key => $defn) $defs[$key]->setWidth($ncols); @@ -807,7 +807,7 @@ class Block_oldlists extends Block_list if (!preg_match('/[*#;]*$/A', $input->getPrefix())) { return false; } - + $prefix = $m->match; $oldindent = '[*#;](?=[#*]|;.*:.*\S)'; @@ -873,7 +873,7 @@ class Block_oldlists extends Block_list */ echo 'count($this->_content): ', count($this->_content),"\n"; echo "\$this->_content[0]: "; var_dump ($this->_content[0]); - + for ($i=1; $i < min(5, count($this->_content)); $i++) { $c =& $this->_content[$i]; echo '$this->_content[',$i,"]: \n"; @@ -918,26 +918,26 @@ class Block_pre extends BlockMarkup } } $input->advance(); - - if ($m->match == '') - $text = join("
\n", $text); - else + + if ($m->match == '') + $text = join("
\n", $text); + else $text = join("\n", $text); - + // FIXME: no , , , , or 's allowed // in a
.
         if ($m->match == '
') {
             $text = TransformInline($text);
         }
-	if ($m->match == '') {
-	    $text = TransformText($text);
-	    $this->_element = new Block_HtmlElement('div', false, $text);
-	} else if ($m->match == '') {
+    if ($m->match == '') {
+        $text = TransformText($text);
+        $this->_element = new Block_HtmlElement('div', false, $text);
+    } else if ($m->match == '') {
             $text = TransformInlineNowiki($text);
-	    $this->_element = new Block_HtmlElement('p', false, $text);
-	} else {
+        $this->_element = new Block_HtmlElement('p', false, $text);
+    } else {
             $this->_element = new Block_HtmlElement('pre', false, $text);
-	}
+    }
         return true;
     }
 }
@@ -1019,7 +1019,7 @@ class Block_plugin extends Block_pre
         }
         $input->advance();
 
-	$this->_element = new Cached_PluginInvocation($pi);
+    $this->_element = new Cached_PluginInvocation($pi);
         return true;
     }
 }
@@ -1207,7 +1207,7 @@ class Block_email_blockquote extends BlockMarkup
 {
     var $_attr = array('class' => 'mail-style-quote');
     var $_re = '>\ ?';
-  
+
     function _match (&$input, $m) {
         //$indent = str_replace(' ', '\\ ', $m->match) . '|>$';
         $indent = $this->_re;
@@ -1244,14 +1244,14 @@ class Block_hr extends BlockMarkup
 class Block_heading extends BlockMarkup
 {
     var $_re = '!{1,3}';
-  
+
     function _match (&$input, $m) {
         $tag = "h" . (5 - strlen($m->match));
         $text = TransformInline(trim($m->postmatch));
         $input->advance();
 
         $this->_element = new Block_HtmlElement($tag, false, $text);
-      
+
         return true;
     }
 }
@@ -1259,7 +1259,7 @@ class Block_heading extends BlockMarkup
 class Block_heading_wikicreole extends BlockMarkup
 {
     var $_re = '={2,6}';
-  
+
     function _match (&$input, $m) {
         $tag = "h" . strlen($m->match);
         // Remove spaces
@@ -1270,7 +1270,7 @@ class Block_heading_wikicreole extends BlockMarkup
         $input->advance();
 
         $this->_element = new Block_HtmlElement($tag, false, $text);
-      
+
         return true;
     }
 }
@@ -1315,12 +1315,12 @@ class Block_divspan extends BlockMarkup
     var $_re = '<(?im)(?: div|span)(?:[^>]*)?>';
 
     function _match (&$input, $m) {
-    	if (substr($m->match,1,4) == 'span') {
-    	    $tag = 'span';
-	} else {
-    	    $tag = 'div';
-	}
-	// without last >
+        if (substr($m->match,1,4) == 'span') {
+            $tag = 'span';
+    } else {
+            $tag = 'div';
+    }
+    // without last >
         $argstr = substr(trim(substr($m->match,strlen($tag)+1)),0,-1);
         $pos = $input->getPos();
         $pi  = $content = $m->postmatch;
@@ -1339,22 +1339,22 @@ class Block_divspan extends BlockMarkup
         $input->advance();
         if (strstr($content, "\n"))
             $content = TransformText($content);
-        else  
+        else
             $content = TransformInline($content);
         if (!$argstr)
             $args = false;
         else {
             $args = array();
             while (preg_match("/(\w+)=(.+)/", $argstr, $m)) {
-            	$k = $m[1]; $v = $m[2];
-            	if (preg_match("/^\"(.+?)\"(.*)$/", $v, $m)) {
-            	    $v = $m[1];
-            	    $argstr = $m[2];
-            	} else {
-            	    preg_match("/^(\s+)(.*)$/", $v, $m);
-            	    $v = $m[1];
-            	    $argstr = $m[2];
-            	}
+                $k = $m[1]; $v = $m[2];
+                if (preg_match("/^\"(.+?)\"(.*)$/", $v, $m)) {
+                    $v = $m[1];
+                    $argstr = $m[2];
+                } else {
+                    preg_match("/^(\s+)(.*)$/", $v, $m);
+                    $v = $m[1];
+                    $argstr = $m[2];
+                }
                 if (trim($k) and trim($v)) $args[$k] = $v;
             }
         }
@@ -1382,7 +1382,7 @@ function TransformTextPre ($text, $markup = 2.0, $basepage=false) {
     }
     // WikiCreole
     /*if (!empty($markup) && $markup == 3) {
-    	$text = ConvertFromCreole($text);
+        $text = ConvertFromCreole($text);
     }*/
     // Expand leading tabs.
     $text = expand_tabs($text);
@@ -1413,5 +1413,5 @@ function TransformText ($text, $markup = 2.0, $basepage = false) {
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End: 
+// End:
 ?>
diff --git a/lib/CachedMarkup.php b/lib/CachedMarkup.php
index e3ec144a0..1c2608107 100644
--- a/lib/CachedMarkup.php
+++ b/lib/CachedMarkup.php
@@ -27,12 +27,12 @@ class CacheableMarkup extends XmlContent {
 
     function CacheableMarkup($content, $basepage) {
         $this->_basepage = $basepage;
-	$this->_buf = '';
-	$this->_content = array();
-	$this->_append($content);
-	if ($this->_buf != '')
-	    $this->_content[] = $this->_buf;
-	unset($this->_buf);
+    $this->_buf = '';
+    $this->_content = array();
+    $this->_append($content);
+    if ($this->_buf != '')
+        $this->_content[] = $this->_buf;
+    unset($this->_buf);
     }
 
     function pack() {
@@ -88,15 +88,15 @@ class CacheableMarkup extends XmlContent {
                       E_USER_WARNING);
         return false;
     }
-  
+
     /** Get names of wikipages linked to.
      *
      * @return array of hashes { linkto=>pagename, relation=>pagename }
      */
     function getWikiPageLinks() {
-	$links = array();
-	foreach ($this->_content as $item) {
-	    if (!isa($item, 'Cached_DynamicContent'))
+    $links = array();
+    foreach ($this->_content as $item) {
+        if (!isa($item, 'Cached_DynamicContent'))
                 continue;
             if (!($item_links = $item->getWikiPageLinks($this->_basepage)))
                 continue;
@@ -104,8 +104,8 @@ class CacheableMarkup extends XmlContent {
         }
         // array_unique has a bug with hashes!
         // set_links checks for duplicates, array_merge does not
-	//return array_unique($links);
-	return $links;
+    //return array_unique($links);
+    return $links;
     }
 
     /** Get link info.
@@ -116,62 +116,62 @@ class CacheableMarkup extends XmlContent {
      * Returns an array of hashes.
      */
     function getLinkInfo() {
-	$link = array();
-	foreach ($this->_content as $link) {
-	    if (! isa($link, 'Cached_Link'))
-		continue;
-	    $info = $link->getLinkInfo($this->_basepage);
-	    $links[$info->href] = $info;
-	}
-	return array_values($links);
+    $link = array();
+    foreach ($this->_content as $link) {
+        if (! isa($link, 'Cached_Link'))
+        continue;
+        $info = $link->getLinkInfo($this->_basepage);
+        $links[$info->href] = $info;
+    }
+    return array_values($links);
     }
 
     function _append($item) {
-	if (is_array($item)) {
-	    foreach ($item as $subitem)
-		$this->_append($subitem);
-	}
-	elseif (!is_object($item)) {
-	    $this->_buf .= $this->_quote((string) $item);
-	}
-	elseif (isa($item, 'Cached_DynamicContent')) {
-	    if ($this->_buf) {
-		$this->_content[] = $this->_buf;
-		$this->_buf = '';
-	    }
-	    $this->_content[] = $item;
-	}
-	elseif (isa($item, 'XmlElement')) {
-	    if ($item->isEmpty()) {
-		$this->_buf .= $item->emptyTag();
-	    }
-	    else {
-		$this->_buf .= $item->startTag();
-		foreach ($item->getContent() as $subitem)
-		    $this->_append($subitem);
-		$this->_buf .= "_tag>";
+    if (is_array($item)) {
+        foreach ($item as $subitem)
+        $this->_append($subitem);
+    }
+    elseif (!is_object($item)) {
+        $this->_buf .= $this->_quote((string) $item);
+    }
+    elseif (isa($item, 'Cached_DynamicContent')) {
+        if ($this->_buf) {
+        $this->_content[] = $this->_buf;
+        $this->_buf = '';
+        }
+        $this->_content[] = $item;
+    }
+    elseif (isa($item, 'XmlElement')) {
+        if ($item->isEmpty()) {
+        $this->_buf .= $item->emptyTag();
+        }
+        else {
+        $this->_buf .= $item->startTag();
+        foreach ($item->getContent() as $subitem)
+            $this->_append($subitem);
+        $this->_buf .= "_tag>";
 
                 if (!$this->getDescription() and $item->getTag() == 'p') {
                     // performance: when is this really needed?
                     $this->_glean_description($item->asString());
                 }
-	    }
-	    if (!$item->isInlineElement())
-		$this->_buf .= "\n";
-	}
-	elseif (isa($item, 'XmlContent')) {
-	    foreach ($item->getContent() as $item)
-		$this->_append($item);
-	}
-	elseif (method_exists($item, 'asXML')) {
-	    $this->_buf .= $item->asXML();
-	}
-	elseif (method_exists($item, 'asString')) {
-	    $this->_buf .= $this->_quote($item->asString());
-	}
-	else {
-	    $this->_buf .= sprintf("==Object(%s)==", get_class($item));
-	}
+        }
+        if (!$item->isInlineElement())
+        $this->_buf .= "\n";
+    }
+    elseif (isa($item, 'XmlContent')) {
+        foreach ($item->getContent() as $item)
+        $this->_append($item);
+    }
+    elseif (method_exists($item, 'asXML')) {
+        $this->_buf .= $item->asXML();
+    }
+    elseif (method_exists($item, 'asString')) {
+        $this->_buf .= $this->_quote($item->asString());
+    }
+    else {
+        $this->_buf .= sprintf("==Object(%s)==", get_class($item));
+    }
     }
 
     function _glean_description($text) {
@@ -181,7 +181,7 @@ class CacheableMarkup extends XmlContent {
                            . ".*"
                            . "[.?!][\")]*\s*[\"(]*([[:upper:])]|$)";
         }
-      
+
         if (!isset($this->_description) and preg_match("/$two_sentences/sx", $text))
             $this->_description = preg_replace("/\s*\n\s*/", " ", trim($text));
     }
@@ -204,12 +204,12 @@ class CacheableMarkup extends XmlContent {
     function getDescription () {
         return isset($this->_description) ? $this->_description : '';
     }
-  
+
     function asXML () {
-	$xml = '';
+    $xml = '';
         $basepage = $this->_basepage;
-      
-	foreach ($this->_content as $item) {
+
+    foreach ($this->_content as $item) {
             if (is_string($item)) {
                 $xml .= $item;
             }
@@ -224,15 +224,15 @@ class CacheableMarkup extends XmlContent {
             else {
                 $xml .= $item->asXML();
             }
-	}
-	return $xml;
+    }
+    return $xml;
     }
 
     function printXML () {
         $basepage = $this->_basepage;
         // _content might be changed from a plugin (CreateToc)
-	for ($i=0; $i < count($this->_content); $i++) {
-	    $item = $this->_content[$i];
+    for ($i=0; $i < count($this->_content); $i++) {
+        $item = $this->_content[$i];
             if (is_string($item)) {
                 print $item;
             }
@@ -240,8 +240,8 @@ class CacheableMarkup extends XmlContent {
                                    check_php_version(5)
                                      ? 'Cached_DynamicContent'
                                      : 'cached_dynamiccontent'))
-            {  	// give the content the chance to know about itself or even
-            	// to change itself
+            {      // give the content the chance to know about itself or even
+                // to change itself
                 $val = $item->expand($basepage, $this);
                 if ($val) $val->printXML();
                 else trigger_error('empty item ' . print_r($item, true));
@@ -249,7 +249,7 @@ class CacheableMarkup extends XmlContent {
             else {
                 $item->printXML();
             }
-	}
+    }
     }
 }
 
@@ -262,7 +262,7 @@ class CacheableMarkup extends XmlContent {
 class Cached_DynamicContent {
 
     function cache(&$cache) {
-	$cache[] = $this;
+    $cache[] = $this;
     }
 
     function expand($basepage, &$obj) {
@@ -276,18 +276,18 @@ class Cached_DynamicContent {
 
 class XmlRpc_LinkInfo {
     function XmlRpc_LinkInfo($page, $type, $href, $relation = '') {
-	$this->page = $page;
-	$this->type = $type;
-	$this->href = $href;
-	$this->relation = $relation;
-	//$this->pageref = str_replace("/RPC2.php", "/index.php", $href);
+    $this->page = $page;
+    $this->type = $type;
+    $this->href = $href;
+    $this->relation = $relation;
+    //$this->pageref = str_replace("/RPC2.php", "/index.php", $href);
     }
 }
 
 class Cached_Link extends Cached_DynamicContent {
 
     function isInlineElement() {
-	return true;
+    return true;
     }
 
     /** Get link info (for XML-RPC support)
@@ -296,17 +296,17 @@ class Cached_Link extends Cached_DynamicContent {
      * (See http://www.ecyrd.com/JSPWiki/Wiki.jsp?page=WikiRPCInterface)
      */
     function getLinkInfo($basepage) {
-	return new XmlRpc_LinkInfo($this->_getName($basepage),
+    return new XmlRpc_LinkInfo($this->_getName($basepage),
                                    $this->_getType(),
                                    $this->_getURL($basepage),
                                    $this->_getRelation($basepage));
     }
-  
+
     function _getURL($basepage) {
-	return $this->_url;
+    return $this->_url;
     }
     function __getRelation($basepage) {
-	return $this->_relation;
+    return $this->_relation;
     }
 }
 /*
@@ -315,55 +315,55 @@ class Cached_Link extends Cached_DynamicContent {
  */
 class Cached_InlinedImage extends Cached_DynamicContent {
     function isInlineElement() {
-	return true;
+    return true;
     }
     function _getURL($basepage) {
-	return $this->_url;
+    return $this->_url;
     }
     // TODO: fix interwiki inline links in case of static dumps
     function expand($basepage, &$markup) {
-	global $WikiTheme;
-    	$this->_basepage = $basepage;
-	$label = isset($this->_label) ? $this->_label : false;
-	if ($WikiTheme->DUMP_MODE) {
+    global $WikiTheme;
+        $this->_basepage = $basepage;
+    $label = isset($this->_label) ? $this->_label : false;
+    if ($WikiTheme->DUMP_MODE) {
             // In case of static dumps we need to check if we should
             // inline the image or not: external: keep link, internal: copy locally
-	    return LinkImage($label);
-	} else {
-	    return LinkImage($label);
-	}
+        return LinkImage($label);
+    } else {
+        return LinkImage($label);
+    }
     }
 }
 
 class Cached_WikiLink extends Cached_Link {
 
     function Cached_WikiLink ($page, $label = false, $anchor = false) {
-	$this->_page = $page;
-	/* ":DontStoreLink" */
-	if (substr($this->_page,0,1) == ':') {
-	    $this->_page = substr($this->_page,1);
-	    $this->_nolink = true;
-        }  
+    $this->_page = $page;
+    /* ":DontStoreLink" */
+    if (substr($this->_page,0,1) == ':') {
+        $this->_page = substr($this->_page,1);
+        $this->_nolink = true;
+        }
         if ($anchor)
             $this->_anchor = $anchor;
         if ($label and $label != $page)
             $this->_label = $label;
-        $this->_basepage = false;  
+        $this->_basepage = false;
     }
 
     function _getType() {
         return 'internal';
     }
-  
+
     function getPagename($basepage) {
         $page = new WikiPageName($this->_page, $basepage);
-	if ($page->isValid()) return $page->name;
-	else return false;
+    if ($page->isValid()) return $page->name;
+    else return false;
     }
 
     function getWikiPageLinks($basepage) {
         if ($basepage == '') return false;
-	if (isset($this->_nolink)) return false;
+    if (isset($this->_nolink)) return false;
         if ($link = $this->getPagename($basepage))
             return array(array('linkto' => $link));
         else
@@ -371,40 +371,40 @@ class Cached_WikiLink extends Cached_Link {
     }
 
     function _getName($basepage) {
-	return $this->getPagename($basepage);
+    return $this->getPagename($basepage);
     }
 
     function _getURL($basepage) {
-	return WikiURL($this->getPagename($basepage));
-	//return WikiURL($this->getPagename($basepage), false, 'abs_url');
+    return WikiURL($this->getPagename($basepage));
+    //return WikiURL($this->getPagename($basepage), false, 'abs_url');
     }
 
     function expand($basepage, &$markup) {
-	global $WikiTheme;
-    	$this->_basepage = $basepage;
-	$label = isset($this->_label) ? $this->_label : false;
-	$anchor = isset($this->_anchor) ? (string)$this->_anchor : '';
+    global $WikiTheme;
+        $this->_basepage = $basepage;
+    $label = isset($this->_label) ? $this->_label : false;
+    $anchor = isset($this->_anchor) ? (string)$this->_anchor : '';
         $page = new WikiPageName($this->_page, $basepage, $anchor);
-	if ($WikiTheme->DUMP_MODE and !empty($WikiTheme->VALID_LINKS)) {
-	    if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
-		return HTML($label ? $label : $page->getName());
-	}
+    if ($WikiTheme->DUMP_MODE and !empty($WikiTheme->VALID_LINKS)) {
+        if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
+        return HTML($label ? $label : $page->getName());
+    }
         if ($page->isValid()) return WikiLink($page, 'auto', $label);
-	else return HTML($label);
+    else return HTML($label);
     }
 
     function asXML() {
-	global $WikiTheme;
-	$label = isset($this->_label) ? $this->_label : false;
-	$anchor = isset($this->_anchor) ? (string)$this->_anchor : '';
-	//TODO: need basepage for subpages like /Remove (within CreateTOC)
+    global $WikiTheme;
+    $label = isset($this->_label) ? $this->_label : false;
+    $anchor = isset($this->_anchor) ? (string)$this->_anchor : '';
+    //TODO: need basepage for subpages like /Remove (within CreateTOC)
         $page = new WikiPageName($this->_page, $this->_basepage, $anchor);
-	if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
-	    if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
-		return $label ? $label : $page->getName();
-	}
-	$link = WikiLink($page, 'auto', $label);
-	return $link->asXML();
+    if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
+        if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
+        return $label ? $label : $page->getName();
+    }
+    $link = WikiLink($page, 'auto', $label);
+    return $link->asXML();
     }
 
     function asString() {
@@ -417,54 +417,54 @@ class Cached_WikiLink extends Cached_Link {
 class Cached_WikiLinkIfKnown extends Cached_WikiLink
 {
     function Cached_WikiLinkIfKnown ($moniker) {
-	$this->_page = $moniker;
+    $this->_page = $moniker;
     }
 
     function expand($basepage, &$markup) {
-	global $WikiTheme;
-	if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
-	    if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
-		return HTML($label ? $label : $page->getName());
-	}
+    global $WikiTheme;
+    if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
+        if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
+        return HTML($label ? $label : $page->getName());
+    }
         return WikiLink($this->_page, 'if_known');
     }
-}  
+}
 
 class Cached_SpellCheck extends Cached_WikiLink
 {
     function Cached_SpellCheck ($word, $suggs) {
-	$this->_page = $word;
-	$this->suggestions = $suggs;
+    $this->_page = $word;
+    $this->suggestions = $suggs;
     }
 
     function expand($basepage, &$markup) {
         $link = HTML::a(array('class' => 'spell-wrong',
-			      'title' => 'SpellCheck: '.join(', ', $this->suggestions),
-			      'name' => $this->_page),
-			$this->_page);
+                  'title' => 'SpellCheck: '.join(', ', $this->suggestions),
+                  'name' => $this->_page),
+            $this->_page);
         return $link;
     }
-}  
-  
+}
+
 class Cached_PhpwikiURL extends Cached_DynamicContent
 {
     function Cached_PhpwikiURL ($url, $label) {
-	$this->_url = $url;
+    $this->_url = $url;
         if ($label)
             $this->_label = $label;
     }
 
     function isInlineElement() {
-	return true;
+    return true;
     }
 
     function expand($basepage, &$markup) {
-	global $WikiTheme;
+    global $WikiTheme;
         $label = isset($this->_label) ? $this->_label : false;
-	if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
-	    if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
-		return HTML($label ? $label : $page->getName());
-	}
+    if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
+        if (!in_array($this->_page, $WikiTheme->VALID_LINKS))
+        return HTML($label ? $label : $page->getName());
+    }
         return LinkPhpwikiURL($this->_url, $label, $basepage);
     }
 
@@ -479,7 +479,7 @@ class Cached_PhpwikiURL extends Cached_DynamicContent
             return $this->_label;
         return $this->_url;
     }
-}  
+}
 
 /*
  * Relations (::) are named links to pages.
@@ -494,21 +494,21 @@ class Cached_PhpwikiURL extends Cached_DynamicContent
 class Cached_SemanticLink extends Cached_WikiLink {
 
     function Cached_SemanticLink ($url, $label=false) {
-	$this->_url = $url;
+    $this->_url = $url;
         if ($label && $label != $url)
             $this->_label = $label;
         $this->_expandurl($this->_url);
     }
 
     function isInlineElement() {
-	return true;
+    return true;
     }
 
     function getPagename($basepage) {
-	if (!isset($this->_page)) return false;
-	$page = new WikiPageName($this->_page, $basepage);
-	if ($page->isValid()) return $page->name;
-	else return false;
+    if (!isset($this->_page)) return false;
+    $page = new WikiPageName($this->_page, $basepage);
+    if ($page->isValid()) return $page->name;
+    else return false;
     }
 
     /* Add relation to the link table.
@@ -516,14 +516,14 @@ class Cached_SemanticLink extends Cached_WikiLink {
      */
     function getWikiPageLinks($basepage) {
         if ($basepage == '') return false;
-	if (!isset($this->_page) and isset($this->_attribute)) {
+    if (!isset($this->_page) and isset($this->_attribute)) {
             // An attribute: we store it in the basepage now, to fill the cache for page->save
             // TODO: side-effect free query
             $page = $GLOBALS['request']->getPage($basepage);
             $page->setAttribute($this->_relation, $this->_attribute);
             $this->_page = $basepage;
             return array(array('linkto' => '', 'relation' => $this->_relation));
-	}
+    }
         if ($link = $this->getPagename($basepage))
             return array(array('linkto' => $link, 'relation' => $this->_relation));
         else
@@ -535,67 +535,67 @@ class Cached_SemanticLink extends Cached_WikiLink {
         if (!preg_match('/^ ([^:]+) (:[:=]) (.+) $/x', $url, $m)) {
             return HTML::span(array('class' => 'error'), _("BAD semantic relation link"));
         }
-	$this->_relation = urldecode($m[1]);
+    $this->_relation = urldecode($m[1]);
         $is_attribute = ($m[2] == ':=');
         if ($is_attribute) {
             $this->_attribute = urldecode($m[3]);
-	    // since this stored in the markup cache, we are extra sensible
-	    // not to store false empty stuff.
-	    $units = new Units();
+        // since this stored in the markup cache, we are extra sensible
+        // not to store false empty stuff.
+        $units = new Units();
             if (!DISABLE_UNITS and !$units->errcode)
-	    {
-		$this->_attribute_base = $units->Definition($this->_attribute);
-		$this->_unit = $units->baseunit($this->_attribute);
-	    }
+        {
+        $this->_attribute_base = $units->Definition($this->_attribute);
+        $this->_unit = $units->baseunit($this->_attribute);
+        }
         } else {
-	    $this->_page = urldecode($m[3]);
+        $this->_page = urldecode($m[3]);
         }
-	return $m;
+    return $m;
     }
 
     function _expand($url, $label = false) {
-	global $WikiTheme;
-	$m = $this->_expandurl($url);
+    global $WikiTheme;
+    $m = $this->_expandurl($url);
         $class = 'wiki';
         // do not link to the attribute value, but to the attribute
         $is_attribute = ($m[2] == ':=');
-	if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
-	    if (isset($this->_page) and !in_array($this->_page, $WikiTheme->VALID_LINKS))
-		return HTML($label ? $label : ($is_attribute ? $this->_relation : $this->_page));
-	}
-	if ($is_attribute)
-	    $title = isset($this->_attribute_base)
-		? sprintf(_("Attribute %s, base value: %s"), $this->_relation, $this->_attribute_base)
-		: sprintf(_("Attribute %s, value: %s"), $this->_relation, $this->_attribute);
+    if ($WikiTheme->DUMP_MODE and $WikiTheme->VALID_LINKS) {
+        if (isset($this->_page) and !in_array($this->_page, $WikiTheme->VALID_LINKS))
+        return HTML($label ? $label : ($is_attribute ? $this->_relation : $this->_page));
+    }
+    if ($is_attribute)
+        $title = isset($this->_attribute_base)
+        ? sprintf(_("Attribute %s, base value: %s"), $this->_relation, $this->_attribute_base)
+        : sprintf(_("Attribute %s, value: %s"), $this->_relation, $this->_attribute);
         if ($label) {
             return HTML::span
-		(
-		 HTML::a(array('href'  => WikiURL($is_attribute ? $this->_relation : $this->_page),
-			       'class' => "wiki ".($is_attribute ? "attribute" : "relation"),
-			       'title' => $is_attribute
-			       ? $title
-			       : sprintf(_("Relation %s to page %s"), $this->_relation, $this->_page)),
-			 $label)
-		 );
+        (
+         HTML::a(array('href'  => WikiURL($is_attribute ? $this->_relation : $this->_page),
+                   'class' => "wiki ".($is_attribute ? "attribute" : "relation"),
+                   'title' => $is_attribute
+                   ? $title
+                   : sprintf(_("Relation %s to page %s"), $this->_relation, $this->_page)),
+             $label)
+         );
         } elseif ($is_attribute) {
             return HTML::span
-		(
-		 HTML::a(array('href'  => WikiURL($this->_relation),
-			       'class' => "wiki attribute",
-			       'title' => $title),
-			 $url)
-		 );
+        (
+         HTML::a(array('href'  => WikiURL($this->_relation),
+                   'class' => "wiki attribute",
+                   'title' => $title),
+             $url)
+         );
         } else {
             return HTML::span
-		(
-		 HTML::a(array('href'  => WikiURL($this->_relation),
-			       'class' => "wiki relation"),
-			 $this->_relation),
-		 HTML::span(array('class'=>'relation-symbol'), $m[2]),
-		 HTML::a(array('href'  => WikiURL($this->_page),
-			       'class' => "wiki"),
-			 $this->_page)
-		 );
+        (
+         HTML::a(array('href'  => WikiURL($this->_relation),
+                   'class' => "wiki relation"),
+             $this->_relation),
+         HTML::span(array('class'=>'relation-symbol'), $m[2]),
+         HTML::a(array('href'  => WikiURL($this->_page),
+                   'class' => "wiki"),
+             $this->_page)
+         );
         }
     }
 
@@ -623,8 +623,8 @@ class Cached_SemanticLink extends Cached_WikiLink {
 class Cached_SearchHighlight extends Cached_DynamicContent
 {
     function Cached_SearchHighlight ($word, $engine) {
-	$this->_word = $word;
-	$this->engine = $engine;
+    $this->_word = $word;
+    $this->engine = $engine;
     }
 
     function expand($basepage, &$markup) {
@@ -632,12 +632,12 @@ class Cached_SearchHighlight extends Cached_DynamicContent
                                 'title' => _("Found by ") . $this->engine),
                           $this->_word);
     }
-}  
-  
+}
+
 class Cached_ExternalLink extends Cached_Link {
 
     function Cached_ExternalLink($url, $label=false) {
-	$this->_url = $url;
+    $this->_url = $url;
         if ($label && $label != $url)
             $this->_label = $label;
     }
@@ -645,17 +645,17 @@ class Cached_ExternalLink extends Cached_Link {
     function _getType() {
         return 'external';
     }
-  
+
     function _getName($basepage) {
-	$label = isset($this->_label) ? $this->_label : false;
-	return ($label and is_string($label)) ? $label : $this->_url;
+    $label = isset($this->_label) ? $this->_label : false;
+    return ($label and is_string($label)) ? $label : $this->_url;
     }
 
     function expand($basepage, &$markup) {
         global $request;
 
-	$label = isset($this->_label) ? $this->_label : false;
-	$link = LinkURL($this->_url, $label);
+    $label = isset($this->_label) ? $this->_label : false;
+    $link = LinkURL($this->_url, $label);
 
         if (GOOGLE_LINKS_NOFOLLOW) {
             // Ignores nofollow when the user who saved the page was authenticated.
@@ -675,26 +675,26 @@ class Cached_ExternalLink extends Cached_Link {
 }
 
 class Cached_InterwikiLink extends Cached_ExternalLink {
-  
+
     function Cached_InterwikiLink($link, $label=false) {
-	$this->_link = $link;
+    $this->_link = $link;
         if ($label)
             $this->_label = $label;
     }
 
     function getPagename($basepage) {
         list ($moniker, $page) = explode (":", $this->_link, 2);
-	$page = new WikiPageName($page, $basepage);
-	if ($page->isValid()) return $page->name;
-	else return false;
+    $page = new WikiPageName($page, $basepage);
+    if ($page->isValid()) return $page->name;
+    else return false;
     }
 
     function getWikiPageLinks($basepage) {
         if ($basepage == '') return false;
-	/* ":DontStoreLink" */
-	if (substr($this->_link,0,1) == ':') return false;
-	/* store only links to valid pagenames */
-	$dbi = $GLOBALS['request']->getDbh();
+    /* ":DontStoreLink" */
+    if (substr($this->_link,0,1) == ':') return false;
+    /* store only links to valid pagenames */
+    $dbi = $GLOBALS['request']->getDbh();
         if ($link = $this->getPagename($basepage) and $dbi->isWikiPage($link)) {
             return array(array('linkto' => $link));
         } else {
@@ -703,30 +703,30 @@ class Cached_InterwikiLink extends Cached_ExternalLink {
     }
 
     function _getName($basepage) {
-	$label = isset($this->_label) ? $this->_label : false;
-	return ($label and is_string($label)) ? $label : $this->_link;
+    $label = isset($this->_label) ? $this->_label : false;
+    return ($label and is_string($label)) ? $label : $this->_link;
     }
-  
+
     /* there may be internal interwiki links also */
     function _getType() {
         return $this->getPagename(false) ? 'internal' : 'external';
     }
 
     function _getURL($basepage) {
-	$link = $this->expand($basepage, $this);
-	return $link->getAttr('href');
+    $link = $this->expand($basepage, $this);
+    return $link->getAttr('href');
     }
 
     function expand($basepage, &$markup) {
-	global $WikiTheme;
-	$intermap = getInterwikiMap();
-	$label = isset($this->_label) ? $this->_label : false;
-	//FIXME: check Upload: inlined images
-	if ($WikiTheme->DUMP_MODE and !empty($WikiTheme->VALID_LINKS)) {
-	    if (!in_array($this->_link, $WikiTheme->VALID_LINKS))
-		return HTML($label ? $label : $this->_link);
-	}
-	return $intermap->link($this->_link, $label);
+    global $WikiTheme;
+    $intermap = getInterwikiMap();
+    $label = isset($this->_label) ? $this->_label : false;
+    //FIXME: check Upload: inlined images
+    if ($WikiTheme->DUMP_MODE and !empty($WikiTheme->VALID_LINKS)) {
+        if (!in_array($this->_link, $WikiTheme->VALID_LINKS))
+        return HTML($label ? $label : $this->_link);
+    }
+    return $intermap->link($this->_link, $label);
     }
 
     function asString() {
@@ -742,9 +742,9 @@ class Cached_InterwikiLink extends Cached_ExternalLink {
 class Cached_UserLink extends Cached_WikiLink {
     function expand($basepage, &$markup) {
         $label = isset($this->_label) ? $this->_label : false;
-	$anchor = isset($this->_anchor) ? (string)$this->_anchor : '';
+    $anchor = isset($this->_anchor) ? (string)$this->_anchor : '';
         $page = new WikiPageName($this->_page, $basepage, $anchor);
-	$link = WikiLink($page, 'auto', $label);
+    $link = WikiLink($page, 'auto', $label);
         // $link = HTML::a(array('href' => $PageName));
         $link->setContent(PossiblyGlueIconToText('wikiuser', $this->_page));
         $link->setAttr('class', 'wikiuser');
@@ -760,8 +760,8 @@ class Cached_UserLink extends Cached_WikiLink {
 class Cached_PluginInvocation extends Cached_DynamicContent {
 
     function Cached_PluginInvocation ($pi) {
-	$this->_pi = $pi;
-	$loader = $this->_getLoader();
+    $this->_pi = $pi;
+    $loader = $this->_getLoader();
         if (is_array($plugin_cmdline = $loader->parsePI($pi)) and $plugin_cmdline[1]) {
             $this->pi_name = $plugin_cmdline[0]; // plugin, plugin-form, plugin-list
             $this->name = $plugin_cmdline[1]->getName();
@@ -771,9 +771,9 @@ class Cached_PluginInvocation extends Cached_DynamicContent {
 
     function setTightness($top, $bottom) {
     }
-  
+
     function isInlineElement() {
-	return false;
+    return false;
     }
 
     function expand($basepage, &$markup) {
@@ -795,9 +795,9 @@ class Cached_PluginInvocation extends Cached_DynamicContent {
     function & _getLoader() {
         static $loader = false;
 
-	if (!$loader) {
+    if (!$loader) {
             include_once('lib/WikiPlugin.php');
-	    $loader = new WikiPluginLoader;
+        $loader = new WikiPluginLoader;
         }
         return $loader;
     }
@@ -809,5 +809,5 @@ class Cached_PluginInvocation extends Cached_DynamicContent {
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End: 
+// End:
 ?>
diff --git a/lib/Captcha.php b/lib/Captcha.php
index d843ddaec..3c89613e9 100644
--- a/lib/Captcha.php
+++ b/lib/Captcha.php
@@ -11,7 +11,7 @@
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
- * 
+ *
  * This File is distributed in the hope that it will be useful, but
  * WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
@@ -35,20 +35,20 @@ class Captcha {
 
     function captchaword() {
         if ( ! $this->request->getSessionVar('captchaword')) {
-	    $this->request->setSessionVar('captchaword', $this->get_word());
-	}
+        $this->request->setSessionVar('captchaword', $this->get_word());
+    }
         return $this->request->getSessionVar('captchaword');
     }
 
     function Failed () {
         if ($this->request->getSessionVar('captcha_ok') == true)
             return false;
-	
+
         if ( ! array_key_exists ( 'captcha_input', $this->meta )
              or ($this->request->getSessionVar('captchaword')
                  and ($this->request->getSessionVar('captchaword') != $this->meta['captcha_input'])))
             return true;
-	
+
         $this->request->setSessionVar('captcha_ok', true);
         return false;
     }
@@ -70,9 +70,9 @@ class Captcha {
         return $el;
     }
 
-    function get_word () { 
+    function get_word () {
         if (USE_CAPTCHA_RANDOM_WORD)
-            return get_dictionary_word(); 
+            return get_dictionary_word();
         else
             return rand_ascii_readable($this->length); // lib/stdlib.php
     }
@@ -99,10 +99,10 @@ class Captcha {
     // Draw the Spiral
     function spiral( &$im, $origin_x = 100, $origin_y = 100, $r = 0, $g = 0, $b = 0 ) {
         $theta = 1;
-        $thetac = 6;  
-        $radius = 15;  
-        $circles = 10;  
-        $points = 35;  
+        $thetac = 6;
+        $radius = 15;
+        $circles = 10;
+        $points = 35;
         $lcolor = imagecolorallocate( $im, $r, $g, $b );
         for( $i = 0; $i < ( $circles * $points ) - 1; $i++ ) {
             $theta = $theta + $thetac;
@@ -121,7 +121,7 @@ class Captcha {
     function image ( $word ) {
         $width  =& $this->width;
         $height =& $this->height;
-    
+
         // Create the Image
         $jpg = ImageCreate($width,$height);
         $bg  = ImageColorAllocate($jpg,255,255,255);
@@ -134,7 +134,7 @@ class Captcha {
 
         $x = rand(10, 30);
         $y = rand(50, $height-20); //50-60
-        
+
         // randomize the chars
         for ($i=0; $i < strlen($word); $i++) {
             $angle += rand(-5, 5);
@@ -145,8 +145,8 @@ class Captcha {
             if ( $y < 10 )  $y = 11;
             elseif ( $y > $height-10 ) $y = $height-11;
             $x += rand($size, $size*2);
-            imagettftext($jpg, $size, $angle, $x, $y, $tx, 
-                         realpath(findfile("lib/captcha/Vera.ttf")), 
+            imagettftext($jpg, $size, $angle, $x, $y, $tx,
+                         realpath(findfile("lib/captcha/Vera.ttf")),
                          $word[$i]);
         }
 
@@ -159,18 +159,18 @@ class Captcha {
         imageline($jpg, 0,$height-1,$width-1,$height-1,$tx);
         imageline($jpg, $width-1,0,$width-1,$height-1,$tx);
 
-	if (function_exists("ImageJpeg")) {
-	    header("Content-type: image/jpeg");
-	    ImageJpeg($jpg);
-	} elseif (function_exists("ImagePNG")) {
-	    header("Content-type: image/png");
-	    ImagePNG($jpg);
-	} elseif (function_exists("ImageGIF")) {
-	    header("Content-type: image/gif");
-	    ImageGIF($jpg);
-	} else {
-	    trigger_error("missing GD bitmap support", E_USER_WARNING);
-	}
+    if (function_exists("ImageJpeg")) {
+        header("Content-type: image/jpeg");
+        ImageJpeg($jpg);
+    } elseif (function_exists("ImagePNG")) {
+        header("Content-type: image/png");
+        ImagePNG($jpg);
+    } elseif (function_exists("ImageGIF")) {
+        header("Content-type: image/gif");
+        ImageGIF($jpg);
+    } else {
+        trigger_error("missing GD bitmap support", E_USER_WARNING);
+    }
     }
 
 }
@@ -181,5 +181,5 @@ class Captcha {
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End:   
+// End:
 ?>
diff --git a/lib/DbSession.php b/lib/DbSession.php
index a58512c6b..a962c1eb1 100644
--- a/lib/DbSession.php
+++ b/lib/DbSession.php
@@ -29,7 +29,7 @@ class DbSession
         $db_type = $dbh->getParam('dbtype');
         if (isa($dbh, 'WikiDB')) {
             @include_once("lib/DbSession/".$db_type.".php");
-            
+
             $class = "DbSession_".$db_type;
             if (class_exists($class)) {
                 // dba has no ->_dbh, so this is used for the session link
@@ -43,7 +43,7 @@ class DbSession
                              $db_type), E_USER_WARNING);
         return false;
     }
-    
+
     function currentSessions() {
         return $this->_backend->currentSessions();
     }
diff --git a/lib/DbaDatabase.php b/lib/DbaDatabase.php
index d62afe36d..5c7b94c92 100644
--- a/lib/DbaDatabase.php
+++ b/lib/DbaDatabase.php
@@ -18,9 +18,9 @@ class DbaDatabase
             if (!in_array($handler, dba_handlers()))
                 $this->_error(
                     sprintf(
-                	    _("The DBA handler %s is unsupported!")."\n".
-                    	    _("Supported handlers are: %s"),
-                    	    $handler, join(",",dba_handlers())));
+                        _("The DBA handler %s is unsupported!")."\n".
+                            _("Supported handlers are: %s"),
+                            $handler, join(",",dba_handlers())));
         }
         $this->readonly = false;
         if ($mode)
@@ -30,11 +30,11 @@ class DbaDatabase
     function set_timeout($timeout) {
         $this->_timeout = $timeout;
     }
-  
+
     function open($mode = 'w') {
         if ($this->_dbh)
             return;             // already open.
-      
+
         $watchdog = $this->_timeout;
 
         global $ErrorManager;
@@ -53,9 +53,9 @@ class DbaDatabase
         if ((strlen($mode) == 1)) {
             // PHP 4.3.x Windows lock bug workaround: http://bugs.php.net/bug.php?id=23975
             if (isWindows()) {
-                $mode .= "-"; 			// suppress locking, or
-            } elseif ($this->_handler != 'gdbm') { 	// gdbm does it internally
-            	$mode .= "d"; 			// else use internal locking
+                $mode .= "-";             // suppress locking, or
+            } elseif ($this->_handler != 'gdbm') {     // gdbm does it internally
+                $mode .= "d";             // else use internal locking
             }
         }
         while (($dbh = dba_open($this->_file, $mode, $this->_handler)) < 1) {
@@ -96,7 +96,7 @@ class DbaDatabase
                 $this->readonly = true;
                 if (!file_exists($this->_file)) {
                     $ErrorManager->handleError($error);
-	            flush();
+                flush();
                 }
             }
             else {
@@ -116,7 +116,7 @@ class DbaDatabase
     function exists($key) {
         return dba_exists($key, $this->_dbh);
     }
-  
+
     function fetch($key) {
         $val = dba_fetch($key, $this->_dbh);
         if ($val === false)
@@ -134,7 +134,7 @@ class DbaDatabase
             return $this->_error("replace($key)");
     }
 
-  
+
     function firstkey() {
         return dba_firstkey($this->_dbh);
     }
@@ -182,7 +182,7 @@ class DbaDatabase
             return $this->_error("optimize()");
         return 1;
     }
-  
+
     function _error($mes) {
         //trigger_error("DbaDatabase: $mes", E_USER_WARNING);
         //return false;
@@ -207,5 +207,5 @@ class DbaDatabase
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End: 
+// End:
 ?>
diff --git a/lib/DbaListSet.php b/lib/DbaListSet.php
index abedcb61e..3a04f56dc 100644
--- a/lib/DbaListSet.php
+++ b/lib/DbaListSet.php
@@ -52,7 +52,7 @@ class DbaListSet
         list( $prev , , ) = explode(':', $this->_dbh->fetch(intval($i)), 3);
         return intval($prev);
     }
-  
+
     function exists($i) {
         $i = intval($i);
         return $i && $this->_dbh->exists($i);
@@ -68,7 +68,7 @@ class DbaListSet
         list($prev, $next,) = explode(':', $dbh->fetch(intval($i)), 3);
         $dbh->replace($i, "$prev:$next:$data");
     }
-  
+
     function insert_before($i, $data) {
         assert(intval($i));
         return $this->_insert_before_nc($i, $data);
@@ -78,7 +78,7 @@ class DbaListSet
         assert(intval($i));
         return $this->_insert_after_nc($i, $data);
     }
-  
+
     function append($seq, $data) {
         $key = "s" . urlencode($seq);
         $this->_insert_before_nc($key, $data);
@@ -88,7 +88,7 @@ class DbaListSet
         $key = "s" . urlencode($seq);
         $this->_insert_after_nc($key, $data);
     }
-  
+
     function _insert_before_nc($i, &$data) {
         $newkey = $this->_new_key();
         $old_prev = $this->_setprev($i, $newkey);
diff --git a/lib/DbaPartition.php b/lib/DbaPartition.php
index 7ed637990..9463d4d6a 100644
--- a/lib/DbaPartition.php
+++ b/lib/DbaPartition.php
@@ -10,11 +10,11 @@ class DbaPartition
     function open($mode = 'w') {
         $this->_h->open();
     }
-    
+
     function close() {
         $this->_h->close();
     }
-            
+
     function firstkey() {
         $dbh = &$this->_h;
         $prefix = &$this->_p;
@@ -40,7 +40,7 @@ class DbaPartition
     function exists($key) {
         return $this->_h->exists($this->_p . $key);
     }
-    
+
     function fetch($key) {
         return $this->_h->fetch($this->_p . $key);
     }
@@ -60,7 +60,7 @@ class DbaPartition
     function get($key) {
         return $this->_h->get($this->_p . $key);
     }
-    
+
     function set($key, $val) {
         return $this->_h->set($this->_p . $key, $val);
     }
@@ -82,4 +82,4 @@ class DbaPartition
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
 // End:
-?>
\ No newline at end of file
+?>
diff --git a/lib/EditToolbar.php b/lib/EditToolbar.php
index b7505d7fc..7fefece6d 100644
--- a/lib/EditToolbar.php
+++ b/lib/EditToolbar.php
@@ -24,7 +24,7 @@
  * EDIT Toolbar Initialization.
  * The default/themes/toolbar.js is from Mediawiki, this PHP is written from scratch.
  *
- * Features: 
+ * Features:
  * - save-preview and formatting buttons from mediawiki
  * - Search&Replace from walterzorn.de
  * - pageinsert popup by Reini Urban (TODO: should be a pulldown, use acdropdown)
@@ -40,10 +40,10 @@ class EditToolbar {
         //FIXME: enable Undo button for all other buttons also, not only the search/replace button
         if (JS_SEARCHREPLACE) {
             $this->tokens['JS_SEARCHREPLACE'] = 1;
-            $undo_btn = $WikiTheme->getImageURL("ed_undo.png"); 
-            $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png"); 
+            $undo_btn = $WikiTheme->getImageURL("ed_undo.png");
+            $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png");
             // JS_SEARCHREPLACE from walterzorn.de
-	    $js = Javascript("
+        $js = Javascript("
 uri_undo_btn   = '".$undo_btn."'
 msg_undo_alt   = '"._("Undo")."'
 uri_undo_d_btn = '".$undo_d_btn."'
@@ -58,24 +58,24 @@ msg_repl_ok        = '"._("OK")."'
 msg_repl_close     = '"._("Close")."'
 ");
             if (empty($WikiTheme->_headers_printed)) {
-		$WikiTheme->addMoreHeaders($js);
-		$WikiTheme->addMoreAttr('body', "SearchReplace"," onload='define_f()'");
-	    } else { // from an actionpage: WikiBlog, AddComment, WikiForum
-		printXML($js);
-	    }
+        $WikiTheme->addMoreHeaders($js);
+        $WikiTheme->addMoreAttr('body', "SearchReplace"," onload='define_f()'");
+        } else { // from an actionpage: WikiBlog, AddComment, WikiForum
+        printXML($js);
+        }
         } else {
             $WikiTheme->addMoreAttr('body', "editfocus", "document.getElementById('edit-content]').editarea.focus()");
         }
-    
+
         if (ENABLE_EDIT_TOOLBAR) {
             $js = JavaScript('',array('src' => $WikiTheme->_findData("toolbar.js")));
             if (empty($WikiTheme->_headers_printed)) {
                 $WikiTheme->addMoreHeaders($js);
             }
-	    else { // from an actionpage: WikiBlog, AddComment, WikiForum
+        else { // from an actionpage: WikiBlog, AddComment, WikiForum
                 printXML($js);
                 printXML(JavaScript('define_f()'));
-	    }
+        }
         }
 
         require_once("lib/WikiPluginCached.php");
@@ -98,7 +98,7 @@ msg_repl_close     = '"._("Close")."'
         } else {
             $content = $this->_generate();
             // regenerate buttons every 1 hr/6 hrs
-            $cache->save($id, $content, DEBUG ? '+3600' : '+21600', 'toolbarcache'); 
+            $cache->save($id, $content, DEBUG ? '+3600' : '+21600', 'toolbarcache');
             $this->tokens['EDIT_TOOLBAR'] =& $content;
         }
     }
@@ -117,7 +117,7 @@ msg_repl_close     = '"._("Close")."'
             if (FUSIONFORGE or DISABLE_MARKUP_WIKIWORD or (!isWikiWord($username))) {
                 $username = '[['.$username.']]';
             }
-	    $signature = " ––".$username." ".CTime();
+        $signature = " ––".$username." ".CTime();
             $toolarray = array(
                            array(
                                  "image"=>"ed_format_bold.png",
@@ -201,20 +201,20 @@ msg_repl_close     = '"._("Close")."'
                                  "sample"=>_("Template Name"),
                                  "title"=>_("Template"))
                            );
-            $btn = new SubmitImageButton(_("Save"), "edit[save]", 'toolbar', 
+            $btn = new SubmitImageButton(_("Save"), "edit[save]", 'toolbar',
                                          $WikiTheme->getImageURL("ed_save.png"));
             $btn->addTooltip(_("Save"));
-	    $btn->setAccesskey("s");
+        $btn->setAccesskey("s");
             $toolbar .= ('document.writeln("'.addslashes($btn->asXml()).'");'."\n");
-	    // preview not supported yet on Wikiblog
+        // preview not supported yet on Wikiblog
             if (empty($WikiTheme->_headers_printed)) {
-		$btn = new SubmitImageButton(_("Preview"), "edit[preview]", 'toolbar', 
-					     $WikiTheme->getImageURL("ed_preview.png"));
-		$btn->addTooltip(_("Preview"));
-		$btn->setAccesskey("p");
-		$toolbar .= ('document.writeln("'.addslashes($btn->asXml()).'");'."\n");
-	    }
-    
+        $btn = new SubmitImageButton(_("Preview"), "edit[preview]", 'toolbar',
+                         $WikiTheme->getImageURL("ed_preview.png"));
+        $btn->addTooltip(_("Preview"));
+        $btn->setAccesskey("p");
+        $toolbar .= ('document.writeln("'.addslashes($btn->asXml()).'");'."\n");
+        }
+
             foreach ($toolarray as $tool) {
                 $image = $WikiTheme->getImageURL($tool["image"]);
                 $open  = $tool["open"];
@@ -230,14 +230,14 @@ msg_repl_close     = '"._("Close")."'
             }
             /* Fails with Chrome */
             if (!isBrowserSafari()) {
-                $toolbar .= ("addInfobox('" 
-                             . addslashes( _("Click a button to get an example text") ) 
+                $toolbar .= ("addInfobox('"
+                             . addslashes( _("Click a button to get an example text") )
                              . "');\n");
             }
         }
 
         if (JS_SEARCHREPLACE) {
-            $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png"); 
+            $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png");
             //$redo_btn = $WikiTheme->getImageURL("ed_redo.png");
             $sr_btn   = $WikiTheme->getImageURL("ed_replace.png");
             //TODO: generalize the UNDO button and fix it for Search & Replace
@@ -260,8 +260,8 @@ msg_repl_close     = '"._("Close")."'
             $sr_html = '';
         }
 
-        //TODO: Delegate this to run-time with showing an hidden input at the right, and do 
-	// a seperate moacdropdown and xmlrpc:titleSearch.
+        //TODO: Delegate this to run-time with showing an hidden input at the right, and do
+    // a seperate moacdropdown and xmlrpc:titleSearch.
 
         // Button to generate categories, display in extra window as popup and insert
         $sr_html = HTML($sr_html, $this->categoriesPulldown());
@@ -300,19 +300,19 @@ msg_repl_close     = '"._("Close")."'
         if ($pages) {
             $categories = array();
             while ($p = $pages->next()) {
-		$page = $p->getName();
+        $page = $p->getName();
                 if (FUSIONFORGE) {
                     $categories[] = "['$page', '%0A----%0A%5B%5B".$page."%5D%5D']";
-		} else if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page))) {
-		    $categories[] = "['$page', '%0A%5B".$page."%5D']";
-		} else {
-		    $categories[] = "['$page', '%0A".$page."']";
+        } else if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page))) {
+            $categories[] = "['$page', '%0A%5B".$page."%5D']";
+        } else {
+            $categories[] = "['$page', '%0A".$page."']";
                 }
             }
             if (!$categories) return '';
-	    // Ensure this to be inserted at the very end. Hence we added the id to the function.
+        // Ensure this to be inserted at the very end. Hence we added the id to the function.
             $more_buttons = HTML::img(array('class'=> "toolbar",
-					    'id' => 'tb-categories',
+                        'id' => 'tb-categories',
                                             'src'  => $WikiTheme->getImageURL("ed_category.png"),
                                             'title'=>_("AddCategory"),
                                             'alt'=>"AddCategory", // to detect this at js
@@ -362,7 +362,7 @@ msg_repl_close     = '"._("Close")."'
             }
             $plugin_js = substr($plugin_js, 1);
             $more_buttons = HTML::img(array('class'=>"toolbar",
-					    'id' => 'tb-plugins',
+                        'id' => 'tb-plugins',
                                             'src'  => $WikiTheme->getImageURL("ed_plugins.png"),
                                             'title'=>_("AddPlugin"),
                                             'alt'=>_("AddPlugin"),
@@ -385,14 +385,14 @@ msg_repl_close     = '"._("Close")."'
             global $WikiTheme;
             $pages = array();
             while ($p = $page_iter->next()) {
-		$page = $p->getName();
-		if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page)))
-		    $pages[] = "['$page', '%5B".$page."%5D']";
-		else
-		    $pages[] = "['$page', '$page']";
+        $page = $p->getName();
+        if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page)))
+            $pages[] = "['$page', '%5B".$page."%5D']";
+        else
+            $pages[] = "['$page', '$page']";
             }
             return HTML("\n", HTML::img(array('class'=>"toolbar",
-					      'id' => 'tb-pages',
+                          'id' => 'tb-pages',
                                               'src'  => $WikiTheme->getImageURL("ed_pages.png"),
                                               'title'=>_("AddPageLink"),
                                               'alt'=>_("AddPageLink"),
@@ -430,7 +430,7 @@ msg_repl_close     = '"._("Close")."'
             }
             $image_js = substr($image_js, 1);
             $more_buttons = HTML::img(array('class'=>"toolbar",
-					    'id' => 'tb-images',
+                        'id' => 'tb-images',
                                             'src'  => $WikiTheme->getImageURL("ed_image.png"),
                                             'title'=>_("Add Image or Video"),
                                             'alt'=>_("Add Image or Video"),
@@ -465,7 +465,7 @@ msg_repl_close     = '"._("Close")."'
             if (!empty($pages_js))
                 return HTML("\n", HTML::img
                             (array('class'=>"toolbar",
-				   'id' => 'tb-templates',
+                   'id' => 'tb-templates',
                                    'src'  => $WikiTheme->getImageURL("ed_template.png"),
                                    'title'=>_("AddTemplate"),
                                    'alt'=>_("AddTemplate"),
diff --git a/lib/ErrorManager.php b/lib/ErrorManager.php
index 8de5e66a3..291d9f0d5 100644
--- a/lib/ErrorManager.php
+++ b/lib/ErrorManager.php
@@ -14,7 +14,7 @@ if (defined('E_STRICT')
 */
 define ('EM_FATAL_ERRORS', E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | ~2048 & ((check_php_version(5,3)) ? ~E_DEPRECATED : ~0));
 define ('EM_WARNING_ERRORS',
-	E_WARNING | E_CORE_WARNING | E_COMPILE_WARNING | E_USER_WARNING | ((check_php_version(5,3)) ? E_DEPRECATED : 0));
+    E_WARNING | E_CORE_WARNING | E_COMPILE_WARNING | E_USER_WARNING | ((check_php_version(5,3)) ? E_DEPRECATED : 0));
 define ('EM_NOTICE_ERRORS', E_NOTICE | E_USER_NOTICE);
 
 /* It is recommended to leave assertions on.
@@ -97,14 +97,14 @@ class ErrorManager
         else
             echo $this->_flush_errors();
     }
-  
+
     /**
      * Get rid of all pending error messages in case of all non-html
      * - pdf or image - output.
      * @access public
      */
     function destroyPostponedErrors () {
-    	$this->_postponed_errors = array();
+        $this->_postponed_errors = array();
     }
 
     /**
@@ -136,7 +136,7 @@ class ErrorManager
         $html->pushContent($flushed);
         return $html;
     }
-  
+
     /**
      * Push a custom error handler on the handler stack.
      *
@@ -227,8 +227,8 @@ class ErrorManager
         // so display now all errors directly.
         if (!empty($GLOBALS['request']->_finishing)) {
             $this->_postpone_mask = 0;
-	}
-      
+    }
+
         $in_handler = true;
 
         foreach ($this->_handlers as $handler) {
@@ -262,7 +262,7 @@ class ErrorManager
             $this->_noCacheHeaders();
             echo "\n";
             echo "\n";
+        echo "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
             echo "\n";
             echo "\n";
             echo "\n";
@@ -277,7 +277,7 @@ class ErrorManager
                 if (function_exists("debug_backtrace")) // >= 4.3.0
                     $error->printSimpleTrace(debug_backtrace());
             }
-	    $this->_die($error);
+        $this->_die($error);
         }
         else if (($error->errno & error_reporting()) != 0) {
             if  (($error->errno & $this->_postpone_mask) != 0) {
@@ -311,7 +311,7 @@ class ErrorManager
     function warning($msg, $errno = E_USER_NOTICE) {
         $this->handleError(new PhpWikiError($errno, $msg, '?', '?'));
     }
-  
+
     /**
      * @access private
      */
@@ -322,8 +322,8 @@ class ErrorManager
         PrintXML($this->_flush_errors());
         if ($this->_fatal_handler)
             $this->_fatal_handler->call($error);
-	if (!$WikiTheme->DUMP_MODE)
-	    exit -1;
+    if (!$WikiTheme->DUMP_MODE)
+        exit -1;
     }
 
     /**
@@ -355,7 +355,7 @@ class ErrorManager
             $request->_validators->_mtime = false;
         }
         if ($already) return;
-      
+
         // FIXME: Howto announce that to Request->cacheControl()?
         if (!headers_sent()) {
             header( "Cache-control: no-cache" );
@@ -461,7 +461,7 @@ class PhpError {
             return 'errors';
         }
     }
-  
+
     function getDescription() {
         if ($this->isNotice()) {
             return 'Notice';
@@ -502,7 +502,7 @@ class PhpError {
                          $this->getDescription(),
                          array_shift($lines));
         }
-      
+
         $html = HTML::div(array('class' => $this->getHtmlClass()), HTML::p($msg));
         // The class is now used for the div container.
         // $html = HTML::div(HTML::p($msg));
@@ -512,7 +512,7 @@ class PhpError {
                 $list->pushContent(HTML::li($line));
             $html->pushContent($list);
         }
-      
+
         return $html;
     }
 
@@ -606,10 +606,10 @@ class PhpErrorOnce extends PhpError {
         }
         return $this->_count;
     }
-  
+
     function _getDetail($count=0) {
-    	if (!$count) $count = $this->_count;
-	$dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__),0,-4);
+        if (!$count) $count = $this->_count;
+    $dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR : substr(dirname(__FILE__),0,-4);
         if (substr(PHP_OS,0,3) == 'WIN') {
            $dir = str_replace('/','\\',$dir);
            $this->errfile = str_replace('/','\\',$this->errfile);
@@ -618,24 +618,24 @@ class PhpErrorOnce extends PhpError {
            $dir .= '/';
         $errfile = preg_replace('|^' . preg_quote($dir) . '|', '', $this->errfile);
         if (is_string($this->errstr))
-	        $lines = explode("\n", $this->errstr);
-	elseif (is_object($this->errstr))
-	        $lines = array($this->errstr->asXML());
+            $lines = explode("\n", $this->errstr);
+    elseif (is_object($this->errstr))
+            $lines = array($this->errstr->asXML());
         $errtype = (DEBUG & _DEBUG_VERBOSE) ? sprintf("%s[%d]", $this->getDescription(), $this->errno)
                                             : sprintf("%s", $this->getDescription());
         if ((DEBUG & _DEBUG_VERBOSE) or $this->isFatal()) {
-	    $msg = sprintf("%s:%d %s: %s %s",
+        $msg = sprintf("%s:%d %s: %s %s",
                        $errfile, $this->errline,
                        $errtype,
                        array_shift($lines),
                        $count > 1 ? sprintf(" (...repeated %d times)",$count) : ""
                        );
-	} else {
+    } else {
           $msg = sprintf("%s: \"%s\" %s",
-			 $errtype,
-			 array_shift($lines),
-			 $count > 1 ? sprintf(" (...repeated %d times)",$count) : "");
-	}
+             $errtype,
+             array_shift($lines),
+             $count > 1 ? sprintf(" (...repeated %d times)",$count) : "");
+    }
         $html = HTML::div(array('class' => $this->getHtmlClass()),
                           HTML::p($msg));
         if ($lines) {
@@ -644,7 +644,7 @@ class PhpErrorOnce extends PhpError {
                 $list->pushContent(HTML::li($line));
             $html->pushContent($list);
         }
-      
+
         return $html;
     }
 }
diff --git a/lib/ExternalReferrer.php b/lib/ExternalReferrer.php
index a661196f8..42ec7a458 100644
--- a/lib/ExternalReferrer.php
+++ b/lib/ExternalReferrer.php
@@ -11,8 +11,8 @@
 if (!function_exists('isExternalReferrer')) { // also defined in stdlib.php
   function isExternalReferrer(&$request) {
     if ($referrer = $request->get('HTTP_REFERER')) {
-    	$home = SCRIPT_NAME; // was SERVER_URL, check sister wiki's: same host but other other script url
-    	if (substr(strtolower($referrer),0,strlen($home)) == strtolower($home)) return false;
+        $home = SCRIPT_NAME; // was SERVER_URL, check sister wiki's: same host but other other script url
+        if (substr(strtolower($referrer),0,strlen($home)) == strtolower($home)) return false;
         require_once("lib/ExternalReferrer.php");
         $se = new SearchEngines();
         return $se->parseSearchQuery($referrer);
diff --git a/lib/FileFinder.php b/lib/FileFinder.php
index 0c6e76da5..c8706acd6 100644
--- a/lib/FileFinder.php
+++ b/lib/FileFinder.php
@@ -4,11 +4,11 @@ require_once(dirname(__FILE__).'/stdlib.php');
 
 /**
  * A class for finding files.
- * 
- * This should really provided by pear. We don't want really to mess around 
+ *
+ * This should really provided by pear. We don't want really to mess around
  * with all the lousy systems. (WindowsNT, Win95, Mac, ...)
  * But pear has only System and File, which do nothing.
- * Anyway, in good PHP style we ignore the rest of the world and try to behave 
+ * Anyway, in good PHP style we ignore the rest of the world and try to behave
  * as on unix only. That means we use / as pathsep in all our constants.
  */
 class FileFinder
@@ -57,11 +57,11 @@ class FileFinder
      * Force using '/' as path seperator.
      */
     function forcePathSlashes ($path, $sep='/') {
-    	if (is_array($path)) {
-    	    $result = array();
-    	    foreach ($path as $dir) { $result[] = $this->forcePathSlashes($dir,$sep); }
-    	    return $result;
-    	} else {
+        if (is_array($path)) {
+            $result = array();
+            foreach ($path as $dir) { $result[] = $this->forcePathSlashes($dir,$sep); }
+            return $result;
+        } else {
             if (isWindows() or $this->_isOtherPathsep()) {
                 if (isWindows()) $from = "\\";
                 else $from = "\\";
@@ -73,9 +73,9 @@ class FileFinder
                         $path = '\\\\' . str_replace('\\\\','\\',substr($path,2));
                 }
                 return strtr($path, $from, $sep);
-            } else 
+            } else
                 return $path;
-    	}
+        }
     }
 
     /**
@@ -106,7 +106,7 @@ class FileFinder
     }
 
     /**
-     * The system-dependent path-separator character. 
+     * The system-dependent path-separator character.
      * UNIX,WindowsNT,MacOSX: /
      * Windows95: \
      * Mac:       :
@@ -115,7 +115,7 @@ class FileFinder
      * @return string path_separator.
      */
     function _get_syspath_separator () {
-    	if (!empty($this->_pathsep)) return $this->_pathsep;
+        if (!empty($this->_pathsep)) return $this->_pathsep;
         elseif (isWindowsNT()) return "/"; // we can safely use '/'
         elseif (isWindows()) return "\\";  // FAT might use '\'
         // VMS or LispM is really weird, we ignore it.
@@ -123,12 +123,12 @@ class FileFinder
     }
 
     /**
-     * The path-separator character of the given path. 
+     * The path-separator character of the given path.
      * Windows accepts "/" also, but gets confused with mixed path_separators,
      * e.g "C:\Apache\phpwiki/locale/button"
-     * > dir "C:\Apache\phpwiki/locale/button" => 
+     * > dir "C:\Apache\phpwiki/locale/button" =>
      *       Parameterformat nicht korrekt - "locale"
-     * So if there's any '\' in the path, either fix them to '/' (not in Win95 or FAT?) 
+     * So if there's any '\' in the path, either fix them to '/' (not in Win95 or FAT?)
      * or use '\' for ours.
      *
      * @access private
@@ -148,13 +148,13 @@ class FileFinder
      *
      * @access private
      * @param $path string Path.
-     * @return bool True if path is absolute. 
+     * @return bool True if path is absolute.
      */
     function _is_abs($path) {
         if (substr($path,0,1) == '/') {
             return true;
         } elseif (isWindows() and preg_match("/^[a-z]:/i", $path)
-                  and (substr($path,2,1) == "/" or substr($path,2,1) == "\\")) 
+                  and (substr($path,2,1) == "/" or substr($path,2,1) == "\\"))
         {
             return true;
         } else {
@@ -170,7 +170,7 @@ class FileFinder
      * @return bool New path (destructive)
      */
     function _strip_last_pathchar(&$path) {
-        if (substr($path,-1) == '/' or substr($path,-1) == "\\") 
+        if (substr($path,-1) == '/' or substr($path,-1) == "\\")
             $path = substr($path,0,-1);
         return $path;
     }
@@ -203,12 +203,12 @@ class FileFinder
         foreach ($this->_path as $dir) {
             // ensure we use the same pathsep
             if ($this->_isOtherPathsep()) {
-            	$dir = $this->slashifyPath($dir);
-            	$file = $this->slashifyPath($file);
+                $dir = $this->slashifyPath($dir);
+                $file = $this->slashifyPath($file);
                 if (file_exists($dir . $this->_pathsep . $file))
                     return $dir;
             } elseif (@file_exists($dir . $this->_pathsep . $file))
-               	return $dir;
+                   return $dir;
         }
         return false;
     }
@@ -224,7 +224,7 @@ class FileFinder
      */
     function _get_ini_separator () {
         return isWindows() ? ';' : ':';
-        // return preg_match('/^Windows/', php_uname()) 
+        // return preg_match('/^Windows/', php_uname())
     }
 
     /**
@@ -322,7 +322,7 @@ class FileFinder
             if (!empty($lang))
                 return $lang;
         }
-            
+
         foreach (array('LC_ALL', 'LC_MESSAGES', 'LC_RESPONSES', 'LANG') as $var) {
             $lang = getenv($var);
             if (!empty($lang))
@@ -462,14 +462,14 @@ function FindFile ($file, $missing_okay = false, $slashify = false)
     static $finder;
     if (!isset($finder)) {
         $finder = new FileFinder;
-    	// remove "/lib" from dirname(__FILE__)
-    	$wikidir = preg_replace('/.lib$/','',dirname(__FILE__));
+        // remove "/lib" from dirname(__FILE__)
+        $wikidir = preg_replace('/.lib$/','',dirname(__FILE__));
         // let the system favor its local pear?
-    	$finder->_append_to_include_path(dirname(__FILE__)."/pear");
-    	$finder->_prepend_to_include_path($wikidir);
+        $finder->_append_to_include_path(dirname(__FILE__)."/pear");
+        $finder->_prepend_to_include_path($wikidir);
         // Don't override existing INCLUDE_PATH config.
         if (!defined("INCLUDE_PATH"))
- 	    define("INCLUDE_PATH", implode($finder->_get_ini_separator(), $finder->_path));
+         define("INCLUDE_PATH", implode($finder->_get_ini_separator(), $finder->_path));
     }
     $s = $finder->findFile($file, $missing_okay);
     if ($slashify)
@@ -495,9 +495,9 @@ function FindLocalizedButtonFile ($file, $missing_okay = false, $re_init = false
     return $buttonfinder->findFile($file, $missing_okay);
 }
 
-/** 
+/**
  * Prefixes with PHPWIKI_DIR and slashify.
- * For example to unify with 
+ * For example to unify with
  *   require_once dirname(__FILE__).'/lib/file.php'
  *   require_once 'lib/file.php' loading style.
  * Doesn't expand "~" or symlinks yet. truename would be perfect.
@@ -522,7 +522,7 @@ function NormalizeLocalFileName($file) {
     }
 }
 
-/** 
+/**
  * Prefixes with DATA_PATH and slashify
  */
 function NormalizeWebFileName($file) {
diff --git a/lib/Google.php b/lib/Google.php
index 7f6d13a13..1a2831b42 100644
--- a/lib/Google.php
+++ b/lib/Google.php
@@ -21,7 +21,7 @@
  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- 
+
  If you have any questions or comments, please email:
 
  Chris Petersen
@@ -35,7 +35,7 @@
  */
 
 /*
- * Objectified, simplified, documented and added the two other queries 
+ * Objectified, simplified, documented and added the two other queries
  * by Reini Urban
  */
 
@@ -132,7 +132,7 @@ class GoogleSearchResults {
  *   resultElement that comes from that host contains the host name in
  *   this parameter.
  *
- *    - array with "fullViewableName" and 
+ *    - array with "fullViewableName" and
  *   "specialEncoding" keys.
  *
  *    - If the URL for this resultElement is contained
@@ -174,13 +174,13 @@ class Google {
         return $this;
     }
 
-    /** 
+    /**
      * doGoogleSearch
      *
      * See http://www.google.com/help/features.html for examples of
      * advanced features.  Anything that works at the Google web site
      * will work as a query string in this method.
-     * 
+     *
      * You can use the start and maxResults parameters to page through
      * multiple pages of results. Note that 'maxResults' is currently
      * limited by Google to 10.  See the API reference for more
@@ -263,7 +263,7 @@ class Google {
     /**
      * Get spelling suggestions from Google
      *
-     * @param  string phrase   word or phrase to spell-check 
+     * @param  string phrase   word or phrase to spell-check
      * @return string          text of any suggested replacement, or None
      */
     function doSpellingSuggestion($phrase) {
@@ -282,4 +282,4 @@ class Google {
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
 // End:
-?>
\ No newline at end of file
+?>
diff --git a/lib/HtmlElement.php b/lib/HtmlElement.php
index f24fc6ccb..b380edd6c 100644
--- a/lib/HtmlElement.php
+++ b/lib/HtmlElement.php
@@ -33,7 +33,7 @@ class HtmlElement extends XmlElement
         assert(count($args) >= 1);
         assert(is_string($args[0]));
         $this->_tag = array_shift($args);
-      
+
         if ($args && is_array($args[0]))
             $this->_attr = array_shift($args);
         else {
@@ -56,7 +56,7 @@ class HtmlElement extends XmlElement
             elseif ($args[0] === false)
                 array_shift($args);
         }
-      
+
         if (count($args) == 1 && is_array($args[0]))
             $args = $args[0];
         $this->_content = $args;
@@ -69,7 +69,7 @@ class HtmlElement extends XmlElement
      */
     function addTooltip ($tooltip_text, $accesskey = null) {
         $this->setAttr('title', $tooltip_text);
-	if ($accesskey) $this->setAccesskey($accesskey);
+    if ($accesskey) $this->setAccesskey($accesskey);
 
         // FIXME: this should be initialized from title by an onLoad() function.
         //        (though, that may not be possible.)
@@ -81,25 +81,25 @@ class HtmlElement extends XmlElement
     }
 
     function setAccesskey ($key) {
-	global $WikiTheme;
-	if (strlen($key) != 1) return;
-	$this->setAttr("accesskey", $key);
+    global $WikiTheme;
+    if (strlen($key) != 1) return;
+    $this->setAttr("accesskey", $key);
 
         if (!empty($this->_attr['title'])) {
-	    if (preg_match("/\[(alt-)?(.)\]$/", $this->_attr['title'], $m))
-	    {
-		$this->_attr['title'] = preg_replace
+        if (preg_match("/\[(alt-)?(.)\]$/", $this->_attr['title'], $m))
+        {
+        $this->_attr['title'] = preg_replace
                     ("/\[(alt-)?(.)\]$/",
                      "[".$WikiTheme->tooltipAccessKeyPrefix()."-\\2]",
                      $this->_attr['title']);
-	    } else  {
-		$this->_attr['title'] .=
+        } else  {
+        $this->_attr['title'] .=
                     " [".$WikiTheme->tooltipAccessKeyPrefix()."-$key]";
-	    }
-	} else {
-	    $this->_attr['title'] =
+        }
+    } else {
+        $this->_attr['title'] =
                 "[".$WikiTheme->tooltipAccessKeyPrefix()."-$key]";
-	}
+    }
     }
 
     function emptyTag () {
@@ -126,7 +126,7 @@ class HTML extends HtmlElement {
     function raw ($html_text) {
         return new RawXml($html_text);
     }
-  
+
     function getTagProperties($tag) {
         $props = &$GLOBALS['HTML_TagProperties'];
         return isset($props[$tag]) ? $props[$tag] : 0;
@@ -544,7 +544,7 @@ function IfJavaScript($if_content = false, $else_content = false) {
     }
     return HTML($html);
 }
-  
+
 // Local Variables:
 // mode: php
 // tab-width: 8
diff --git a/lib/HtmlElement5.php b/lib/HtmlElement5.php
index 87e306010..337aa04b7 100644
--- a/lib/HtmlElement5.php
+++ b/lib/HtmlElement5.php
@@ -33,7 +33,7 @@ class HtmlElement extends XmlElement
         assert(count($args) >= 1);
         assert(is_string($args[0]));
         $this->_tag = array_shift($args);
-      
+
         if ($args && is_array($args[0]))
             $this->_attr = array_shift($args);
         else {
@@ -56,7 +56,7 @@ class HtmlElement extends XmlElement
             elseif ($args[0] === false)
                 array_shift($args);
         }
-      
+
         if (count($args) == 1 && is_array($args[0]))
             $args = $args[0];
         $this->_content = $args;
@@ -69,7 +69,7 @@ class HtmlElement extends XmlElement
      */
     function addTooltip ($tooltip_text, $accesskey = null) {
         $this->setAttr('title', $tooltip_text);
-	if ($accesskey) $this->setAccesskey($accesskey);
+    if ($accesskey) $this->setAccesskey($accesskey);
 
         // FIXME: this should be initialized from title by an onLoad() function.
         //        (though, that may not be possible.)
@@ -81,25 +81,25 @@ class HtmlElement extends XmlElement
     }
 
     function setAccesskey ($key) {
-	global $WikiTheme;
-	if (strlen($key) != 1) return;
-	$this->setAttr("accesskey", $key);
+    global $WikiTheme;
+    if (strlen($key) != 1) return;
+    $this->setAttr("accesskey", $key);
 
         if (!empty($this->_attr['title'])) {
-	    if (preg_match("/\[(alt-)?(.)\]$/", $this->_attr['title'], $m))
-	    {
-		$this->_attr['title'] = preg_replace
+        if (preg_match("/\[(alt-)?(.)\]$/", $this->_attr['title'], $m))
+        {
+        $this->_attr['title'] = preg_replace
                     ("/\[(alt-)?(.)\]$/",
                      "[".$WikiTheme->tooltipAccessKeyPrefix()."-\\2]",
                      $this->_attr['title']);
-	    } else  {
-		$this->_attr['title'] .=
+        } else  {
+        $this->_attr['title'] .=
                     " [".$WikiTheme->tooltipAccessKeyPrefix()."-$key]";
-	    }
-	} else {
-	    $this->_attr['title'] =
+        }
+    } else {
+        $this->_attr['title'] =
                 "[".$WikiTheme->tooltipAccessKeyPrefix()."-$key]";
-	}
+    }
     }
 
     function emptyTag () {
@@ -126,7 +126,7 @@ class HTML extends HtmlElement {
     public static function raw ($html_text) {
         return new RawXml($html_text);
     }
-  
+
     function getTagProperties($tag) {
         $props = &$GLOBALS['HTML_TagProperties'];
         return isset($props[$tag]) ? $props[$tag] : 0;
@@ -544,7 +544,7 @@ function IfJavaScript($if_content = false, $else_content = false) {
     }
     return HTML($html);
 }
-  
+
 // Local Variables:
 // mode: php
 // tab-width: 8
diff --git a/lib/HtmlParser.php b/lib/HtmlParser.php
index 5b22f27cc..82f3aaa20 100644
--- a/lib/HtmlParser.php
+++ b/lib/HtmlParser.php
@@ -50,7 +50,7 @@ extends XmlParser
      *  possible more dialects: MediaWiki, kwiki, c2
      */
     function HtmlParser($dialect = "PhpWiki2", $encoding = '') {
-    	$classname = "HtmlParser_".$dialect;
+        $classname = "HtmlParser_".$dialect;
         if (class_exists($classname))
             $this->dialect = new $classname;
         else {
@@ -58,8 +58,8 @@ extends XmlParser
         }
         $this->_handlers =& $this->dialect->_handlers;
         $this->XmlParser($encoding);
-	xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, 0);
-	xml_parser_set_option($this->_parser, XML_OPTION_SKIP_WHITE, 1);
+    xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, 0);
+    xml_parser_set_option($this->_parser, XML_OPTION_SKIP_WHITE, 1);
     }
 
     // The three callbacks, called on walking through the HTML tree.
@@ -75,8 +75,8 @@ extends XmlParser
     */
 
     function output () {
-    	if (is_null($this->root))
-    	    $this->root = $GLOBALS['xml_parser_root'];
+        if (is_null($this->root))
+            $this->root = $GLOBALS['xml_parser_root'];
         $output = $this->wikify( $this->root );
         return $output;
     }
diff --git a/lib/HttpClient.php b/lib/HttpClient.php
index 220de54fa..b54fb954e 100644
--- a/lib/HttpClient.php
+++ b/lib/HttpClient.php
@@ -65,21 +65,21 @@ class HttpClient {
         $this->path = $path;
         $this->method = 'POST';
         $this->postdata = $this->buildQueryString($data);
-    	return $this->doRequest();
+        return $this->doRequest();
     }
     function postfile($path, $filename) {
         $this->path = $path;
         $this->method = 'POST';
-	$boundary = $this->boundary; //"httpclient_boundary";
-	$headers[] = "Content-Type: multipart/form-data; boundary=\"$boundary\"";
-	$basename = basename($filename);
-	$this->postdata =
-	    "\r\n--$boundary\r\n"
-	    ."Content-Disposition: form-data; filename=\"$basename\"\r\n"
-	    ."Content-Type: application/octet-stream\r\n\r\n";
-	$this->postdata .= join("",file($filename));
-	$this->postdata .= "\r\n\r\n--$boundary--\r\n";
-    	return $this->doRequest();
+    $boundary = $this->boundary; //"httpclient_boundary";
+    $headers[] = "Content-Type: multipart/form-data; boundary=\"$boundary\"";
+    $basename = basename($filename);
+    $this->postdata =
+        "\r\n--$boundary\r\n"
+        ."Content-Disposition: form-data; filename=\"$basename\"\r\n"
+        ."Content-Type: application/octet-stream\r\n\r\n";
+    $this->postdata .= join("",file($filename));
+    $this->postdata .= "\r\n\r\n--$boundary--\r\n";
+        return $this->doRequest();
     }
     function buildQueryString($data) {
         $querystring = '';
@@ -95,10 +95,10 @@ class HttpClient {
                 }
             }
             $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
-    	} else {
-    	    $querystring = $data;
-    	}
-    	return $querystring;
+        } else {
+            $querystring = $data;
+        }
+        return $querystring;
     }
 
     function doRequest() {
@@ -122,75 +122,75 @@ class HttpClient {
             return false;
         }
         socket_set_timeout($fp, $this->timeout);
-	if ( $this->method == 'POST' and preg_match("/\/", $this->postdata))
-	    $request = $this->buildRequest("text/xml"); //xmlrpc
-	else if ( $this->method == 'POST' and strstr("\r\nContent-Disposition: form-data; filename=",
-						     $this->postdata))
-	{
-	    //file upload
-	    $boundary = $this->boundary;
-	    $request = $this->buildRequest("multipart/form-data; boundary=\"$boundary\"");
-	} else
-	    $request = $this->buildRequest();
+    if ( $this->method == 'POST' and preg_match("/\/", $this->postdata))
+        $request = $this->buildRequest("text/xml"); //xmlrpc
+    else if ( $this->method == 'POST' and strstr("\r\nContent-Disposition: form-data; filename=",
+                             $this->postdata))
+    {
+        //file upload
+        $boundary = $this->boundary;
+        $request = $this->buildRequest("multipart/form-data; boundary=\"$boundary\"");
+    } else
+        $request = $this->buildRequest();
         $this->debug('Request', $request);
         fwrite($fp, $request);
-    	// Reset all the variables that should not persist between requests
-    	$this->headers = array();
-    	$this->content = '';
-    	$this->errormsg = '';
-    	// Set a couple of flags
-    	$inHeaders = true;
-    	$atStart = true;
-    	// Now start reading back the response
-    	while (!feof($fp)) {
-    	    $line = fgets($fp, 4096);
-    	    if ($atStart) {
-    	        // Deal with first line of returned data
-    	        $atStart = false;
-    	        if ($line === false) {
-    	            $this->errormsg = "Empty ". $this->method. " response";
-    	            return false;
-    	        }
-    	        if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
-    	            $this->errormsg = "Status code line invalid: ".htmlentities($line);
-    	            $this->debug($this->errormsg);
-    	            return false;
-    	        }
-    	        $http_version = $m[1]; // not used
-    	        $this->status = $m[2];
-    	        $status_string = $m[3]; // not used
-    	        $this->debug(trim($line));
-    	        continue;
-    	    }
-    	    if ($inHeaders) {
-    	        if (trim($line) == '') {
-    	            $inHeaders = false;
-    	            $this->debug('Received Headers', $this->headers);
-    	            if ($this->headers_only) {
-    	                break; // Skip the rest of the input
-    	            }
-    	            continue;
-    	        }
-    	        if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
-    	            // Skip to the next header
-    	            continue;
-    	        }
-    	        $key = strtolower(trim($m[1]));
-    	        $val = trim($m[2]);
-    	        // Deal with the possibility of multiple headers of same name
-    	        if (isset($this->headers[$key])) {
-    	            if (is_array($this->headers[$key])) {
-    	                $this->headers[$key][] = $val;
-    	            } else {
-    	                $this->headers[$key] = array($this->headers[$key], $val);
-    	            }
-    	        } else {
-    	            $this->headers[$key] = $val;
-    	        }
-    	        continue;
-    	    }
-    	    // We're not in the headers, so append the line to the contents
-    	    $this->content .= $line;
+        // Reset all the variables that should not persist between requests
+        $this->headers = array();
+        $this->content = '';
+        $this->errormsg = '';
+        // Set a couple of flags
+        $inHeaders = true;
+        $atStart = true;
+        // Now start reading back the response
+        while (!feof($fp)) {
+            $line = fgets($fp, 4096);
+            if ($atStart) {
+                // Deal with first line of returned data
+                $atStart = false;
+                if ($line === false) {
+                    $this->errormsg = "Empty ". $this->method. " response";
+                    return false;
+                }
+                if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
+                    $this->errormsg = "Status code line invalid: ".htmlentities($line);
+                    $this->debug($this->errormsg);
+                    return false;
+                }
+                $http_version = $m[1]; // not used
+                $this->status = $m[2];
+                $status_string = $m[3]; // not used
+                $this->debug(trim($line));
+                continue;
+            }
+            if ($inHeaders) {
+                if (trim($line) == '') {
+                    $inHeaders = false;
+                    $this->debug('Received Headers', $this->headers);
+                    if ($this->headers_only) {
+                        break; // Skip the rest of the input
+                    }
+                    continue;
+                }
+                if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
+                    // Skip to the next header
+                    continue;
+                }
+                $key = strtolower(trim($m[1]));
+                $val = trim($m[2]);
+                // Deal with the possibility of multiple headers of same name
+                if (isset($this->headers[$key])) {
+                    if (is_array($this->headers[$key])) {
+                        $this->headers[$key][] = $val;
+                    } else {
+                        $this->headers[$key] = array($this->headers[$key], $val);
+                    }
+                } else {
+                    $this->headers[$key] = $val;
+                }
+                continue;
+            }
+            // We're not in the headers, so append the line to the contents
+            $this->content .= $line;
         }
         fclose($fp);
         // If data is compressed, uncompress it
@@ -246,7 +246,7 @@ class HttpClient {
 
     function buildRequest($ContentType = 'application/x-www-form-urlencoded') {
         $headers = array();
-	// Using 1.1 leads to all manner of problems, such as "chunked" encoding
+    // Using 1.1 leads to all manner of problems, such as "chunked" encoding
         $headers[] = "{$this->method} {$this->path} HTTP/1.0";
         $headers[] = "Host: {$this->host}";
         $headers[] = "User-Agent: {$this->user_agent}";
@@ -258,25 +258,25 @@ class HttpClient {
         if (!empty($this->referer)) {
             $headers[] = "Referer: {$this->referer}";
         }
-    	// Cookies
-    	if (!empty($this->cookies)) {
-    	    $cookie = 'Cookie: ';
-    	    foreach ($this->cookies as $key => $value) {
-    	        $cookie .= "$key=$value; ";
-    	    }
-    	    $headers[] = $cookie;
-    	}
-    	// Basic authentication
-    	if (!empty($this->username) && !empty($this->password)) {
-    	    $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
-    	}
-    	// If this is a POST, set the content type and length
-    	if ($this->postdata) {
-	    $headers[] = 'Content-Type: ' . $ContentType;
-    	    $headers[] = 'Content-Length: '.strlen($this->postdata);
-    	}
-    	$request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
-    	return $request;
+        // Cookies
+        if (!empty($this->cookies)) {
+            $cookie = 'Cookie: ';
+            foreach ($this->cookies as $key => $value) {
+                $cookie .= "$key=$value; ";
+            }
+            $headers[] = $cookie;
+        }
+        // Basic authentication
+        if (!empty($this->username) && !empty($this->password)) {
+            $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
+        }
+        // If this is a POST, set the content type and length
+        if ($this->postdata) {
+        $headers[] = 'Content-Type: ' . $ContentType;
+            $headers[] = 'Content-Length: '.strlen($this->postdata);
+        }
+        $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
+        return $request;
     }
     function getStatus() {
         return $this->status;
diff --git a/lib/InlineParser.php b/lib/InlineParser.php
index 05e9e6347..6a6db4430 100644
--- a/lib/InlineParser.php
+++ b/lib/InlineParser.php
@@ -147,27 +147,27 @@ class RegexpSet
         // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
         //         (tried to allocate 634 bytes)
         if (_INLINE_OPTIMIZATION) { // disabled, wrong
-	    // So we try to minize memory usage, by looping explicitly,
-	    // and storing only those regexp which actually match.
-	    // There may be more than one, so we have to find the longest,
-	    // and match inside until the shortest is empty.
-	    $matched = array(); $matched_ind = array();
-	    for ($i=0; $isuggestions = $GLOBALS['request']->getArg('suggestions');
+    $this->suggestions = $GLOBALS['request']->getArg('suggestions');
     }
     function getMatchRegexp () {
-    	if (empty($this->suggestions))
-    	    return "(?# false )";
-	$words = array_keys($this->suggestions);
+        if (empty($this->suggestions))
+            return "(?# false )";
+    $words = array_keys($this->suggestions);
         return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
     }
 
     function markup ($match) {
-    	if (empty($this->suggestions) or empty($this->suggestions[$match]))
-    	    return $match;
+        if (empty($this->suggestions) or empty($this->suggestions[$match]))
+            return $match;
         return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
     }
 }
@@ -738,41 +738,41 @@ class Markup_old_emphasis  extends BalancedMarkup
 class Markup_nestled_emphasis extends BalancedMarkup
 {
     function getStartRegexp() {
-	static $start_regexp = false;
+    static $start_regexp = false;
 
-	if (!$start_regexp) {
-	    // The three possible delimiters
+    if (!$start_regexp) {
+        // The three possible delimiters
             // (none of which can be followed by itself.)
-	    $i = "_ (?! _)";
-	    $b = "\\* (?! \\*)";
-	    $tt = "= (?! =)";
+        $i = "_ (?! _)";
+        $b = "\\* (?! \\*)";
+        $tt = "= (?! =)";
+
+        $any = "(?: ${i}|${b}|${tt})"; // any of the three.
 
-	    $any = "(?: ${i}|${b}|${tt})"; // any of the three.
+        // Any of [_*=] is okay if preceded by space or one of [-"'/:]
+        $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
 
-	    // Any of [_*=] is okay if preceded by space or one of [-"'/:]
-	    $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
+        // _ or * is okay after = as long as not immediately followed by =
+        $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
+        // etc...
+        $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
+        $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
 
-	    // _ or * is okay after = as long as not immediately followed by =
-	    $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
-	    // etc...
-	    $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
-	    $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
 
+        // any delimiter okay after an opening brace ( [{<(] )
+        // as long as it's not immediately followed by the matching closing
+        // brace.
+        $start[] = "(?<= { ) ${any} (?! } )";
+        $start[] = "(?<= < ) ${any} (?! > )";
+        $start[] = "(?<= \\( ) ${any} (?! \\) )";
 
-	    // any delimiter okay after an opening brace ( [{<(] )
-	    // as long as it's not immediately followed by the matching closing
-	    // brace.
-	    $start[] = "(?<= { ) ${any} (?! } )";
-	    $start[] = "(?<= < ) ${any} (?! > )";
-	    $start[] = "(?<= \\( ) ${any} (?! \\) )";
-	
-	    $start = "(?:" . join('|', $start) . ")";
-	
-	    // Any of the above must be immediately followed by non-whitespace.
-	    $start_regexp = $start . "(?= \S)";
-	}
+        $start = "(?:" . join('|', $start) . ")";
 
-	return $start_regexp;
+        // Any of the above must be immediately followed by non-whitespace.
+        $start_regexp = $start . "(?= \S)";
+    }
+
+    return $start_regexp;
     }
 
     function getEndRegexp ($match) {
@@ -810,22 +810,22 @@ class Markup_html_divspan extends BalancedMarkup
         "<(?: div|span )(?: \s[^>]*)?>";
 
     function getEndRegexp ($match) {
-    	if (substr($match,1,4) == 'span')
-    	    $tag = 'span';
-    	else
-    	    $tag = 'div';
+        if (substr($match,1,4) == 'span')
+            $tag = 'span';
+        else
+            $tag = 'div';
         return "<\\/" . $tag . '>';
     }
 
     function markup ($match, $body) {
-    	if (substr($match,1,4) == 'span')
-    	    $tag = 'span';
-    	else
-    	    $tag = 'div';
-    	$rest = substr($match,1+strlen($tag),-1);
-    	if (!empty($rest)) {
+        if (substr($match,1,4) == 'span')
+            $tag = 'span';
+        else
+            $tag = 'div';
+        $rest = substr($match,1+strlen($tag),-1);
+        if (!empty($rest)) {
             $args = parse_attributes($rest);
-    	} else {
+        } else {
             $args = array();
         }
         return new HtmlElement($tag, $args, $body);
@@ -840,18 +840,18 @@ class Markup_html_abbr extends BalancedMarkup
     var $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
 
     function getEndRegexp ($match) {
-    	if (substr($match,1,4) == 'abbr')
-    	    $tag = 'abbr';
-    	else
-    	    $tag = 'acronym';
+        if (substr($match,1,4) == 'abbr')
+            $tag = 'abbr';
+        else
+            $tag = 'acronym';
         return "<\\/" . $tag . '>';
     }
 
     function markup ($match, $body) {
-    	if (substr($match,1,4) == 'abbr')
-    	    $tag = 'abbr';
-    	else
-    	    $tag = 'acronym';
+        if (substr($match,1,4) == 'abbr')
+            $tag = 'abbr';
+        else
+            $tag = 'acronym';
         $rest = substr($match,1+strlen($tag),-1);
         $attrs = parse_attributes($rest);
         // Remove attributes other than title and lang
@@ -875,7 +875,7 @@ class Markup_color extends BalancedMarkup {
     var $_end_regexp = "%%";
 
     function markup ($match, $body) {
-    	$color = strtolower(substr($match, 7, -1));
+        $color = strtolower(substr($match, 7, -1));
 
         $morecolors = array('beige' => '#f5f5dc',
                             'brown' => '#a52a2a',
@@ -942,7 +942,7 @@ class Markup_plugin extends SimpleMarkup
     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
 
     function markup ($match) {
-	return new Cached_PluginInvocation($match);
+    return new Cached_PluginInvocation($match);
     }
 }
 
@@ -954,7 +954,7 @@ class Markup_plugin_wikicreole extends SimpleMarkup
     function markup ($match) {
         $pi = str_replace("<<", ">", " ?>", $pi);
-	return new Cached_PluginInvocation($pi);
+    return new Cached_PluginInvocation($pi);
     }
 }
 
@@ -966,21 +966,21 @@ class Markup_xml_plugin extends BalancedMarkup
     //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
 
     function getStartRegexp () {
-	global $PLUGIN_MARKUP_MAP;
+    global $PLUGIN_MARKUP_MAP;
         static $_start_regexp;
         if ($_start_regexp) return $_start_regexp;
         if (empty($PLUGIN_MARKUP_MAP)) return '';
         //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>"
-	$_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]*|\\/ )>";
+    $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]*|\\/ )>";
         return $_start_regexp;
     }
     function getEndRegexp ($match) {
         return "<\\/" . $match . '>';
     }
     function markup ($match, $body) {
-	global $PLUGIN_MARKUP_MAP;
+    global $PLUGIN_MARKUP_MAP;
         $name = substr($match,2,-2);
-	$vars = '';
+    $vars = '';
         if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
             $name = $_m[1];
             $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
@@ -990,7 +990,7 @@ class Markup_xml_plugin extends BalancedMarkup
             return "";
         }
         $plugin = $PLUGIN_MARKUP_MAP[$name];
-	return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
+    return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
     }
 }
 
@@ -1093,8 +1093,8 @@ class Markup_template_plugin  extends SimpleMarkup
 
         // It's a video
         if (is_video($imagename)) {
-    	    $s = '<'.'?plugin Video file="' . $imagename . '" ?'.'>';
-	    return new Cached_PluginInvocation($s);
+            $s = '<'.'?plugin Video file="' . $imagename . '" ?'.'>';
+        return new Cached_PluginInvocation($s);
         }
 
         $page = str_replace("\n", "", $page);
@@ -1119,10 +1119,10 @@ class Markup_template_plugin  extends SimpleMarkup
         }
 
         if ($vars)
-    	    $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
-    	else
-    	    $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
-	return new Cached_PluginInvocation($s);
+            $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
+        else
+            $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
+    return new Cached_PluginInvocation($s);
     }
 }
 
@@ -1178,8 +1178,8 @@ class InlineTransformer
 
     function InlineTransformer ($markup_types = false) {
         global $request;
-	// We need to extend the inline parsers by certain actions, like SearchHighlight,
-	// SpellCheck and maybe CreateToc.
+    // We need to extend the inline parsers by certain actions, like SearchHighlight,
+    // SpellCheck and maybe CreateToc.
         if (!$markup_types) {
             $non_default = false;
             $markup_types = array
@@ -1195,22 +1195,22 @@ class InlineTransformer
                  'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
                  'isonumchars', 'isohexchars', /*'html_entities'*/
                  );
-	    if (DISABLE_MARKUP_WIKIWORD)
+        if (DISABLE_MARKUP_WIKIWORD)
                 $markup_types = array_remove($markup_types, 'wikiword');
 
-	    $action = $request->getArg('action');
-	    if ($action == 'SpellCheck' and $request->getArg('suggestions'))
-	    {   // insert it after url
-		array_splice($markup_types, 2, 1, array('url','spellcheck'));
-	    }
-	    if (isset($request->_searchhighlight))
-	    {   // insert it after url
-		array_splice($markup_types, 2, 1, array('url','searchhighlight'));
+        $action = $request->getArg('action');
+        if ($action == 'SpellCheck' and $request->getArg('suggestions'))
+        {   // insert it after url
+        array_splice($markup_types, 2, 1, array('url','spellcheck'));
+        }
+        if (isset($request->_searchhighlight))
+        {   // insert it after url
+        array_splice($markup_types, 2, 1, array('url','searchhighlight'));
                 //$request->setArg('searchhighlight', false);
-	    }
+        }
         } else {
             $non_default = true;
-	}
+    }
         foreach ($markup_types as $mtype) {
             $class = "Markup_$mtype";
             $this->_addMarkup(new $class);
diff --git a/lib/MailNotify.php b/lib/MailNotify.php
index f867e2438..484ae4bc6 100644
--- a/lib/MailNotify.php
+++ b/lib/MailNotify.php
@@ -28,7 +28,7 @@
  * We add WikiDB handlers and register ourself there:
  *   onChangePage, onDeletePage, onRenamePage
  * Administrative actions:
- *   [Watch] WatchPage - add a page, or delete watch handlers into the users 
+ *   [Watch] WatchPage - add a page, or delete watch handlers into the users
  *                       pref[notifyPages] slot.
  *   My WatchList      - view or edit list/regex of pref[notifyPages].
  *   EMailConfirm methods: send and verify
@@ -51,9 +51,9 @@ if (!defined("MAILER_LOG"))
 class MailNotify {
 
     function MailNotify($pagename) {
-	$this->pagename = $pagename; /* which page */
+    $this->pagename = $pagename; /* which page */
         $this->emails  = array();    /* to which addresses */
-        $this->userids = array();    /* corresponding array of displayed names, 
+        $this->userids = array();    /* corresponding array of displayed names,
                                         don't display the email addresses */
         /* From: from whom the mail appears to be */
         $this->from = $this->fromId();
@@ -142,8 +142,8 @@ class MailNotify {
                         }
                     }
 
-                    if (!$user) { // handle the case for ModeratePage: 
-                        	  // no prefs, just userid's.
+                    if (!$user) { // handle the case for ModeratePage:
+                              // no prefs, just userid's.
                         $emails[] = $this->userEmail($userid, false);
                         $userids[] = $userid;
                     } else {
@@ -175,7 +175,7 @@ class MailNotify {
         $this->userids = array_unique($userids);
         return array($this->emails, $this->userids);
     }
-    
+
     function sendMail($subject,
                       $content,
                       $notice = false,
@@ -199,28 +199,28 @@ class MailNotify {
                    "Content-Transfer-Encoding: 8bit";
 
         $ok = mail(($to = array_shift($emails)),
-                   $encoded_subject, 
-		   $subject."\n".$content,
-		   $headers
-		   );
-	if (MAILER_LOG and is_writable(MAILER_LOG)) {
-	    $f = fopen(MAILER_LOG, "a");
-	    fwrite($f, "\n\nX-MailSentOK: " . $ok ? 'OK' : 'FAILED');
-	    if (!$ok) {
-		global $ErrorManager;
-		// get last error message
-		$last_err = 
+                   $encoded_subject,
+           $subject."\n".$content,
+           $headers
+           );
+    if (MAILER_LOG and is_writable(MAILER_LOG)) {
+        $f = fopen(MAILER_LOG, "a");
+        fwrite($f, "\n\nX-MailSentOK: " . $ok ? 'OK' : 'FAILED');
+        if (!$ok) {
+        global $ErrorManager;
+        // get last error message
+        $last_err =
                     $ErrorManager->_postponed_errors[count($ErrorHandler->_postponed_errors)-1];
-		fwrite($f, "\nX-MailFailure: " . $last_err);
-	    }
-	    fwrite($f, "\nDate: " . CTime());
-	    fwrite($f, "\nSubject: $encoded_subject");
-	    fwrite($f, "\nFrom: $from");
-	    fwrite($f, "\nTo: $to");
-	    fwrite($f, "\nBcc: ".join(',', $emails));
-	    fwrite($f, "\n\n". $content);
-	    fclose($f);
-	}
+        fwrite($f, "\nX-MailFailure: " . $last_err);
+        }
+        fwrite($f, "\nDate: " . CTime());
+        fwrite($f, "\nSubject: $encoded_subject");
+        fwrite($f, "\nFrom: $from");
+        fwrite($f, "\nTo: $to");
+        fwrite($f, "\nBcc: ".join(',', $emails));
+        fwrite($f, "\n\n". $content);
+        fclose($f);
+    }
         if ($ok) {
             if (!$silent)
                 trigger_error(sprintf($notice, $this->pagename)
@@ -231,13 +231,13 @@ class MailNotify {
         } else {
             trigger_error(sprintf($notice, $this->pagename)
                           . " "
-                          . sprintf(_("Error: Couldn't send %s to %s"), 
-                                   $subject."\n".$content, join(',',$this->userids)), 
+                          . sprintf(_("Error: Couldn't send %s to %s"),
+                                   $subject."\n".$content, join(',',$this->userids)),
                           E_USER_WARNING);
             return false;
         }
     }
-    
+
     /**
      * Send udiff for a changed page to multiple users.
      * See rename and remove methods also
@@ -248,7 +248,7 @@ class MailNotify {
 
         if (@is_array($request->_deferredPageChangeNotification)) {
             // collapse multiple changes (loaddir) into one email
-            $request->_deferredPageChangeNotification[] = 
+            $request->_deferredPageChangeNotification[] =
                 array($this->pagename, $this->emails, $this->userids);
             return;
         }
@@ -264,21 +264,21 @@ class MailNotify {
             if (empty($prevdata['%content']))
                 $prevdata = $backend->get_versiondata($this->pagename, $previous, true);
             $other_content = explode("\n", $prevdata['%content']);
-            
+
             include_once("lib/difflib.php");
             $diff2 = new Diff($other_content, $this_content);
             //$context_lines = max(4, count($other_content) + 1,
             //                     count($this_content) + 1);
             $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
-            $content  = $this->pagename . " " . $previous . " " . 
+            $content  = $this->pagename . " " . $previous . " " .
                 Iso8601DateTime($prevdata['mtime']) . "\n";
-            $content .= $this->pagename . " " . $version . " " .  
+            $content .= $this->pagename . " " . $version . " " .
                 Iso8601DateTime($meta['mtime']) . "\n";
             $content .= $fmt->format($diff2);
-            
+
         } else {
             $difflink = WikiURL($this->pagename,array(),true);
-            $content = $this->pagename . " " . $version . " " .  
+            $content = $this->pagename . " " . $version . " " .
                 Iso8601DateTime($meta['mtime']) . "\n";
             $content .= _("New page");
             $content .= "\n\n";
@@ -286,25 +286,25 @@ class MailNotify {
         }
         $editedby = sprintf(_("Edited by: %s"), $this->from);
         $summary = sprintf(_("Summary: %s"), $meta['summary']);
-        $this->sendMail($subject, 
+        $this->sendMail($subject,
                         $editedby."\n".$summary."\n".$difflink."\n\n".$content);
     }
 
-    /** 
+    /**
      * Support mass rename / remove (not yet tested)
      */
     function sendPageRenameNotification ($to, &$meta) {
         global $request;
 
         if (@is_array($request->_deferredPageRenameNotification)) {
-            $request->_deferredPageRenameNotification[] = 
+            $request->_deferredPageRenameNotification[] =
                 array($this->pagename, $to, $meta, $this->emails, $this->userids);
         } else {
             $pagename = $this->pagename;
             $editedby = sprintf(_("Edited by: %s"), $this->from);
             $subject = sprintf(_("Page rename %s to %s"), $pagename, $to);
             $link = WikiURL($to, true);
-            $this->sendMail($subject, 
+            $this->sendMail($subject,
                             $editedby."\n".$link."\n\n"."Renamed $pagename to $to");
         }
     }
@@ -314,20 +314,20 @@ class MailNotify {
      */
     function onChangePage (&$wikidb, &$wikitext, $version, &$meta) {
         $result = true;
-	if (!isa($GLOBALS['request'],'MockRequest')) {
-	    $notify = $wikidb->get('notify');
+    if (!isa($GLOBALS['request'],'MockRequest')) {
+        $notify = $wikidb->get('notify');
             /* Generate notification emails? */
-	    if (!empty($notify) and is_array($notify)) {
+        if (!empty($notify) and is_array($notify)) {
                 if (empty($this->pagename))
                     $this->pagename = $meta['pagename'];
-		// TODO: Should be used for ModeratePage and RSS2 Cloud xml-rpc also.
+        // TODO: Should be used for ModeratePage and RSS2 Cloud xml-rpc also.
                 $this->getPageChangeEmails($notify);
                 if (!empty($this->emails)) {
                     $result = $this->sendPageChangeNotification($wikitext, $version, $meta);
                 }
-	    }
-	}
-	return $result;
+        }
+    }
+    return $result;
     }
 
     function onDeletePage (&$wikidb, $pagename) {
@@ -349,19 +349,19 @@ class MailNotify {
 
     function onRenamePage (&$wikidb, $oldpage, $new_pagename) {
         $result = true;
-	if (!isa($GLOBALS['request'], 'MockRequest')) {
-	    $notify = $wikidb->get('notify');
-	    if (!empty($notify) and is_array($notify)) {
-		$this->getPageChangeEmails($notify);
-		if (!empty($this->emails)) {
-		    $newpage = $wikidb->getPage($new_pagename);
-		    $current = $newpage->getCurrentRevision();
-		    $meta = $current->_data;
+    if (!isa($GLOBALS['request'], 'MockRequest')) {
+        $notify = $wikidb->get('notify');
+        if (!empty($notify) and is_array($notify)) {
+        $this->getPageChangeEmails($notify);
+        if (!empty($this->emails)) {
+            $newpage = $wikidb->getPage($new_pagename);
+            $current = $newpage->getCurrentRevision();
+            $meta = $current->_data;
                     $this->pagename = $oldpage;
-		    $result = $this->sendPageRenameNotification($new_pagename, $meta);
-		}
-	    }
-	}
+            $result = $this->sendPageRenameNotification($new_pagename, $meta);
+        }
+        }
+    }
     }
 
     /**
@@ -387,10 +387,10 @@ e-mail features on %s, open this link in your browser:
 %s
 
 If this is *not* you, don't follow the link. This confirmation code
-will expire at %s.", 
-                       $ip, $userid, WIKI_NAME, WIKI_NAME, 
+will expire at %s.",
+                       $ip, $userid, WIKI_NAME, WIKI_NAME,
                        WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
-                                                'id' => $id), 
+                                                'id' => $id),
                                true),
                        CTime($expire_date));
         $this->sendMail($subject, $content, "", true);
@@ -463,5 +463,5 @@ will expire at %s.",
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End:   
+// End:
 ?>
diff --git a/lib/PageList.php b/lib/PageList.php
index d8726b4da..d55e903fa 100644
--- a/lib/PageList.php
+++ b/lib/PageList.php
@@ -725,14 +725,14 @@ class PageList {
     }
 
     /**
-     * @param	caption	string or HTML
+     * @param    caption    string or HTML
      */
     function setCaption ($caption) {
         $this->_caption = $caption;
     }
 
     /**
-     * @param	caption	string or HTML
+     * @param    caption    string or HTML
      */
     function addCaption ($caption) {
         $this->_caption = HTML($this->_caption," ",$caption);
@@ -836,49 +836,49 @@ class PageList {
     /* ignore from, but honor limit */
     function addPages ($page_iter) {
         // TODO: if limit check max(strlen(pagename))
-	$limit = $page_iter->limit();
+    $limit = $page_iter->limit();
         $i = 0;
-	if ($limit) {
-	    list($from, $limit) = $this->limit($limit);
-	    $this->_options['slice'] = 0;
-	    $limit += $from;
+    if ($limit) {
+        list($from, $limit) = $this->limit($limit);
+        $this->_options['slice'] = 0;
+        $limit += $from;
             while ($page = $page_iter->next()) {
                 $i++;
                 if ($from and $i < $from)
                     continue;
-	        if (!$limit or ($limit and $i < $limit))
-		    $this->addPage($page);
+            if (!$limit or ($limit and $i < $limit))
+            $this->addPage($page);
             }
-	} else {
-	    $this->_options['slice'] = 0;
+    } else {
+        $this->_options['slice'] = 0;
             while ($page = $page_iter->next()) {
-		$this->addPage($page);
+        $this->addPage($page);
             }
-	}
-	if (! is_array($page_iter->_options) || ! array_key_exists('limit_by_db', $page_iter->_options) || ! $page_iter->_options['limit_by_db'])
-		$this->_options['slice'] = 1;
-	if ($i and empty($this->_options['count']))
-	    $this->_options['count'] = $i;
+    }
+    if (! is_array($page_iter->_options) || ! array_key_exists('limit_by_db', $page_iter->_options) || ! $page_iter->_options['limit_by_db'])
+        $this->_options['slice'] = 1;
+    if ($i and empty($this->_options['count']))
+        $this->_options['count'] = $i;
     }
 
     function addPageList (&$list) {
         if (empty($list)) return;  // Protect reset from a null arg
         if (isset($this->_options['limit'])) { // extract from,count from limit
-	    list($from, $limit) = WikiDB_backend::limit($this->_options['limit']);
-	    $limit += $from;
+        list($from, $limit) = WikiDB_backend::limit($this->_options['limit']);
+        $limit += $from;
         } else {
-	    $limit = 0;
+        $limit = 0;
         }
-	$this->_options['slice'] = 0;
+    $this->_options['slice'] = 0;
         $i = 0;
         foreach ($list as $page) {
             $i++;
             if ($from and $i < $from)
                 continue;
-	    if (!$limit or ($limit and $i < $limit)) {
+        if (!$limit or ($limit and $i < $limit)) {
                 if (is_object($page)) $page = $page->_pagename;
                 $this->addPage((string)$page);
-	    }
+        }
         }
     }
 
diff --git a/lib/PagePerm.php b/lib/PagePerm.php
index e6a39de05..8e24a482d 100644
--- a/lib/PagePerm.php
+++ b/lib/PagePerm.php
@@ -62,15 +62,15 @@
  */
 
 /* Symbolic special ACL groups. Untranslated to be stored in page metadata*/
-define('ACL_EVERY',	   '_EVERY');
-define('ACL_ANONYMOUS',	   '_ANONYMOUS');
-define('ACL_BOGOUSER',	   '_BOGOUSER');
+define('ACL_EVERY',       '_EVERY');
+define('ACL_ANONYMOUS',       '_ANONYMOUS');
+define('ACL_BOGOUSER',       '_BOGOUSER');
 define('ACL_HASHOMEPAGE',  '_HASHOMEPAGE');
-define('ACL_SIGNED',	   '_SIGNED');
+define('ACL_SIGNED',       '_SIGNED');
 define('ACL_AUTHENTICATED','_AUTHENTICATED');
-define('ACL_ADMIN',	   '_ADMIN');
-define('ACL_OWNER',	   '_OWNER');
-define('ACL_CREATOR',	   '_CREATOR');
+define('ACL_ADMIN',       '_ADMIN');
+define('ACL_OWNER',       '_OWNER');
+define('ACL_CREATOR',       '_CREATOR');
 
 // Return an page permissions array for this page.
 // To provide ui helpers to view and change page permissions:
@@ -90,7 +90,7 @@ function pagePermissions($pagename) {
         return array('page', $perm);
     // or no permissions defined; returned inherited permissions, to be displayed in gray
     } elseif ($pagename == '.') { // stop recursion in pathological case.
-    	// "." defined, without any acl
+        // "." defined, without any acl
         return array('default', new PagePermission());
     } else {
         return array('inherited', pagePermissions(getParentPage($pagename)));
@@ -106,9 +106,9 @@ function pagePermissionsSimpleFormat($perm_tree, $owner, $group=false) {
         $perm = $perm_tree[1];
     elseif (is_array($perm_tree[1])) {
         $perm_tree = pagePermissionsSimpleFormat($perm_tree[1],$owner,$group);
-	if (isa($perm_tree[1],'pagepermission'))
-	    $perm = $perm_tree[1];
-	elseif (isa($perm_tree,'htmlelement'))
+    if (isa($perm_tree[1],'pagepermission'))
+        $perm = $perm_tree[1];
+    elseif (isa($perm_tree,'htmlelement'))
             return $perm_tree;
     }
     */
@@ -174,10 +174,10 @@ function action2access ($action) {
         return 'view';
 
     case 'dumpserial':
-	if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost())
-	    return 'dump';
-	else
-	    return 'view';
+    if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost())
+        return 'dump';
+    else
+        return 'view';
 
     // performance and security relevant
     case 'xmlrpc':
@@ -203,7 +203,7 @@ function action2access ($action) {
         break;
     case 'upload':
     case 'loadfile':
-	// probably create/edit but we cannot check all page permissions, can we?
+    // probably create/edit but we cannot check all page permissions, can we?
     case 'remove':
     case 'purge':
     case 'lock':
@@ -211,7 +211,7 @@ function action2access ($action) {
     case 'upgrade':
     case 'chown':
     case 'setacl':
-	return 'change';
+    return 'change';
     default:
         //Todo: Plugins should be able to override its access type
         if (isWikiWord($action))
@@ -237,10 +237,10 @@ function _requiredAuthorityForPagename($access, $pagename) {
 
     // Exceptions:
     if (FUSIONFORGE) {
-    	if ($pagename != '.' && isset($request->_user->_is_external) && $request->_user->_is_external && ! $page->get('external')) {
-    		$permcache[$pagename][$access] = 0;
-    		return 0;
-    	}
+        if ($pagename != '.' && isset($request->_user->_is_external) && $request->_user->_is_external && ! $page->get('external')) {
+            $permcache[$pagename][$access] = 0;
+            return 0;
+        }
     }
     if ((READONLY or $request->_dbi->readonly)
         and in_array($access, array('edit','create','change')))
@@ -260,7 +260,7 @@ function _requiredAuthorityForPagename($access, $pagename) {
         if ($pagename == '.') {
             $perm = new PagePermission();
             if ($perm->isAuthorized('change', $request->_user)) {
-            	// warn the user to set ACL of ".", if he has permissions to do so.
+                // warn the user to set ACL of ".", if he has permissions to do so.
                 trigger_error(". (dotpage == rootpage for inheriting pageperm ACLs) exists without any ACL!\n".
                               "Please do ?action=setacl&pagename=.", E_USER_WARNING);
             }
@@ -281,7 +281,7 @@ function _requiredAuthorityForPagename($access, $pagename) {
         $permcache[$pagename][$access] = $authorized;
         return $authorized;
     } elseif ($pagename == '.') {
-    	return false;
+        return false;
     } else {
         return _requiredAuthorityForPagename($access, getParentPage($pagename));
     }
@@ -372,7 +372,7 @@ class PagePermission {
      */
     function isAuthorized($access, $user) {
         $allow = -1;
-    	if (!empty($this->perm{$access})) {
+        if (!empty($this->perm{$access})) {
             foreach ($this->perm[$access] as $group => $bool) {
                 if ($this->isMember($user, $group)) {
                     return $bool;
@@ -456,29 +456,29 @@ class PagePermission {
             $perm['dump'] = array(ACL_ADMIN => true,
                                   ACL_OWNER => true);
         elseif (INSECURE_ACTIONS_LOCALHOST_ONLY) {
-	    if (is_localhost())
-		$perm['dump'] = array(ACL_EVERY => true);
-	    else
-		$perm['dump'] = array(ACL_ADMIN => true);
-	}
-	else
-	    $perm['dump'] = array(ACL_EVERY => true);
+        if (is_localhost())
+        $perm['dump'] = array(ACL_EVERY => true);
+        else
+        $perm['dump'] = array(ACL_ADMIN => true);
+    }
+    else
+        $perm['dump'] = array(ACL_EVERY => true);
         if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
             $perm['edit'] = array(ACL_SIGNED => true);
         // view:
         if (!ALLOW_ANON_USER) {
             if (!ALLOW_USER_PASSWORDS)
-            	$perm['view'] = array(ACL_SIGNED => true);
+                $perm['view'] = array(ACL_SIGNED => true);
             else
-            	$perm['view'] = array(ACL_AUTHENTICATED => true);
+                $perm['view'] = array(ACL_AUTHENTICATED => true);
             $perm['view'][ACL_BOGOUSER] = ALLOW_BOGO_LOGIN ? true : false;
         }
         // edit:
         if (!ALLOW_ANON_EDIT) {
             if (!ALLOW_USER_PASSWORDS)
-            	$perm['edit'] = array(ACL_SIGNED => true);
+                $perm['edit'] = array(ACL_SIGNED => true);
             else
-            	$perm['edit'] = array(ACL_AUTHENTICATED => true);
+                $perm['edit'] = array(ACL_AUTHENTICATED => true);
             $perm['edit'][ACL_BOGOUSER] = ALLOW_BOGO_LOGIN ? true : false;
             $perm['create'] = $perm['edit'];
         }
@@ -500,9 +500,9 @@ class PagePermission {
      * do a recursive comparison
      */
     function equal($otherperm) {
-    	// The equal function seems to be unable to detect removed perm.
-    	// Use case is when a rule is removed.
-    	return (print_r($this->perm, true) === print_r($otherperm, true));
+        // The equal function seems to be unable to detect removed perm.
+        // Use case is when a rule is removed.
+        return (print_r($this->perm, true) === print_r($otherperm, true));
     }
 
     /**
diff --git a/lib/PageType.php b/lib/PageType.php
index 73899f848..1132a59f9 100644
--- a/lib/PageType.php
+++ b/lib/PageType.php
@@ -34,18 +34,18 @@ class TransformedText extends CacheableMarkup {
      *        pagetype than that specified in its version meta-data.
      */
     function TransformedText($page, $text, $meta, $type_override=false) {
-    	$pagetype = false;
+        $pagetype = false;
         if ($type_override)
             $pagetype = $type_override;
         elseif (isset($meta['pagetype']))
             $pagetype = $meta['pagetype'];
-	$this->_type = PageType::GetPageType($pagetype);
-	$this->CacheableMarkup($this->_type->transform($page, $text, $meta),
+    $this->_type = PageType::GetPageType($pagetype);
+    $this->CacheableMarkup($this->_type->transform($page, $text, $meta),
                                $page->getName());
     }
 
     function getType() {
-	return $this->_type;
+    return $this->_type;
     }
 }
 
@@ -90,9 +90,9 @@ class PageType {
      * @return string  Page type name.
      */
     function getName() {
-	if (!preg_match('/^PageType_(.+)$/i', get_class($this), $m))
-	    trigger_error("Bad class name for formatter(?)", E_USER_ERROR);
-	return $m[1];
+    if (!preg_match('/^PageType_(.+)$/i', get_class($this), $m))
+        trigger_error("Bad class name for formatter(?)", E_USER_ERROR);
+    return $m[1];
     }
 
     /**
@@ -155,7 +155,7 @@ class PageType_interwikimap extends PageType
     }
 
     function GetMap ($pagetext = false) {
-    	/*PHP5 Fatal error: Using $this when not in object context */
+        /*PHP5 Fatal error: Using $this when not in object context */
         if (empty($this->_map)) {
             $map = new PageType_interwikimap($pagetext);
             return $map;
@@ -169,7 +169,7 @@ class PageType_interwikimap extends PageType
     }
 
     function link ($link, $linktext = false) {
-	global $WikiTheme;
+    global $WikiTheme;
         list ($moniker, $page) = explode (":", $link, 2);
 
         if (!isset($this->_map[$moniker])) {
@@ -178,26 +178,26 @@ class PageType_interwikimap extends PageType
         }
 
         $url = $this->_map[$moniker];
-	// localize Upload:links for WIKIDUMP
-	if (!empty($WikiTheme->DUMP_MODE) and $moniker == 'Upload') {
-	    global $request;
-	    include_once("lib/config.php");
-	    $url = getUploadFilePath();
-	    // calculate to a relative local path to /uploads for pdf images.
-	    $doc_root = $request->get("DOCUMENT_ROOT");
-    	    $ldir = NormalizeLocalFileName($url);
+    // localize Upload:links for WIKIDUMP
+    if (!empty($WikiTheme->DUMP_MODE) and $moniker == 'Upload') {
+        global $request;
+        include_once("lib/config.php");
+        $url = getUploadFilePath();
+        // calculate to a relative local path to /uploads for pdf images.
+        $doc_root = $request->get("DOCUMENT_ROOT");
+            $ldir = NormalizeLocalFileName($url);
             $wikiroot = NormalizeLocalFileName('');
             if (isWindows()) {
-            	$ldir = strtolower($ldir);
-            	$doc_root = strtolower($doc_root);
-            	$wikiroot = strtolower($wikiroot);
+                $ldir = strtolower($ldir);
+                $doc_root = strtolower($doc_root);
+                $wikiroot = strtolower($wikiroot);
             }
-    	    if (string_starts_with($ldir, $doc_root)) {
-        	$link_prefix = substr($url, strlen($doc_root));
-    	    } elseif (string_starts_with($ldir, $wikiroot)) {
-        	$link_prefix = NormalizeWebFileName(substr($url, strlen($wikiroot)));
-	    }
-	}
+            if (string_starts_with($ldir, $doc_root)) {
+            $link_prefix = substr($url, strlen($doc_root));
+            } elseif (string_starts_with($ldir, $wikiroot)) {
+            $link_prefix = NormalizeWebFileName(substr($url, strlen($wikiroot)));
+        }
+    }
 
         // Urlencode page only if it's a query arg.
         // FIXME: this is a somewhat broken heuristic.
@@ -214,7 +214,7 @@ class PageType_interwikimap extends PageType
 
         $link = HTML::a(array('href' => $url));
 
-	if (!$linktext) {
+    if (!$linktext) {
             $link->pushContent(PossiblyGlueIconToText('interwiki', "$moniker:"),
                                HTML::span(array('class' => 'wikipage'), $page));
             $link->setAttr('class', 'interwiki');
@@ -331,18 +331,18 @@ class PageFormatter {
      */
     function PageFormatter(&$page, $meta) {
         $this->_page = $page;
-	$this->_meta = $meta;
-	if (!empty($meta['markup']))
-	    $this->_markup = $meta['markup'];
-	else
-	    $this->_markup = 2; // dump used old-markup as empty.
+    $this->_meta = $meta;
+    if (!empty($meta['markup']))
+        $this->_markup = $meta['markup'];
+    else
+        $this->_markup = 2; // dump used old-markup as empty.
         // FIXME: To be able to restore old plain-backups we should keep markup 1 as default.
         // New policy: default = new markup (old crashes quite often)
     }
 
     function _transform(&$text) {
-	include_once('lib/BlockParser.php');
-	return TransformText($text, $this->_markup);
+    include_once('lib/BlockParser.php');
+    return TransformText($text, $this->_markup);
     }
 
     /** Transform the page text.
@@ -358,26 +358,26 @@ class PageFormatter {
 class PageFormatter_wikitext extends PageFormatter
 {
     function format(&$text) {
-	return HTML::div(array('class' => 'wikitext'),
-			 $this->_transform($text));
+    return HTML::div(array('class' => 'wikitext'),
+             $this->_transform($text));
     }
 }
 
 class PageFormatter_interwikimap extends PageFormatter
 {
     function format($text) {
-	return HTML::div(array('class' => 'wikitext'),
-			 $this->_transform($this->_getHeader($text)),
-			 $this->_formatMap($text),
-			 $this->_transform($this->_getFooter($text)));
+    return HTML::div(array('class' => 'wikitext'),
+             $this->_transform($this->_getHeader($text)),
+             $this->_formatMap($text),
+             $this->_transform($this->_getFooter($text)));
     }
 
     function _getHeader($text) {
-	return preg_replace('/.*/s', '', $text);
+    return preg_replace('/.*/s', '', $text);
     }
 
     function _getFooter($text) {
-	return preg_replace('@.*?(|\Z)@s', '', $text, 1);
+    return preg_replace('@.*?(|\Z)@s', '', $text, 1);
     }
 
     function _getMap($pagetext) {
@@ -386,23 +386,23 @@ class PageFormatter_interwikimap extends PageFormatter
     }
 
     function _formatMap($pagetext) {
-	$map = $this->_getMap($pagetext);
-	if (!$map)
-	    return HTML::p(""); // Shouldn't happen.
+    $map = $this->_getMap($pagetext);
+    if (!$map)
+        return HTML::p(""); // Shouldn't happen.
 
         $mon_attr = array('class' => 'interwiki-moniker');
         $url_attr = array('class' => 'interwiki-url');
 
         $thead = HTML::thead(HTML::tr(HTML::th($mon_attr, _("Moniker")),
-				      HTML::th($url_attr, _("InterWiki Address"))));
-	foreach ($map as $moniker => $interurl) {
-	    $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)),
-			       HTML::td($url_attr, HTML::tt($interurl)));
+                      HTML::th($url_attr, _("InterWiki Address"))));
+    foreach ($map as $moniker => $interurl) {
+        $rows[] = HTML::tr(HTML::td($mon_attr, new Cached_WikiLinkIfKnown($moniker)),
+                   HTML::td($url_attr, HTML::tt($interurl)));
         }
 
-	return HTML::table(array('class' => 'interwiki-map'),
-			   $thead,
-			   HTML::tbody(false, $rows));
+    return HTML::table(array('class' => 'interwiki-map'),
+               $thead,
+               HTML::tbody(false, $rows));
     }
 }
 
@@ -425,8 +425,8 @@ class PageFormatter_attach extends PageFormatter
 
     // Display templated contents for wikiblog, comment and wikiforum
     function format($text) {
-    	if (empty($this->type))
-    	    trigger_error('PageFormatter_attach->format: $type missing');
+        if (empty($this->type))
+            trigger_error('PageFormatter_attach->format: $type missing');
         include_once('lib/Template.php');
         global $request;
         $tokens['CONTENT'] = $this->_transform($text);
@@ -466,10 +466,10 @@ class PageFormatter_wikiforum extends PageFormatter_attach {
 class PageFormatter_html extends PageFormatter
 {
     function _transform($text) {
-	return $text;
+    return $text;
     }
     function format($text) {
-    	return $text;
+        return $text;
     }
 }
 
@@ -480,8 +480,8 @@ class PageFormatter_pdf extends PageFormatter
 {
 
     function _transform($text) {
-	include_once('lib/BlockParser.php');
-	return TransformText($text, $this->_markup);
+    include_once('lib/BlockParser.php');
+    return TransformText($text, $this->_markup);
     }
 
     // one page or set of pages?
@@ -530,18 +530,18 @@ class PageFormatter_pdf extends PageFormatter
 class PageFormatter_MediaWiki extends PageFormatter
 {
     function _transform(&$text) {
-	include_once('lib/BlockParser.php');
-	// Expand leading tabs.
-	$text = expand_tabs($text);
+    include_once('lib/BlockParser.php');
+    // Expand leading tabs.
+    $text = expand_tabs($text);
 
         $input = new BlockParser_Input($text);
         $output = $this->ParsedBlock($input);
-	return new XmlContent($output->getContent());
+    return new XmlContent($output->getContent());
     }
 
     function format(&$text) {
-	return HTML::div(array('class' => 'wikitext'),
-			 $this->_transform($text));
+    return HTML::div(array('class' => 'wikitext'),
+             $this->_transform($text));
     }
 }
 
diff --git a/lib/RSSWriter091.php b/lib/RSSWriter091.php
index 4d3dae4e6..ca1358072 100644
--- a/lib/RSSWriter091.php
+++ b/lib/RSSWriter091.php
@@ -38,13 +38,13 @@ class RSSWriter091 extends RSSWriter
     {
         if (isset($this->_finished))
             return;
-      
+
         $channel = &$this->_channel;
         $items = &$this->_items;
-    
+
         if ($items)
             {
-		foreach ($items as $i)
+        foreach ($items as $i)
                     $channel->pushContent($i);
             }
         $this->pushContent($channel);
@@ -56,7 +56,7 @@ class RSSWriter091 extends RSSWriter
      * Create a new RDF typedNode.
      */
     function __node($type, $properties, $uri = false) {
-	return new XmlElement($type, '',
+    return new XmlElement($type, '',
                               $this->__elementize($properties));
     }
 
@@ -66,8 +66,8 @@ class RSSWriter091 extends RSSWriter
     function __spew() {
         header("Content-Type: application/xml; charset=" . RSS_ENCODING);
         printf("\n", RSS_ENCODING);
-		print("\n\n");
+        print("\n\n");
         $this->printXML();
     }
 
@@ -114,24 +114,24 @@ extends _RecentChanges_RSSFormatter
                      'language' => 'en-US');
 
         /* FIXME: language should come from $LANG (or other config variable). */
-      
-        /* FIXME: other things one might like in :                 
+
+        /* FIXME: other things one might like in :
          * managingEditor
          * webmaster
          * lastBuildDate
          * copyright
          */
     }
-  
-      
+
+
     function item_properties ($rev)
     {
         $page = $rev->getPage();
         $pagename = $page->getName();
-      
-        return array( 'title'		=> SplitPagename($pagename),
-                      'description'	=> $this->summary($rev),
-                      'link'		=> $this->pageURL($rev)                
+
+        return array( 'title'        => SplitPagename($pagename),
+                      'description'    => $this->summary($rev),
+                      'link'        => $this->pageURL($rev)
                       );
     }
 }
@@ -142,5 +142,5 @@ extends _RecentChanges_RSSFormatter
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End: 
+// End:
 ?>
diff --git a/lib/Request.php b/lib/Request.php
index 1bcc22534..7118bf070 100644
--- a/lib/Request.php
+++ b/lib/Request.php
@@ -2,7 +2,7 @@
 // $Id$
 /*
  * Copyright (C) 2002,2004,2005,2006,2009 $ThePhpWikiProgrammingTeam
- * 
+ *
  * This file is part of PhpWiki.
  *
  * PhpWiki is free software; you can redistribute it and/or modify
@@ -21,11 +21,11 @@
  */
 
 class Request {
-        
+
     function Request() {
         $this->_fix_magic_quotes_gpc();
         $this->_fix_multipart_form_data();
-        
+
         switch($this->get('REQUEST_METHOD')) {
         case 'GET':
         case 'HEAD':
@@ -38,14 +38,14 @@ class Request {
             $this->args = array();
             break;
         }
-        
+
         $this->session = new Request_SessionVars;
         $this->cookies = new Request_CookieVars;
-        
+
         if (ACCESS_LOG or ACCESS_LOG_SQL) {
             $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
         }
-        
+
         $GLOBALS['request'] = $this;
     }
 
@@ -84,14 +84,14 @@ class Request {
     function getArgs () {
         return $this->args;
     }
-    
+
     function setArg($key, $val) {
         if ($val === false)
             unset($this->args[$key]);
         else
             $this->args[$key] = $val;
     }
-    
+
     // Well oh well. Do we really want to pass POST params back as GET?
     function getURLtoSelf($args = false, $exclude = array()) {
         $get_args = $this->args;
@@ -140,13 +140,13 @@ class Request {
             return false;
         return (float) $m[1];
     }
-    
-    /* Redirects after edit may fail if no theme signature image is defined. 
+
+    /* Redirects after edit may fail if no theme signature image is defined.
      * Set DISABLE_HTTP_REDIRECT = true then.
      */
     function redirect($url, $noreturn = true) {
         $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
-        
+
         if (!$bogus) {
             header("Location: $url");
             /*
@@ -175,7 +175,7 @@ class Request {
         if ($noreturn) {
             $this->discardOutput(); // This might print the gzip headers. Not good.
             $this->buffer_output(false);
-            
+
             include_once('lib/Template.php');
             $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
             $tmpl->printXML();
@@ -226,11 +226,11 @@ class Request {
             $validator_set = new HTTP_ValidatorSet($validator_set);
         $this->_validators = $validator_set;
     }
-    
-    /** Append more validators for this response. 
+
+    /** Append more validators for this response.
      *  i.e dependencies on other pages mtimes
      *  now it may be called in init also to simplify client code.
-     */ 
+     */
     function appendValidators($validator_set) {
         if (!isset($this->_validators)) {
             $this->setValidators($validator_set);
@@ -238,7 +238,7 @@ class Request {
         }
         $this->_validators->append($validator_set);
     }
-    
+
     /** Check validators and set headers in HTTP response
      *
      * This sets the appropriate "Last-Modified" and "ETag"
@@ -251,7 +251,7 @@ class Request {
      */
     function checkValidators() {
         $validators = &$this->_validators;
-        
+
         // Set validator headers
         if (!empty($this->_is_buffering_output) or !headers_sent()) {
             if (($etag = $validators->getETag()) !== false)
@@ -265,7 +265,7 @@ class Request {
 
         if (CACHE_CONTROL == 'NO_CACHE')
             return;             // don't check conditionals...
-        
+
         // Check conditional headers in request
         $status = $validators->checkConditionalRequest($this);
         if ($status) {
@@ -296,7 +296,7 @@ class Request {
         header("Expires: " . Rfc1123DateTime(time() + $max_age));
         header("Vary: Cookie"); // FIXME: add more here?
     }
-    
+
     function setStatus($status) {
         if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
             header($status);
@@ -333,19 +333,19 @@ class Request {
         }
         elseif (isCGI()) // necessary?
             $compress = false;
-            
+
         if ($this->getArg('start_debug')) $compress = false;
         if ($this->getArg('nocache'))
             $compress = false;
-        
+
         // Should we compress even when apache_note is not available?
         // sf.net bug #933183 and http://bugs.php.net/17557
         // This effectively eliminates CGI, but all other servers also. hmm.
-        if ($compress 
-            and (!function_exists('ob_gzhandler') 
-                 or !function_exists('apache_note'))) 
+        if ($compress
+            and (!function_exists('ob_gzhandler')
+                 or !function_exists('apache_note')))
             $compress = false;
-            
+
         // "output handler 'ob_gzhandler' cannot be used twice"
         // http://www.php.net/ob_gzhandler
         if ($compress and ini_get("zlib.output_compression"))
@@ -358,21 +358,21 @@ class Request {
                  or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")))
             $compress = false;
 
-        // Most RSS clients are NOT(!) application/xml gzip compatible yet. 
+        // Most RSS clients are NOT(!) application/xml gzip compatible yet.
         // Even if they are sending the accept-encoding gzip header!
         // wget is, Mozilla, and MSIE no.
         // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
         // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
-        if ($compress 
-            and $this->getArg('format') 
+        if ($compress
+            and $this->getArg('format')
             and strstr($this->getArg('format'), 'rss'))
             $compress = false;
 
         if ($compress) {
             ob_start('phpwiki_gzhandler');
-            
+
             // TODO: dont send a length or get the gzip'ed data length.
-            $this->_is_compressing_output = true; 
+            $this->_is_compressing_output = true;
             header("Content-Encoding: gzip");
             /*
              * Attempt to prevent Apache from doing the dreaded double-gzip.
@@ -405,18 +405,18 @@ class Request {
         }
     }
 
-    /** 
+    /**
      * Longer texts need too much memory on tiny or memory-limit=8MB systems.
      * We might want to flush our buffer and restart again.
      * (This would be fine if php would release its memory)
-     * Note that this must not be called inside Template expansion or other 
+     * Note that this must not be called inside Template expansion or other
      * sections with ob_buffering.
      */
     function chunkOutput() {
-        if (!empty($this->_is_buffering_output) 
-	    or 
-            (function_exists('ob_get_level') and @ob_get_level())) 
-	{
+        if (!empty($this->_is_buffering_output)
+        or
+            (function_exists('ob_get_level') and @ob_get_level()))
+    {
             $this->_do_chunked_output = true;
             if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
             $this->_ob_get_length += ob_get_length();
@@ -427,7 +427,7 @@ class Request {
     }
 
     function finish() {
-    	$this->_finishing = true;
+        $this->_finishing = true;
         if (!empty($this->_accesslog)) {
             $this->_accesslog->push($this);
             if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
@@ -439,11 +439,11 @@ class Request {
             if (isset($this->_accesslog->logtable))
                 $this->_accesslog->write_sql();
         }
-        
+
         if (!empty($this->_is_buffering_output)) {
-            // if _is_compressing_output then ob_get_length() returns 
+            // if _is_compressing_output then ob_get_length() returns
             // the uncompressed length, not the gzip'ed as required.
-	    if (!headers_sent() and !$this->_is_compressing_output) {
+        if (!headers_sent() and !$this->_is_compressing_output) {
                 // php url-rewriting miscalculates the ob length. fixes bug #1376007
                 if (ini_get('use_trans_sid') == 'off') {
                     if (empty($this->_do_chunked_output)) {
@@ -454,7 +454,7 @@ class Request {
             }
             $this->_is_buffering_output = false;
             ob_end_flush();
-	} elseif (function_exists('ob_get_level') and @ob_get_level()) {
+    } elseif (function_exists('ob_get_level') and @ob_get_level()) {
             ob_end_flush();
         }
         session_write_close();
@@ -506,11 +506,11 @@ class Request {
     function deleteCookieVar($key) {
         return $this->cookies->delete($key);
     }
-    
+
     function getUploadedFile($key) {
         return Request_UploadedFile::getUploadedFile($key);
     }
-    
+
 
     function _fix_magic_quotes_gpc() {
         $needs_fix = array('HTTP_POST_VARS',
@@ -518,7 +518,7 @@ class Request {
                            'HTTP_COOKIE_VARS',
                            'HTTP_SERVER_VARS',
                            'HTTP_POST_FILES');
-        
+
         // Fix magic quotes.
         if (get_magic_quotes_gpc()) {
             foreach ($needs_fix as $vars)
@@ -534,12 +534,12 @@ class Request {
         elseif (is_string($var))
             $var = stripslashes($var);
     }
-    
+
     function _fix_multipart_form_data () {
         if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
             $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
     }
-    
+
     function _strip_leading_nl(&$var) {
         if (is_array($var)) {
             foreach ($var as $key => $val)
@@ -554,13 +554,13 @@ class Request_SessionVars {
     function Request_SessionVars() {
         // Prevent cacheing problems with IE 5
         session_cache_limiter('none');
-                                        
+
         // Avoid to get a notice if session is already started,
         // for example if session.auto_start is activated
         if (!session_id())
             session_start();
     }
-    
+
     function get($key) {
         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
         if (isset($vars[$key]))
@@ -569,7 +569,7 @@ class Request_SessionVars {
             return $_SESSION[$key];
         return false;
     }
-    
+
     function set($key, $val) {
         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
         if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
@@ -582,7 +582,7 @@ class Request_SessionVars {
         if (!check_php_version(5,3))
             session_register($key);
     }
-    
+
     function delete($key) {
         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
         if (!function_usable('ini_get') or ini_get('register_globals'))
@@ -597,7 +597,7 @@ class Request_SessionVars {
 }
 
 class Request_CookieVars {
-    
+
     function get($key) {
         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
         if (isset($vars[$key])) {
@@ -634,8 +634,8 @@ class Request_CookieVars {
     }
 
     function set($key, $val, $persist_days = false, $path = false) {
-    	// if already defined, ignore
-    	if (defined('MAIN_setUser') and $key = getCookieName()) return;
+        // if already defined, ignore
+        if (defined('MAIN_setUser') and $key = getCookieName()) return;
         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
 
         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
@@ -656,16 +656,16 @@ class Request_CookieVars {
         else
             @setcookie($key, $packedval, $expires);
     }
-    
+
     function delete($key) {
         static $deleted = array();
         if (isset($deleted[$key])) return;
         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
-        
+
         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
         if (!defined('COOKIE_DOMAIN'))
             @setcookie($key, '', 0);
-        else    
+        else
             @setcookie($key, '', 0, COOKIE_DOMAIN);
         unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
         unset($_COOKIE[$key]);
@@ -676,7 +676,7 @@ class Request_CookieVars {
 /* Win32 Note:
    [\winnt\php.ini]
    You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
-   Best on the same drive as apache, with forward slashes 
+   Best on the same drive as apache, with forward slashes
    and with ending slash!
    Otherwise "\\" => "" and the uploaded file will not be found.
 */
@@ -689,7 +689,7 @@ class Request_UploadedFile {
             $HTTP_POST_FILES =& $_FILES;
         if (!isset($HTTP_POST_FILES[$postname]))
             return false;
-        
+
         $fileinfo =& $HTTP_POST_FILES[$postname];
         if ($fileinfo['error']) {
             // See https://sourceforge.net/forum/message.php?msg_id=3093651
@@ -725,20 +725,20 @@ class Request_UploadedFile {
                 /* ending slash in php.ini upload_tmp_dir is required. */
                 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
                     trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']).
-                    	          "\n".
-                    	          "Probably illegal TEMP environment or upload_tmp_dir setting. ".
-                    	          "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and ".
-                    	          "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
+                                  "\n".
+                                  "Probably illegal TEMP environment or upload_tmp_dir setting. ".
+                                  "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and ".
+                                  "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
                                   E_USER_ERROR);
                     return false;
                 } else {
                     /*
                     trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
                                           $fileinfo['tmp_name'])."\n".
-            	                  "Probably illegal TEMP environment or upload_tmp_dir setting.", 
-            	                  E_USER_NOTICE);
-            	    */
-            	    ;
+                                  "Probably illegal TEMP environment or upload_tmp_dir setting.",
+                                  E_USER_NOTICE);
+                    */
+                    ;
                 }
             } else {
               trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name'])."\n".
@@ -748,7 +748,7 @@ class Request_UploadedFile {
         }
         return new Request_UploadedFile($fileinfo);
     }
-    
+
     function Request_UploadedFile($fileinfo) {
         $this->_info = $fileinfo;
     }
@@ -828,7 +828,7 @@ class Request_AccessLog {
         //$request->_accesslog =& $this;
         //if (empty($request->_accesslog->entries))
         register_shutdown_function("Request_AccessLogEntry_shutdown_function");
-        
+
         if ($do_sql) {
             global $DBParams;
             if (!in_array($DBParams['dbtype'], array('SQL','ADODB'))) {
@@ -901,7 +901,7 @@ class Request_AccessLog {
     function get_host($host, $since_minutes=20) {
         if ($this->logtable) {
             // mysql specific only:
-            return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60) 
+            return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60)
                             ." ORDER BY time_stamp DESC");
         } else {
             $iter = new WikiDB_Array_generic_iter();
@@ -933,7 +933,7 @@ class Request_AccessLog {
         if ($s = fgets($this->reader)) {
             $entry = new Request_AccessLogEntry($this);
             if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/',$s,$m)) {
-            	list(,$entry->host, $entry->ident, $entry->user, $entry->time,
+                list(,$entry->host, $entry->ident, $entry->user, $entry->time,
                      $entry->request, $entry->status, $entry->size,
                      $entry->referer, $entry->user_agent) = $m;
             }
@@ -959,7 +959,7 @@ class Request_AccessLog {
 
     /* done in request->finish() before the db is closed */
     function write_sql() {
-    	$dbh =& $GLOBALS['request']->_dbi;
+        $dbh =& $GLOBALS['request']->_dbi;
         if (isset($this->entries) and $dbh and $dbh->isOpen())
             foreach ($this->entries as $entry) {
                 $entry->write_sql();
@@ -986,7 +986,7 @@ class Request_AccessLogEntry
     /**
      * Constructor.
      *
-     * The log entry will be automatically appended to the log file or 
+     * The log entry will be automatically appended to the log file or
      * SQL table when the current request terminates.
      *
      * If you want to modify a Request_AccessLogEntry before it gets
@@ -1007,7 +1007,7 @@ class Request_AccessLogEntry
         $this->logfile = $accesslog->logfile;
         $this->time = time();
         $this->status = 200;    // see setStatus()
-        $this->size = 0;	// see setSize()
+        $this->size = 0;    // see setSize()
     }
 
     /**
@@ -1038,7 +1038,7 @@ class Request_AccessLogEntry
     function setStatus ($status) {
         $this->status = $status;
     }
-    
+
     /**
      * Set response size.
      *
@@ -1052,7 +1052,7 @@ class Request_AccessLogEntry
         // Workaround:
         $this->duration = strtr(sprintf("%f", $seconds),",",".");
     }
-    
+
     /**
      * Get time zone offset.
      *
@@ -1121,8 +1121,8 @@ class Request_AccessLogEntry
     /* This is better been done by apache mod_log_sql */
     /* If ACCESS_LOG_SQL & 2 we do write it by our own */
     function write_sql() {
-    	global $request;
-    	
+        global $request;
+
         $dbh =& $request->_dbi;
         if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
             //$log_tbl =& $this->_accesslog->logtable;
@@ -1136,7 +1136,7 @@ class Request_AccessLogEntry
                 if (!empty($args['pref']['passwd2']))   $args['pref']['passwd2'] = '';
                 $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used.
             } else {
-          	$this->request_args = $request->get('QUERY_STRING'); 
+              $this->request_args = $request->get('QUERY_STRING');
             }
             $this->request_method = $request->get('REQUEST_METHOD');
             $this->request_uri = $request->get('REQUEST_URI');
@@ -1154,7 +1154,7 @@ class Request_AccessLogEntry
  */
 function Request_AccessLogEntry_shutdown_function () {
     global $request;
-    
+
     if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
         foreach ($request->_accesslog->entries as $entry) {
             $entry->write_file();
@@ -1224,16 +1224,16 @@ class HTTP_ETag {
 
 // Possible results from the HTTP_ValidatorSet::_check*() methods.
 // (Higher numerical values take precedence.)
-define ('_HTTP_VAL_PASS', 0);         	// Test is irrelevant
-define ('_HTTP_VAL_NOT_MODIFIED', 1); 	// Test passed, content not changed
-define ('_HTTP_VAL_MODIFIED', 2); 	// Test failed, content changed
-define ('_HTTP_VAL_FAILED', 3);   	// Precondition failed.
+define ('_HTTP_VAL_PASS', 0);             // Test is irrelevant
+define ('_HTTP_VAL_NOT_MODIFIED', 1);     // Test passed, content not changed
+define ('_HTTP_VAL_MODIFIED', 2);     // Test failed, content changed
+define ('_HTTP_VAL_FAILED', 3);       // Precondition failed.
 
 class HTTP_ValidatorSet {
     function HTTP_ValidatorSet($validators) {
         $this->_mtime = $this->_weak = false;
         $this->_tag = array();
-        
+
         foreach ($validators as $key => $val) {
             if ($key == '%mtime') {
                 $this->_mtime = $val;
@@ -1275,7 +1275,7 @@ class HTTP_ValidatorSet {
     function getModificationTime() {
         return $this->_mtime;
     }
-    
+
     function checkConditionalRequest (&$request) {
         $result = max($this->_checkIfUnmodifiedSince($request),
                       $this->_checkIfModifiedSince($request),
@@ -1347,5 +1347,5 @@ class HTTP_ValidatorSet {
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End:   
+// End:
 ?>
diff --git a/lib/RssParser.php b/lib/RssParser.php
index 4ae559d8c..87cb925fd 100644
--- a/lib/RssParser.php
+++ b/lib/RssParser.php
@@ -78,7 +78,7 @@ extends XmlParser {
                 $this->items = array();
                 $GLOBALS['rss_parser_items'] =& $this->items;
             } elseif (!empty($this->items[0]['link']) and $this->items[0]['title'] == '') {
-            	// override the initial  list with detailed 's
+                // override the initial  list with detailed 's
                 $this->items = array();
                 $GLOBALS['rss_parser_items'] =& $this->items;
             }
@@ -124,15 +124,15 @@ extends XmlParser {
             if (empty($this->item[$current_tag]))
                 $this->item[$current_tag] = '';
             if ($current_tag == 'LINK') {
-            	if (trim($data))
-            	    $this->item[$current_tag] = trim($data);
+                if (trim($data))
+                    $this->item[$current_tag] = trim($data);
             } else {
                 $this->item[$current_tag] .= trim($data);
             }
         } elseif ($this->list_items) {
             if ($current_tag == 'RDF:LI') {
-            	// FIXME: avoid duplicates. cdata called back 4x per RDF:LI
-            	if ($this->items[count($this->items)-1]['link'] != @$current_attrs['RDF:RESOURCE'])
+                // FIXME: avoid duplicates. cdata called back 4x per RDF:LI
+                if ($this->items[count($this->items)-1]['link'] != @$current_attrs['RDF:RESOURCE'])
                     $this->items[] = array('link' => @$current_attrs['RDF:RESOURCE'],
                                            'title' => '');
             }
@@ -169,12 +169,12 @@ extends XmlParser {
                           E_USER_WARNING);
         //OO workaround: parser object looses its params. we have to store them in globals
         if ($is_final) {
-    	    if (empty($this->items)) {
+            if (empty($this->items)) {
                 $this->items   = @$GLOBALS['rss_parser_items'];
                 $this->channel = @$GLOBALS['rss_parser_channel'];
-    	    }
-    	    unset($GLOBALS['rss_parser_items']);
-    	    unset($GLOBALS['rss_parser_channel']);
+            }
+            unset($GLOBALS['rss_parser_items']);
+            unset($GLOBALS['rss_parser_channel']);
         }
     }
 }
diff --git a/lib/RssWriter.php b/lib/RssWriter.php
index 6370b8ac4..b67e1f9a1 100644
--- a/lib/RssWriter.php
+++ b/lib/RssWriter.php
@@ -20,30 +20,30 @@ class RssWriter extends XmlElement
                           array('xmlns' => "http://purl.org/rss/1.0/",
                                 'xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'));
 
-	$this->_modules = array(
+    $this->_modules = array(
             //Standards
-	    'content'	=> "http://purl.org/rss/1.0/modules/content/",
-	    'dc'	=> "http://purl.org/dc/elements/1.1/",
-	    'sy'	=> "http://purl.org/rss/1.0/modules/syndication/",
+        'content'    => "http://purl.org/rss/1.0/modules/content/",
+        'dc'    => "http://purl.org/dc/elements/1.1/",
+        'sy'    => "http://purl.org/rss/1.0/modules/syndication/",
             //Proposed
             'wiki'      => "http://purl.org/rss/1.0/modules/wiki/",
-	    'ag'	=> "http://purl.org/rss/1.0/modules/aggregation/",
-	    'annotate'	=> "http://purl.org/rss/1.0/modules/annotate/",
-	    'audio'	=> "http://media.tangent.org/rss/1.0/",
-	    'cp'	=> "http://my.theinfo.org/changed/1.0/rss/",
-	    'rss091'	=> "http://purl.org/rss/1.0/modules/rss091/",
-	    'slash'	=> "http://purl.org/rss/1.0/modules/slash/",
-	    'taxo'	=> "http://purl.org/rss/1.0/modules/taxonomy/",
-	    'thr'	=> "http://purl.org/rss/1.0/modules/threading/"
-	    );
+        'ag'    => "http://purl.org/rss/1.0/modules/aggregation/",
+        'annotate'    => "http://purl.org/rss/1.0/modules/annotate/",
+        'audio'    => "http://media.tangent.org/rss/1.0/",
+        'cp'    => "http://my.theinfo.org/changed/1.0/rss/",
+        'rss091'    => "http://purl.org/rss/1.0/modules/rss091/",
+        'slash'    => "http://purl.org/rss/1.0/modules/slash/",
+        'taxo'    => "http://purl.org/rss/1.0/modules/taxonomy/",
+        'thr'    => "http://purl.org/rss/1.0/modules/threading/"
+        );
 
-	$this->_uris_seen = array();
+    $this->_uris_seen = array();
         $this->_items = array();
     }
 
     function registerModule($alias, $uri) {
-	assert(!isset($this->_modules[$alias]));
-	$this->_modules[$alias] = $uri;
+    assert(!isset($this->_modules[$alias]));
+    $this->_modules[$alias] = $uri;
     }
 
     // Args should include:
@@ -53,7 +53,7 @@ class RssWriter extends XmlElement
     function channel($properties, $uri = false) {
         $this->_channel = $this->__node('channel', $properties, $uri);
     }
-  
+
     // Args should include:
     //  'title', 'link'
     // and can include:
@@ -94,24 +94,24 @@ class RssWriter extends XmlElement
                 $seq->pushContent($this->__ref('rdf:li', $item));
         }
         $channel->pushContent(new XmlElement('items', false, $seq));
-   
-	if (isset($this->_image)) {
+
+    if (isset($this->_image)) {
             $channel->pushContent($this->__ref('image', $this->_image));
-	    $items[] = $this->_image;
-	}
-	if (isset($this->_textinput)) {
+        $items[] = $this->_image;
+    }
+    if (isset($this->_textinput)) {
             $channel->pushContent($this->__ref('textinput', $this->_textinput));
-	    $items[] = $this->_textinput;
-	}
+        $items[] = $this->_textinput;
+    }
 
-	$this->pushContent($channel);
-	if ($items)
-	    $this->pushContent($items);
+    $this->pushContent($channel);
+    if ($items)
+        $this->pushContent($items);
 
         $this->__spew();
         $this->_finished = true;
     }
-          
+
     /**
      * Write output to HTTP client.
      */
@@ -121,16 +121,16 @@ class RssWriter extends XmlElement
         //printf("\n", PHPWIKI_VERSION);
         $this->printXML();
     }
-      
-  
+
+
     /**
      * Create a new RDF typedNode.
      */
     function __node($type, $properties, $uri = false) {
-	if (! $uri)
-	    $uri = $properties['link'];
-	$attr['rdf:about'] = $this->__uniquify_uri($uri);
-	return new XmlElement($type, $attr,
+    if (! $uri)
+        $uri = $properties['link'];
+    $attr['rdf:about'] = $this->__uniquify_uri($uri);
+    return new XmlElement($type, $attr,
                               $this->__elementize($properties));
     }
 
@@ -138,44 +138,44 @@ class RssWriter extends XmlElement
      * Check object URI for uniqueness, create a unique URI if needed.
      */
     function __uniquify_uri ($uri) {
-	if (!$uri || isset($this->_uris_seen[$uri])) {
-	    $n = count($this->_uris_seen);
-	    $uri = $this->_channel->getAttr('rdf:about') . "#uri$n";
-	    assert(!isset($this->_uris_seen[$uri]));
-	}
-	$this->_uris_seen[$uri] = true;
-	return $uri;
+    if (!$uri || isset($this->_uris_seen[$uri])) {
+        $n = count($this->_uris_seen);
+        $uri = $this->_channel->getAttr('rdf:about') . "#uri$n";
+        assert(!isset($this->_uris_seen[$uri]));
+    }
+    $this->_uris_seen[$uri] = true;
+    return $uri;
     }
 
     /**
      * Convert hash of RDF properties to propertyElts.
      */
     function __elementize ($elements) {
-	$out = array();
+    $out = array();
         foreach ($elements as $prop => $val) {
-	    $this->__check_predicate($prop);
-	    if (is_array($val))
-	        $out[] = new XmlElement($prop, $val);
-	    elseif (is_object($val))  
-		    $out[] = $val;
-	    else
-	        $out[] = new XmlElement($prop, false, $val);
-	}
-	return $out;
+        $this->__check_predicate($prop);
+        if (is_array($val))
+            $out[] = new XmlElement($prop, $val);
+        elseif (is_object($val))
+            $out[] = $val;
+        else
+            $out[] = new XmlElement($prop, false, $val);
+    }
+    return $out;
     }
 
     /**
      * Check property predicates for XMLNS sanity.
      */
     function __check_predicate ($name) {
-	if (preg_match('/^([^:]+):[^:]/', $name, $m)) {
-	    $ns = $m[1];
-	    if (! $this->getAttr("xmlns:$ns")) {
-		if (!isset($this->_modules[$ns]))
-		    die("$name: unknown namespace ($ns)");
-		$this->setAttr("xmlns:$ns", $this->_modules[$ns]);
-	    }
-	}
+    if (preg_match('/^([^:]+):[^:]/', $name, $m)) {
+        $ns = $m[1];
+        if (! $this->getAttr("xmlns:$ns")) {
+        if (!isset($this->_modules[$ns]))
+            die("$name: unknown namespace ($ns)");
+        $this->setAttr("xmlns:$ns", $this->_modules[$ns]);
+        }
+    }
     }
 
     /**
@@ -197,10 +197,10 @@ class AtomFeed extends RssWriter {
     // and can include:
     //  'URI'
     function feed($properties, $uri = false) {
-    	global $LANG;
-    	$attr = array('xmlns' => 'http://www.w3.org/2005/Atom',
-        	      'version' => '0.3', // or 1.0
-        	      'lang' => $LANG);
+        global $LANG;
+        $attr = array('xmlns' => 'http://www.w3.org/2005/Atom',
+                  'version' => '0.3', // or 1.0
+                  'lang' => $LANG);
         $this->_channel = $this->__node('feed', $attr, $properties, $uri);
     }
 
@@ -218,10 +218,10 @@ class AtomFeed extends RssWriter {
      * Create a new entry
      */
     function __node($type, $attr, $properties, $uri = false) {
-	if (! $uri)
-	    $uri = $properties['link'];
-	//$attr['rdf:about'] = $this->__uniquify_uri($uri);
-	return new XmlElement($type, $attr,
+    if (! $uri)
+        $uri = $properties['link'];
+    //$attr['rdf:about'] = $this->__uniquify_uri($uri);
+    return new XmlElement($type, $attr,
                               $this->__elementize($properties));
     }
 
@@ -242,9 +242,9 @@ class AtomFeed extends RssWriter {
 
         $channel = &$this->_channel;
         $items = &$this->_items;
-	if ($items)
-	    $channel->pushContent($items);
-	$this->pushContent($channel);
+    if ($items)
+        $channel->pushContent($items);
+    $this->pushContent($channel);
 
         $this->__spew();
         $this->_finished = true;
@@ -257,5 +257,5 @@ class AtomFeed extends RssWriter {
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End: 
+// End:
 ?>
diff --git a/lib/RssWriter2.php b/lib/RssWriter2.php
index 7c502e49a..1e9971b39 100644
--- a/lib/RssWriter2.php
+++ b/lib/RssWriter2.php
@@ -22,23 +22,23 @@ class RssWriter2 extends RssWriter
                           array('version' => "2.0"));
 
         // not used. no namespaces should be used.
-	$this->_modules = array(
+    $this->_modules = array(
             //Standards
-	    'content'	=> "http://purl.org/rss/1.0/modules/content/",
-	    'dc'	=> "http://purl.org/dc/elements/1.1/",
-	    'sy'	=> "http://purl.org/rss/1.0/modules/syndication/",
+        'content'    => "http://purl.org/rss/1.0/modules/content/",
+        'dc'    => "http://purl.org/dc/elements/1.1/",
+        'sy'    => "http://purl.org/rss/1.0/modules/syndication/",
             //Proposed
             'wiki'      => "http://purl.org/rss/1.0/modules/wiki/",
-	    'ag'	=> "http://purl.org/rss/1.0/modules/aggregation/",
-	    'annotate'	=> "http://purl.org/rss/1.0/modules/annotate/",
-	    'audio'	=> "http://media.tangent.org/rss/1.0/",
-	    'cp'	=> "http://my.theinfo.org/changed/1.0/rss/",
-	    'rss091'	=> "http://purl.org/rss/1.0/modules/rss091/",
-	    'slash'	=> "http://purl.org/rss/1.0/modules/slash/",
-	    'taxo'	=> "http://purl.org/rss/1.0/modules/taxonomy/",
-	    'thr'	=> "http://purl.org/rss/1.0/modules/threading/"
-	    );
-	$this->_uris_seen = array();
+        'ag'    => "http://purl.org/rss/1.0/modules/aggregation/",
+        'annotate'    => "http://purl.org/rss/1.0/modules/annotate/",
+        'audio'    => "http://media.tangent.org/rss/1.0/",
+        'cp'    => "http://my.theinfo.org/changed/1.0/rss/",
+        'rss091'    => "http://purl.org/rss/1.0/modules/rss091/",
+        'slash'    => "http://purl.org/rss/1.0/modules/slash/",
+        'taxo'    => "http://purl.org/rss/1.0/modules/taxonomy/",
+        'thr'    => "http://purl.org/rss/1.0/modules/threading/"
+        );
+    $this->_uris_seen = array();
         $this->_items = array();
     }
 
@@ -81,5 +81,5 @@ class RssWriter2 extends RssWriter
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End: 
+// End:
 ?>
diff --git a/lib/SemanticWeb.php b/lib/SemanticWeb.php
index efeb8566f..f1b0bede3 100644
--- a/lib/SemanticWeb.php
+++ b/lib/SemanticWeb.php
@@ -119,117 +119,117 @@ require_once('lib/Units.php');
 class RdfWriter extends RssWriter // in fact it should be rewritten to be other way round.
 {
     function RdfWriter (&$request, &$pagelist) {
-	$this->_request =& $request;
-	$this->_pagelist =& $pagelist;
+    $this->_request =& $request;
+    $this->_pagelist =& $pagelist;
         $this->XmlElement('rdf:RDF',
                           array('xmlns' => "http://purl.org/rss/1.0/",
                                 'xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'));
 
-	$this->_modules = array(
+    $this->_modules = array(
             //Standards
-	    'content'	=> "http://purl.org/rss/1.0/modules/content/",
-	    'dc'	=> "http://purl.org/dc/elements/1.1/",
-	    );
+        'content'    => "http://purl.org/rss/1.0/modules/content/",
+        'dc'    => "http://purl.org/dc/elements/1.1/",
+        );
 
-	$this->_uris_seen = array();
+    $this->_uris_seen = array();
         $this->_items = array();
 
-	$this->wiki_xmlns_xml = WikiURL(_("UriResolver")."?",false,true);
-	$this->wiki_xmlns_url = PHPWIKI_BASE_URL;
+    $this->wiki_xmlns_xml = WikiURL(_("UriResolver")."?",false,true);
+    $this->wiki_xmlns_url = PHPWIKI_BASE_URL;
 
-	$this->pre_ns_buffer =
-	    "\n" .
-	    "\n" .
-	    "\t"."\n" .
-	    "\t"."\n" .
-	    "\t"."\n" .
-	    "\t"."\n" .
-	    // A note on "wiki": this namespace is crucial as a fallback when it would be illegal to start e.g. with a number. In this case, one can always use wiki:... followed by "_" and possibly some namespace, since _ is legal as a first character.
-	    "\t"."wiki_xmlns_xml .  "'>\n" .
-	    "\t"."wiki_xmlns_xml .
-	    $this->makeXMLExportId(urlencode(str_replace(' ', '_', _("Relation") . ':'))) .  "'>\n" .
-	    "\t"."wiki_xmlns_xml .
-	    $this->makeXMLExportId(urlencode(str_replace(' ', '_', _("Attribute") . ':'))) .  "'>\n" .
-	    "\t"."wiki_xmlns_url .  "'>\n" .
-	    "]>\n\n" .
-	    "post_ns_buffer =
-	    "\n\t\n" .
-	    "\t"."\n" .
-	    "\t\t"."\n" .
-	    "\t"."\n" .
-	    "\t"."\n" .
-	    "\t\t"."\n" .
-	    "\t"."\n" .
-	    "\t"."\n" .
-	    "\t\t"."\n" .
-	    "\t"."\n" .
-	    "\t\n";
+    $this->pre_ns_buffer =
+        "\n" .
+        "\n" .
+        "\t"."\n" .
+        "\t"."\n" .
+        "\t"."\n" .
+        "\t"."\n" .
+        // A note on "wiki": this namespace is crucial as a fallback when it would be illegal to start e.g. with a number. In this case, one can always use wiki:... followed by "_" and possibly some namespace, since _ is legal as a first character.
+        "\t"."wiki_xmlns_xml .  "'>\n" .
+        "\t"."wiki_xmlns_xml .
+        $this->makeXMLExportId(urlencode(str_replace(' ', '_', _("Relation") . ':'))) .  "'>\n" .
+        "\t"."wiki_xmlns_xml .
+        $this->makeXMLExportId(urlencode(str_replace(' ', '_', _("Attribute") . ':'))) .  "'>\n" .
+        "\t"."wiki_xmlns_url .  "'>\n" .
+        "]>\n\n" .
+        "post_ns_buffer =
+        "\n\t\n" .
+        "\t"."\n" .
+        "\t\t"."\n" .
+        "\t"."\n" .
+        "\t"."\n" .
+        "\t\t"."\n" .
+        "\t"."\n" .
+        "\t"."\n" .
+        "\t\t"."\n" .
+        "\t"."\n" .
+        "\t\n";
     }
 
     function format() {
-	header( "Content-type: application/rdf+xml; charset=UTF-8" );
-	echo $this->pre_ns_buffer;
-	echo ">\n";
+    header( "Content-type: application/rdf+xml; charset=UTF-8" );
+    echo $this->pre_ns_buffer;
+    echo ">\n";
 
-	$first = true;
-	$dbi =	$this->_request->_dbi;
-	/* Elements per page:
-	   out-links internal, out-links external
-	   backlinks
-	   relations
-	   attributes
-	*/
-	foreach ($this->_pagelist->_pages as $page) {
-	    $relation = new TextSearchQuery("*");
-	    foreach (array('linkto','linkfrom','relation','attribute') as $linktype) {
-		$linkiter = $dbi->linkSearch($pages, $search, $linktype, $relation);
-	    }
-	    while ($link = $linkiter->next()) {
-		if (mayAccessPage('view', $rev->_pagename)) {
-		    $linkto->addItem($this->item_properties($rev),
-				     $this->pageURI($rev));
-		    if ($first)
-			$this->setValidators($rev);
-		    $first = false;
-		}
-	    }
-	}
+    $first = true;
+    $dbi =    $this->_request->_dbi;
+    /* Elements per page:
+       out-links internal, out-links external
+       backlinks
+       relations
+       attributes
+    */
+    foreach ($this->_pagelist->_pages as $page) {
+        $relation = new TextSearchQuery("*");
+        foreach (array('linkto','linkfrom','relation','attribute') as $linktype) {
+        $linkiter = $dbi->linkSearch($pages, $search, $linktype, $relation);
+        }
+        while ($link = $linkiter->next()) {
+        if (mayAccessPage('view', $rev->_pagename)) {
+            $linkto->addItem($this->item_properties($rev),
+                     $this->pageURI($rev));
+            if ($first)
+            $this->setValidators($rev);
+            $first = false;
+        }
+        }
+    }
 
-	echo $this->post_ns_buffer;
-	echo "\n";
+    echo $this->post_ns_buffer;
+    echo "\n";
     }
 
     /** This function transforms a valid url-encoded URI into a string
      *  that can be used as an XML-ID. The mapping should be injective.
      */
     function makeXMLExportId($uri) {
-	$uri = str_replace( '-', '-2D', $uri);
-	//$uri = str_replace( ':', '-3A', $uri); //already done by PHP
-	//$uri = str_replace( '_', '-5F', $uri); //not necessary
-	$uri = str_replace( array('"',  '#',   '&', "'",  '+',  '=',  '%'),
-			    array('-22','-23','-26','-27','-2B','-3D','-'),
-			    $uri);
-	return $uri;
+    $uri = str_replace( '-', '-2D', $uri);
+    //$uri = str_replace( ':', '-3A', $uri); //already done by PHP
+    //$uri = str_replace( '_', '-5F', $uri); //not necessary
+    $uri = str_replace( array('"',  '#',   '&', "'",  '+',  '=',  '%'),
+                array('-22','-23','-26','-27','-2B','-3D','-'),
+                $uri);
+    return $uri;
     }
 
     /** This function transforms an XML-ID string into a valid
      *  url-encoded URI. This is the inverse to makeXMLExportID.
      */
     function makeURIfromXMLExportId($id) {
-	$id = str_replace( array('-22','-23','-26','-27','-2B','-3D','-'),
-			   array('"',  '#',  '&',  "'",  '+',  '=',  '%'),
-			   $id);
-	$id = str_replace( '-2D', '-', $id);
-	return $id;
+    $id = str_replace( array('-22','-23','-26','-27','-2B','-3D','-'),
+               array('"',  '#',  '&',  "'",  '+',  '=',  '%'),
+               $id);
+    $id = str_replace( '-2D', '-', $id);
+    return $id;
     }
 }
 
@@ -283,9 +283,9 @@ extends NumericSearchQuery
 {
     /*
     var $base_units = array('m'   => explode(',','km,miles,cm,dm,mm,ft,inch,inches,meter'),
-			    'm^2' => explode(',','km^2,ha,cm^2,mi^2'),
-			    'm^3' => explode(',','km^3,lit,cm^3,dm^3,gallons'),
-			    );
+                'm^2' => explode(',','km^2,ha,cm^2,mi^2'),
+                'm^3' => explode(',','km^3,lit,cm^3,dm^3,gallons'),
+                );
     */
 
     /**
@@ -293,9 +293,9 @@ extends NumericSearchQuery
      * population > 1 million
      */
     function SemanticAttributeSearchQuery($search_query, $placeholders, $unit = '') {
-	$this->NumericSearchQuery($search_query, $placeholders);
-	$this->_units = new Units();
-	$this->unit = $unit;
+    $this->NumericSearchQuery($search_query, $placeholders);
+    $this->_units = new Units();
+    $this->unit = $unit;
     }
 
     /**
@@ -310,33 +310,33 @@ extends NumericSearchQuery
      * @return string
      */
     function _bind($value, $x) {
-    	$ori_value = $value;
-	$value = preg_replace("/,/", "", $value);
-	$this->_bound[] = array('linkname'  => $x,
-	        		'linkvalue' => $value);
-	// We must ensure that the same baseunits are matched against.
-	// We cannot compare m^2 to m or ''
-	$val_base = $this->_units->basevalue($value);
+        $ori_value = $value;
+    $value = preg_replace("/,/", "", $value);
+    $this->_bound[] = array('linkname'  => $x,
+                    'linkvalue' => $value);
+    // We must ensure that the same baseunits are matched against.
+    // We cannot compare m^2 to m or ''
+    $val_base = $this->_units->basevalue($value);
         if (!DISABLE_UNITS and $this->_units->baseunit($value) != $this->unit) {
-	    // Poor user has selected an attribute, but no unit. assume he means the baseunit
-	    if (count($this->getVars() == 1) and $this->unit == '') {
-		;
-	    } else {
-		// non-matching units are silently ignored
-		$this->_workquery = '';
-		return '';
-	    }
+        // Poor user has selected an attribute, but no unit. assume he means the baseunit
+        if (count($this->getVars() == 1) and $this->unit == '') {
+        ;
+        } else {
+        // non-matching units are silently ignored
+        $this->_workquery = '';
+        return '';
+        }
         }
         $value = $val_base;
-	if (!is_numeric($value)) {
-	    $this->_workquery = ''; //must return false
-	    trigger_error("Cannot match against non-numeric attribute value $x := $ori_value",
-			  E_USER_NOTICE);
-	    return '';
-	}
+    if (!is_numeric($value)) {
+        $this->_workquery = ''; //must return false
+        trigger_error("Cannot match against non-numeric attribute value $x := $ori_value",
+              E_USER_NOTICE);
+        return '';
+    }
 
-	$this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery);
-	return $this->_workquery;
+    $this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery);
+    return $this->_workquery;
     }
 
 }
diff --git a/lib/SpamBlocklist.php b/lib/SpamBlocklist.php
index 58fde13a9..5d5849428 100644
--- a/lib/SpamBlocklist.php
+++ b/lib/SpamBlocklist.php
@@ -8,19 +8,19 @@
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
- * 
+ *
  * PhpWiki is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
- * 
+ *
  * You should have received a copy of the GNU General Public License
  * along with PhpWiki; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- * 
+ *
  */
 
-/** 
+/**
  * See http://www.surbl.org/
  *
  * Perform a name lookup (A) for any link tld against multi.surbl.org and bl.spamcop.net,
@@ -30,40 +30,40 @@
  */
 
 /*
- * Strip domain prefixes so that either the last two name parts are returned, 
+ * Strip domain prefixes so that either the last two name parts are returned,
  * or if it's a known tld (like "co.uk") the last three.
  */
 function stripDomainPrefixes($host) {
     static $twoleveltlds = array();
     $host_elements = explode('.', $host);
     while (count($host_elements) > 3) {
-	array_shift($host_elements);
+    array_shift($host_elements);
     }
     $host_3_elements = implode('.', $host_elements);
     if (count($host_elements) > 2) {
-	array_shift($host_elements);
+    array_shift($host_elements);
     }
     $host_2_elements = implode('.', $host_elements);
     if (empty($twoleveltlds)) {
-	$data = @file(dirname(__FILE__)."/../config/two-level-tlds");
-	$twoleveltlds = $data ? array_flip($data) : array();
+    $data = @file(dirname(__FILE__)."/../config/two-level-tlds");
+    $twoleveltlds = $data ? array_flip($data) : array();
     }
     if (array_key_exists($host_2_elements, $twoleveltlds))
-	//IS_IN_2LEVEL: we want the last three names
-	$host = $host_3_elements;
+    //IS_IN_2LEVEL: we want the last three names
+    $host = $host_3_elements;
     else
-	// IS_NOT_2LEVEL: we want the last two names
-	$host = $host_2_elements;
+    // IS_NOT_2LEVEL: we want the last two names
+    $host = $host_2_elements;
     return $host;
 }
 
 function IsBlackListed($uri) {
     static $blacklists = array("multi.surbl.org", "bl.spamcop.net");
-    	                      /* "sbl-xbl.spamhaus.net" */
+                              /* "sbl-xbl.spamhaus.net" */
     static $whitelist = array();
     if (empty($whitelist)) { // list of domains
-	$data = @file(dirname(__FILE__)."/../config/whitelist");
-	$whitelist = $data ? array_flip($data) : array();
+    $data = @file(dirname(__FILE__)."/../config/whitelist");
+    $whitelist = $data ? array_flip($data) : array();
     }
 
     $parsed_uri = parse_url($uri);
@@ -72,26 +72,26 @@ function IsBlackListed($uri) {
     else
         $host = $parsed_uri['path'];
     if (array_key_exists($host, $whitelist))
-	return 0;
+    return 0;
     if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $host)) {
-	$host = implode('.', array_reverse(explode('.', $host))); 
-	$revip = 1;
+    $host = implode('.', array_reverse(explode('.', $host)));
+    $revip = 1;
     } else {
-	$revip = 0;
+    $revip = 0;
     }
     foreach ($blacklists as $bl) {
-	if (!$revip and $bl == "multi.surbl.org") {
-	    $host = stripDomainPrefixes($host); // strip domain prefixes
-	    if (array_key_exists($host, $whitelist))
-		return 0;
-	} elseif (!$revip) {
-	    // convert to IP addr and revert it.
-	    $host = implode('.', array_reverse(explode('.', gethostbyname($host)))); 
-	}
-	//echo "($host.$bl)";
-	$res = gethostbyname($host . "." . $bl);
-	if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $res))
-	    return array($bl, $res, $host);
+    if (!$revip and $bl == "multi.surbl.org") {
+        $host = stripDomainPrefixes($host); // strip domain prefixes
+        if (array_key_exists($host, $whitelist))
+        return 0;
+    } elseif (!$revip) {
+        // convert to IP addr and revert it.
+        $host = implode('.', array_reverse(explode('.', gethostbyname($host))));
+    }
+    //echo "($host.$bl)";
+    $res = gethostbyname($host . "." . $bl);
+    if (preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $res))
+        return array($bl, $res, $host);
     }
     return 0;
 }
@@ -113,9 +113,9 @@ function BlackListDebug($host) {
     $res = IsBlackListed($host);
     echo sprintf("%12s", $host), "\tis";
     if ($res)
-	echo " listed at $res[0] - $res[1]\n";
+    echo " listed at $res[0] - $res[1]\n";
     else
-	echo " not blacklisted.\n";
+    echo " not blacklisted.\n";
 }
 */
 
@@ -125,5 +125,5 @@ function BlackListDebug($host) {
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End:   
+// End:
 ?>
diff --git a/lib/Template.php b/lib/Template.php
index 7f2434079..17764910f 100644
--- a/lib/Template.php
+++ b/lib/Template.php
@@ -30,9 +30,9 @@ class Template
             trigger_error("no template for $name found.", E_USER_WARNING);
             return;
         }
-        if (isset($oldname)) { 
-            $WikiTheme->_name = $oldname; 
-            $WikiTheme->_theme = $oldtheme; 
+        if (isset($oldname)) {
+            $WikiTheme->_name = $oldname;
+            $WikiTheme->_theme = $oldtheme;
         }
         $fp = fopen($file, "rb");
         if (!$fp) {
@@ -56,15 +56,15 @@ class Template
         // Convert < ?plugin expr ? > to < ?php $this->_printPluginPI("expr"); ? >
         $orig[] = '/<\?plugin.*?\?>/se';
         $repl[] = "\$this->_mungePlugin('\\0')";
-        
+
         // Convert < ?= expr ? > to < ?php $this->_print(expr); ? >
         $orig[] = '/<\?=(.*?)\?>/s';
         $repl[] = '_print(\1);?>';
-        
+
         // Convert < ?php echo expr ? > to < ?php $this->_print(expr); ? >
         $orig[] = '/<\?php echo (.*?)\?>/s';
         $repl[] = '_print(\1);?>';
-        
+
         return preg_replace($orig, $repl, $template);
     }
 
@@ -77,17 +77,17 @@ class Template
         return sprintf('_printPlugin(%s); ?>',
                        "'" . str_replace("'", "\'", $pi) . "'");
     }
-    
+
     function _printPlugin ($pi) {
-	include_once("lib/WikiPlugin.php");
-	static $loader;
+    include_once("lib/WikiPlugin.php");
+    static $loader;
 
         if (empty($loader))
             $loader = new WikiPluginLoader;
-        
+
         $this->_print($loader->expandPI($pi, $this->_request, $this, $this->_basepage));
     }
-    
+
     function _print ($val) {
         if (isa($val, 'Template')) {
             $this->_expandSubtemplate($val);
@@ -97,7 +97,7 @@ class Template
     }
 
     function _expandSubtemplate (&$template) {
-        // FIXME: big hack!        
+        // FIXME: big hack!
         //if (!$template->_request)
         //    $template->_request = &$this->_request;
         if (DEBUG) {
@@ -109,9 +109,9 @@ class Template
             echo "\n";
         }
     }
-        
+
     /**
-     * Substitute HTML replacement text for tokens in template. 
+     * Substitute HTML replacement text for tokens in template.
      *
      * Constructs a new WikiTemplate based upon the named template.
      *
@@ -125,7 +125,7 @@ class Template
         $this->_locals[$varname] = $value;
     }
 
-    
+
     function printExpansion ($defaults = false) {
         if (!is_array($defaults)) // HTML object or template object
             $defaults = array('CONTENT' => $defaults);
@@ -137,11 +137,11 @@ class Template
             $user = $request->getUser();
         if (!isset($page))
             $page = $request->getPage();
-	// Speedup. I checked all templates
-        if (!isset($revision)) 
-	    $revision = false;
+    // Speedup. I checked all templates
+        if (!isset($revision))
+        $revision = false;
 
-        global $WikiTheme, $charset; 
+        global $WikiTheme, $charset;
         //$this->_dump_template();
         $SEP = $WikiTheme->getButtonSeparator();
 
@@ -161,7 +161,7 @@ class Template
         ob_start();
         $this->printExpansion($defaults);
         $xml = ob_get_contents();
-        ob_end_clean(); 	// PHP problem: Doesn't release its memory?
+        ob_end_clean();     // PHP problem: Doesn't release its memory?
         return $xml;
     }
 
@@ -172,8 +172,8 @@ class Template
     function asXML () {
         return $this->getExpansion();
     }
-    
-            
+
+
     // Debugging:
     function _dump_template () {
         $lines = explode("\n", $this->_munge_input($this->_tmpl));
@@ -186,7 +186,7 @@ class Template
 
     function _errorHandler($error) {
         //if (!preg_match('/: eval\(\)\'d code$/', $error->errfile))
-	//    return false;
+    //    return false;
 
         if (preg_match('/: eval\(\)\'d code$/', $error->errfile)) {
             $error->errfile = "In template '$this->_name'";
@@ -201,7 +201,7 @@ class Template
             ; //return $error;
         }
         elseif (strstr($error->errfile, "In template '")) { // merge
-            $error->errfile = preg_replace("/'(\w+)'\)$/", "'\\1' < '$this->_name')", 
+            $error->errfile = preg_replace("/'(\w+)'\)$/", "'\\1' < '$this->_name')",
                                            $error->errfile);
         }
         else {
@@ -213,7 +213,7 @@ class Template
             if (isset($lines[$error->errline - 1]))
                 $error->errstr .= ":\n\t" . $lines[$error->errline - 1];
         }
-	return $error;
+    return $error;
     }
 };
 
@@ -235,7 +235,7 @@ function alreadyTemplateProcessed($name) {
     return !empty($request->_TemplatesProcessed[$name]) ? true : false;
 }
 /**
- * Make and expand the top-level template. 
+ * Make and expand the top-level template.
  *
  *
  * @param $content mixed html content to put into the page
@@ -247,17 +247,17 @@ function alreadyTemplateProcessed($name) {
  */
 function GeneratePage($content, $title, $page_revision = false, $args = false) {
     global $request;
-    
+
     if (!is_array($args))
         $args = array();
 
     $args['CONTENT'] = $content;
     $args['TITLE'] = $title;
     $args['revision'] = $page_revision;
-    
+
     if (!isset($args['HEADER']))
         $args['HEADER'] = $title;
-    
+
     printXML(new Template('html', $request, $args));
 }
 
@@ -268,7 +268,7 @@ function GeneratePage($content, $title, $page_revision = false, $args = false) {
  */
 function GeneratePageasXML($content, $title, $page_revision = false, $args = false) {
     global $request;
-    
+
     if (!is_array($args))
         $args = array();
 
@@ -276,18 +276,18 @@ function GeneratePageasXML($content, $title, $page_revision = false, $args = fal
     $args['CONTENT'] = $content;
     $args['TITLE'] = SplitPagename($title);
     $args['revision'] = $page_revision;
-    
+
     if (!isset($args['HEADER']))
         $args['HEADER'] = SplitPagename($title);
-    
+
     global $HIDE_TOOLBARS, $NO_BASEHREF, $WikiTheme;
     $HIDE_TOOLBARS = true;
     if (!$WikiTheme->DUMP_MODE)
-	$WikiTheme->DUMP_MODE = 'HTML';
+    $WikiTheme->DUMP_MODE = 'HTML';
 
     // FIXME: unfatal errors and login requirements
     $html = asXML(new Template('htmldump', $request, $args));
-    
+
     $HIDE_TOOLBARS = false;
     //$WikiTheme->DUMP_MODE = false;
     return $html;
@@ -299,5 +299,5 @@ function GeneratePageasXML($content, $title, $page_revision = false, $args = fal
 // c-basic-offset: 4
 // c-hanging-comment-ender-p: nil
 // indent-tabs-mode: nil
-// End:   
+// End:
 ?>
diff --git a/lib/TextSearchQuery.php b/lib/TextSearchQuery.php
index ac3b9af36..93a0ca2a4 100644
--- a/lib/TextSearchQuery.php
+++ b/lib/TextSearchQuery.php
@@ -11,7 +11,7 @@
  * 
wiki word or page *
Match strings containing the substring 'wiki' AND either the substring * 'word' OR the substring 'page'. - *
auto-detect regex hints, glob-style or regex-style, and converts them + *
auto-detect regex hints, glob-style or regex-style, and converts them * to PCRE and SQL matchers: *
"^word$" => EXACT(phrase) *
"^word" => STARTS_WITH(phrase) @@ -45,11 +45,11 @@ * double-up on the quote character: 'I''m hungry' is equivalent to * "I'm hungry". * - * Force regex on "re:word" => posix-style, "/word/" => pcre-style + * Force regex on "re:word" => posix-style, "/word/" => pcre-style * or use regex='glob' to use file wildcard-like matching. (not yet) * - * The parsed tree is then converted to the needed PCRE (highlight, - * simple backends) or SQL functions. + * The parsed tree is then converted to the needed PCRE (highlight, + * simple backends) or SQL functions. * * @author: Jeff Dairiki * @author: Reini Urban (case and regex detection, enhanced sql callbacks) @@ -107,7 +107,7 @@ class TextSearchQuery { * @see TextSearchQuery */ function TextSearchQuery($search_query, $case_exact=false, $regex='auto') { - if ($regex == 'none' or !$regex) + if ($regex == 'none' or !$regex) $this->_regex = 0; elseif (defined("TSQ_REGEX_".strtoupper($regex))) $this->_regex = constant("TSQ_REGEX_".strtoupper($regex)); @@ -115,24 +115,24 @@ class TextSearchQuery { trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex)); $this->_regex = 0; } - $this->_regex_modifier = ($case_exact?'':'i').'sS'; + $this->_regex_modifier = ($case_exact?'':'i').'sS'; $this->_case_exact = $case_exact; if ($regex != 'pcre') { - $parser = new TextSearchQuery_Parser; - $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex); - $this->_optimize(); // broken under certain circumstances: "word -word -word" - if (defined("FULLTEXTSEARCH_STOPLIST")) - $this->_stoplist = FULLTEXTSEARCH_STOPLIST; - else // default stoplist, localizable. - $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)"); - } - else { - $this->_tree = new TextSearchQuery_node_regex_pcre($search_query); - if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) { - $this->_tree->word = $m[1]; - $this->_regex_modifier = $m[2]; // overrides case_exact - } - } + $parser = new TextSearchQuery_Parser; + $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex); + $this->_optimize(); // broken under certain circumstances: "word -word -word" + if (defined("FULLTEXTSEARCH_STOPLIST")) + $this->_stoplist = FULLTEXTSEARCH_STOPLIST; + else // default stoplist, localizable. + $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)"); + } + else { + $this->_tree = new TextSearchQuery_node_regex_pcre($search_query); + if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) { + $this->_tree->word = $m[1]; + $this->_regex_modifier = $m[2]; // overrides case_exact + } + } } function getType() { return 'text'; } @@ -146,7 +146,7 @@ class TextSearchQuery { */ function asRegexp() { if (!isset($this->_regexp)) { - if (!isset($this->_regex_modifier)) + if (!isset($this->_regex_modifier)) $this->_regex_modifier = ($this->_case_exact?'':'i').'sS'; if ($this->_regex) $this->_regexp = '/' . $this->_tree->regexp() . '/'.$this->_regex_modifier; @@ -160,29 +160,29 @@ class TextSearchQuery { * Match query against string. * EXACT ("Term") ignores the case_exact setting. * - * @param $string string The string to match. + * @param $string string The string to match. * @return boolean True if the string matches the query. */ function match($string) { - if ($this->_tree->_op == TSQ_TOK_ALL) return true; - if ($this->_tree->_op == TSQ_TOK_EXACT) return $this->_tree->word == $string; + if ($this->_tree->_op == TSQ_TOK_ALL) return true; + if ($this->_tree->_op == TSQ_TOK_EXACT) return $this->_tree->word == $string; return preg_match($this->asRegexp(), $string); } /* How good does it match? Returns a number */ function score($string) { - $score = 0.0; - $i = 10; - foreach (array_unique($this->_tree->highlight_words()) as $word) { - if ($nummatch = preg_match_all("/".preg_quote($word, '/')."/". - $this->_regex_modifier, - $string, $out)) - $score += ($i-- * $nummatch); - } - return min(1.0, $score / 10.0); + $score = 0.0; + $i = 10; + foreach (array_unique($this->_tree->highlight_words()) as $word) { + if ($nummatch = preg_match_all("/".preg_quote($word, '/')."/". + $this->_regex_modifier, + $string, $out)) + $score += ($i-- * $nummatch); } + return min(1.0, $score / 10.0); + } + - /** * Get a regular expression suitable for highlighting matched words. * @@ -199,7 +199,7 @@ class TextSearchQuery { } else { foreach ($words as $key => $word) $words[$key] = preg_quote($word, '/'); - $this->_hilight_regexp = '(?'.($this->_case_exact?'':'i').':' + $this->_hilight_regexp = '(?'.($this->_case_exact?'':'i').':' . join('|', $words) . ')'; } } @@ -207,7 +207,7 @@ class TextSearchQuery { } /** - * Make an SQL clause which matches the query. + * Make an SQL clause which matches the query. * Deprecated, use makeSqlClauseObj instead. * * @param $make_sql_clause_cb WikiCallback @@ -353,8 +353,8 @@ class NullTextSearchQuery extends TextSearchQuery { * @see TextSearchQuery */ function NullTextSearchQuery() {} - function asRegexp() { return '/^(?!a)a/x'; } - function match($string) { return false; } + function asRegexp() { return '/^(?!a)a/x'; } + function match($string) { return false; } function getHighlightRegexp() { return ""; } function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; } function asString() { return "NullTextSearchQuery"; } @@ -363,14 +363,14 @@ class NullTextSearchQuery extends TextSearchQuery { /** * A simple algebraic matcher for numeric attributes. * NumericSearchQuery can do ("population < 20000 and area > 1000000", array("population", "area")) - * ->match(array('population' => 100000, 'area' => 10000000)) + * ->match(array('population' => 100000, 'area' => 10000000)) * * Supports all mathematical PHP comparison operators, plus ':=' for equality. * "(x < 2000000 and x >= 10000) or (x >= 100 and x < 2000)" * "x := 100000" is the same as "x == 100000" * - * Since this is basic numerics only, we simply try to get away with - * replacing the variable values at the right positions and do an eval then. + * Since this is basic numerics only, we simply try to get away with + * replacing the variable values at the right positions and do an eval then. * * @package NumericSearchQuery * @author Reini Urban @@ -383,111 +383,111 @@ class NumericSearchQuery * NumericSearchQuery("population > 20000 or population < 200", "population") * NumericSearchQuery("population < 20000 and area > 1000000", array("population", "area")) * - * With a single variable it is easy: The valid name must be matched elsewhere, just + * With a single variable it is easy: The valid name must be matched elsewhere, just * replace the given number in match in the query. * ->match(2000) * * With matching a struct we need strict names, no * as name is allowed. - * So always when the placeholder is an array, the names of the target struct must match + * So always when the placeholder is an array, the names of the target struct must match * and all vars be defined. Use the method can_match($struct) therefore. * * @access public * @param $search_query string A numerical query with placeholders as variable. - * @param $placeholders array or string All placeholders in the query must be defined - * here, and will be replaced by the matcher. + * @param $placeholders array or string All placeholders in the query must be defined + * here, and will be replaced by the matcher. */ function NumericSearchQuery($search_query, $placeholders) { - // added some basic security checks against user input + // added some basic security checks against user input $this->_query = $search_query; - $this->_placeholders = $placeholders; - - // we should also allow the M_ constants - $this->_allowed_functions = explode(':','abs:acos:acosh:asin:asinh:atan2:atan:atanh:base_convert:bindec:ceil:cos:cosh:decbin:dechex:decoct:deg2rad:exp:expm1:floor:fmod:getrandmax:hexdec:hypot:is_finite:is_infinite:is_nan:lcg_value:log10:log1p:log:max:min:mt_getrandmax:mt_rand:mt_srand:octdec:pi:pow:rad2deg:rand:round:sin:sinh:sqrt:srand:tan:tanh'); - $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||'); - $this->_parser_check = array(); - // check should be fast, so make a hash - foreach ($this->_allowed_functions as $f) - $this->_parser_check[$f] = 1; - foreach ($this->_allowed_operators as $f) - $this->_parser_check[$f] = 1; - if (is_array($placeholders)) - foreach ($placeholders as $f) - $this->_parser_check[$f] = 1; - else $this->_parser_check[$placeholders] = 1; - - // This is a speciality: := looks like the attribute definition and is - // therefore a dummy check for this definition. - // php-4.2.2 has a problem with /\b:=\b/ matching "population := 1223400" - $this->_query = preg_replace("/:=/", "==", $this->_query); - $this->_query = $this->check_query($this->_query); + $this->_placeholders = $placeholders; + + // we should also allow the M_ constants + $this->_allowed_functions = explode(':','abs:acos:acosh:asin:asinh:atan2:atan:atanh:base_convert:bindec:ceil:cos:cosh:decbin:dechex:decoct:deg2rad:exp:expm1:floor:fmod:getrandmax:hexdec:hypot:is_finite:is_infinite:is_nan:lcg_value:log10:log1p:log:max:min:mt_getrandmax:mt_rand:mt_srand:octdec:pi:pow:rad2deg:rand:round:sin:sinh:sqrt:srand:tan:tanh'); + $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||'); + $this->_parser_check = array(); + // check should be fast, so make a hash + foreach ($this->_allowed_functions as $f) + $this->_parser_check[$f] = 1; + foreach ($this->_allowed_operators as $f) + $this->_parser_check[$f] = 1; + if (is_array($placeholders)) + foreach ($placeholders as $f) + $this->_parser_check[$f] = 1; + else $this->_parser_check[$placeholders] = 1; + + // This is a speciality: := looks like the attribute definition and is + // therefore a dummy check for this definition. + // php-4.2.2 has a problem with /\b:=\b/ matching "population := 1223400" + $this->_query = preg_replace("/:=/", "==", $this->_query); + $this->_query = $this->check_query($this->_query); } function getType() { return 'numeric'; } /** * Check the symbolic definition query against unwanted functions and characters. - * "population < 20000 and area > 1000000" vs - * "area > 1000000 and mail($me,file("/etc/passwd"),...)" + * "population < 20000 and area > 1000000" vs + * "area > 1000000 and mail($me,file("/etc/passwd"),...)" * http://localhost/wikicvs/SemanticSearch?attribute=*&attr_op=<0 and find(1)>&s=-0.01&start_debug=1 */ function check_query ($query) { - $tmp = $query; // check for all function calls, in case the tokenizer is not available. - while (preg_match("/([a-z][a-z0-9]+)\s*\((.*)$/i", $tmp, $m)) { - if (!in_array($m[1], $this->_allowed_functions) - and !in_array($m[1], $this->_allowed_operators)) - { - trigger_error("Illegal function in query: ".$m[1], E_USER_WARNING); - return ''; - } - $tmp = $m[2]; - } - - // Strictly check for illegal functions and operators, which are no placeholders. - if (function_exists('token_get_all')) { - $parsed = token_get_all(""); - foreach ($parsed as $x) { // flat, non-recursive array - if (is_string($x) and !isset($this->_parser_check[$x])) { - // single char op or name - trigger_error("Illegal string or operator in query: \"$x\"", E_USER_WARNING); - $query = ''; - } - elseif (is_array($x)) { - $n = token_name($x[0]); - if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE' - or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER' - or $n == 'T_CONST' or $n == 'T_DNUMBER' ) continue; - if ($n == 'T_VARIABLE') { // but we do allow consts - trigger_error("Illegal variable in query: \"$x[1]\"", E_USER_WARNING); - $query = ''; - } - if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) { - // multi-char char op or name - trigger_error("Illegal $n in query: \"$x[1]\"", E_USER_WARNING); - $query = ''; - } - } - } - //echo "$query
"; - //$this->_parse_token($parsed); - //echo "
\n"; - //var_dump($parsed); - /* -"_x > 0" => + $tmp = $query; // check for all function calls, in case the tokenizer is not available. + while (preg_match("/([a-z][a-z0-9]+)\s*\((.*)$/i", $tmp, $m)) { + if (!in_array($m[1], $this->_allowed_functions) + and !in_array($m[1], $this->_allowed_operators)) + { + trigger_error("Illegal function in query: ".$m[1], E_USER_WARNING); + return ''; + } + $tmp = $m[2]; + } + + // Strictly check for illegal functions and operators, which are no placeholders. + if (function_exists('token_get_all')) { + $parsed = token_get_all(""); + foreach ($parsed as $x) { // flat, non-recursive array + if (is_string($x) and !isset($this->_parser_check[$x])) { + // single char op or name + trigger_error("Illegal string or operator in query: \"$x\"", E_USER_WARNING); + $query = ''; + } + elseif (is_array($x)) { + $n = token_name($x[0]); + if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE' + or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER' + or $n == 'T_CONST' or $n == 'T_DNUMBER' ) continue; + if ($n == 'T_VARIABLE') { // but we do allow consts + trigger_error("Illegal variable in query: \"$x[1]\"", E_USER_WARNING); + $query = ''; + } + if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) { + // multi-char char op or name + trigger_error("Illegal $n in query: \"$x[1]\"", E_USER_WARNING); + $query = ''; + } + } + } + //echo "$query
"; + //$this->_parse_token($parsed); + //echo "
\n"; + //var_dump($parsed); + /* +"_x > 0" => { T_OPEN_TAG "" { T_WHITESPACE " "} { T_LNUMBER "0"} { T_CLOSE_TAG "?>"} - Interesting: on-char ops, as ">" are not tokenized. + Interesting: on-char ops, as ">" are not tokenized. "_x <= 0" { T_OPEN_TAG "< ?" } { T_STRING "_x" } { T_WHITESPACE " " } { T_IS_SMALLER_OR_EQUAL "<=" } { T_WHITESPACE " " } { T_LNUMBER "0" } { T_CLOSE_TAG "?>" } - */ - } else { - // Detect illegal characters besides nums, words and ops. - // So attribute names can not be utf-8 - $c = "/([^\d\w.,\s".preg_quote(join("",$this->_allowed_operators),"/")."])/"; - if (preg_match($c, $query, $m)) { - trigger_error("Illegal character in query: ".$m[1], E_USER_WARNING); - return ''; - } - } - return $query; + */ + } else { + // Detect illegal characters besides nums, words and ops. + // So attribute names can not be utf-8 + $c = "/([^\d\w.,\s".preg_quote(join("",$this->_allowed_operators),"/")."])/"; + if (preg_match($c, $query, $m)) { + trigger_error("Illegal character in query: ".$m[1], E_USER_WARNING); + return ''; + } + } + return $query; } /** @@ -495,8 +495,8 @@ class NumericSearchQuery * "4560000 < 20000 and 1456022 > 1000000" */ function _live_check () { - // TODO: check $this->_workquery again? - return !empty($this->_workquery); + // TODO: check $this->_workquery again? + return !empty($this->_workquery); } /** @@ -505,12 +505,12 @@ class NumericSearchQuery * @return array The names as array of strings. => ('x', 'y') the placeholders. */ function getVars() { - if(is_array($this->_placeholders)) return $this->_placeholders; - else return array($this->_placeholders); + if(is_array($this->_placeholders)) return $this->_placeholders; + else return array($this->_placeholders); } /** - * Strip non-numeric chars from the variable (as the groupseperator) and replace + * Strip non-numeric chars from the variable (as the groupseperator) and replace * it in the symbolic query for evaluation. * * @access private @@ -519,23 +519,23 @@ class NumericSearchQuery * @return string */ function _bind($value, $x) { - // TODO: check is_number, is_float, is_integer and do casting - $this->_bound[] = array('linkname' => $x, - 'linkvalue' => $value); - $value = preg_replace("/[^-+0123456789.,]/", "", $value); - //$c = "/\b".preg_quote($x,"/")."\b/"; - $this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery); - // FIXME: do again a final check. now only numbers and some operators are allowed. - return $this->_workquery; + // TODO: check is_number, is_float, is_integer and do casting + $this->_bound[] = array('linkname' => $x, + 'linkvalue' => $value); + $value = preg_replace("/[^-+0123456789.,]/", "", $value); + //$c = "/\b".preg_quote($x,"/")."\b/"; + $this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery); + // FIXME: do again a final check. now only numbers and some operators are allowed. + return $this->_workquery; } - + /* array of successfully bound vars, and in case of success, the resulting vars */ function _bound() { - return $this->_bound; + return $this->_bound; } - /** + /** * With an array of placeholders we need a hash to check against, if all required names are given. * Purpose: Be silent about missing vars, just return false. `* @@ -545,20 +545,20 @@ class NumericSearchQuery * @return boolean */ function can_match(&$variables) { - if (empty($this->_query)) - return false; - $p =& $this->_placeholders; - if (!is_array($variables) and !is_array($p)) - return $variables == $p; // This was easy. - // Check if all placeholders have definitions. can be overdefined but not underdefined. - if (!is_array($p)) { - if (!isset($variables[$p])) return false; - } else { - foreach ($p as $x) { - if (!isset($variables[$x])) return false; - } - } - return true; + if (empty($this->_query)) + return false; + $p =& $this->_placeholders; + if (!is_array($variables) and !is_array($p)) + return $variables == $p; // This was easy. + // Check if all placeholders have definitions. can be overdefined but not underdefined. + if (!is_array($p)) { + if (!isset($variables[$p])) return false; + } else { + foreach ($p as $x) { + if (!isset($variables[$x])) return false; + } + } + return true; } /** @@ -571,36 +571,36 @@ class NumericSearchQuery * @return boolean */ function match(&$variable) { - $p =& $this->_placeholders; - $this->_workquery = $this->_query; - if (!is_array($p)) { - if (is_array($variable)) { // which var to match? we cannot decide this here - if (!isset($variable[$p])) - trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR); - $this->_bind($variable[$p], $p); - } else { - $this->_bind($variable, $p); - } - } else { - foreach ($p as $x) { - if (!isset($variable[$x])) - trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR); - $this->_bind($variable[$x], $x); - } - } - if (!$this->_live_check()) // check returned an error - return false; - $search = $this->_workquery; - $result = false; - //if (DEBUG & _DEBUG_VERBOSE) - // trigger_error("\$result = (boolean)($search);", E_USER_NOTICE); - // We might have a numerical problem: - // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false; - // php-5.1.2 cgi true, 4.2.2 cgi true - eval("\$result = (boolean)($search);"); - if ($result and is_array($p)) { - return $this->_bound(); - } + $p =& $this->_placeholders; + $this->_workquery = $this->_query; + if (!is_array($p)) { + if (is_array($variable)) { // which var to match? we cannot decide this here + if (!isset($variable[$p])) + trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR); + $this->_bind($variable[$p], $p); + } else { + $this->_bind($variable, $p); + } + } else { + foreach ($p as $x) { + if (!isset($variable[$x])) + trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR); + $this->_bind($variable[$x], $x); + } + } + if (!$this->_live_check()) // check returned an error + return false; + $search = $this->_workquery; + $result = false; + //if (DEBUG & _DEBUG_VERBOSE) + // trigger_error("\$result = (boolean)($search);", E_USER_NOTICE); + // We might have a numerical problem: + // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false; + // php-5.1.2 cgi true, 4.2.2 cgi true + eval("\$result = (boolean)($search);"); + if ($result and is_array($p)) { + return $this->_bound(); + } return $result; } } @@ -647,7 +647,7 @@ class TextSearchQuery_node function sql() { return $this->word; } function _sql_quote() { - global $request; + global $request; $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word); return $request->_dbi->_backend->qstr($word); } @@ -661,7 +661,7 @@ extends TextSearchQuery_node { var $op = "WORD"; var $_op = TSQ_TOK_WORD; - + function TextSearchQuery_node_word($word) { $this->word = $word; } @@ -756,7 +756,7 @@ extends TextSearchQuery_node { var $op = "NOT"; var $_op = TSQ_TOK_NOT; - + function TextSearchQuery_node_not($leaf) { $this->leaves = array($leaf); } @@ -768,7 +768,7 @@ extends TextSearchQuery_node return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x return $this; } - + function regexp() { $leaf = &$this->leaves[0]; return '(?!' . $leaf->regexp() . ')'; @@ -828,7 +828,7 @@ class TextSearchQuery_node_and extends TextSearchQuery_node_binop { var $op = "AND"; - + function optimize() { $this->_flatten(); @@ -851,7 +851,7 @@ extends TextSearchQuery_node_binop (new TextSearchQuery_node_or($nots)) ); array_unshift($this->leaves, $node->optimize()); } - + assert(!empty($this->leaves)); if (count($this->leaves) == 1) return $this->leaves[0]; // (AND x) -> x @@ -882,7 +882,7 @@ extends TextSearchQuery_node_binop function regexp() { // We will combine any of our direct descendents which are WORDs // into a single (?=.*(?:word1|word2|...)) regexp. - + $regexps = array(); $words = array(); @@ -917,39 +917,39 @@ extends TextSearchQuery_node_binop // op's (and, or, not) are forced to lowercase in the tokenizer. // //////////////////////////////////////////////////////////////// -class TextSearchQuery_Parser +class TextSearchQuery_Parser { /* * This is a simple recursive descent parser, based on the following grammar: * - * toplist : - * | toplist expr - * ; + * toplist : + * | toplist expr + * ; * * - * list : expr - * | list expr - * ; + * list : expr + * | list expr + * ; * - * expr : atom - * | expr BINOP atom - * ; + * expr : atom + * | expr BINOP atom + * ; * - * atom : '(' list ')' - * | NOT atom - * | WORD - * ; + * atom : '(' list ')' + * | NOT atom + * | WORD + * ; * * The terminal tokens are: * * - * and|or BINOP - * -|not NOT - * ( LPAREN - * ) RPAREN + * and|or BINOP + * -|not NOT + * ( LPAREN + * ) RPAREN * /[^-()\s][^()\s]* WORD - * /"[^"]*"/ WORD - * /'[^']*'/ WORD + * /"[^"]*"/ WORD + * /'[^']*'/ WORD * * ^WORD TextSearchQuery_phrase_starts_with * WORD* STARTS_WITH @@ -968,7 +968,7 @@ class TextSearchQuery_Parser unset($this->lexer); return $tree; } - + function get_list ($is_toplevel = false) { $list = array(); @@ -977,10 +977,10 @@ class TextSearchQuery_Parser $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP; if ($is_toplevel) $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN; - + while ( ($expr = $this->get_expr()) || ($expr = $this->get_word($accept_as_words)) ) - { + { $list[] = $expr; } @@ -1002,14 +1002,14 @@ class TextSearchQuery_Parser function get_expr () { if ( ($expr = $this->get_atom()) === false ) // protect against '0' return false; - + $savedpos = $this->lexer->tell(); // Bug#1791564: allow string '0' while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) !== false) { if ( ! ($right = $this->get_atom()) ) { break; } - + if ($op == 'and') $expr = new TextSearchQuery_node_and(array($expr, $right)); else { @@ -1023,7 +1023,7 @@ class TextSearchQuery_Parser return $expr; } - + function get_atom() { if ($atom = $this->get_word(TSQ_ALLWORDS)) // Bug#1791564 not involved: '*' @@ -1034,9 +1034,9 @@ class TextSearchQuery_Parser if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) ) { return $list; } else { - // Fix Bug#1792170 + // Fix Bug#1792170 // Handle " ( " or "(test" without closing ")" as plain word - $this->lexer->seek($savedpos); + $this->lexer->seek($savedpos); return new TextSearchQuery_node_word($this->lexer->get(-1)); } } @@ -1049,23 +1049,23 @@ class TextSearchQuery_Parser } function get_word($accept = TSQ_ALLWORDS) { - // Performance shortcut for ( and ). This is always false - if (!empty($this->lexer->tokens[$this->lexer->pos])) { - list ($type, $val) = $this->lexer->tokens[$this->lexer->pos]; - if ($type == TSQ_TOK_LPAREN or $type == TSQ_TOK_RPAREN) - return false; - } + // Performance shortcut for ( and ). This is always false + if (!empty($this->lexer->tokens[$this->lexer->pos])) { + list ($type, $val) = $this->lexer->tokens[$this->lexer->pos]; + if ($type == TSQ_TOK_LPAREN or $type == TSQ_TOK_RPAREN) + return false; + } foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT", "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) { $const = constant("TSQ_TOK_".$tok); // Bug#1791564: allow word '0' - if ( $accept & $const and + if ( $accept & $const and (($word = $this->lexer->get($const)) !== false)) { // phrase or word level? if ($tok == 'STARTS_WITH' and $this->lexer->query_str[0] == '^') $classname = "TextSearchQuery_phrase_".strtolower($tok); - elseif ($tok == 'ENDS_WITH' and + elseif ($tok == 'ENDS_WITH' and string_ends_with($this->lexer->query_str,'$')) $classname = "TextSearchQuery_phrase_".strtolower($tok); else @@ -1078,8 +1078,8 @@ class TextSearchQuery_Parser } class TextSearchQuery_Lexer { - function TextSearchQuery_Lexer ($query_str, $case_exact=false, - $regex=TSQ_REGEX_AUTO) + function TextSearchQuery_Lexer ($query_str, $case_exact=false, + $regex=TSQ_REGEX_AUTO) { $this->tokens = $this->tokenize($query_str, $case_exact, $regex); $this->query_str = $query_str; @@ -1097,7 +1097,7 @@ class TextSearchQuery_Lexer { function eof() { return $this->pos == count($this->tokens); } - + /** * TODO: support more regex styles, esp. prefer the forced ones over auto * re: and // stuff @@ -1128,7 +1128,7 @@ class TextSearchQuery_Lexer { $val = "%"; $type = TSQ_TOK_ALL; } - + // ^word elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE) and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) { @@ -1167,7 +1167,7 @@ class TextSearchQuery_Lexer { $val = strtolower($m[1]); $type = TSQ_TOK_NOT; } - + // "words " elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) { $val = str_replace('""', '"', $m[1]); @@ -1191,27 +1191,27 @@ class TextSearchQuery_Lexer { /* refine the simple parsing from above: bla*bla, bla?bla, ... if ($regex and $type == TSQ_TOK_WORD) { - if (substr($val,0,1) == "^") - $type = TSQ_TOK_STARTS_WITH; - elseif (substr($val,0,1) == "*") - $type = TSQ_TOK_ENDS_WITH; - elseif (substr($val,-1,1) == "*") - $type = TSQ_TOK_STARTS_WITH; + if (substr($val,0,1) == "^") + $type = TSQ_TOK_STARTS_WITH; + elseif (substr($val,0,1) == "*") + $type = TSQ_TOK_ENDS_WITH; + elseif (substr($val,-1,1) == "*") + $type = TSQ_TOK_STARTS_WITH; } */ $tokens[] = array($type, $val); } return $tokens; } - + function get($accept) { if ($this->pos >= count($this->tokens)) return false; - + list ($type, $val) = $this->tokens[$this->pos]; if (($type & $accept) == 0) return false; - + $this->pos++; return $val; } @@ -1223,5 +1223,5 @@ class TextSearchQuery_Lexer { // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/Units.php b/lib/Units.php index 4a30b2714..5d23741ed 100644 --- a/lib/Units.php +++ b/lib/Units.php @@ -8,7 +8,7 @@ * $ units "372.0 mi2" m^2 * Definition: 9.6347558e+08 m^2 * - * Called by: + * Called by: * CachedMarkup.php: Cached_SemanticLink::_expandurl() * SemanticWeb.php: class SemanticAttributeSearchQuery * @@ -23,57 +23,57 @@ class Units { function Units ($UNITSFILE = false) { - if (DISABLE_UNITS) - $this->errcode = 1; - elseif (defined("UNITS_EXE")) // ignore dynamic check - $this->errcode = 0; - else - exec("units m2", $o, $this->errcode); + if (DISABLE_UNITS) + $this->errcode = 1; + elseif (defined("UNITS_EXE")) // ignore dynamic check + $this->errcode = 0; + else + exec("units m2", $o, $this->errcode); } /** * $this->_attribute_base = $units->Definition($this->_attribute); */ function Definition ($query) { - static $Definitions = array(); - if (isset($Definitions[$query])) return $Definitions[$query]; - if ($this->errcode) + static $Definitions = array(); + if (isset($Definitions[$query])) return $Definitions[$query]; + if ($this->errcode) return $query; - $query = preg_replace("/,/","", $query); - if ($query == '' or $query == '*') - return ($Definitions[$query] = ''); - // detect date values, currently only ISO: YYYY-MM-DD or YY-MM-DD - if (preg_match("/^(\d{2,4})-(\d{1,2})-(\d{1,2})$/",$query, $m)) { - $date = mktime(0,0,0,$m[2],$m[3],$m[1]); - return ($Definitions[$query] = "$date date"); - } - if (preg_match("/^(\d{2,4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{2}):?(\d{2})?$/",$query, $m)) { - $date = mktime($m[4],$m[5],@$m[6],$m[2],$m[3],$m[1]); - return ($Definitions[$query] = "$date date"); - } - $def = $this->_cmd("\"$query\""); - if (preg_match("/Definition: (.+)$/",$def,$m)) - return ($Definitions[$query] = $m[1]); - else { - trigger_error("units: ". $def, E_USER_WARNING); - return ''; - } + $query = preg_replace("/,/","", $query); + if ($query == '' or $query == '*') + return ($Definitions[$query] = ''); + // detect date values, currently only ISO: YYYY-MM-DD or YY-MM-DD + if (preg_match("/^(\d{2,4})-(\d{1,2})-(\d{1,2})$/",$query, $m)) { + $date = mktime(0,0,0,$m[2],$m[3],$m[1]); + return ($Definitions[$query] = "$date date"); + } + if (preg_match("/^(\d{2,4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{2}):?(\d{2})?$/",$query, $m)) { + $date = mktime($m[4],$m[5],@$m[6],$m[2],$m[3],$m[1]); + return ($Definitions[$query] = "$date date"); + } + $def = $this->_cmd("\"$query\""); + if (preg_match("/Definition: (.+)$/",$def,$m)) + return ($Definitions[$query] = $m[1]); + else { + trigger_error("units: ". $def, E_USER_WARNING); + return ''; + } } /** - * We must ensure that the same baseunits are matched against. + * We must ensure that the same baseunits are matched against. * We cannot compare m^2 to m or '' * $val_base = $this->_units->basevalue($value); // SemanticAttributeSearchQuery */ function basevalue($query, $def = false) { - if (!$def) $def = $this->Definition($query); - if ($def) { - if (is_numeric($def)) // e.g. "1 million" - return $def; - if (preg_match("/^([-0-9].*) \w.*$/",$def,$m)) - return $m[1]; - } - return ''; + if (!$def) $def = $this->Definition($query); + if ($def) { + if (is_numeric($def)) // e.g. "1 million" + return $def; + if (preg_match("/^([-0-9].*) \w.*$/",$def,$m)) + return $m[1]; + } + return ''; } /** @@ -81,22 +81,22 @@ class Units { * and Cached_SemanticLink::_expandurl() */ function baseunit($query, $def = false) { - if (!$def) $def = $this->Definition($query); - if ($def) { - if (preg_match("/ (.+)$/",$def,$m)) - return $m[1]; - } - return ''; + if (!$def) $def = $this->Definition($query); + if ($def) { + if (preg_match("/ (.+)$/",$def,$m)) + return $m[1]; + } + return ''; } function _cmd($args) { - if ($this->errcode) return $args; - if (defined("UNITS_EXE")) { - $s = UNITS_EXE ." $args"; - $result = `$s`; - } - else - $result = `units $args`; - return trim($result); + if ($this->errcode) return $args; + if (defined("UNITS_EXE")) { + $s = UNITS_EXE ." $args"; + $result = `$s`; + } + else + $result = `units $args`; + return trim($result); } } diff --git a/lib/WikiCallback.php b/lib/WikiCallback.php index 14576207f..f1a1ab44b 100644 --- a/lib/WikiCallback.php +++ b/lib/WikiCallback.php @@ -36,7 +36,7 @@ class WikiCallback } trigger_error("WikiCallback::new: bad arg", E_USER_ERROR); } - + /** * Call callback. * @@ -161,5 +161,5 @@ class WikiAnonymousCb // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/WikiDB.php b/lib/WikiDB.php index dc3a7e725..456fda895 100644 --- a/lib/WikiDB.php +++ b/lib/WikiDB.php @@ -17,7 +17,7 @@ require_once('lib/PageType.php'); if (!defined('WIKIDB_FORCE_CREATE')) define('WIKIDB_FORCE_CREATE', -1); -/** +/** * Abstract base class for the database used by PhpWiki. * * A WikiDB is a container for WikiDB_Pages which in @@ -62,7 +62,7 @@ class WikiDB { *
dba *
Dba based backend. The default and by far the fastest. *
cvs - *
+ *
*
file *
flat files * @@ -79,9 +79,9 @@ class WikiDB { * Which directory db files reside in. * *
timeout - *
Used only by the dba backend so far. + *
Used only by the dba backend so far. * And: When optimizing mysql it closes timed out mysql processes. - * otherwise only used for dba: Timeout in seconds for opening (and + * otherwise only used for dba: Timeout in seconds for opening (and * obtaining lock) on the dbm file. * *
dba_handler @@ -100,7 +100,7 @@ class WikiDB { function open ($dbparams) { $dbtype = $dbparams{'dbtype'}; include_once("lib/WikiDB/$dbtype.php"); - + $class = 'WikiDB_' . $dbtype; return new $class ($dbparams); } @@ -116,22 +116,22 @@ class WikiDB { $this->_backend =& $backend; // don't do the following with the auth_dsn! if (isset($dbparams['auth_dsn'])) return; - + $this->_cache = new WikiDB_cache($backend); if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this; // If the database doesn't yet have a timestamp, initialize it now. if ($this->get('_timestamp') === false) $this->touch(); - + // devel checking. if ((int)DEBUG & _DEBUG_SQL) { $this->_backend->check(); - } + } // might be changed when opening the database fails $this->readonly = defined("READONLY") ? READONLY : false; } - + /** * Close database connection. * @@ -147,7 +147,7 @@ class WikiDB { $this->_backend->close(); $this->_cache->close(); } - + /** * Get a WikiDB_Page from a WikiDB. * @@ -202,12 +202,12 @@ class WikiDB { } /** - * Delete page from the WikiDB. + * Delete page from the WikiDB. * * Deletes the page from the WikiDB with the possibility to revert and diff. * //Also resets all page meta-data to the default values. * - * Note: purgePage() effectively destroys all revisions of the page from the WikiDB. + * Note: purgePage() effectively destroys all revisions of the page from the WikiDB. * * @access public * @param string $pagename Name of page to delete. @@ -215,10 +215,10 @@ class WikiDB { */ function deletePage($pagename) { if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } - // don't create empty revisions of already purged pages. + // don't create empty revisions of already purged pages. if ($this->_backend->get_latest_version($pagename)) $result = $this->_cache->delete_page($pagename); - else + else $result = -1; /* Generate notification emails */ @@ -252,7 +252,7 @@ class WikiDB { $this->deletePage($pagename); // just for the notification return $result; } - + /** * Retrieve all pages. * @@ -264,21 +264,21 @@ class WikiDB { * recent revision has empty content are considered to be * non-existant. Unless $include_defaulted is set to true, those * pages will not be returned. - * @param string or false $sortby Optional. "+-column,+-column2". - * If false the result is faster in natural order. + * @param string or false $sortby Optional. "+-column,+-column2". + * If false the result is faster in natural order. * @param string or false $limit Optional. Encoded as "$offset,$count". - * $offset defaults to 0. - * @param string $exclude: Optional comma-seperated list of pagenames. + * $offset defaults to 0. + * @param string $exclude: Optional comma-seperated list of pagenames. * * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages * in the WikiDB which have non-default contents. */ - function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='') + function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='') { - $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit, + $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit, $exclude); - return new WikiDB_PageIterator($this, $result, - array('include_empty' => $include_empty, + return new WikiDB_PageIterator($this, $result, + array('include_empty' => $include_empty, 'exclude' => $exclude, 'limit_by_db' => $result->_options['limit_by_db'], 'limit' => $result->limit())); @@ -288,13 +288,13 @@ class WikiDB { * @access public * * @param boolean $include_empty If true include also empty pages - * @param string $exclude: comma-seperated list of pagenames. - * TBD: array of pagenames + * @param string $exclude: comma-seperated list of pagenames. + * TBD: array of pagenames * @return integer - * + * */ function numPages($include_empty=false, $exclude='') { - if (method_exists($this->_backend, 'numPages')) + if (method_exists($this->_backend, 'numPages')) // FIXME: currently are all args ignored. $count = $this->_backend->numPages($include_empty, $exclude); else { @@ -305,7 +305,7 @@ class WikiDB { } return (int)$count; } - + /** * Title search. * @@ -318,11 +318,11 @@ class WikiDB { * * @access public * @param TextSearchQuery $search A TextSearchQuery object - * @param string or false $sortby Optional. "+-column,+-column2". - * If false the result is faster in natural order. + * @param string or false $sortby Optional. "+-column,+-column2". + * If false the result is faster in natural order. * @param string or false $limit Optional. Encoded as "$offset,$count". - * $offset defaults to 0. - * @param string $exclude: Optional comma-seperated list of pagenames. + * $offset defaults to 0. + * @param string $exclude: Optional comma-seperated list of pagenames. * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages. * @see TextSearchQuery */ @@ -348,11 +348,11 @@ class WikiDB { * @access public * * @param TextSearchQuery $search A TextSearchQuery object. - * @param string or false $sortby Optional. "+-column,+-column2". - * If false the result is faster in natural order. + * @param string or false $sortby Optional. "+-column,+-column2". + * If false the result is faster in natural order. * @param string or false $limit Optional. Encoded as "$offset,$count". - * $offset defaults to 0. - * @param string $exclude: Optional comma-seperated list of pagenames. + * $offset defaults to 0. + * @param string $exclude: Optional comma-seperated list of pagenames. * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages. * @see TextSearchQuery */ @@ -375,8 +375,8 @@ class WikiDB { * @param integer $limit The maximum number of pages to return. * Set $limit to zero to return all pages. If $limit < 0, pages will * be sorted in decreasing order of popularity. - * @param string or false $sortby Optional. "+-column,+-column2". - * If false the result is faster in natural order. + * @param string or false $sortby Optional. "+-column,+-column2". + * If false the result is faster in natural order. * * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching * pages. @@ -396,11 +396,11 @@ class WikiDB { * @param hash $params This hash is used to specify various optional * parameters: *
- *
limit + *
limit *
(integer) At most this many revisions will be returned. *
since - *
(integer) Only revisions since this time (unix-timestamp) - * will be returned. + *
(integer) Only revisions since this time (unix-timestamp) + * will be returned. *
include_minor_revisions *
(boolean) Also include minor revisions. (Default is not to.) *
exclude_major_revisions @@ -412,7 +412,7 @@ class WikiDB { * for each page. *
* - * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator + * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator * containing the matching revisions. */ function mostRecent($params = false) { @@ -423,12 +423,12 @@ class WikiDB { /** * @access public * - * @param string or false $sortby Optional. "+-column,+-column2". - * If false the result is faster in natural order. + * @param string or false $sortby Optional. "+-column,+-column2". + * If false the result is faster in natural order. * @param string or false $limit Optional. Encoded as "$offset,$count". - * $offset defaults to 0. - * @return Iterator A generic iterator containing rows of - * (duplicate) pagename, wantedfrom. + * $offset defaults to 0. + * @return Iterator A generic iterator containing rows of + * (duplicate) pagename, wantedfrom. */ function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') { return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit); @@ -436,7 +436,7 @@ class WikiDB { } /** - * Generic interface to the link table. Esp. useful to search for rdf triples as in + * Generic interface to the link table. Esp. useful to search for rdf triples as in * SemanticSearch and ListRelations. * * @access public @@ -451,22 +451,22 @@ class WikiDB { *
"linkfrom" *
in-links, i.e BackLinks *
"relation" - *
the first part in a <>::<> link + *
the first part in a <>::<> link *
"attribute" - *
the first part in a <>:=<> link + *
the first part in a <>:=<> link * - * @param $relation object An optional TextSearchQuery to match the + * @param $relation object An optional TextSearchQuery to match the * relation name. Ignored on simple in-out links. * * @return Iterator A generic iterator containing links to pages or values. - * hash of "pagename", "linkname", "linkvalue. + * hash of "pagename", "linkname", "linkvalue. */ function linkSearch($pages, $search, $linktype, $relation=false) { return $this->_backend->link_search($pages, $search, $linktype, $relation); } /** - * Return a simple list of all defined relations (and attributes), mainly + * Return a simple list of all defined relations (and attributes), mainly * for the SemanticSearch autocompletion. * * @access public @@ -476,24 +476,24 @@ class WikiDB { function listRelations($also_attributes=false, $only_attributes=false, $sorted=true) { if (method_exists($this->_backend, "list_relations")) return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted); - // dumb, slow fallback. no iter, so simply define it here. + // dumb, slow fallback. no iter, so simply define it here. $relations = array(); $iter = $this->getAllPages(); while ($page = $iter->next()) { $reliter = $page->getRelations(); $names = array(); while ($rel = $reliter->next()) { - // if there's no pagename it's an attribute + // if there's no pagename it's an attribute $names[] = $rel->getName(); } $relations = array_merge($relations, $names); $reliter->free(); } $iter->free(); - if ($sorted) { - sort($relations); - reset($relations); - } + if ($sorted) { + sort($relations); + reset($relations); + } return $relations; } @@ -517,27 +517,27 @@ class WikiDB { //update all WikiLinks in existing pages //non-atomic! i.e. if rename fails the links are not undone if ($updateWikiLinks) { - $lookbehind = "/(?<=[\W:])\Q"; - $lookahead = "\E(?=[\W:])/"; + $lookbehind = "/(?<=[\W:])\Q"; + $lookahead = "\E(?=[\W:])/"; require_once('lib/plugin/WikiAdminSearchReplace.php'); $links = $oldpage->getBackLinks(); while ($linked_page = $links->next()) { WikiPlugin_WikiAdminSearchReplace::replaceHelper - ($this, - $linked_page->getName(), - $lookbehind.$from.$lookahead, $to, - true, true); + ($this, + $linked_page->getName(), + $lookbehind.$from.$lookahead, $to, + true, true); } - // FIXME: Disabled to avoid recursive modification when renaming + // FIXME: Disabled to avoid recursive modification when renaming // a page like 'PageFoo to 'PageFooTwo' if (0) { $links = $newpage->getBackLinks(); while ($linked_page = $links->next()) { WikiPlugin_WikiAdminSearchReplace::replaceHelper - ($this, - $linked_page->getName(), - $lookbehind.$from.$lookahead, $to, - true, true); + ($this, + $linked_page->getName(), + $lookbehind.$from.$lookahead, $to, + true, true); } } } @@ -549,7 +549,7 @@ class WikiDB { $meta = $current->_data; $version = $current->getVersion(); $meta['summary'] = sprintf(_("renamed from %s"), $from); - unset($meta['mtime']); // force new date + unset($meta['mtime']); // force new date $page->save($current->getPackedContent(), $version + 1, $meta); } } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) { @@ -587,7 +587,7 @@ class WikiDB { $ts = $this->get('_timestamp'); return sprintf("%d %d", $ts[0], $ts[1]); } - + /** * Update the database timestamp. * @@ -606,7 +606,7 @@ class WikiDB { function set_db_version($ver) { return $this->set('_db_version', (float)$ver); } - + /** * Access WikiDB global meta-data. * @@ -656,7 +656,7 @@ class WikiDB { if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } if (!$key || $key[0] == '%') return; - + $gd = $this->getPage('global_data'); $data = $gd->get('__global'); if ($data === false) @@ -691,7 +691,7 @@ class WikiDB { trigger_error("no SQL database", E_USER_ERROR); return false; } - + // see backend upstream methods // ADODB adds surrounding quotes, SQL not yet! function quote ($s) { @@ -701,7 +701,7 @@ class WikiDB { function isOpen () { global $request; if (!$request->_dbi) return false; - else return false; /* so far only needed for sql so false it. + else return false; /* so far only needed for sql so false it. later we have to check dba also */ } @@ -729,7 +729,7 @@ class WikiDB { * A WikiDB_Page contains a number (at least one) of * WikiDB_PageRevisions. */ -class WikiDB_Page +class WikiDB_Page { function WikiDB_Page(&$wikidb, $pagename) { $this->_wikidb = &$wikidb; @@ -759,9 +759,9 @@ class WikiDB_Page function getName() { return $this->_pagename; } - + // To reduce the memory footprint for larger sets of pagelists, - // we don't cache the content (only true or false) and + // we don't cache the content (only true or false) and // we purge the pagedata (_cached_html) also function exists() { if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true; @@ -876,13 +876,13 @@ class WikiDB_Page $backend->unlock(array('version')); } - + /** * Create a new revision of a {@link WikiDB_Page}. * * @access public * - * @param int $version Version number for new revision. + * @param int $version Version number for new revision. * To ensure proper serialization of edits, $version must be * exactly one higher than the current latest version. * (You can defeat this check by setting $version to @@ -904,7 +904,7 @@ class WikiDB_Page $cache = &$this->_wikidb->_cache; $pagename = &$this->_pagename; $cache->invalidate_cache($pagename); - + $backend->lock(array('version','page','recent','link','nonempty')); $latestversion = $backend->get_latest_version($pagename); @@ -917,16 +917,16 @@ class WikiDB_Page } $data = $metadata; - + foreach ($data as $key => $val) { if (empty($val) || $key[0] == '_' || $key[0] == '%') unset($data[$key]); } - + assert(!empty($data['author'])); if (empty($data['author_id'])) @$data['author_id'] = $data['author']; - + if (empty($data['mtime'])) $data['mtime'] = time(); @@ -940,9 +940,9 @@ class WikiDB_Page $data['orig_mtime'] = $data['mtime']; $data['mtime'] = $pdata['mtime']; } - - // FIXME: use (possibly user specified) 'mtime' time or - // time()? + + // FIXME: use (possibly user specified) 'mtime' time or + // time()? $cache->update_versiondata($pagename, $latestversion, array('_supplanted' => $data['mtime'])); } @@ -953,7 +953,7 @@ class WikiDB_Page //$cache->update_pagedata($pagename, array(':latestversion' => $newversion, //':deleted' => empty($content))); - + $backend->set_links($pagename, $links); $backend->unlock(array('version','page','recent','link','nonempty')); @@ -969,7 +969,7 @@ class WikiDB_Page * * @param string $wikitext The page content. * - * @param int $version Version number for new revision. + * @param int $version Version number for new revision. * To ensure proper serialization of edits, $version must be * exactly one higher than the current latest version. * (You can defeat this check by setting $version to @@ -979,11 +979,11 @@ class WikiDB_Page */ function save($wikitext, $version, $meta, $formatted = null) { if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; } - if (is_null($formatted)) - $formatted = new TransformedText($this, $wikitext, $meta); + if (is_null($formatted)) + $formatted = new TransformedText($this, $wikitext, $meta); $type = $formatted->getType(); - $meta['pagetype'] = $type->getName(); - $links = $formatted->getWikiPageLinks(); // linkto => relation + $meta['pagetype'] = $type->getName(); + $links = $formatted->getWikiPageLinks(); // linkto => relation $attributes = array(); foreach ($links as $link) { if ($link['linkto'] === "" and !empty($link['relation'])) { @@ -992,18 +992,18 @@ class WikiDB_Page } $meta['attribute'] = $attributes; - $backend = &$this->_wikidb->_backend; - $newrevision = $this->createRevision($version, $wikitext, $meta, $links); - if ($newrevision and !WIKIDB_NOCACHE_MARKUP) + $backend = &$this->_wikidb->_backend; + $newrevision = $this->createRevision($version, $wikitext, $meta, $links); + if ($newrevision and !WIKIDB_NOCACHE_MARKUP) $this->set('_cached_html', $formatted->pack()); - // FIXME: probably should have some global state information - // in the backend to control when to optimize. + // FIXME: probably should have some global state information + // in the backend to control when to optimize. // // We're doing this here rather than in createRevision because // postgresql can't optimize while locked. if (((int)DEBUG & _DEBUG_SQL) - or (DATABASE_OPTIMISE_FREQUENCY > 0 and + or (DATABASE_OPTIMISE_FREQUENCY > 0 and (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) { if ($backend->optimize()) { if ((int)DEBUG) @@ -1015,20 +1015,20 @@ class WikiDB_Page if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) { // Save didn't fail because of concurrent updates. $notify = $this->_wikidb->get('notify'); - if (!empty($notify) - and is_array($notify) - and !isa($GLOBALS['request'],'MockRequest')) - { + if (!empty($notify) + and is_array($notify) + and !isa($GLOBALS['request'],'MockRequest')) + { include_once("lib/MailNotify.php"); $MailNotify = new MailNotify($newrevision->getName()); - $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta); + $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta); } $newrevision->_transformedContent = $formatted; } // more pagechange callbacks: (in a hackish manner for now) - if (ENABLE_RECENTCHANGESBOX + if (ENABLE_RECENTCHANGESBOX and empty($meta['is_minor_edit']) - and !in_array($GLOBALS['request']->getArg('action'), + and !in_array($GLOBALS['request']->getArg('action'), array('loadfile','upgrade'))) { require_once("lib/WikiPlugin.php"); @@ -1036,7 +1036,7 @@ class WikiDB_Page $p = $w->getPlugin("RecentChangesCached", false); $p->box_update(false, $GLOBALS['request'], $this->_pagename); } - return $newrevision; + return $newrevision; } /** @@ -1044,17 +1044,17 @@ class WikiDB_Page * * @access public * - * @return WikiDB_PageRevision The current WikiDB_PageRevision object. + * @return WikiDB_PageRevision The current WikiDB_PageRevision object. */ function getCurrentRevision ($need_content=true) { $backend = &$this->_wikidb->_backend; $cache = &$this->_wikidb->_cache; $pagename = &$this->_pagename; - + // Prevent deadlock in case of memory exhausted errors // Pure selection doesn't really need locking here. // sf.net bug#927395 - // I know it would be better to lock, but with lots of pages this deadlock is more + // I know it would be better to lock, but with lots of pages this deadlock is more // severe than occasionally get not the latest revision. // In spirit to wikiwiki: read fast, edit slower. //$backend->lock(); @@ -1080,7 +1080,7 @@ class WikiDB_Page function getRevision ($version, $need_content=true) { $cache = &$this->_wikidb->_cache; $pagename = &$this->_pagename; - + if (! $version or $version == -1) // 0 or false return new WikiDB_PageRevision($this->_wikidb, $pagename, 0); @@ -1142,11 +1142,11 @@ class WikiDB_Page $revs = $backend->get_all_revisions($this->_pagename); return new WikiDB_PageRevisionIterator($this->_wikidb, $revs); } - + /** * Find pages which link to or are linked from a page. - * relations: $backend->get_links is responsible to add the relation to the pagehash - * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next + * relations: $backend->get_links is responsible to add the relation to the pagehash + * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next * if (isset($next['linkrelation'])) * * @access public @@ -1156,17 +1156,17 @@ class WikiDB_Page * @return WikiDB_PageIterator A WikiDB_PageIterator containing * all matching pages. */ - function getLinks ($reversed=true, $include_empty=false, $sortby='', - $limit='', $exclude='', $want_relations=false) + function getLinks ($reversed=true, $include_empty=false, $sortby='', + $limit='', $exclude='', $want_relations=false) { $backend = &$this->_wikidb->_backend; - $result = $backend->get_links($this->_pagename, $reversed, + $result = $backend->get_links($this->_pagename, $reversed, $include_empty, $sortby, $limit, $exclude, $want_relations); - return new WikiDB_PageIterator($this->_wikidb, $result, + return new WikiDB_PageIterator($this->_wikidb, $result, array('include_empty' => $include_empty, - 'sortby' => $sortby, - 'limit' => $limit, + 'sortby' => $sortby, + 'limit' => $limit, 'exclude' => $exclude, 'want_relations'=> $want_relations)); } @@ -1174,37 +1174,37 @@ class WikiDB_Page /** * All Links from other pages to this page. */ - function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='', - $want_relations=false) + function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='', + $want_relations=false) { return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude); } /** * Forward Links: All Links from this page to other pages. */ - function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='', - $want_relations=false) + function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='', + $want_relations=false) { return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude); } /** - * Relations: All links from this page to other pages with relation <> 0. + * Relations: All links from this page to other pages with relation <> 0. * is_a:=page or population:=number */ function getRelations($sortby='', $limit='', $exclude='') { $backend = &$this->_wikidb->_backend; $result = $backend->get_links($this->_pagename, false, true, - $sortby, $limit, $exclude, + $sortby, $limit, $exclude, true); // we do not care for the linked page versiondata, just the pagename and linkrelation - return new WikiDB_PageIterator($this->_wikidb, $result, + return new WikiDB_PageIterator($this->_wikidb, $result, array('include_empty' => true, - 'sortby' => $sortby, - 'limit' => $limit, + 'sortby' => $sortby, + 'limit' => $limit, 'exclude' => $exclude, 'want_relations'=> true)); } - + /** * possibly faster link existance check. not yet accelerated. */ @@ -1229,11 +1229,11 @@ class WikiDB_Page => "At the page San Diego there is a relation link of 'is a' to the page 'city'." */ - /* Semantic attributes for a page. + /* Semantic attributes for a page. [San Diego] population:=1,305,736 Attributes are links with the relation pointing to another page. */ - + /** * Access WikiDB_Page non version-specific meta-data. * @@ -1251,7 +1251,7 @@ class WikiDB_Page *
'pref'
Users preferences, stored only in homepages. *
'owner'
Default: first author_id. We might add a group with a dot here: * E.g. "owner.users" - *
'perm'
Permission flag to authorize read/write/execution of + *
'perm'
Permission flag to authorize read/write/execution of * page-headers and content. +
'moderation'
ModeratedPage data. Handled by plugin/ModeratedPage *
'rating'
Page rating. Handled by plugin/RateIt @@ -1267,8 +1267,8 @@ class WikiDB_Page return false; // several new SQL backends optimize this. if (!WIKIDB_NOCACHE_MARKUP - and $key == '_cached_html' - and method_exists($backend, 'get_cached_html')) + and $key == '_cached_html' + and method_exists($backend, 'get_cached_html')) { return $backend->get_cached_html($this->_pagename); } @@ -1305,12 +1305,12 @@ class WikiDB_Page $cache = &$this->_wikidb->_cache; $backend = &$this->_wikidb->_backend; $pagename = &$this->_pagename; - + assert($key && $key[0] != '%'); // several new SQL backends optimize this. - if (!WIKIDB_NOCACHE_MARKUP - and $key == '_cached_html' + if (!WIKIDB_NOCACHE_MARKUP + and $key == '_cached_html' and method_exists($backend, 'set_cached_html')) { if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; } @@ -1411,7 +1411,7 @@ class WikiDB_Page for ($v=1; $v <= $latestversion; $v++) { $rev = $this->getRevision($v,false); if ($rev and $owner = $rev->get('author_id')) { - return $owner; + return $owner; } } return ''; @@ -1433,20 +1433,20 @@ class WikiDB_Page * todo: unify with some unit knowledge */ function setAttribute($relation, $value) { - $attr = $this->get('attributes'); - if (empty($attr)) - $attr = array($relation => $value); - else - $attr[$relation] = $value; - $this->set('attributes', $attr); + $attr = $this->get('attributes'); + if (empty($attr)) + $attr = array($relation => $value); + else + $attr[$relation] = $value; + $this->set('attributes', $attr); } function getAttribute($relation) { - $meta = $this->get('attributes'); - if (empty($meta)) - return ''; - else - return $meta[$relation]; + $meta = $this->get('attributes'); + if (empty($meta)) + return ''; + else + return $meta[$relation]; } }; @@ -1462,9 +1462,9 @@ class WikiDB_Page class WikiDB_PageRevision { //var $_transformedContent = false; // set by WikiDB_Page::save() - - function WikiDB_PageRevision(&$wikidb, $pagename, $version, - $versiondata = false) + + function WikiDB_PageRevision(&$wikidb, $pagename, $version, + $versiondata = false) { $this->_wikidb = &$wikidb; $this->_pagename = $pagename; @@ -1472,7 +1472,7 @@ class WikiDB_PageRevision $this->_data = $versiondata ? $versiondata : array(); $this->_transformedContent = false; // set by WikiDB_Page::save() } - + /** * Get the WikiDB_Page which this revision belongs to. * @@ -1494,7 +1494,7 @@ class WikiDB_PageRevision function getVersion() { return $this->_version; } - + /** * Determine whether this revision has defaulted content. * @@ -1527,7 +1527,7 @@ class WikiDB_PageRevision function getContent() { return explode("\n", $this->getPackedContent()); } - + /** * Get the pagename of the revision. * @@ -1567,18 +1567,18 @@ class WikiDB_PageRevision * contents. */ function getTransformedContent($pagetype_override=false) { - $backend = &$this->_wikidb->_backend; - - if ($pagetype_override) { - // Figure out the normal page-type for this page. + $backend = &$this->_wikidb->_backend; + + if ($pagetype_override) { + // Figure out the normal page-type for this page. $type = PageType::GetPageType($this->get('pagetype')); - if ($type->getName() == $pagetype_override) - $pagetype_override = false; // Not really an override... - } + if ($type->getName() == $pagetype_override) + $pagetype_override = false; // Not really an override... + } if ($pagetype_override) { // Overriden page type, don't cache (or check cache). - return new TransformedText($this->getPage(), + return new TransformedText($this->getPage(), $this->getPackedContent(), $this->getMetaData(), $pagetype_override); @@ -1590,7 +1590,7 @@ class WikiDB_PageRevision if (WIKIDB_NOCACHE_MARKUP == 'purge') { // flush cache for this page. $page = $this->getPage(); - $page->set('_cached_html', ''); // ignored with !USECACHE + $page->set('_cached_html', ''); // ignored with !USECACHE } $possibly_cache_results = false; } @@ -1604,14 +1604,14 @@ class WikiDB_PageRevision $possibly_cache_results = false; } //$backend->unlock(); - } - + } + if (!$this->_transformedContent) { $this->_transformedContent = new TransformedText($this->getPage(), $this->getPackedContent(), $this->getMetaData()); - + if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) { // If we're still the current version, cache the transfomed page. //$backend->lock(); @@ -1635,7 +1635,7 @@ class WikiDB_PageRevision */ function getPackedContent() { $data = &$this->_data; - + if (empty($data['%content']) || (!$this->_wikidb->isWikiPage($this->_pagename) && $this->isCurrent())) { @@ -1643,32 +1643,32 @@ class WikiDB_PageRevision // A feature similar to taglines at http://www.wlug.org.nz/ // Lib from http://www.aasted.org/quote/ - if (defined('FORTUNE_DIR') - and is_dir(FORTUNE_DIR) - and in_array($GLOBALS['request']->getArg('action'), + if (defined('FORTUNE_DIR') + and is_dir(FORTUNE_DIR) + and in_array($GLOBALS['request']->getArg('action'), array('create','edit'))) { include_once("lib/fortune.php"); $fortune = new Fortune(); - $quote = $fortune->quoteFromDir(FORTUNE_DIR); - if ($quote != -1) - $quote = "\n" - . str_replace("\n
","\n", $quote) - . "
\n\n"; - else - $quote = ""; + $quote = $fortune->quoteFromDir(FORTUNE_DIR); + if ($quote != -1) + $quote = "\n" + . str_replace("\n
","\n", $quote) + . "
\n\n"; + else + $quote = ""; return $quote - . sprintf(_("Describe %s here."), - "[" . WikiEscape($this->_pagename) . "]"); + . sprintf(_("Describe %s here."), + "[" . WikiEscape($this->_pagename) . "]"); } // Replace empty content with default value. - return sprintf(_("Describe %s here."), + return sprintf(_("Describe %s here."), "[" . WikiEscape($this->_pagename) . "]"); } // There is (non-default) content. assert($this->_version > 0); - + if (!is_string($data['%content'])) { // Content was not provided to us at init time. // (This is allowed because for some backends, fetching @@ -1679,7 +1679,7 @@ class WikiDB_PageRevision $data['%content'] = $this->_get_content(); assert(is_string($data['%content'])); } - + return $data['%content']; } @@ -1689,7 +1689,7 @@ class WikiDB_PageRevision $version = $this->_version; assert($version > 0); - + $newdata = $cache->get_versiondata($pagename, $version, true); if ($newdata) { assert(is_string($newdata['%content'])); @@ -1764,8 +1764,8 @@ class WikiDB_PageRevision } return $meta; } - - + + /** * Return a string representation of the revision. * @@ -1790,7 +1790,7 @@ class WikiDB_PageRevision /** * Class representing a sequence of WikiDB_Pages. * TODO: Enhance to php5 iterators - * TODO: + * TODO: * apply filters for options like 'sortby', 'limit', 'exclude' * for simple queries like titleSearch, where the backend is not ready yet. */ @@ -1801,7 +1801,7 @@ class WikiDB_PageIterator $this->_wikidb = &$wikidb; $this->_options = $options; } - + function count () { return $this->_iter->count(); } @@ -1821,25 +1821,25 @@ class WikiDB_PageIterator return false; $pagename = &$next['pagename']; - if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous - /*if (is_array($pagename) && isset($pagename['linkto'])) { - $pagename = $pagename['linkto']; - } + if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous + /*if (is_array($pagename) && isset($pagename['linkto'])) { + $pagename = $pagename['linkto']; + } $pagename = strval($pagename);*/ trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING); - } + } if (!$pagename) { - if (isset($next['linkrelation']) - or isset($next['pagedata']['linkrelation'])) return false; + if (isset($next['linkrelation']) + or isset($next['pagedata']['linkrelation'])) return false; trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING); var_dump($next); return false; } - // There's always hits, but we cache only if more + // There's always hits, but we cache only if more // (well not with file, cvs and dba) if (isset($next['pagedata']) and count($next['pagedata']) > 1) { $this->_wikidb->_cache->cache_data($next); - // cache existing page id's since we iterate over all links in GleanDescription + // cache existing page id's since we iterate over all links in GleanDescription // and need them later for LinkExistingWord } elseif ($this->_options and array_key_exists('include_empty', $this->_options) and !$this->_options['include_empty'] and isset($next['id'])) { @@ -1872,13 +1872,13 @@ class WikiDB_PageIterator $this->_iter->reset(); } function asArray() { - $result = array(); - while ($page = $this->next()) + $result = array(); + while ($page = $this->next()) $result[] = $page; $this->reset(); return $result; } - + /** * Apply filters for options like 'sortby', 'limit', 'exclude' * for simple queries like titleSearch, where the backend is not ready yet. @@ -1895,12 +1895,12 @@ class WikiDB_PageIterator $this->_doSort($array, $options['sortby']); } /* the rest is not destructive. - * reconstruct a new iterator + * reconstruct a new iterator */ $pagenames = array(); $i = 0; if (isset($options['limit'])) $limit = $options['limit']; - else + else $limit = 0; if (isset($options['exclude'])) $exclude = $options['exclude']; @@ -1940,7 +1940,7 @@ class WikiDB_PageRevisionIterator $this->_wikidb = &$wikidb; $this->_options = $options; } - + function count () { return $this->_revisions->count(); } @@ -1997,13 +1997,13 @@ class WikiDB_PageRevisionIterator * * @access public */ - function free() { + function free() { $this->_revisions->free(); } function asArray() { - $result = array(); - while ($rev = $this->next()) + $result = array(); + while ($rev = $this->next()) $result[] = $rev; $this->free(); return $result; @@ -2029,7 +2029,7 @@ class WikiDB_Array_PageIterator return count($this->_pages); } function reset() { - reset($this->_pages); + reset($this->_pages); } function free() {} function asArray() { @@ -2061,7 +2061,7 @@ class WikiDB_Array_generic_iter return count($this->_array); } function reset() { - reset($this->_array); + reset($this->_array); } function free() {} function asArray() { @@ -2078,7 +2078,7 @@ class WikiDB_Array_generic_iter * * @access private */ -class WikiDB_cache +class WikiDB_cache { // FIXME: beautify versiondata cache. Cache only limited data? @@ -2094,7 +2094,7 @@ class WikiDB_cache if (isset($GLOBALS['request']->_dbi)) $this->readonly = $GLOBALS['request']->_dbi->readonly; } - + function close() { $this->_pagedata_cache = array(); $this->_versiondata_cache = array(); @@ -2116,21 +2116,21 @@ class WikiDB_cache return $this->_backend->get_pagedata($pagename); } } - + function update_pagedata($pagename, $newdata) { assert(is_string($pagename) && $pagename != ''); if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } - + $this->_backend->update_pagedata($pagename, $newdata); if (USECACHE) { - if (!empty($this->_pagedata_cache[$pagename]) - and is_array($this->_pagedata_cache[$pagename])) + if (!empty($this->_pagedata_cache[$pagename]) + and is_array($this->_pagedata_cache[$pagename])) { $cachedata = &$this->_pagedata_cache[$pagename]; foreach($newdata as $key => $val) $cachedata[$key] = $val; - } else + } else $this->_pagedata_cache[$pagename] = $newdata; } } @@ -2142,7 +2142,7 @@ class WikiDB_cache unset ($this->_id_cache[$pagename]); //unset ($this->_backend->_page_data); } - + function delete_page($pagename) { if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } $result = $this->_backend->delete_page($pagename); @@ -2159,41 +2159,41 @@ class WikiDB_cache // FIXME: ugly and wrong. may overwrite full cache with partial cache function cache_data($data) { - ; + ; //if (isset($data['pagedata'])) // $this->_pagedata_cache[$data['pagename']] = $data['pagedata']; } - + function get_versiondata($pagename, $version, $need_content = false) { // FIXME: Seriously ugly hackage $readdata = false; - if (USECACHE) { //temporary - for debugging + if (USECACHE) { //temporary - for debugging assert(is_string($pagename) && $pagename != ''); // There is a bug here somewhere which results in an assertion failure at line 105 // of ArchiveCleaner.php It goes away if we use the next line. //$need_content = true; $nc = $need_content ? '1':'0'; $cache = &$this->_versiondata_cache; - if (!isset($cache[$pagename][$version][$nc]) - || !(is_array ($cache[$pagename])) - || !(is_array ($cache[$pagename][$version]))) + if (!isset($cache[$pagename][$version][$nc]) + || !(is_array ($cache[$pagename])) + || !(is_array ($cache[$pagename][$version]))) { - $cache[$pagename][$version][$nc] = + $cache[$pagename][$version][$nc] = $this->_backend->get_versiondata($pagename, $version, $need_content); $readdata = true; - // If we have retrieved all data, we may as well set the cache for + // If we have retrieved all data, we may as well set the cache for // $need_content = false if ($need_content){ $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1']; } } $vdata = $cache[$pagename][$version][$nc]; - } else { + } else { $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content); $readdata = true; - } + } if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) { - if (empty($this->_pagedata_cache)) + if (empty($this->_pagedata_cache)) $this->_pagedata_cache = array(); /* PHP Fatal error: Cannot create references to/from string offsets nor overloaded objects in /var/www/html/phpwiki/lib/WikiDB.php on line 2180, referer: wiki/TitleSearch?s=and&auto_redirect=1 */ $this->_pagedata_cache[$pagename] = $vdata['%pagedata']; @@ -2203,7 +2203,7 @@ class WikiDB_cache function set_versiondata($pagename, $version, $data) { //unset($this->_versiondata_cache[$pagename][$version]); - + if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; } $new = $this->_backend->set_versiondata($pagename, $version, $data); // Update the cache @@ -2233,7 +2233,7 @@ class WikiDB_cache if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version) unset ($this->_glv_cache[$pagename]); } - + function get_latest_version($pagename) { if (USECACHE) { assert (is_string($pagename) && $pagename != ''); @@ -2245,7 +2245,7 @@ class WikiDB_cache } return $cache[$pagename]; } else { - return $this->_backend->get_latest_version($pagename); + return $this->_backend->get_latest_version($pagename); } } }; @@ -2275,5 +2275,5 @@ function _sql_debuglog_shutdown_function() { // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/WikiGroup.php b/lib/WikiGroup.php index 43c361078..16898d795 100644 --- a/lib/WikiGroup.php +++ b/lib/WikiGroup.php @@ -27,14 +27,14 @@ if (!defined('GROUP_METHOD') or trigger_error(_("No or unsupported GROUP_METHOD defined"), E_USER_WARNING); /* Special group names for ACL */ -define('GROUP_EVERY', _("Every")); -define('GROUP_ANONYMOUS', _("Anonymous Users")); -define('GROUP_BOGOUSER', _("Bogo Users")); -define('GROUP_SIGNED', _("Signed Users")); -define('GROUP_AUTHENTICATED', _("Authenticated Users")); -define('GROUP_ADMIN', _("Administrators")); -define('GROUP_OWNER', _("Owner")); -define('GROUP_CREATOR', _("Creator")); +define('GROUP_EVERY', _("Every")); +define('GROUP_ANONYMOUS', _("Anonymous Users")); +define('GROUP_BOGOUSER', _("Bogo Users")); +define('GROUP_SIGNED', _("Signed Users")); +define('GROUP_AUTHENTICATED', _("Authenticated Users")); +define('GROUP_ADMIN', _("Administrators")); +define('GROUP_OWNER', _("Owner")); +define('GROUP_CREATOR', _("Creator")); /** * WikiGroup is an abstract class to provide the base functions for determining @@ -73,7 +73,7 @@ class WikiGroup{ * @param object $request The global WikiRequest object -- ignored. */ function WikiGroup($not_current = false) { - $this->not_current = $not_current; + $this->not_current = $not_current; //$this->request =& $GLOBALS['request']; } @@ -137,15 +137,15 @@ class WikiGroup{ * translated */ function specialGroup($group){ - return in_array($group,$this->specialGroups()); + return in_array($group,$this->specialGroups()); } /** untranslated */ function _specialGroup($group){ - return in_array($group,$this->_specialGroups()); + return in_array($group,$this->_specialGroups()); } /** translated */ function specialGroups(){ - return array( + return array( GROUP_EVERY, GROUP_ANONYMOUS, GROUP_BOGOUSER, @@ -157,7 +157,7 @@ class WikiGroup{ } /** untranslated */ function _specialGroups(){ - return array( + return array( "_EVERY", "_ANONYMOUS", "_BOGOUSER", @@ -179,8 +179,8 @@ class WikiGroup{ function isMember($group){ if (isset($this->membership[$group])) return $this->membership[$group]; - if ($this->specialGroup($group)) { - return $this->isSpecialMember($group); + if ($this->specialGroup($group)) { + return $this->isSpecialMember($group); } else { trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s", 'isMember', GROUP_METHOD), @@ -236,9 +236,9 @@ class WikiGroup{ } function _allUsers() { - static $result = array(); - if (!empty($result)) - return $result; + static $result = array(); + if (!empty($result)) + return $result; global $request; /* WikiPage users: */ @@ -308,9 +308,9 @@ class WikiGroup{ * @return array Array of usernames that have joined the group (always empty). */ function getMembersOf($group){ - if ($this->specialGroup($group)) { - return $this->getSpecialMembersOf($group); - } + if ($this->specialGroup($group)) { + return $this->getSpecialMembersOf($group); + } trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s", 'getMembersOf', GROUP_METHOD), E_USER_WARNING); @@ -421,8 +421,8 @@ class GroupNone extends WikiGroup{ * @return boolean True if user is a member, else false (always false). */ function isMember($group){ - if ($this->specialGroup($group)) { - return $this->isSpecialMember($group); + if ($this->specialGroup($group)) { + return $this->isSpecialMember($group); } else { return false; } @@ -497,9 +497,9 @@ class GroupWikiPage extends WikiGroup{ } $this->membership[$group] = false; // Let grouppages override certain defaults, such as members of admin - if ($this->specialGroup($group)) { - return $this->isSpecialMember($group); - } + if ($this->specialGroup($group)) { + return $this->isSpecialMember($group); + } return false; } @@ -539,7 +539,7 @@ class GroupWikiPage extends WikiGroup{ function getAllGroupsIn(){ $membership = array(); - $specialgroups = $this->specialGroups(); + $specialgroups = $this->specialGroups(); foreach ($specialgroups as $group) { $this->membership[$group] = $this->isSpecialMember($group); } @@ -567,7 +567,7 @@ class GroupWikiPage extends WikiGroup{ * @return array Array of usernames that have joined the group (always empty). */ function getMembersOf($group){ - if ($this->specialGroup($group)) + if ($this->specialGroup($group)) return $this->getSpecialMembersOf($group); $group_page = $GLOBALS['request']->getPage($group); @@ -605,7 +605,7 @@ class GroupDb extends WikiGroup { * @param object $request The global WikiRequest object. ignored */ function GroupDb() { - global $DBAuthParams, $DBParams; + global $DBAuthParams, $DBParams; //$this->request = &$GLOBALS['request']; $this->username = $this->_getUserName(); $this->membership = array(); @@ -666,7 +666,7 @@ class GroupDb_PearDB extends GroupDb { } $this->membership[$group] = false; // Let override certain defaults, such as members of admin - if ($this->specialGroup($group)) + if ($this->specialGroup($group)) return $this->isSpecialMember($group); return false; } @@ -679,7 +679,7 @@ class GroupDb_PearDB extends GroupDb { * @return array Array of groups to which the user belongs. */ function getAllGroupsIn(){ - $membership = array(); + $membership = array(); $dbh = & $this->dbh; $db_result = $dbh->query(sprintf($this->_user_groups, $dbh->quote($this->username))); @@ -690,7 +690,7 @@ class GroupDb_PearDB extends GroupDb { } } - $specialgroups = $this->specialGroups(); + $specialgroups = $this->specialGroups(); foreach ($specialgroups as $group) { if ($this->isMember($group)) { $membership[] = $group; @@ -718,7 +718,7 @@ class GroupDb_PearDB extends GroupDb { } } // add certain defaults, such as members of admin - if ($this->specialGroup($group)) + if ($this->specialGroup($group)) $members = array_merge($members, $this->getSpecialMembersOf($group)); return $members; } @@ -754,7 +754,7 @@ class GroupDb_ADODB extends GroupDb { } } $this->membership[$group] = false; - if ($this->specialGroup($group)) + if ($this->specialGroup($group)) return $this->isSpecialMember($group); return false; @@ -768,7 +768,7 @@ class GroupDb_ADODB extends GroupDb { * @return array Array of groups to which the user belongs. */ function getAllGroupsIn(){ - $membership = array(); + $membership = array(); $dbh = & $this->dbh; $rs = $dbh->Execute(sprintf($this->_user_groups, $dbh->qstr($this->username))); @@ -782,7 +782,7 @@ class GroupDb_ADODB extends GroupDb { } $rs->Close(); - $specialgroups = $this->specialGroups(); + $specialgroups = $this->specialGroups(); foreach ($specialgroups as $group) { if ($this->isMember($group)) { $membership[] = $group; @@ -809,7 +809,7 @@ class GroupDb_ADODB extends GroupDb { } $rs->Close(); // add certain defaults, such as members of admin - if ($this->specialGroup($group)) + if ($this->specialGroup($group)) $members = array_merge($members, $this->getSpecialMembersOf($group)); return $members; } @@ -875,7 +875,7 @@ class GroupFile extends WikiGroup { } } $this->membership[$group] = false; - if ($this->specialGroup($group)) + if ($this->specialGroup($group)) return $this->isSpecialMember($group); return false; } @@ -901,7 +901,7 @@ class GroupFile extends WikiGroup { } } - $specialgroups = $this->specialGroups(); + $specialgroups = $this->specialGroups(); foreach ($specialgroups as $group) { if ($this->isMember($group)) { $this->membership[$group] = true; @@ -923,7 +923,7 @@ class GroupFile extends WikiGroup { if (!empty($this->_file->users[$group])) { $members = explode(' ',$this->_file->users[$group]); } - if ($this->specialGroup($group)) { + if ($this->specialGroup($group)) { $members = array_merge($members, $this->getSpecialMembersOf($group)); } return $members; @@ -994,7 +994,7 @@ class GroupLdap extends WikiGroup { $this->membership[$group] = in_array($this->username,$this->getMembersOf($group)); if ($this->membership[$group]) return true; - if ($this->specialGroup($group)) + if ($this->specialGroup($group)) return $this->isSpecialMember($group); } @@ -1009,7 +1009,7 @@ class GroupLdap extends WikiGroup { //$username = $this->_getUserName(); $membership = array(); - $specialgroups = $this->specialGroups(); + $specialgroups = $this->specialGroups(); foreach ($specialgroups as $group) { if ($this->isMember($group)) { $this->membership[$group] = true; @@ -1020,21 +1020,21 @@ class GroupLdap extends WikiGroup { // must be a valid LDAP server, and username must not contain a wildcard if ($ldap = $this->_user->_init()) { $st_search = LDAP_SEARCH_FIELD ? LDAP_SEARCH_FIELD."=".$this->username - : "uid=".$this->username; + : "uid=".$this->username; $sr = ldap_search($ldap, (LDAP_OU_USERS ? LDAP_OU_USERS : "ou=Users") .($this->base_dn ? ",".$this->base_dn : ''), $st_search); if (!$sr) { - $this->_user->_free(); + $this->_user->_free(); return $this->membership; } $info = ldap_get_entries($ldap, $sr); if (empty($info["count"])) { - $this->_user->_free(); + $this->_user->_free(); return $this->membership; } for ($i = 0; $i < $info["count"]; $i++) { - if ($info[$i]["gidNumber"]["count"]) { + if ($info[$i]["gidNumber"]["count"]) { $gid = $info[$i]["gidnumber"][0]; $sr2 = ldap_search($ldap, (LDAP_OU_GROUP ? LDAP_OU_GROUP : "ou=Groups") .($this->base_dn ? ",".$this->base_dn : ''), @@ -1094,7 +1094,7 @@ class GroupLdap extends WikiGroup { $this->_user->_free(); //ldap_close($ldap); - if ($this->specialGroup($group)) { + if ($this->specialGroup($group)) { $members = array_merge($members, $this->getSpecialMembersOf($group)); } return $members; diff --git a/lib/WikiPlugin.php b/lib/WikiPlugin.php index b43ff162d..7bce5755d 100644 --- a/lib/WikiPlugin.php +++ b/lib/WikiPlugin.php @@ -28,7 +28,7 @@ class WikiPlugin function managesValidators() { return false; } - + // FIXME: args? function run ($dbi, $argstr, &$request, $basepage) { trigger_error("WikiPlugin::run: pure virtual function", @@ -59,7 +59,7 @@ class WikiPlugin function getWikiPageLinks ($argstr, $basepage) { return false; } - + /** * Get name of plugin. * @@ -82,7 +82,7 @@ class WikiPlugin function getDescription() { return $this->getName(); } - + function getArgs($argstr, $request=false, $defaults=false) { if ($defaults === false) { $defaults = $this->getDefaultArguments(); @@ -109,9 +109,9 @@ class WikiPlugin unset($argstr_args[$arg]); unset($argstr_defaults[$arg]); } - + foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) { - // TODO: where the heck comes this from? Put the new method over there and peace. + // TODO: where the heck comes this from? Put the new method over there and peace. /*if ($request and $request->getArg('pagename') == _("PhpWikiAdministration") and $arg == 'overwrite') // silence this warning ;*/ @@ -147,9 +147,9 @@ class WikiPlugin function parseArgStr($argstr) { $args = array(); $defaults = array(); - if (empty($argstr)) + if (empty($argstr)) return array($args, $defaults); - + $arg_p = '\w+'; $op_p = '(?:\|\|)?='; $word_p = '\S+'; @@ -200,7 +200,7 @@ class WikiPlugin elseif ($count >= 7) $val = $word_val; else - $val = ''; + $val = ''; if ($op == '=') { $args[$arg] = $val; @@ -229,14 +229,14 @@ class WikiPlugin trigger_error(sprintf(_("trailing cruft in plugin args: '%s'"), $argstr), E_USER_NOTICE); } - + /* A plugin can override this to allow undeclared arguments. Or to silence the warning. */ function allow_undeclared_arg($name, $value) { trigger_error(sprintf(_("Argument '%s' not declared by plugin."), $name), E_USER_NOTICE); - return false; + return false; } /* handle plugin-list argument: use run(). */ @@ -248,7 +248,7 @@ class WikiPlugin return $pagelist->pageNames(); elseif (is_array($pagelist)) return $pagelist; - else + else return $list; } @@ -268,18 +268,18 @@ class WikiPlugin 'description'=> $this->getDescription(), 'formsize' => 30); } - + function makeForm($argstr, $request) { $form_defaults = $this->getDefaultFormArguments(); $defaults = array_merge($form_defaults, array('start_debug' => $request->getArg('start_debug')), - $this->getDefaultArguments()); - + $this->getDefaultArguments()); + $args = $this->getArgs($argstr, $request, $defaults); $plugin = $this->getName(); $textinput = $args['textinput']; assert(!empty($textinput) && isset($args['textinput'])); - + $form = HTML::form(array('action' => WikiURL($args['targetpage']), 'method' => $args['method'], 'class' => $args['class'], @@ -297,15 +297,15 @@ class WikiPlugin } $contents = HTML::div(); $contents->setAttr('class', $args['class']); - + foreach ($args as $arg => $val) { if (isset($form_defaults[$arg])) continue; if ($arg != $textinput && $val == $defaults[$arg]) continue; - + $i = HTML::input(array('name' => $arg, 'value' => $val)); - + if ($arg == $textinput) { //if ($inputs[$arg] == 'file') // $attr['type'] = 'file'; @@ -319,7 +319,7 @@ class WikiPlugin $i->setAttr('type', 'hidden'); } $contents->pushContent($i); - + // FIXME: hackage if ($i->getAttr('type') == 'file') { $form->setAttr('enctype', 'multipart/form-data'); @@ -329,7 +329,7 @@ class WikiPlugin 'type' => 'hidden'))); } } - + if (!empty($args['buttontext'])) $contents->pushContent(HTML::input(array('type' => 'submit', 'class' => 'button', @@ -351,7 +351,7 @@ class WikiPlugin HTML::div(array('class'=>'box-title'), $title), HTML::div(array('class'=>'box-data'), $body)); } - + function error ($message) { return HTML::span(array('class' => 'error'), HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ', @@ -377,7 +377,7 @@ class WikiPlugin $customPageListColumns[$column] = $obj; } } - + // provide a sample usage text for automatic edit-toolbar insertion function getUsage() { $args = $this->getDefaultArguments(); @@ -435,15 +435,15 @@ class WikiPluginLoader { // Output of plugin (potentially) depends on // the state of the WikiDB (other than the current // page.) - + // Lacking other information, we'll assume things // changed last time the wikidb was touched. - + // As an additional hack, mark the ETag weak, since, // for all we know, the page might depend // on things other than the WikiDB (e.g. PhpWeather, // Calendar...) - + $timestamp = $dbi->getTimestamp(); $request->appendValidators(array('dbi_timestamp' => $timestamp, '%mtime' => (int)$timestamp, @@ -467,7 +467,7 @@ class WikiPluginLoader { return false; return $plugin->getWikiPageLinks($plugin_args, $basepage); } - + function parsePI($pi) { if (!preg_match('/^\s*<\?(plugin(?:-form|-link|-list)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m)) return $this->_error(sprintf("Bad %s", 'PI')); @@ -477,7 +477,7 @@ class WikiPluginLoader { return array($pi_name, $plugin, $plugin_args); } - + function getPlugin($plugin_name, $pi=false) { global $ErrorManager; global $AllAllowedPlugins; diff --git a/lib/WikiPluginCached.php b/lib/WikiPluginCached.php index 09a1eb646..2b976c06e 100644 --- a/lib/WikiPluginCached.php +++ b/lib/WikiPluginCached.php @@ -32,19 +32,19 @@ require_once "lib/WikiPlugin.php"; // types: define('PLUGIN_CACHED_HTML', 0); // cached html (extensive calculation) define('PLUGIN_CACHED_IMG_INLINE', 1); // gd images -define('PLUGIN_CACHED_MAP', 2); // area maps -define('PLUGIN_CACHED_SVG', 3); // special SVG/SVGZ object +define('PLUGIN_CACHED_MAP', 2); // area maps +define('PLUGIN_CACHED_SVG', 3); // special SVG/SVGZ object define('PLUGIN_CACHED_SVG_PNG', 4); // special SVG/SVGZ object with PNG fallback -define('PLUGIN_CACHED_SWF', 5); // special SWF (flash) object -define('PLUGIN_CACHED_PDF', 6); // special PDF object (inlinable?) -define('PLUGIN_CACHED_PS', 7); // special PS object (inlinable?) +define('PLUGIN_CACHED_SWF', 5); // special SWF (flash) object +define('PLUGIN_CACHED_PDF', 6); // special PDF object (inlinable?) +define('PLUGIN_CACHED_PS', 7); // special PS object (inlinable?) // boolean tests: define('PLUGIN_CACHED_IMG_ONDEMAND', 64);// don't cache -define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, not via /getimg.php?id= +define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, not via /getimg.php?id= /** - * An extension of the WikiPlugin class to allow image output and - * cacheing. + * An extension of the WikiPlugin class to allow image output and + * cacheing. * There are several abstract functions to be overloaded. * Have a look at the example files *
  • plugin/TexToPng.php
  • @@ -55,9 +55,9 @@ define('PLUGIN_CACHED_STATIC', 128); // make it available via /uploads/, not v *
* * @author Johannes Große, Reini Urban - */ + */ class WikiPluginCached extends WikiPlugin -{ +{ var $_static; /** * Produces URL and id number from plugin arguments which later on, @@ -74,7 +74,7 @@ class WikiPluginCached extends WikiPlugin * TODO: check if args is needed at all (on lost cache) */ function genUrl($cache, $argarray) { - global $request; + global $request; //$cacheparams = $GLOBALS['CacheParams']; $plugincall = serialize( array( @@ -146,21 +146,21 @@ class WikiPluginCached extends WikiPlugin $this->_static = false; if ($this->_type & PLUGIN_CACHED_STATIC or $request->getArg('action') == 'pdf') // htmldoc doesn't grok subrequests - { + { $this->_type = $this->_type & ~PLUGIN_CACHED_STATIC; $this->_static = true; } - + // ---------- embed static image, no getimg.php? url ----------------- if (0 and $this->_static) { //$content = $cache->get($id, 'imagecache'); $content = array(); if ($this->produceImage($content, $this, $dbi, $sortedargs, $request, 'html')) { - // save the image in uploads - return $this->embedImg($content['url'], $dbi, $sortedargs, $request); + // save the image in uploads + return $this->embedImg($content['url'], $dbi, $sortedargs, $request); } else { - // copy the cached image into uploads if older - return HTML(); + // copy the cached image into uploads if older + return HTML(); } } @@ -268,7 +268,7 @@ class WikiPluginCached extends WikiPlugin *
  • PLUGIN_CACHED_IMG_INLINE
  • *
  • PLUGIN_CACHED_IMG_ONDEMAND
  • *
  • PLUGIN_CACHED_MAP
  • - * + * */ function getPluginType() { return PLUGIN_CACHED_IMG_ONDEMAND; @@ -327,7 +327,7 @@ class WikiPluginCached extends WikiPlugin * WikiPlugin->getArgs anymore. * @param request Request ??? * @return string 'png', 'jpeg' or 'gif' - */ + */ function getImageType(&$dbi, $argarray, &$request) { if (in_array($argarray['imgtype'], preg_split('/\s*:\s*/', PLUGIN_CACHED_IMGTYPES))) return $argarray['imgtype']; @@ -521,14 +521,14 @@ class WikiPluginCached extends WikiPlugin */ function decideImgType($wish) { - if ($wish=='html') return $wish; + if ($wish=='html') return $wish; if ($wish=='jpg') { $wish = 'jpeg'; } $supportedtypes = array(); // Todo: swf, pdf, ... $imagetypes = array( 'png' => IMG_PNG, - 'gif' => IMG_GIF, + 'gif' => IMG_GIF, 'jpeg' => IMG_JPEG, 'wbmp' => IMG_WBMP, 'xpm' => IMG_XPM, @@ -542,7 +542,7 @@ class WikiPluginCached extends WikiPlugin $presenttypes = ImageTypes(); foreach ($imagetypes as $imgtype => $bitmask) if ( $presenttypes && $bitmask ) - array_push($supportedtypes, $imgtype); + array_push($supportedtypes, $imgtype); } else { foreach ($imagetypes as $imgtype => $bitmask) if (function_exists("Image".$imgtype)) @@ -554,7 +554,7 @@ class WikiPluginCached extends WikiPlugin return reset($supportedtypes); else return 'html'; - + } // decideImgType @@ -660,8 +660,8 @@ class WikiPluginCached extends WikiPlugin } else { $id = $cache->generateId( $plugincall ); } - } - return true; + } + return true; } // checkCall1 @@ -674,7 +674,7 @@ class WikiPluginCached extends WikiPlugin * name and parameters of the plugin call * @param request Request ??? * @return boolean false if an error occurs, true otherwise. - * + * */ function checkCall2(&$plugincall, $request) { // if plugincall wasn't sent by URL, it must have been @@ -688,7 +688,7 @@ class WikiPluginCached extends WikiPlugin $id ); $this->printError($errorformat, $errortext); return false; - } + } } $plugincall = unserialize($plugincall); return true; @@ -730,13 +730,13 @@ class WikiPluginCached extends WikiPlugin return false; } - // image handle -> image data + // image handle -> image data if (!empty($this->_static)) { $ext = "." . $content['imagetype']; if (is_string($imagehandle) and file_exists($imagehandle)) { - if (preg_match("/.(\w+)$/",$imagehandle,$m)) { - $ext = "." . $m[1]; - } + if (preg_match("/.(\w+)$/",$imagehandle,$m)) { + $ext = "." . $m[1]; + } } $tmpfile = tempnam(getUploadFilePath(), PLUGIN_CACHED_FILENAME_PREFIX . $ext); if (!strstr(basename($tmpfile), $ext)) { @@ -764,7 +764,7 @@ class WikiPluginCached extends WikiPlugin $content['image'] = fread($fp, filesize($tmpfile)); fclose($fp); if (!empty($this->_static)) { - // on static it is in "uploads/" but in wikicached also + // on static it is in "uploads/" but in wikicached also $content['file'] = $tmpfile; $content['url'] = getUploadDataPath() . basename($tmpfile); return true; @@ -783,21 +783,21 @@ class WikiPluginCached extends WikiPlugin } function tempnam($prefix = "") { - if (preg_match("/^(.+)\.(\w{2,4})$/", $prefix, $m)) { - $prefix = $m[1]; - $ext = ".".$m[2]; - } else { - $ext = isWindows()? ".tmp" : ""; - } + if (preg_match("/^(.+)\.(\w{2,4})$/", $prefix, $m)) { + $prefix = $m[1]; + $ext = ".".$m[2]; + } else { + $ext = isWindows()? ".tmp" : ""; + } $temp = tempnam(isWindows() ? str_replace('/', "\\", PLUGIN_CACHED_CACHE_DIR) : PLUGIN_CACHED_CACHE_DIR, $prefix ? $prefix : PLUGIN_CACHED_FILENAME_PREFIX); if (isWindows()) { - if ($ext != ".tmp") unlink($temp); + if ($ext != ".tmp") unlink($temp); $temp = preg_replace("/\.tmp$/", $ext, $temp); - } else { - $temp .= $ext; - } + } else { + $temp .= $ext; + } return $temp; } @@ -811,7 +811,7 @@ class WikiPluginCached extends WikiPlugin * @param errorformat string outputs errors in 'png', 'gif', 'jpeg' or 'html' */ function fetchImageFromCache($dbi, $request, $errorformat='png') { - $cache = $this->newCache(); + $cache = $this->newCache(); $errorformat = $this->decideImgType($errorformat); // get id if (!$this->checkCall1($id, $plugincall, $cache, $request, $errorformat)) return false; @@ -883,7 +883,7 @@ class WikiPluginCached extends WikiPlugin function resetError() { $this->_errortext = ''; } - + /** * Returns all accumulated error messages. * @@ -977,7 +977,7 @@ class WikiPluginCached extends WikiPlugin } // prepare Parameters - + // set maximum values $IMAGESIZE = array( 'cols' => 80, @@ -1028,7 +1028,7 @@ class WikiPluginCached extends WikiPlugin $bg = ImageColorAllocate($im, $bgcol[0], $bgcol[1], $bgcol[2]); ImageFilledRectangle($im, 0, 0, $IMAGESIZE['width']-1, $IMAGESIZE['height']-1, $bg); - + // write text lines foreach($lines as $nr => $textstr) { ImageString( $im, $fontnr, $marginx, $marginy+$nr*$chary, diff --git a/lib/WikiTheme.php b/lib/WikiTheme.php index 7285ad643..061bb1256 100644 --- a/lib/WikiTheme.php +++ b/lib/WikiTheme.php @@ -59,7 +59,7 @@ function WikiLink ($page_or_rev, $type = 'known', $label = false) { } $version = false; - + if (isa($page_or_rev, 'WikiDB_PageRevision')) { $version = $page_or_rev->getVersion(); if ($page_or_rev->isCurrent()) @@ -86,13 +86,13 @@ function WikiLink ($page_or_rev, $type = 'known', $label = false) { if (!$wikipage->isValid('strict')) return $WikiTheme->linkBadWikiWord($wikipage, $label); } - + if ($type == 'auto' or $type == 'if_known') { if (isset($page)) { $exists = $page->exists(); } else { - $dbi =& $request->_dbi; + $dbi =& $request->_dbi; $exists = $dbi->isWikiPage($wikipage->name); } } @@ -215,7 +215,7 @@ class WikiTheme { } if ($noinit) return; $this->_css = array(); - + // on derived classes do not add headers twice if (count($this->_parents) > 1) { return; @@ -260,7 +260,7 @@ class WikiTheme { /* Derived classes should search all parent classes */ foreach ($this->_parents as $parent) { - $path = $parent->_findFile($file, 1); + $path = $parent->_findFile($file, 1); if ($path) { return $path; } elseif (0 and DEBUG & (_DEBUG_VERBOSE + _DEBUG_REMOTE)) { @@ -280,19 +280,19 @@ class WikiTheme { } function _findData ($file, $missing_okay = false) { - if (!string_starts_with($file, "themes")) { // common case - $path = $this->_findFile($file, $missing_okay); - } else { - // _findButton only - if (file_exists($file)) { - $path = $file; - } elseif (defined('DATA_PATH') - and file_exists(DATA_PATH . "/$file")) { - $path = $file; - } else { // fallback for buttons in parent themes + if (!string_starts_with($file, "themes")) { // common case + $path = $this->_findFile($file, $missing_okay); + } else { + // _findButton only + if (file_exists($file)) { + $path = $file; + } elseif (defined('DATA_PATH') + and file_exists(DATA_PATH . "/$file")) { + $path = $file; + } else { // fallback for buttons in parent themes $path = $this->_findFile($file, $missing_okay); - } - } + } + } if (!$path) return false; if (!DEBUG) { @@ -312,10 +312,10 @@ class WikiTheme { //////////////////////////////////////////////////////////////// // Note: Windows' implementation of strftime does not include certain - // format specifiers, such as %e (for date without leading zeros). In - // general, see: - // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strftime.2c_.wcsftime.asp - // As a result, we have to use %d, and strip out leading zeros ourselves. + // format specifiers, such as %e (for date without leading zeros). In + // general, see: + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strftime.2c_.wcsftime.asp + // As a result, we have to use %d, and strip out leading zeros ourselves. var $_dateFormat = "%B %d, %Y"; var $_timeFormat = "%I:%M %p"; @@ -417,13 +417,13 @@ class WikiTheme { */ function getDay ($time_t) { global $request; - + if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($time_t))) { return ucfirst($date); } return $this->formatDate($time_t); } - + /** * Format the "last modified" message for a page revision. * @@ -439,11 +439,11 @@ class WikiTheme { function getLastModifiedMessage ($revision, $show_version = 'auto') { global $request; if (!$revision) return ''; - + // dates >= this are considered invalid. if (! defined('EPOCH')) define('EPOCH', 0); // seconds since ~ January 1 1970 - + $mtime = $revision->get('mtime'); if ($mtime <= EPOCH) return fmt("Never edited"); @@ -455,7 +455,7 @@ class WikiTheme { if ($this->_showModTime) $date = sprintf(_("%s at %s"), $date, $this->formatTime($mtime)); - + if ($show_version) return fmt("Version %s, saved on %s", $revision->getVersion(), $date); else @@ -466,20 +466,20 @@ class WikiTheme { $date = $this->formatDateTime($mtime); else $date = $this->formatDate($mtime); - + if ($show_version) return fmt("Version %s, saved on %s", $revision->getVersion(), $date); else return fmt("Last edited on %s", $date); } - + function _relativeDay ($time_t) { global $request; - + if (is_numeric($request->getPref('timeOffset'))) $offset = 3600 * $request->getPref('timeOffset'); else - $offset = 0; + $offset = 0; $now = time() + $offset; $today = localtime($now, true); @@ -487,7 +487,7 @@ class WikiTheme { if ($time['tm_yday'] == $today['tm_yday'] && $time['tm_year'] == $today['tm_year']) return _("today"); - + // Note that due to daylight savings chages (and leap seconds), $now minus // 24 hours is not guaranteed to be yesterday. $yesterday = localtime($now - (12 + $today['tm_hour']) * 3600, true); @@ -504,7 +504,7 @@ class WikiTheme { function getOwnerMessage ($page) { if (!ENABLE_PAGEPERM or !class_exists("PagePermission")) return ''; - $dbi =& $GLOBALS['request']->_dbi; + $dbi =& $GLOBALS['request']->_dbi; $owner = $page->getOwner(); if ($owner) { /* @@ -594,7 +594,7 @@ class WikiTheme { $default_text = $wikiword->shortName; else $default_text = $wikiword; - + if (!empty($linktext)) { $link->pushContent($linktext); $link->setAttr('class', 'named-wiki'); @@ -620,7 +620,7 @@ class WikiTheme { else { $default_text = $wikiword; } - + if ($this->DUMP_MODE) { // HTML, PDF or XML $link = HTML::span( empty($linktext) ? $wikiword : $linktext); $link->setAttr('style', 'text-decoration: underline'); @@ -671,7 +671,7 @@ class WikiTheme { function linkBadWikiWord($wikiword, $linktext = '') { global $ErrorManager; - + if ($linktext) { $text = $linktext; } @@ -687,10 +687,10 @@ class WikiTheme { else $message = sprintf(_("'%s': Bad page name"), $wikiword); $ErrorManager->warning($message); - + return HTML::span(array('class' => 'badwikiword'), $text); } - + //////////////////////////////////////////////////////////////// // // Images and Icons @@ -704,9 +704,9 @@ class WikiTheme { */ function addImageAlias ($alias, $image_name) { // fall back to the PhpWiki-supplied image if not found - if ((empty($this->_imageAliases[$alias]) - and $this->_findFile("images/$image_name", true)) - or $image_name === false) + if ((empty($this->_imageAliases[$alias]) + and $this->_findFile("images/$image_name", true)) + or $image_name === false) $this->_imageAliases[$alias] = $image_name; } @@ -824,7 +824,7 @@ class WikiTheme { if (!file_exists($path_dir) || !is_dir($path_dir)) return array(); $path = array($button_dir); - + $dir = dir($path_dir); while (($subdir = $dir->read()) !== false) { if ($subdir[0] == '.') @@ -866,14 +866,14 @@ class WikiTheme { if (preg_match('/^submit:(.*)$/', $url, $m)) return $this->makeSubmitButton($text, $m[1], $class, $options); - if (is_string($text)) + if (is_string($text)) $imgurl = $this->getButtonURL($text); else $imgurl = $text; if ($imgurl) return new ImageButton($text, $url, - in_array($class,array("wikiaction","wikiadmin"))?"wikibutton":$class, - $imgurl, $options); + in_array($class,array("wikiaction","wikiadmin"))?"wikibutton":$class, + $imgurl, $options); else return new Button($this->maybeSplitWikiWord($text), $url, $class, $options); @@ -938,20 +938,20 @@ class WikiTheme { return $this->makeButton($label, WikiURL($pagename, $attr), $class, $options); } - + function tooltipAccessKeyPrefix() { - static $tooltipAccessKeyPrefix = null; - if ($tooltipAccessKeyPrefix) return $tooltipAccessKeyPrefix; + static $tooltipAccessKeyPrefix = null; + if ($tooltipAccessKeyPrefix) return $tooltipAccessKeyPrefix; $tooltipAccessKeyPrefix = 'alt'; - if (isBrowserOpera()) $tooltipAccessKeyPrefix = 'shift-esc'; - elseif (isBrowserSafari() or browserDetect("Mac") or isBrowserKonqueror()) - $tooltipAccessKeyPrefix = 'ctrl'; - // ff2 win and x11 only - elseif ((browserDetect("firefox/2") or browserDetect("minefield/3") or browserDetect("SeaMonkey/1.1")) - and ((browserDetect("windows") or browserDetect("x11")))) - $tooltipAccessKeyPrefix = 'alt-shift'; - return $tooltipAccessKeyPrefix; + if (isBrowserOpera()) $tooltipAccessKeyPrefix = 'shift-esc'; + elseif (isBrowserSafari() or browserDetect("Mac") or isBrowserKonqueror()) + $tooltipAccessKeyPrefix = 'ctrl'; + // ff2 win and x11 only + elseif ((browserDetect("firefox/2") or browserDetect("minefield/3") or browserDetect("SeaMonkey/1.1")) + and ((browserDetect("windows") or browserDetect("x11")))) + $tooltipAccessKeyPrefix = 'alt-shift'; + return $tooltipAccessKeyPrefix; } /** Define the accesskey in the title only, with ending [p] or [alt-p]. @@ -960,13 +960,13 @@ class WikiTheme { function fixAccesskey($attrs) { if (!empty($attrs['title']) and preg_match("/\[(alt-)?(.)\]$/", $attrs['title'], $m)) { - if (empty($attrs['accesskey'])) $attrs['accesskey'] = $m[2]; - // firefox 'alt-shift', MSIE: 'alt', ... see wikibits.js - $attrs['title'] = preg_replace("/\[(alt-)?(.)\]$/", "[".$this->tooltipAccessKeyPrefix()."-\\2]", $attrs['title']); + if (empty($attrs['accesskey'])) $attrs['accesskey'] = $m[2]; + // firefox 'alt-shift', MSIE: 'alt', ... see wikibits.js + $attrs['title'] = preg_replace("/\[(alt-)?(.)\]$/", "[".$this->tooltipAccessKeyPrefix()."-\\2]", $attrs['title']); } return $attrs; } - + /** * Make a "button" which links to a wiki-page. * @@ -1117,7 +1117,7 @@ class WikiTheme { if (!in_array($css_file,$this->dumped_css)) $this->dumped_css[] = $css_file; $link->setAttr('href', basename($link->getAttr('href'))); } - + return $link; } @@ -1169,12 +1169,12 @@ class WikiTheme { foreach ($this->_css as $title => $css_files) { ksort($css_files); // move $css_files[''] to front. foreach ($css_files as $media => $css_file) { - if (!empty($this->DUMP_MODE)) { - if ($media == 'print') - $css[] = $this->_CSSlink($title, $css_file, '', $is_alt); - } else { - $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt); - } + if (!empty($this->DUMP_MODE)) { + if ($media == 'print') + $css[] = $this->_CSSlink($title, $css_file, '', $is_alt); + } else { + $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt); + } if ($is_alt) break; } $is_alt = true; @@ -1183,13 +1183,13 @@ class WikiTheme { } function findTemplate ($name) { - if ($tmp = $this->_findFile("templates/$name.tmpl", 1)) + if ($tmp = $this->_findFile("templates/$name.tmpl", 1)) return $this->_path . $tmp; else { $f1 = $this->file("templates/$name.tmpl"); foreach ($this->_parents as $parent) { - if ($tmp = $parent->_findFile("templates/$name.tmpl", 1)) - return $this->_path . $tmp; + if ($tmp = $parent->_findFile("templates/$name.tmpl", 1)) + return $this->_path . $tmp; } trigger_error("$f1 not found", E_USER_ERROR); return false; @@ -1205,8 +1205,8 @@ class WikiTheme { function addMoreHeaders ($element) { $GLOBALS['request']->_MoreHeaders[] = $element; if (!empty($this->_headers_printed) and $this->_headers_printed) { - trigger_error(_("Some action(page) wanted to add more headers, but they were already printed.") - ."\n". $element->asXML(), + trigger_error(_("Some action(page) wanted to add more headers, but they were already printed.") + ."\n". $element->asXML(), E_USER_NOTICE); } } @@ -1215,10 +1215,10 @@ class WikiTheme { * Singleton. Only called once, by the head template. See the warning above. */ function getMoreHeaders () { - global $request; - // actionpages cannot add headers, because recursive template expansion - // already expanded the head template before. - $this->_headers_printed = 1; + global $request; + // actionpages cannot add headers, because recursive template expansion + // already expanded the head template before. + $this->_headers_printed = 1; if (empty($request->_MoreHeaders)) return ''; $out = ''; @@ -1250,7 +1250,7 @@ else window.onload = downloadJSAtOnload;'); //$GLOBALS['request']->_MoreAttr = array(); // new arg: named elements to be able to remove them. such as DoubleClickEdit for htmldumps function addMoreAttr ($tag, $name, $element) { - global $request; + global $request; // protect from duplicate attr (body jscript: themes, prefs, ...) static $_attr_cache = array(); $hash = md5($tag."/".$element); @@ -1264,7 +1264,7 @@ else window.onload = downloadJSAtOnload;'); } function getMoreAttr ($tag) { - global $request; + global $request; if (empty($request->_MoreAttr[$tag])) return ''; $out = ''; @@ -1289,118 +1289,118 @@ else window.onload = downloadJSAtOnload;'); function load() { $this->initGlobals(); - - // CSS file defines fonts, colors and background images for this - // style. The companion '*-heavy.css' file isn't defined, it's just - // expected to be in the same directory that the base style is in. - - // This should result in phpwiki-printer.css being used when - // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. - $this->setDefaultCSS('PhpWiki', - array('' => 'phpwiki.css', - 'print' => 'phpwiki-printer.css')); - - // This allows one to manually select "Printer" style (when browsing page) - // to see what the printer style looks like. - $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); - $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); - $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); - - if (isBrowserIE()) { - $this->addMoreHeaders($this->_CSSlink(0, - $this->_findFile('IEFixes.css'),'all')); - $this->addMoreHeaders("\n"); - } - - /** - * The logo image appears on every page and links to the HomePage. - */ - $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); - - $this->addImageAlias('search', 'search.png'); - - /** - * The Signature image is shown after saving an edited page. If this - * is set to false then the "Thank you for editing..." screen will - * be omitted. - */ - - $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); - // Uncomment this next line to disable the signature. - //$this->addImageAlias('signature', false); - - /* - * Link icons. - */ - $this->setLinkIcon('http'); - $this->setLinkIcon('https'); - $this->setLinkIcon('ftp'); - $this->setLinkIcon('mailto'); - $this->setLinkIcon('interwiki'); - $this->setLinkIcon('wikiuser'); - $this->setLinkIcon('*', 'url'); - - $this->setButtonSeparator("\n | "); - - /** - * WikiWords can automatically be split by inserting spaces between - * the words. The default is to leave WordsSmashedTogetherLikeSo. - */ - $this->setAutosplitWikiWords(false); - - /** - * Layout improvement with dangling links for mostly closed wiki's: - * If false, only users with edit permissions will be presented the - * special wikiunknown class with "?" and Tooltip. - * If true (default), any user will see the ?, but will be presented - * the PrintLoginForm on a click. - */ - //$this->setAnonEditUnknownLinks(false); - - /* - * You may adjust the formats used for formatting dates and times - * below. (These examples give the default formats.) - * Formats are given as format strings to PHP strftime() function See - * http://www.php.net/manual/en/function.strftime.php for details. - * Do not include the server's zone (%Z), times are converted to the - * user's time zone. - * - * Suggestion for french: - * $this->setDateFormat("%A %e %B %Y"); - * $this->setTimeFormat("%H:%M:%S"); - * Suggestion for capable php versions, using the server locale: - * $this->setDateFormat("%x"); - * $this->setTimeFormat("%X"); - */ - //$this->setDateFormat("%B %d, %Y"); - //$this->setTimeFormat("%I:%M %p"); - - /* - * To suppress times in the "Last edited on" messages, give a - * give a second argument of false: - */ - //$this->setDateFormat("%B %d, %Y", false); - - - /** - * Custom UserPreferences: - * A list of name => _UserPreference class pairs. - * Rationale: Certain themes should be able to extend the predefined list - * of preferences. Display/editing is done in the theme specific userprefs.tmpl - * but storage/sanification/update/... must be extended to the Get/SetPreferences methods. - * See themes/wikilens/themeinfo.php - */ - //$this->customUserPreference(); - - /** - * Register custom PageList type and define custom PageList classes. - * Rationale: Certain themes should be able to extend the predefined list - * of pagelist types. E.g. certain plugins, like MostPopular might use - * info=pagename,hits,rating - * which displays the rating column whenever the wikilens theme is active. - * See themes/wikilens/themeinfo.php - */ - //$this->addPageListColumn(); + + // CSS file defines fonts, colors and background images for this + // style. The companion '*-heavy.css' file isn't defined, it's just + // expected to be in the same directory that the base style is in. + + // This should result in phpwiki-printer.css being used when + // printing or print-previewing with style "PhpWiki" or "MacOSX" selected. + $this->setDefaultCSS('PhpWiki', + array('' => 'phpwiki.css', + 'print' => 'phpwiki-printer.css')); + + // This allows one to manually select "Printer" style (when browsing page) + // to see what the printer style looks like. + $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen'); + $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css'); + $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css'); + + if (isBrowserIE()) { + $this->addMoreHeaders($this->_CSSlink(0, + $this->_findFile('IEFixes.css'),'all')); + $this->addMoreHeaders("\n"); + } + + /** + * The logo image appears on every page and links to the HomePage. + */ + $this->addImageAlias('logo', WIKI_NAME . 'Logo.png'); + + $this->addImageAlias('search', 'search.png'); + + /** + * The Signature image is shown after saving an edited page. If this + * is set to false then the "Thank you for editing..." screen will + * be omitted. + */ + + $this->addImageAlias('signature', WIKI_NAME . "Signature.png"); + // Uncomment this next line to disable the signature. + //$this->addImageAlias('signature', false); + + /* + * Link icons. + */ + $this->setLinkIcon('http'); + $this->setLinkIcon('https'); + $this->setLinkIcon('ftp'); + $this->setLinkIcon('mailto'); + $this->setLinkIcon('interwiki'); + $this->setLinkIcon('wikiuser'); + $this->setLinkIcon('*', 'url'); + + $this->setButtonSeparator("\n | "); + + /** + * WikiWords can automatically be split by inserting spaces between + * the words. The default is to leave WordsSmashedTogetherLikeSo. + */ + $this->setAutosplitWikiWords(false); + + /** + * Layout improvement with dangling links for mostly closed wiki's: + * If false, only users with edit permissions will be presented the + * special wikiunknown class with "?" and Tooltip. + * If true (default), any user will see the ?, but will be presented + * the PrintLoginForm on a click. + */ + //$this->setAnonEditUnknownLinks(false); + + /* + * You may adjust the formats used for formatting dates and times + * below. (These examples give the default formats.) + * Formats are given as format strings to PHP strftime() function See + * http://www.php.net/manual/en/function.strftime.php for details. + * Do not include the server's zone (%Z), times are converted to the + * user's time zone. + * + * Suggestion for french: + * $this->setDateFormat("%A %e %B %Y"); + * $this->setTimeFormat("%H:%M:%S"); + * Suggestion for capable php versions, using the server locale: + * $this->setDateFormat("%x"); + * $this->setTimeFormat("%X"); + */ + //$this->setDateFormat("%B %d, %Y"); + //$this->setTimeFormat("%I:%M %p"); + + /* + * To suppress times in the "Last edited on" messages, give a + * give a second argument of false: + */ + //$this->setDateFormat("%B %d, %Y", false); + + + /** + * Custom UserPreferences: + * A list of name => _UserPreference class pairs. + * Rationale: Certain themes should be able to extend the predefined list + * of preferences. Display/editing is done in the theme specific userprefs.tmpl + * but storage/sanification/update/... must be extended to the Get/SetPreferences methods. + * See themes/wikilens/themeinfo.php + */ + //$this->customUserPreference(); + + /** + * Register custom PageList type and define custom PageList classes. + * Rationale: Certain themes should be able to extend the predefined list + * of pagelist types. E.g. certain plugins, like MostPopular might use + * info=pagename,hits,rating + * which displays the rating column whenever the wikilens theme is active. + * See themes/wikilens/themeinfo.php + */ + //$this->addPageListColumn(); } // end of load @@ -1435,7 +1435,7 @@ else window.onload = downloadJSAtOnload;'); function initGlobals() { global $request; - static $already = 0; + static $already = 0; if (!$already) { $script_url = deduce_script_name(); if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) @@ -1450,7 +1450,7 @@ else window.onload = downloadJSAtOnload;'); ."var folderArrowPath = '".javascript_quote_string($folderArrowPath)."';\n" ."var use_path_info = " . (USE_PATH_INFO ? "true" : "false") .";\n"; $this->addMoreHeaders(JavaScript($js)); - $already = 1; + $already = 1; } } @@ -1466,8 +1466,8 @@ else window.onload = downloadJSAtOnload;'); // by Bitflux GmbH, bitflux.ch. You need to install the livesearch.js seperately. // Google's or acdropdown is better. function initLiveSearch() { - //subclasses of Sidebar will init this twice - static $already = 0; + //subclasses of Sidebar will init this twice + static $already = 0; if (!$this->HTML_DUMP_SUFFIX and !$already) { $this->addMoreAttr('body', 'LiveSearch', HTML::Raw(" onload=\"liveSearchInit()")); @@ -1475,15 +1475,15 @@ else window.onload = downloadJSAtOnload;'); .WikiURL(_("TitleSearch"),false,true).'";')); $this->addMoreHeaders(JavaScript('', array ('src' => $this->_findData('livesearch.js')))); - $already = 1; + $already = 1; } } // Immediate title search results via XMLHttpRequest // using the shipped moacdropdown js-lib function initMoAcDropDown() { - //subclasses of Sidebar will init this twice - static $already = 0; + //subclasses of Sidebar will init this twice + static $already = 0; if (!$this->HTML_DUMP_SUFFIX and !$already) { $dir = $this->_findData('moacdropdown'); if (!DEBUG and ($css = $this->_findFile('moacdropdown/css/dropdown-min.css'))) { @@ -1492,27 +1492,27 @@ else window.onload = downloadJSAtOnload;'); $this->addMoreHeaders(HTML::style(array('type' => 'text/css'), " @import url( $dir/css/dropdown.css );\n")); } // if autocomplete_remote is used: (getobject2 also for calc. the showlist width) - if (DEBUG) { - foreach (array("mobrowser.js","modomevent3.js","modomt.js", - "modomext.js","getobject2.js","xmlextras.js") as $js) - { - $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/$js"))); - } - $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/acdropdown.js"))); - } else { + if (DEBUG) { + foreach (array("mobrowser.js","modomevent3.js","modomt.js", + "modomext.js","getobject2.js","xmlextras.js") as $js) + { + $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/$js"))); + } + $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/acdropdown.js"))); + } else { // already in wikicommon-min.js - ; //$this->addMoreHeaders(JavaScript('', array('src' => DATA_PATH . "/themes/default/moacdropdown.js"))); - } - /* - // for local xmlrpc requests - $xmlrpc_url = deduce_script_name(); - //if (1 or DATABASE_TYPE == 'dba') - $xmlrpc_url = DATA_PATH . "/RPC2.php"; - if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) - $xmlrpc_url .= ("?start_debug=".$_GET['start_debug']); + ; //$this->addMoreHeaders(JavaScript('', array('src' => DATA_PATH . "/themes/default/moacdropdown.js"))); + } + /* + // for local xmlrpc requests + $xmlrpc_url = deduce_script_name(); + //if (1 or DATABASE_TYPE == 'dba') + $xmlrpc_url = DATA_PATH . "/RPC2.php"; + if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug'])) + $xmlrpc_url .= ("?start_debug=".$_GET['start_debug']); $this->addMoreHeaders(JavaScript("var xmlrpc_url = '$xmlrpc_url'")); - */ - $already = 1; + */ + $already = 1; } } @@ -1609,14 +1609,14 @@ function dateStatusFunc(date, y, m, d) { return false;}')); * Callback when a user logs in */ function CbUserLogin (&$request, $userid) { - ; // do nothing + ; // do nothing } /** CbNewUserEdit (&$request, $userid) * Callback when a new user creates or edits a page */ function CbNewUserEdit (&$request, $userid) { - ; // i.e. create homepage with Template/UserPage + ; // i.e. create homepage with Template/UserPage } /** CbNewUserLogin (&$request, $userid) @@ -1626,14 +1626,14 @@ function dateStatusFunc(date, y, m, d) { return false;}')); * Let's say a new user is a user without homepage. */ function CbNewUserLogin (&$request, $userid) { - ; // do nothing + ; // do nothing } /** CbUserLogout (&$request, $userid) * Callback when a user logs out */ function CbUserLogout (&$request, $userid) { - ; // do nothing + ; // do nothing } }; @@ -1800,7 +1800,7 @@ class PluginSidebarBox extends SidebarBox { var $_plugin, $_args = false, $_basepage = false; function PluginSidebarBox($name, $args = false, $basepage = false) { - require_once("lib/WikiPlugin.php"); + require_once("lib/WikiPlugin.php"); $loader = new WikiPluginLoader(); $plugin = $loader->getPlugin($name); diff --git a/lib/WikiUser.php b/lib/WikiUser.php index 42289b487..204bb2263 100644 --- a/lib/WikiUser.php +++ b/lib/WikiUser.php @@ -51,7 +51,7 @@ function UpgradeUser ($olduser, $user) { if (isa($user,'WikiUser') and isa($olduser,'WikiUser')) { // populate the upgraded class with the values from the old object foreach (get_object_vars($olduser) as $k => $v) { - $user->$k = $v; + $user->$k = $v; } $GLOBALS['request']->_user = $user; return $user; @@ -61,7 +61,7 @@ function UpgradeUser ($olduser, $user) { } /** -* +* */ class WikiUser { var $_userid = false; @@ -71,8 +71,8 @@ class WikiUser { /** * Constructor. - * - * Populates the instance variables and calls $this->_ok() + * + * Populates the instance variables and calls $this->_ok() * to ensure that the parameters are valid. * @param mixed $userid String of username or WikiUser object. * @param integer $authlevel Authorization level. @@ -103,7 +103,7 @@ class WikiUser { /** * Get the string indicating how the user was authenticated. - * + * * Get the string indicating how the user was authenticated. * Does not seem to be set - jbw * @return string The method of authentication. @@ -114,8 +114,8 @@ class WikiUser { /** * Invariant - * - * If the WikiUser object has a valid authorization level and the + * + * If the WikiUser object has a valid authorization level and the * userid is a string returns true, else false. * @return boolean If valid level and username string true, else false */ @@ -147,7 +147,7 @@ class WikiUser { } function getAuthenticatedId() { - //assert($this->_request); + //assert($this->_request); return ( $this->isAuthenticated() ? $this->_userid : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals @@ -352,7 +352,7 @@ class WikiUser { } // No cookies anymore for all prefs, only the userid. PHP creates - // a session cookie in memory, which is much more efficient, + // a session cookie in memory, which is much more efficient, // but not persistent. Get persistency with a homepage or DB Prefs // // Return the number of changed entries @@ -389,7 +389,7 @@ class WikiUser { // An "empty" page could still be // intentionally locked by admin to // prevent its creation. - // + // // FIXME: This permission situation should // probably be handled by the DB backend, // once the new WikiUser code has been @@ -431,7 +431,7 @@ class WikiUser { if (empty($this->_dbi)) { if (DEBUG) printSimpleTrace(debug_backtrace()); } else { - $this->_homepage = $this->_dbi->getPage($this->_userid); + $this->_homepage = $this->_dbi->getPage($this->_userid); } return $this->_homepage; } @@ -539,7 +539,7 @@ class WikiUser { $prefs = $this->getPreferences(); if (ENCRYPTED_PASSWD) $prefs->set('passwd', crypt($newpasswd)); - else + else $prefs->set('passwd', $newpasswd); $this->setPreferences($prefs); return true; diff --git a/lib/WikiUserNew.php b/lib/WikiUserNew.php index 278858d3d..5a7ff4d00 100644 --- a/lib/WikiUserNew.php +++ b/lib/WikiUserNew.php @@ -24,30 +24,30 @@ * This is a complete OOP rewrite of the old WikiUser code with various * configurable external authentication methods. * - * There's only one entry point, the function WikiUser which returns + * There's only one entry point, the function WikiUser which returns * a WikiUser object, which contains the name, authlevel and user's preferences. * This object might get upgraded during the login step and later also. * There exist three preferences storage methods: cookie, homepage and db, * and multiple password checking methods. - * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if + * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if * ALLOW_USER_PASSWORDS is defined. * - * Each user object must define the two preferences methods - * getPreferences(), setPreferences(), + * Each user object must define the two preferences methods + * getPreferences(), setPreferences(), * and the following 1-4 auth methods * checkPass() must be defined by all classes, - * userExists() only if USER_AUTH_POLICY'=='strict' + * userExists() only if USER_AUTH_POLICY'=='strict' * mayChangePass() only if the password is storable. * storePass() only if the password is storable. * * WikiUser() given no name, returns an _AnonUser (anonymous user) - * object, who may or may not have a cookie. - * However, if the there's a cookie with the userid or a session, + * object, who may or may not have a cookie. + * However, if the there's a cookie with the userid or a session, * the user is upgraded to the matching user object. - * Given a user name, returns a _BogoUser object, who may or may not - * have a cookie and/or PersonalPage, one of the various _PassUser objects + * Given a user name, returns a _BogoUser object, who may or may not + * have a cookie and/or PersonalPage, one of the various _PassUser objects * or an _AdminUser object. - * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might + * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might * have stored a password or not. If so, his account is secure, if not * anybody can use it, because the username is visible e.g. in RecentChanges. * @@ -55,46 +55,46 @@ * user's page and any cookies. lib/main.php will query the user object to * verify the password as appropriate. * - * @author: Reini Urban (the tricky parts), + * @author: Reini Urban (the tricky parts), * Carsten Klapp (started rolling the ball) * * Random architectural notes, sorted by date: * 2004-01-25 rurban * Test it by defining ENABLE_USER_NEW in config/config.ini * 1) Now a ForbiddenUser is returned instead of false. - * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit, - * but may browse. Now with ALLOW_ANON_USER = false he may not browse, + * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit, + * but may browse. Now with ALLOW_ANON_USER = false he may not browse, * which is needed to disable browse PagePermissions. - * I added now ALLOW_ANON_EDIT = true to makes things clear. + * I added now ALLOW_ANON_EDIT = true to makes things clear. * (which replaces REQUIRE_SIGNIN_BEFORE_EDIT) * 2004-02-27 rurban: - * 3) Removed pear prepare. Performance hog, and using integers as + * 3) Removed pear prepare. Performance hog, and using integers as * handler doesn't help. Do simple sprintf as with adodb. And a prepare - * in the object init is no advantage, because in the init loop a lot of + * in the object init is no advantage, because in the init loop a lot of * objects are tried, but not used. - * 4) Already gotten prefs are passed to the next object to avoid + * 4) Already gotten prefs are passed to the next object to avoid * duplicate getPreferences() calls. * 2004-03-18 rurban * 5) Major php-5 problem: $this re-assignment is disallowed by the parser - * So we cannot just discrimate with + * So we cannot just discrimate with * if (!check_php_version(5)) * $this = $user; - * A /php5-patch.php is provided, which patches the src automatically + * A /php5-patch.php is provided, which patches the src automatically * for php4 and php5. Default is php4. * Update: not needed anymore. we use eval to fool the load-time syntax checker. * 2004-03-24 rurban * 6) enforced new cookie policy: prefs don't get stored in cookies - * anymore, only in homepage and/or database, but always in the + * anymore, only in homepage and/or database, but always in the * current session. old pref cookies will get deleted. * 2004-04-04 rurban - * 7) Certain themes should be able to extend the predefined list + * 7) Certain themes should be able to extend the predefined list * of preferences. Display/editing is done in the theme specific userprefs.tmpl, * but storage must be extended to the Get/SetPreferences methods. * /themeinfo.php must provide CustomUserPreferences: * A list of name => _UserPreference class pairs. * 2010-06-07 rurban - * Fixed a nasty recursion bug (i.e. php crash), when user = new class - * which returned false, did not return false on php-4.4.7. Check for + * Fixed a nasty recursion bug (i.e. php crash), when user = new class + * which returned false, did not return false on php-4.4.7. Check for * a object member now. */ @@ -127,7 +127,7 @@ if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0); $EMailHosts = array('avl.com' => 'mail.avl.com'); /** - * There are be the following constants in config/config.ini to + * There are be the following constants in config/config.ini to * establish login parameters: * * ALLOW_ANON_USER default true @@ -150,7 +150,7 @@ $EMailHosts = array('avl.com' => 'mail.avl.com'); * any page. * * There are other possible combinations, but the typical wiki (such - * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four + * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four * enabled. * */ @@ -208,26 +208,26 @@ function _determineBogoUserOrPassUser($UserName) { return $_BogoUser; } if (_isUserPasswordsAllowed()) { - // PassUsers override BogoUsers if a password is stored - if (isset($_BogoUser) and isset($_BogoUser->_prefs) + // PassUsers override BogoUsers if a password is stored + if (isset($_BogoUser) and isset($_BogoUser->_prefs) and $_BogoUser->_prefs->get('passwd')) return new _PassUser($UserName, $_BogoUser->_prefs); - else { + else { $_PassUser = new _PassUser($UserName, isset($_BogoUser) ? $_BogoUser->_prefs : false); if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) { - if (isset($GLOBALS['request']->_user_class)) - $class = $GLOBALS['request']->_user_class; - elseif (strtolower(get_class($_PassUser)) == "_passuser") - $class = $_PassUser->nextClass(); - else - $class = get_class($_PassUser); - if ($user = new $class($UserName, $_PassUser->_prefs) - and $user->_userid) { - return $user; - } else { - return $_PassUser; - } + if (isset($GLOBALS['request']->_user_class)) + $class = $GLOBALS['request']->_user_class; + elseif (strtolower(get_class($_PassUser)) == "_passuser") + $class = $_PassUser->nextClass(); + else + $class = get_class($_PassUser); + if ($user = new $class($UserName, $_PassUser->_prefs) + and $user->_userid) { + return $user; + } else { + return $_PassUser; + } } } } @@ -239,7 +239,7 @@ function _determineBogoUserOrPassUser($UserName) { /** * Primary WikiUser function, called by lib/main.php. - * + * * This determines the user's type and returns an appropriate user * object. lib/main.php then querys the resultant object for password * validity as necessary. @@ -247,9 +247,9 @@ function _determineBogoUserOrPassUser($UserName) { * If an _AnonUser object is returned, the user may only browse pages * (and save prefs in a cookie). * - * To disable access but provide prefs the global $ForbiddenUser class + * To disable access but provide prefs the global $ForbiddenUser class * is returned. (was previously false) - * + * */ function WikiUser ($UserName = '') { global $ForbiddenUser, $HTTP_SESSION_VARS; @@ -308,7 +308,7 @@ function UpgradeUser ($user, $newuser) { if (isa($user,'_WikiUser') and isa($newuser,'_WikiUser')) { // populate the upgraded class $newuser with the values from the current user object //only _auth_level, _current_method, _current_index, - if (!empty($user->_level) and + if (!empty($user->_level) and $user->_level > $newuser->_level) $newuser->_level = $user->_level; if (!empty($user->_current_index) and @@ -318,10 +318,10 @@ function UpgradeUser ($user, $newuser) { } if (!empty($user->_authmethod)) $newuser->_authmethod = $user->_authmethod; - $GLOBALS['request']->_user_class = get_class($newuser); + $GLOBALS['request']->_user_class = get_class($newuser); /* foreach (get_object_vars($user) as $k => $v) { - if (!empty($v)) $olduser->$k = $v; + if (!empty($v)) $olduser->$k = $v; } */ $newuser->hasHomePage(); // revive db handle, because these don't survive sessions @@ -340,7 +340,7 @@ function UserExists ($UserName) { global $request; if (!($user = $request->getUser())) $user = WikiUser($UserName); - if (!$user) + if (!$user) return false; if ($user->userExists($UserName)) { $request->_user = $user; @@ -394,7 +394,7 @@ class _WikiUser } function setPreferences($prefs, $id_only) { - trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." + trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " " . "New subclasses of _WikiUser must override this function."); return false; @@ -406,7 +406,7 @@ class _WikiUser function checkPass($submitted_password) { // By definition, an undefined user class cannot sign in. - trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." + trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " " . "New subclasses of _WikiUser must override this function."); return false; @@ -451,15 +451,15 @@ class _WikiUser } function nextAuthMethodIndex() { - if (empty($this->_auth_methods)) + if (empty($this->_auth_methods)) $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER']; if (empty($this->_current_index)) { if (strtolower(get_class($this)) != '_passuser') { - $this->_current_method = substr(get_class($this),1,-8); + $this->_current_method = substr(get_class($this),1,-8); $this->_current_index = $this->array_position($this->_current_method, $this->_auth_methods); } else { - $this->_current_index = -1; + $this->_current_index = -1; } } $this->_current_index++; @@ -470,8 +470,8 @@ class _WikiUser } function AuthMethod($index = false) { - return $this->_auth_methods[ $index === false - ? count($this->_auth_methods)-1 + return $this->_auth_methods[ $index === false + ? count($this->_auth_methods)-1 : $index]; } @@ -527,7 +527,7 @@ class _WikiUser } function isAdmin () { - static $group; + static $group; if ($this->_level == WIKIAUTH_ADMIN) return true; if (!$this->isSignedIn()) return false; if (!$this->isAuthenticated()) return false; @@ -556,7 +556,7 @@ class _WikiUser return $this->_level >= $require_level; } - /* This is quite restrictive and not according the login description online. + /* This is quite restrictive and not according the login description online. Any word char (A-Za-z0-9_), " ", ".", "@" and "-" The backends may loosen or tighten this. */ @@ -583,33 +583,33 @@ class _WikiUser $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level)); if ($logout) { // Log out - if (LOGIN_LOG and is_writeable(LOGIN_LOG)) { - global $request; - $zone_offset = Request_AccessLogEntry::_zone_offset(); - $ncsa_time = date("d/M/Y:H:i:s", time()); - $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"', - (string) $request->get('REMOTE_HOST'), - (string) $request->_user->_userid, - $ncsa_time, $zone_offset, - "logout ".get_class($request->_user), - "401", - (string) $request->get('HTTP_REFERER'), - (string) $request->get('HTTP_USER_AGENT') - ); - if (($fp = fopen(LOGIN_LOG, "a"))) { - flock($fp, LOCK_EX); - fputs($fp, "$entry\n"); - fclose($fp); - } - //error_log("$entry\n", 3, LOGIN_LOG); - } + if (LOGIN_LOG and is_writeable(LOGIN_LOG)) { + global $request; + $zone_offset = Request_AccessLogEntry::_zone_offset(); + $ncsa_time = date("d/M/Y:H:i:s", time()); + $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"', + (string) $request->get('REMOTE_HOST'), + (string) $request->_user->_userid, + $ncsa_time, $zone_offset, + "logout ".get_class($request->_user), + "401", + (string) $request->get('HTTP_REFERER'), + (string) $request->get('HTTP_USER_AGENT') + ); + if (($fp = fopen(LOGIN_LOG, "a"))) { + flock($fp, LOCK_EX); + fputs($fp, "$entry\n"); + fclose($fp); + } + //error_log("$entry\n", 3, LOGIN_LOG); + } if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser - $GLOBALS['request']->_user->logout(); + $GLOBALS['request']->_user->logout(); } $user = new _AnonUser(); $user->_userid = ''; $user->_level = WIKIAUTH_ANON; - return $user; + return $user; } elseif ($cancel) return false; // User hit cancel button. elseif (!$login && !$userid) @@ -620,47 +620,47 @@ class _WikiUser $authlevel = $this->checkPass($passwd === false ? '' : $passwd); - if (LOGIN_LOG and is_writeable(LOGIN_LOG)) { - global $request; - $zone_offset = Request_AccessLogEntry::_zone_offset(); - $ncsa_time = date("d/M/Y:H:i:s", time()); - $manglepasswd = $passwd; - for ($i=0; $i= 127) $manglepasswd[$i] = ">"; - } + if (LOGIN_LOG and is_writeable(LOGIN_LOG)) { + global $request; + $zone_offset = Request_AccessLogEntry::_zone_offset(); + $ncsa_time = date("d/M/Y:H:i:s", time()); + $manglepasswd = $passwd; + for ($i=0; $i= 127) $manglepasswd[$i] = ">"; + } if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd; - $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"', - $request->get('REMOTE_HOST'), - (string) $request->_user->_userid, - $ncsa_time, $zone_offset, - "login $userid/$manglepasswd => $authlevel ".get_class($request->_user), - $authlevel > 0 ? "200" : "403", - (string) $request->get('HTTP_REFERER'), - (string) $request->get('HTTP_USER_AGENT') - ); - if (($fp = fopen(LOGIN_LOG, "a"))) { - flock($fp, LOCK_EX); - fputs($fp, "$entry\n"); - fclose($fp); - } - //error_log("$entry\n", 3, LOGIN_LOG); - } + $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"', + $request->get('REMOTE_HOST'), + (string) $request->_user->_userid, + $ncsa_time, $zone_offset, + "login $userid/$manglepasswd => $authlevel ".get_class($request->_user), + $authlevel > 0 ? "200" : "403", + (string) $request->get('HTTP_REFERER'), + (string) $request->get('HTTP_USER_AGENT') + ); + if (($fp = fopen(LOGIN_LOG, "a"))) { + flock($fp, LOCK_EX); + fputs($fp, "$entry\n"); + fclose($fp); + } + //error_log("$entry\n", 3, LOGIN_LOG); + } if ($authlevel <= 0) { // anon or forbidden if ($passwd) return _("Invalid password."); else return _("Invalid password or userid."); - } elseif ($authlevel < $require_level) { // auth ok, but not enough - if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') + } elseif ($authlevel < $require_level) { // auth ok, but not enough + if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') { // upgrade class $class = "_" . $this->_current_method . "PassUser"; @@ -679,8 +679,8 @@ class _WikiUser // Successful login. //$user = $GLOBALS['request']->_user; - if (!empty($this->_current_method) and - strtolower(get_class($this)) == '_passuser') + if (!empty($this->_current_method) and + strtolower(get_class($this)) == '_passuser') { // upgrade class $class = "_" . $this->_current_method . "PassUser"; @@ -706,7 +706,7 @@ class _WikiUser class _AnonUser extends _WikiUser { - var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated + var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated /** Anon only gets to load and save prefs in a cookie, that's it. */ @@ -720,7 +720,7 @@ extends _WikiUser // Try to read deprecated 1.3.x style cookies if ($cookie = $request->cookies->get_old(WIKI_NAME)) { if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) { - trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.") + trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.") . "\n" . sprintf("%s='%s'", WIKI_NAME, $cookie) . "\n" @@ -739,8 +739,8 @@ extends _WikiUser $UserName = @$unboxedcookie['userid']; if (is_string($UserName) and (substr($UserName,0,2) != 's:')) $this->_userid = $UserName; - else - $UserName = false; + else + $UserName = false; } // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies if (!headers_sent()) @@ -755,8 +755,8 @@ extends _WikiUser $UserName = $unboxedcookie['userid']; if (is_string($UserName) and (substr($UserName,0,2) != 's:')) $this->_userid = $UserName; - else - $UserName = false; + else + $UserName = false; } if (!headers_sent()) $request->deleteCookieVar("WIKI_PREF2"); @@ -813,7 +813,7 @@ extends _WikiUser if ($updated) { if ($id_only and !headers_sent()) { global $request; - // new 1.3.8 policy: no array cookies, only plain userid string as in + // new 1.3.8 policy: no array cookies, only plain userid string as in // the pre 1.3.x versions. // prefs should be stored besides the session in the homepagehandle or in a db. $request->setCookieVar(getCookieName(), $this->_userid, @@ -827,8 +827,8 @@ extends _WikiUser $unpacked = $prefs->unpack($packed); if (count($unpacked)) { foreach (array('_method','_select','_update','_insert') as $param) { - if (!empty($this->_prefs->{$param})) - $prefs->{$param} = $this->_prefs->{$param}; + if (!empty($this->_prefs->{$param})) + $prefs->{$param} = $this->_prefs->{$param}; } $this->_prefs = $prefs; } @@ -855,7 +855,7 @@ extends _WikiUser } /** - * Helper class to finish the PassUser auth loop. + * Helper class to finish the PassUser auth loop. * This is added automatically to USER_AUTH_ORDER. */ class _ForbiddenUser @@ -877,7 +877,7 @@ extends _AnonUser * Do NOT extend _BogoUser to other classes, for checkPass() * security. (In case of defects in code logic of the new class!) * The intermediate step between anon and passuser. - * We also have the _BogoLoginPassUser class with stricter + * We also have the _BogoLoginPassUser class with stricter * password checking, which fits into the auth loop. * Note: This class is not called anymore by WikiUser() */ @@ -906,14 +906,14 @@ extends _AnonUser /** * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed. * - * The classes for all subsequent auth methods extend from this class. - * This handles the auth method type dispatcher according $USER_AUTH_ORDER, + * The classes for all subsequent auth methods extend from this class. + * This handles the auth method type dispatcher according $USER_AUTH_ORDER, * the three auth method policies first-only, strict and stacked - * and the two methods for prefs: homepage or database, + * and the two methods for prefs: homepage or database, * if $DBAuthParams['pref_select'] is defined. * * Default is PersonalPage auth and prefs. - * + * * @author: Reini Urban * @tables: pref */ @@ -937,40 +937,40 @@ extends _AnonUser // Check the configured Prefs methods $dbi = $this->getAuthDbh(); $dbh = $GLOBALS['request']->getDbh(); - if ( $dbi - and !$dbh->readonly - and !isset($this->_prefs->_select) - and $dbh->getAuthParam('pref_select')) + if ( $dbi + and !$dbh->readonly + and !isset($this->_prefs->_select) + and $dbh->getAuthParam('pref_select')) { if (!$this->_prefs) { - $this->_prefs = new UserPreferences(); - $need_pref = true; + $this->_prefs = new UserPreferences(); + $need_pref = true; } $this->_prefs->_method = $dbh->getParam('dbtype'); $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid"); // read-only prefs? if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) { - $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'), + $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'), array("userid", "pref_blob")); } } else { if (!$this->_prefs) { - $this->_prefs = new UserPreferences(); - $need_pref = true; + $this->_prefs = new UserPreferences(); + $need_pref = true; } $this->_prefs->_method = 'HomePage'; } - + if (! $this->_prefs or isset($need_pref) ) { if ($prefs) $this->_prefs = $prefs; else $this->getPreferences(); } - + // Upgrade to the next parent _PassUser class. Avoid recursion. if ( strtolower(get_class($this)) === '_passuser' ) { //auth policy: Check the order of the configured auth methods // 1. first-only: Upgrade the class here in the constructor - // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as + // 2. old: ignore USER_AUTH_ORDER and try to use all available methods as /// in the previous PhpWiki releases (slow) // 3. strict: upgrade the class after checking the user existance in userExists() // 4. stacked: upgrade the class after the password verification in checkPass() @@ -1009,7 +1009,7 @@ extends _AnonUser return $user; } } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and - defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and + defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_connect')) { include_once("lib/WikiUser/LDAP.php"); if (check_php_version(5)) @@ -1054,7 +1054,7 @@ extends _AnonUser } } } - else + else // else use the page methods defined in _PassUser. return $this; } @@ -1065,7 +1065,7 @@ extends _AnonUser global $request; //, $DBParams, $DBAuthParams; $dbh = $request->getDbh(); - // session restauration doesn't re-connect to the database automatically, + // session restauration doesn't re-connect to the database automatically, // so dirty it here, to force a reconnect. if (isset($this->_auth_dbi)) { if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection)) @@ -1074,22 +1074,22 @@ extends _AnonUser unset($this->_auth_dbi); } if (empty($this->_auth_dbi)) { - if ($dbh->getParam('dbtype') != 'SQL' + if ($dbh->getParam('dbtype') != 'SQL' and $dbh->getParam('dbtype') != 'ADODB' and $dbh->getParam('dbtype') != 'PDO') return false; if (empty($GLOBALS['DBAuthParams'])) return false; if (!$dbh->getAuthParam('auth_dsn')) { - $dbh = $request->getDbh(); // use phpwiki database + $dbh = $request->getDbh(); // use phpwiki database } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) { - $dbh = $request->getDbh(); // same phpwiki database + $dbh = $request->getDbh(); // same phpwiki database } else { // use another external database handle. needs PHP >= 4.1 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']); $local_params['dsn'] = $local_params['auth_dsn']; $dbh = WikiDB::open($local_params); - } - $this->_auth_dbi =& $dbh->_backend->_dbh; + } + $this->_auth_dbi =& $dbh->_backend->_dbh; } return $this->_auth_dbi; } @@ -1108,7 +1108,7 @@ extends _AnonUser // TODO: use it again for the auth and member tables // sprintfstyle vs prepare style: %s or ? - // multiple vars should be executed via prepare(?,?)+execute, + // multiple vars should be executed via prepare(?,?)+execute, // single vars with execute(sprintf(quote(var))) // help with position independency function prepare ($stmt, $variables, $oldstyle = false, $sprintfstyle = true) { @@ -1121,7 +1121,7 @@ extends _AnonUser $new = array(); if (is_array($variables)) { //$sprintfstyle = false; - for ($i=0; $i < count($variables); $i++) { + for ($i=0; $i < count($variables); $i++) { $var = $this->_normalize_stmt_var($variables[$i], $oldstyle); if (!$var) trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s", @@ -1129,7 +1129,7 @@ extends _AnonUser $variables[$i] = $var; if (!$var) $new[] = ''; else { - $s = "%" . ($i+1) . "s"; + $s = "%" . ($i+1) . "s"; $new[] = $sprintfstyle ? $s : "?"; } } @@ -1139,16 +1139,16 @@ extends _AnonUser trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s", $variables, $stmt), E_USER_WARNING); $variables = $var; - if (!$var) $new = ''; - else $new = $sprintfstyle ? '%s' : "?"; + if (!$var) $new = ''; + else $new = $sprintfstyle ? '%s' : "?"; } $prefix = $dbi->getParam('prefix'); // probably prefix table names if in same database - if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and + if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn'))) { if (!stristr($stmt, $prefix)) { - $oldstmt = $stmt; + $oldstmt = $stmt; $stmt = str_replace(array(" user "," pref "," member "), array(" ".$prefix."user ", " ".$prefix."pref ", @@ -1230,14 +1230,14 @@ extends _AnonUser } if ($updated = _AnonUser::setPreferences($prefs, $id_only)) { // Encode only the _prefs array of the UserPreference object - // If no DB method exists to store the prefs we must store it in the page, not in the cookies. + // If no DB method exists to store the prefs we must store it in the page, not in the cookies. if (empty($this->_HomePagehandle)) { $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid); - } + } if (! $this->_HomePagehandle->exists() ) { $this->createHomePage(); } - if (!empty($this->_HomePagehandle) and !$id_only) { + if (!empty($this->_HomePagehandle) and !$id_only) { $this->_HomePagehandle->set('pref', $this->_prefs->store()); } } @@ -1248,7 +1248,7 @@ extends _AnonUser return true; } - //The default method is getting the password from prefs. + //The default method is getting the password from prefs. // child methods obtain $stored_password from external auth. function userExists() { //if ($this->_HomePagehandle) return true; @@ -1276,7 +1276,7 @@ extends _AnonUser return false; } - //The default method is getting the password from prefs. + //The default method is getting the password from prefs. // child methods obtain $stored_password from external auth. function checkPass($submitted_password) { $stored_password = $this->_prefs->get('passwd'); @@ -1309,11 +1309,11 @@ extends _AnonUser * @see UserPreferences::set * * DBPassUser password's have their own crypt definition. - * That's why DBPassUser::checkPass() doesn't call this method, if - * the db password method is 'plain', which means that the DB SQL - * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and + * That's why DBPassUser::checkPass() doesn't call this method, if + * the db password method is 'plain', which means that the DB SQL + * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and * don't store plain passwords in the DB. - * + * * TODO: remove crypt() function check from config.php:396 ?? */ function _checkPass($submitted_password, $stored_password) { @@ -1361,8 +1361,8 @@ extends _AnonUser return false; } - /** The default method is storing the password in prefs. - * Child methods (DB, File) may store in external auth also, but this + /** The default method is storing the password in prefs. + * Child methods (DB, File) may store in external auth also, but this * must be explicitly enabled. * This may be called by plugin/UserPreferences or by ->SetPreferences() */ @@ -1381,7 +1381,7 @@ extends _AnonUser $this->SetPreferences($this->_prefs); return true; } - //Todo: return an error msg to the caller what failed? + //Todo: return an error msg to the caller what failed? // same password or no privilege return ENCRYPTED_PASSWD ? true : false; } @@ -1415,12 +1415,12 @@ extends _AnonUser $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser'; } if (USER_AUTH_POLICY === 'strict' - or USER_AUTH_POLICY === 'stacked') { + or USER_AUTH_POLICY === 'stacked') { $class = $this->nextClass(); while ($user = new $class($this->_userid, $this->_prefs)) { if (!check_php_version(5)) eval("\$this = \$user;"); - $user = UpgradeUser($this, $user); + $user = UpgradeUser($this, $user); if ($user->userExists()) { $user = UpgradeUser($this, $user); return true; @@ -1436,7 +1436,7 @@ extends _AnonUser /** * Insert more auth classes here... - * For example a customized db class for another db connection + * For example a customized db class for another db connection * or a socket-based auth server. * */ @@ -1448,7 +1448,7 @@ extends _AnonUser * * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser! * Other members of the Administrators group must raise their level otherwise somehow. - * Currently every member is a AdminUser, which will not work for the various + * Currently every member is a AdminUser, which will not work for the various * storage methods. */ class _AdminUser @@ -1458,7 +1458,7 @@ extends _PassUser return false; } function checkPass($submitted_password) { - if ($this->_userid == ADMIN_USER) + if ($this->_userid == ADMIN_USER) $stored_password = ADMIN_PASSWD; else { // Should not happen! Only ADMIN_USER should use this class. @@ -1481,7 +1481,7 @@ extends _PassUser } function storePass($submitted_password) { - if ($this->_userid == ADMIN_USER) + if ($this->_userid == ADMIN_USER) return false; else { // should not happen! only ADMIN_USER should use this class. @@ -1492,9 +1492,9 @@ extends _PassUser /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** - * Various data classes for the preference types, + * Various data classes for the preference types, * to support get, set, sanify (range checking, ...) - * update() will do the neccessary side-effects if a + * update() will do the neccessary side-effects if a * setting gets changed (theme, language, ...) */ @@ -1511,36 +1511,36 @@ class _UserPreference } function get ($name) { - if (isset($this->{$name})) - return $this->{$name}; - else + if (isset($this->{$name})) + return $this->{$name}; + else return $this->default_value; } function getraw ($name) { - if (!empty($this->{$name})) - return $this->{$name}; + if (!empty($this->{$name})) + return $this->{$name}; } // stores the value as $this->$name, and not as $this->value (clever?) function set ($name, $value) { - $return = 0; - $value = $this->sanify($value); - if ($this->get($name) != $value) { - $this->update($value); - $return = 1; - } - if ($value != $this->default_value) { - $this->{$name} = $value; + $return = 0; + $value = $this->sanify($value); + if ($this->get($name) != $value) { + $this->update($value); + $return = 1; + } + if ($value != $this->default_value) { + $this->{$name} = $value; } else { unset($this->{$name}); } return $return; } - // default: no side-effects + // default: no side-effects function update ($value) { - ; + ; } } @@ -1620,7 +1620,7 @@ extends _UserPreference return (string) $value; } - + function update ($newvalue) { if (! $this->_init ) { // invalidate etag to force fresh output @@ -1663,7 +1663,7 @@ class _UserPreference_notify extends _UserPreference { function sanify ($value) { - if (!empty($value)) + if (!empty($value)) return $value; else return $this->default_value; @@ -1671,18 +1671,18 @@ extends _UserPreference /** update to global user prefs: side-effect on set notify changes * use a global_data notify hash: - * notify = array('pagematch' => array(userid => ('email' => mail, + * notify = array('pagematch' => array(userid => ('email' => mail, * 'verified' => 0|1), * ...), * ...); */ function update ($value) { - if (!empty($this->_init)) return; + if (!empty($this->_init)) return; $dbh = $GLOBALS['request']->getDbh(); $notify = $dbh->get('notify'); if (empty($notify)) $data = array(); - else + else $data =& $notify; // expand to existing pages only or store matches? // for now we store (glob-style) matches which is easier for the user @@ -1710,7 +1710,7 @@ extends _UserPreference if (!isset($data[$page])) $data[$page] = array(); if (!isset($data[$page][$userid])) { - // should we really store the verification notice here or + // should we really store the verification notice here or // check it dynamically at every page->save? if ($verified) { $data[$page][$userid] = array('email' => $email, @@ -1763,7 +1763,7 @@ extends _UserPreference return $this->default_value; } } - + /** Side-effect on email changes: * Send a verification mail or for now just a notification email. * For true verification (value = 2), we'd need a mailserver hook. @@ -1771,7 +1771,7 @@ extends _UserPreference function update($value) { // e-mail address is already checked by FusionForge if (FUSIONFORGE) return $value; - if (!empty($this->_init)) return; + if (!empty($this->_init)) return; $verified = $this->getraw('emailVerified'); // hack! if (($value == 1 or $value === true) and $verified) @@ -1783,7 +1783,7 @@ extends _UserPreference WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true)))) { $this->set('emailVerified',1); } else { - trigger_error($msg, E_USER_WARNING); + trigger_error($msg, E_USER_WARNING); } } } @@ -1833,7 +1833,7 @@ function ValidateMail($email, $noconnect=false) { $mailbox = "(?:$addr_spec|$phrase$route_addr)"; $rfc822re = "/$lwsp*$mailbox/"; - unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart, + unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart, $atom, $word, $quoted_string); unset($dtext, $controls, $specials, $lwsp, $domain_literal); @@ -1847,11 +1847,11 @@ function ValidateMail($email, $noconnect=false) { list ( $Username, $Domain ) = explode("@", $email); //Todo: getmxrr workaround on windows or manual input field to verify it manually - if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows. + if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows. $ConnectAddress = $MXHost[0]; } else { $ConnectAddress = $Domain; - if (isset($EMailHosts[ $Domain ])) { + if (isset($EMailHosts[ $Domain ])) { $ConnectAddress = $EMailHosts[ $Domain ]; } } @@ -1889,16 +1889,16 @@ function ValidateMail($email, $noconnect=false) { $result[0]=true; $result[1]="E-mail address '$email' appears to be valid."; return $result; -} // end of function +} // end of function /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * UserPreferences - * + * * This object holds the $request->_prefs subobjects. * A simple packed array of non-default values get's stored as cookie, - * homepage, or database, which are converted to the array of + * homepage, or database, which are converted to the array of * ->_prefs objects. * We don't store the objects, because otherwise we will * not be able to upgrade any subobject. And it's a waste of space also. @@ -1907,20 +1907,20 @@ function ValidateMail($email, $noconnect=false) { class UserPreferences { var $notifyPagesAll; - + function UserPreferences($saved_prefs = false) { // userid stored too, to ensure the prefs are being loaded for // the correct (currently signing in) userid if stored in a // cookie. - // Update: for db prefs we disallow passwd. - // userid is needed for pref reflexion. current pref must know its username, + // Update: for db prefs we disallow passwd. + // userid is needed for pref reflexion. current pref must know its username, // if some app needs prefs from different users, different from current user. $this->_prefs = array( 'userid' => new _UserPreference(''), 'passwd' => new _UserPreference(''), 'autologin' => new _UserPreference_bool(), - //'emailVerified' => new _UserPreference_emailVerified(), + //'emailVerified' => new _UserPreference_emailVerified(), //fixed: store emailVerified as email parameter, 1.3.8 'email' => new _UserPreference_email(''), 'notifyPages' => new _UserPreference_notify(''), // 1.3.8 @@ -1929,7 +1929,7 @@ class UserPreferences 'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS, EDITWIDTH_MIN_COLS, EDITWIDTH_MAX_COLS), - 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8 + 'noLinkIcons' => new _UserPreference_bool(), // 1.3.8 'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS, EDITHEIGHT_MIN_ROWS, EDITHEIGHT_MAX_ROWS), @@ -1968,7 +1968,7 @@ class UserPreferences } // add custom theme-specific pref types: - // FIXME: on theme changes the wiki_user session pref object will fail. + // FIXME: on theme changes the wiki_user session pref object will fail. // We will silently ignore this. if (!empty($customUserPreferenceColumns)) $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns); @@ -1993,8 +1993,8 @@ class UserPreferences } function _getPref($name) { - if ($name == 'emailVerified') - $name = 'email'; + if ($name == 'emailVerified') + $name = 'email'; if (!isset($this->_prefs[$name])) { if ($name == 'passwd2') return false; if ($name == 'passwd') return false; @@ -2003,16 +2003,16 @@ class UserPreferences } return $this->_prefs[$name]; } - + // get the value or default_value of the subobject function get($name) { - if ($_pref = $this->_getPref($name)) - if ($name == 'emailVerified') - return $_pref->getraw($name); - else - return $_pref->get($name); - else - return false; + if ($_pref = $this->_getPref($name)) + if ($name == 'emailVerified') + return $_pref->getraw($name); + else + return $_pref->get($name); + else + return false; } // check and set the new value in the subobject @@ -2022,8 +2022,8 @@ class UserPreferences return false; /* do it here or outside? */ - if ($name == 'passwd' and - defined('PASSWORD_LENGTH_MINIMUM') and + if ($name == 'passwd' and + defined('PASSWORD_LENGTH_MINIMUM') and strlen($value) <= PASSWORD_LENGTH_MINIMUM ) { //TODO: How to notify the user? return false; @@ -2039,7 +2039,7 @@ class UserPreferences { if ($name == 'emailVerified') $newvalue = $value; else $newvalue = $pref->sanify($value); - $pref->set($name, $newvalue); + $pref->set($name, $newvalue); } $this->_prefs[$name] =& $pref; return true; @@ -2058,13 +2058,13 @@ class UserPreferences $count++; } foreach (array_keys($this->_prefs) as $type) { - $obj =& $this->_prefs[$type]; + $obj =& $this->_prefs[$type]; $obj->_init = $init; if ($prefs->get($type) !== $obj->get($type)) { // special systemdefault prefs: (probably not needed) - if ($type == 'theme' and $prefs->get($type) == '' and + if ($type == 'theme' and $prefs->get($type) == '' and $obj->get($type) == THEME) continue; - if ($type == 'lang' and $prefs->get($type) == '' and + if ($type == 'lang' and $prefs->get($type) == '' and $obj->get($type) == DEFAULT_LANGUAGE) continue; if ($this->_prefs[$type]->set($type, $prefs->get($type))) $count++; @@ -2073,12 +2073,12 @@ class UserPreferences } elseif (is_array($prefs)) { //unset($this->_prefs['userid']); /* - if (isset($this->_method) and - ($this->_method == 'SQL' or $this->_method == 'ADODB')) { + if (isset($this->_method) and + ($this->_method == 'SQL' or $this->_method == 'ADODB')) { unset($this->_prefs['passwd']); - } - */ - // emailVerified at first, the rest later + } + */ + // emailVerified at first, the rest later $type = 'emailVerified'; $obj =& $this->_prefs['email']; $obj->_init = $init; if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) { @@ -2086,17 +2086,17 @@ class UserPreferences $count++; } foreach (array_keys($this->_prefs) as $type) { - $obj =& $this->_prefs[$type]; + $obj =& $this->_prefs[$type]; $obj->_init = $init; - if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool")) + if (!isset($prefs[$type]) and isa($obj,"_UserPreference_bool")) $prefs[$type] = false; if (isset($prefs[$type]) and isa($obj,"_UserPreference_int")) $prefs[$type] = (int) $prefs[$type]; if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) { // special systemdefault prefs: - if ($type == 'theme' and $prefs[$type] == '' and + if ($type == 'theme' and $prefs[$type] == '' and $obj->get($type) == THEME) continue; - if ($type == 'lang' and $prefs[$type] == '' and + if ($type == 'lang' and $prefs[$type] == '' and $obj->get($type) == DEFAULT_LANGUAGE) continue; if ($obj->set($type,$prefs[$type])) $count++; @@ -2149,7 +2149,7 @@ class UserPreferences and substr($packed_pref, 0, 2) == "O:") { //legacy: check if it's an old array of objects - // Looks like a serialized object. + // Looks like a serialized object. // This might fail if the object definition does not exist anymore. // object with ->$name and ->default_value vars. $pref = @unserialize($packed_pref); @@ -2157,10 +2157,10 @@ class UserPreferences $prefs[$name] = $pref->get($name); // fix old-style prefs } elseif (is_numeric($name) and is_array($packed_pref)) { - if (count($packed_pref) == 1) { - list($name,$value) = each($packed_pref); - $prefs[$name] = $value; - } + if (count($packed_pref) == 1) { + list($name,$value) = each($packed_pref); + $prefs[$name] = $value; + } } else { if (isSerialized($packed_pref)) $prefs[$name] = @unserialize($packed_pref); @@ -2171,7 +2171,7 @@ class UserPreferences $prefs[$name] = $packed_pref; } } - + if (FUSIONFORGE) { // Restore notifyPages from notifyPagesAll // notifyPages are pages to notify in the current project @@ -2201,13 +2201,13 @@ class UserPreferences } function defaultPreferences() { - $prefs = array(); - foreach ($this->_prefs as $key => $obj) { - $prefs[$key] = $obj->default_value; - } - return $prefs; + $prefs = array(); + foreach ($this->_prefs as $key => $obj) { + $prefs[$key] = $obj->default_value; + } + return $prefs; } - + // array of objects function getAll() { return $this->_prefs; @@ -2247,7 +2247,7 @@ class CookieUserPreferences extends UserPreferences { function CookieUserPreferences ($saved_prefs = false) { - //_AnonUser::_AnonUser('',$saved_prefs); + //_AnonUser::_AnonUser('',$saved_prefs); UserPreferences::UserPreferences($saved_prefs); } } diff --git a/lib/WysiwygEdit.php b/lib/WysiwygEdit.php index 08012f4b7..83f7c97f9 100644 --- a/lib/WysiwygEdit.php +++ b/lib/WysiwygEdit.php @@ -7,10 +7,10 @@ * tinymce, htmlarea3, FCKeditor, spaw, htmlarea2, Wikiwyg * Not yet enabled as default, since we cannot convert HTML to Wiki Markup yet. * (See HtmlParser.php for the ongoing efforts) - * We might use a PageType=html, which is contra wiki, but some people + * We might use a PageType=html, which is contra wiki, but some people * might prefer HTML markup. * - * TODO: Change from ENABLE_WYSIWYG constant to user preference variable + * TODO: Change from ENABLE_WYSIWYG constant to user preference variable * (checkbox setting or edit click as in gmail), * when HtmlParser is finished. * Based upon htmlarea3.php and tinymce.php @@ -25,17 +25,17 @@ require_once("lib/InlineParser.php"); class WysiwygEdit { - function WysiwygEdit() { + function WysiwygEdit() { $this->_transformer_tags = false; } function Head($name='edit[content]') { - trigger_error("virtual", E_USER_ERROR); + trigger_error("virtual", E_USER_ERROR); } // to be called after function Textarea($textarea,$wikitext,$name='edit[content]') { - trigger_error("virtual", E_USER_ERROR); + trigger_error("virtual", E_USER_ERROR); } /** @@ -45,10 +45,10 @@ class WysiwygEdit { */ function ConvertBefore($text) { require_once("lib/BlockParser.php"); - $xml = TransformText($text, 2.0, $GLOBALS['request']->getArg('pagename')); + $xml = TransformText($text, 2.0, $GLOBALS['request']->getArg('pagename')); return $xml->AsXML(); } - + /** * FIXME: Handler to convert the HTML formatting back to wiki formatting. * Derived from InlineParser, but returning wiki text instead of HtmlElement objects. @@ -81,7 +81,7 @@ class Markup_html_simple_tag extends Markup_html_emphasis { case 'b': case 'strong': return "*".$body."*"; - case 'big': + case 'big': return "".$body.""; case 'i': case 'em': @@ -119,7 +119,7 @@ class Markup_html_spanbold extends BalancedMarkup class HtmlTransformer extends InlineTransformer { function HtmlTransformer ($tags = false) { - if (!$tags) $tags = + if (!$tags) $tags = array('escape','html_br','html_spanbold','html_simple_tag', 'html_p',); /* diff --git a/lib/XmlElement.php b/lib/XmlElement.php index 0fa79c786..ef42397e4 100644 --- a/lib/XmlElement.php +++ b/lib/XmlElement.php @@ -71,7 +71,7 @@ class XmlContent else array_unshift($this->_content, $item); } - + function getContent () { return $this->_content; } @@ -94,12 +94,12 @@ class XmlContent printf("==Object(%s)==", get_class($item)); } elseif (is_array($item)) { - // DEPRECATED: - // Use XmlContent objects instead of arrays for collections of XmlElements. - trigger_error("Passing arrays to printXML() is deprecated: (" . AsXML($item, true) . ")", + // DEPRECATED: + // Use XmlContent objects instead of arrays for collections of XmlElements. + trigger_error("Passing arrays to printXML() is deprecated: (" . AsXML($item, true) . ")", E_USER_NOTICE); - foreach ($item as $x) - $this->printXML($x); + foreach ($item as $x) + $this->printXML($x); } else { echo $this->_quote((string) $item); } @@ -118,10 +118,10 @@ class XmlContent $xml .= sprintf("==Object(%s)==", get_class($item)); } elseif (is_array($item)) { - trigger_error("Passing arrays to ->asXML() is deprecated: (" . AsXML($item, true) . ")", + trigger_error("Passing arrays to ->asXML() is deprecated: (" . AsXML($item, true) . ")", E_USER_NOTICE); - foreach ($item as $x) - $xml .= $this->asXML($x); + foreach ($item as $x) + $xml .= $this->asXML($x); } else $xml .= $this->_quote((string) $item); @@ -157,11 +157,11 @@ class XmlContent if (is_object($item)) { if (method_exists($item, 'asString')) { $string = $item->asString(); - if (is_object($string)) { - ; // ignore error so far: ImageLink labels - } else { + if (is_object($string)) { + ; // ignore error so far: ImageLink labels + } else { $val .= $this->_quote($item->asString()); - } + } } else { $val .= sprintf("==Object(%s)==", get_class($item)); } @@ -188,10 +188,10 @@ class XmlContent } return true; } - + function _quote ($string) { - if (!$string) return $string; - return htmlspecialchars($string, ENT_COMPAT, $GLOBALS['charset']); + if (!$string) return $string; + return htmlspecialchars($string, ENT_COMPAT, $GLOBALS['charset']); } }; @@ -215,7 +215,7 @@ class XmlElement extends XmlContent assert(count($args) >= 1); //assert(is_string($args[0])); $this->_tag = array_shift($args); - + if ($args && is_array($args[0])) $this->_attr = array_shift($args); else { @@ -226,7 +226,7 @@ class XmlElement extends XmlContent $this->setContent($args); } - + /** Methods only needed for XmlParser, * to be fully compatible to perl Html::Element */ @@ -241,7 +241,7 @@ class XmlElement extends XmlContent unset($this->_attr); unset($this->_content); } - + function getChildren () { return $this->_children; } @@ -255,19 +255,19 @@ class XmlElement extends XmlContent function getTag () { return $this->_tag; } - + function setAttr ($attr, $value = false) { - if (is_array($attr)) { + if (is_array($attr)) { assert($value === false); foreach ($attr as $a => $v) { $this->_attr[strtolower($a)] = $v; - //$this->set($a, $v); + //$this->set($a, $v); } return; - } + } assert(is_string($attr)); - + if ($value === false) { unset($this->_attr[$attr]); } @@ -277,42 +277,42 @@ class XmlElement extends XmlContent $this->_attr[$attr] = (string) $value; } - if ($attr == 'class') - unset($this->_classes); + if ($attr == 'class') + unset($this->_classes); } function getAttr ($attr) { - if ($attr == 'class') - $this->_setClasses(); + if ($attr == 'class') + $this->_setClasses(); - if (isset($this->_attr[strtolower($attr)])) - return $this->_attr[strtolower($attr)]; - else - return false; + if (isset($this->_attr[strtolower($attr)])) + return $this->_attr[strtolower($attr)]; + else + return false; } function _getClasses() { - if (!isset($this->_classes)) { - $this->_classes = array(); - if (isset($this->_attr['class'])) { - $classes = explode(' ', (string) $this->_attr['class']); - foreach ($classes as $class) { - $class = trim($class); - if ($class) - $this->_classes[$class] = $class; - } - } - } - return $this->_classes; + if (!isset($this->_classes)) { + $this->_classes = array(); + if (isset($this->_attr['class'])) { + $classes = explode(' ', (string) $this->_attr['class']); + foreach ($classes as $class) { + $class = trim($class); + if ($class) + $this->_classes[$class] = $class; + } + } + } + return $this->_classes; } function _setClasses() { - if (isset($this->_classes)) { - if ($this->_classes) - $this->_attr['class'] = join(' ', $this->_classes); - else - unset($this->_attr['class']); - } + if (isset($this->_classes)) { + if ($this->_classes) + $this->_attr['class'] = join(' ', $this->_classes); + else + unset($this->_attr['class']); + } } /** @@ -328,12 +328,12 @@ class XmlElement extends XmlContent * If false, the element is removed from the class. */ function setInClass($class, $in_class=true) { - $this->_getClasses(); - $class = trim($class); - if ($in_class) - $this->_classes[$class] = $class; - else - unset($this->_classes[$class]); + $this->_getClasses(); + $class = trim($class); + if ($in_class) + $this->_classes[$class] = $class; + else + unset($this->_classes[$class]); } /** @@ -346,13 +346,13 @@ class XmlElement extends XmlContent * @return bool True if the element is a member of $class. */ function inClass($class) { - $this->_parseClasses(); - return isset($this->_classes[trim($class)]); + $this->_parseClasses(); + return isset($this->_classes[trim($class)]); } function startTag() { $start = "<" . $this->_tag; - $this->_setClasses(); + $this->_setClasses(); foreach ($this->_attr as $attr => $val) { if (is_bool($val)) { if (!$val) @@ -370,12 +370,12 @@ class XmlElement extends XmlContent return substr($this->startTag(), 0, -1) . "/>"; } - + function endTag() { return "_tag>"; } - - + + function printXML () { if ($this->isEmpty()) echo $this->emptyTag(); @@ -422,7 +422,7 @@ class XmlElement extends XmlContent return false; return true; } - + /** * Is this element part of inline content? * @@ -432,7 +432,7 @@ class XmlElement extends XmlContent function isInlineElement () { return false; } - + }; class RawXml { @@ -452,9 +452,9 @@ class RawXml { function asXML () { return $this->_xml; } - + function asString () { - return $this->_xml; + return $this->_xml; } function isEmpty () { @@ -486,7 +486,7 @@ class FormattedText { // strings uncluttered trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"), '%1\$s','%s'), E_USER_WARNING); - + $this->_fs = preg_replace('/(?_fs); $this->_args = array(); @@ -630,7 +630,7 @@ function AsString ($val) { $str .= AsString($x); return $str; } - + return (string) $val; } @@ -649,5 +649,5 @@ function fmt ($fs /* , ... */) { // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/XmlParser.php b/lib/XmlParser.php index 8526d6726..45a0008f8 100644 --- a/lib/XmlParser.php +++ b/lib/XmlParser.php @@ -93,7 +93,7 @@ class XmlParser { if (is_string($attrs) and !empty($attrs)) { // lowercase attr names foreach(explode(' ', $attrs) as $pair) { - if (strstr($pair,"=")) { + if (strstr($pair,"=")) { list($key,$val) = explode('=', $pair); $key = strtolower(trim($key)); $val = str_replace(array('"',"'"),'',trim($val)); @@ -114,9 +114,9 @@ class XmlParser { $this->current->_content[] =& $node; // copy or ref? $node->previous =& $this->current; // ref to parallel prev } - $this->current =& $node; // ref + $this->current =& $node; // ref if (empty($this->root)) { - $this->root =& $node; // ref for === test below + $this->root =& $node; // ref for === test below $GLOBALS['xml_parser_root'] =& $this->root; // copy } } @@ -155,7 +155,7 @@ class XmlParser { } $content = ""; while ($data = fread($fp, 4096)) { - $content .= $data; + $content .= $data; } fclose($fp); $this->parse($content); diff --git a/lib/XmlRpcClient.php b/lib/XmlRpcClient.php index 4168d285d..73673c9b6 100644 --- a/lib/XmlRpcClient.php +++ b/lib/XmlRpcClient.php @@ -80,27 +80,27 @@ function short_string_decode ($str) { function wiki_xmlrpc_post($method, $args = null, $url = null, $auth = null) { if (is_null($url)) { - //$url = deduce_script_name(); - $url = DATA_PATH . "/RPC2.php"; // connect to self + //$url = deduce_script_name(); + $url = DATA_PATH . "/RPC2.php"; // connect to self } $debug = 0; $server = parse_url($url); if (empty($server['host'])) { - $server['host'] = 'localhost'; + $server['host'] = 'localhost'; } if (!empty($_GET['start_debug'])) { - $debug = 2; + $debug = 2; } if (DEBUG & _DEBUG_REMOTE) { // xmlrpc remote debugging - $debug = 2; - $server['path'] .= '?start_debug=1'; + $debug = 2; + $server['path'] .= '?start_debug=1'; } $params = array('method' => $method, - 'args' => $args, - 'host' => $server['host'], - 'uri' => $server['path'], - 'debug' => $debug, - 'output' => null); + 'args' => $args, + 'host' => $server['host'], + 'uri' => $server['path'], + 'debug' => $debug, + 'output' => null); //TODO: auth and/or session cookie if (isset($auth['sid'])) $params['cookies'] = array(session_name() => $auth['sid']); @@ -118,5 +118,5 @@ function wiki_xmlrpc_post($method, $args = null, $url = null, $auth = null) { // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/XmlRpcServer.php b/lib/XmlRpcServer.php index fc0f31b8a..f6de51452 100644 --- a/lib/XmlRpcServer.php +++ b/lib/XmlRpcServer.php @@ -61,11 +61,11 @@ ToDo: Done: Test hwiki.jar xmlrpc interface (java visualization plugin) - Make use of the xmlrpc extension if found. http://xmlrpc-epi.sourceforge.net/ - Resolved namespace conflicts - Added various phpwiki specific methods (mailPasswordToUser, getUploadedFileInfo, - putPage, titleSearch, listPlugins, getPluginSynopsis, listRelations) - Use client methods in inter-phpwiki calls: SyncWiki, tests/xmlrpc/ + Make use of the xmlrpc extension if found. http://xmlrpc-epi.sourceforge.net/ + Resolved namespace conflicts + Added various phpwiki specific methods (mailPasswordToUser, getUploadedFileInfo, + putPage, titleSearch, listPlugins, getPluginSynopsis, listRelations) + Use client methods in inter-phpwiki calls: SyncWiki, tests/xmlrpc/ */ // Intercept GET requests from confused users. Only POST is allowed here! @@ -133,9 +133,9 @@ global $wiki_dmap; * int getRPCVersionSupported(): Returns 1 for this version of the API */ $wiki_dmap['getRPCVersionSupported'] -= array('signature' => array(array($xmlrpcInt)), += array('signature' => array(array($xmlrpcInt)), 'documentation' => 'Get the version of the wiki API', - 'function' => 'getRPCVersionSupported'); + 'function' => 'getRPCVersionSupported'); // The function must be a function in the global scope which services the XML-RPC // method. @@ -158,9 +158,9 @@ function getRPCVersionSupported($params) * Additionally to API version 1 and 2 we added the summary field. */ $wiki_dmap['getRecentChanges'] -= array('signature' => array(array($xmlrpcArray, $xmlrpcDateTime)), += array('signature' => array(array($xmlrpcArray, $xmlrpcDateTime)), 'documentation' => 'Get a list of changed pages since [timestamp]', - 'function' => 'getRecentChanges'); + 'function' => 'getRecentChanges'); function getRecentChanges($params) { @@ -183,7 +183,7 @@ function getRecentChanges($params) $pages[] = new xmlrpcval(array('name' => $name, 'lastModified' => $lastmodified, 'author' => $author, - 'summary' => short_string($page->get('summary')), + 'summary' => short_string($page->get('summary')), 'version' => $version), 'struct'); } @@ -197,9 +197,9 @@ function getRecentChanges($params) * with UTF-8 encoded page data. */ $wiki_dmap['getPage'] -= array('signature' => array(array($xmlrpcBase64, $xmlrpcString)), += array('signature' => array(array($xmlrpcBase64, $xmlrpcString)), 'documentation' => 'Get the raw Wiki text of the current version of a page', - 'function' => 'getPage'); + 'function' => 'getPage'); function getPage($params) { @@ -220,9 +220,9 @@ function getPage($params) * Returns UTF-8, expects UTF-8 with URL encoding. */ $wiki_dmap['getPageVersion'] -= array('signature' => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)), += array('signature' => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)), 'documentation' => 'Get the raw Wiki text of a page version', - 'function' => 'getPageVersion'); + 'function' => 'getPageVersion'); function getPageVersion($params) { @@ -236,22 +236,22 @@ function getPageVersion($params) */ $wiki_dmap['getPageHTML'] -= array('signature' => array(array($xmlrpcBase64, $xmlrpcString)), += array('signature' => array(array($xmlrpcBase64, $xmlrpcString)), 'documentation' => 'Get the current version of a page rendered in HTML', - 'function' => 'getPageHTML'); + 'function' => 'getPageHTML'); function getPageHTML($params) { $revision = _getPageRevision($params); if (!$revision) return NoSuchPage(); - + $content = $revision->getTransformedContent(); $html = $content->asXML(); // HACK: Get rid of outer
    if (preg_match('/^\s*
    /', $html, $m1) - && preg_match('@
    \s*$@', $html, $m2)) { - $html = substr($html, strlen($m1[0]), -strlen($m2[0])); + && preg_match('@
    \s*$@', $html, $m2)) { + $html = substr($html, strlen($m1[0]), -strlen($m2[0])); } return new xmlrpcresp(long_string($html)); @@ -261,9 +261,9 @@ function getPageHTML($params) * base64 getPageHTMLVersion( String pagename, int version ): Return page in rendered HTML, UTF-8. */ $wiki_dmap['getPageHTMLVersion'] -= array('signature' => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)), += array('signature' => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)), 'documentation' => 'Get a version of a page rendered in HTML', - 'function' => 'getPageHTMLVersion'); + 'function' => 'getPageHTMLVersion'); function getPageHTMLVersion($params) { @@ -274,9 +274,9 @@ function getPageHTMLVersion($params) * getAllPages(): Returns a list of all pages. The result is an array of strings. */ $wiki_dmap['getAllPages'] -= array('signature' => array(array($xmlrpcArray)), += array('signature' => array(array($xmlrpcArray)), 'documentation' => 'Returns a list of all pages as an array of strings', - 'function' => 'getAllPages'); + 'function' => 'getAllPages'); function getAllPages($params) { @@ -298,22 +298,22 @@ function getAllPages($params) * author (string): author name */ $wiki_dmap['getPageInfo'] -= array('signature' => array(array($xmlrpcStruct, $xmlrpcString)), += array('signature' => array(array($xmlrpcStruct, $xmlrpcString)), 'documentation' => 'Gets info about the current version of a page', - 'function' => 'getPageInfo'); + 'function' => 'getPageInfo'); function getPageInfo($params) { $revision = _getPageRevision($params); if (!$revision) return NoSuchPage(); - + $name = short_string($revision->getPageName()); $version = new xmlrpcval ($revision->getVersion(), "int"); $lastmodified = new xmlrpcval(iso8601_encode($revision->get('mtime'), 0), "dateTime.iso8601"); $author = short_string($revision->get('author')); - + return new xmlrpcresp(new xmlrpcval(array('name' => $name, 'lastModified' => $lastmodified, 'version' => $version, @@ -327,9 +327,9 @@ function getPageInfo($params) * specific version. */ $wiki_dmap['getPageInfoVersion'] -= array('signature' => array(array($xmlrpcStruct, $xmlrpcString, $xmlrpcInt)), += array('signature' => array(array($xmlrpcStruct, $xmlrpcString, $xmlrpcInt)), 'documentation' => 'Gets info about a page version', - 'function' => 'getPageInfoVersion'); + 'function' => 'getPageInfoVersion'); function getPageInfoVersion($params) { @@ -339,19 +339,19 @@ function getPageInfoVersion($params) /* array listLinks( string pagename ): Lists all links for a given page. The * returned array contains structs, with the following elements: - * name (string) : The page name or URL the link is to. + * name (string) : The page name or URL the link is to. * type (int) : The link type. Zero (0) for internal Wiki link, * one (1) for external link (URL - image link, whatever). */ $wiki_dmap['listLinks'] -= array('signature' => array(array($xmlrpcArray, $xmlrpcString)), += array('signature' => array(array($xmlrpcArray, $xmlrpcString)), 'documentation' => 'Lists all links for a given page', - 'function' => 'listLinks'); + 'function' => 'listLinks'); function listLinks($params) { global $request; - + $ParamPageName = $params->getParam(0); $pagename = short_string_decode($ParamPageName->scalarval()); $dbh = $request->getDbh(); @@ -359,7 +359,7 @@ function listLinks($params) return NoSuchPage($pagename); $page = $dbh->getPage($pagename); - + // The fast WikiDB method. below is the slow method which goes through the formatter // NB no clean way to extract a list of external links yet, so // only internal links returned. i.e. all type 'local'. @@ -377,7 +377,7 @@ function listLinks($params) // Also, if USE_PATH_INFO is false, WikiURL is wrong // due to its use of SCRIPT_NAME. //$use_abspath = USE_PATH_INFO && ! preg_match('/RPC2.php$/', VIRTUAL_PATH); - + // USE_PATH_INFO must be defined in index.php or config.ini but not before, // otherwise it is ignored and xmlrpc urls are wrong. // SCRIPT_NAME here is always .../RPC2.php @@ -393,7 +393,7 @@ function listLinks($params) 'href' => short_string($url)), "struct"); } - + /* $current = $page->getCurrentRevision(); $content = $current->getTransformedContent(); @@ -435,7 +435,7 @@ $wiki_dmap['putPage'] function _getUser($userid='') { global $request; - + if (! $userid ) { if (!isset($_SERVER)) $_SERVER =& $GLOBALS['HTTP_SERVER_VARS']; @@ -459,7 +459,7 @@ function _getUser($userid='') { return new WikiUser($request, $userid); } } - + function putPage($params) { global $request; @@ -476,12 +476,12 @@ function putPage($params) { $passwd = short_string_decode($ParamPassword->scalarval()); } } else { - $userid = $request->_user->_userid; + $userid = $request->_user->_userid; } $request->_user = _getUser($userid); $request->_user->_group = $request->getGroup(); $request->_user->AuthCheck($userid, $passwd); - + if (! mayAccessPage ('edit', $pagename)) { return new xmlrpcresp( new xmlrpcval( @@ -520,8 +520,8 @@ function putPage($params) { else $message = "Problem creating version $version of page $pagename"; } else { - $res = 0; - $message = $message = "Page $pagename unchanged"; + $res = 0; + $message = $message = "Page $pagename unchanged"; } return new xmlrpcresp(new xmlrpcval(array('code' => new xmlrpcval($res ? 200 : 400, "int"), 'version' => new xmlrpcval($version, "int"), @@ -544,9 +544,9 @@ function putPage($params) { * base64 getAttachment( utf8 attachmentName ), putAttachment( utf8 attachmentName, base64 content ) */ $wiki_dmap['getUploadedFileInfo'] -= array('signature' => array(array($xmlrpcStruct, $xmlrpcString)), += array('signature' => array(array($xmlrpcStruct, $xmlrpcString)), 'documentation' => 'Gets date and size about an uploaded local file', - 'function' => 'getUploadedFileInfo'); + 'function' => 'getUploadedFileInfo'); function getUploadedFileInfo($params) { @@ -559,11 +559,11 @@ function getUploadedFileInfo($params) $size = filesize($file); $lastmodified = filemtime($file); } else { - $size = 0; - $lastmodified = 0; - } + $size = 0; + $lastmodified = 0; + } return new xmlrpcresp(new xmlrpcval - (array('lastModified' => new xmlrpcval(iso8601_encode($lastmodified, 1), + (array('lastModified' => new xmlrpcval(iso8601_encode($lastmodified, 1), "dateTime.iso8601"), 'size' => new xmlrpcval($size, "int")), "struct")); @@ -589,9 +589,9 @@ function getUploadedFileInfo($params) * http://www.thetwowayweb.com/soapmeetsrss#rsscloudInterface */ $wiki_dmap['rssPleaseNotify'] -= array('signature' => array(array($xmlrpcBoolean, $xmlrpcStruct)), += array('signature' => array(array($xmlrpcBoolean, $xmlrpcStruct)), 'documentation' => 'RSS2 change notification subscriber channel', - 'function' => 'rssPleaseNotify'); + 'function' => 'rssPleaseNotify'); function rssPleaseNotify($params) { @@ -605,9 +605,9 @@ function rssPleaseNotify($params) */ $wiki_dmap['mailPasswordToUser'] -= array('signature' => array(array($xmlrpcBoolean, $xmlrpcString)), += array('signature' => array(array($xmlrpcBoolean, $xmlrpcString)), 'documentation' => 'RSS2 user management helper', - 'function' => 'mailPasswordToUser'); + 'function' => 'mailPasswordToUser'); function mailPasswordToUser($params) { @@ -648,8 +648,8 @@ function titleSearch($params) $ParamOption = $params->getParam(1); $option = (int) $ParamOption->scalarval(); } else - $option = 0; - // default option: substring, case-inexact + $option = 0; + // default option: substring, case-inexact $case_exact = $option & 1; $regex = $option & 2; @@ -664,10 +664,10 @@ function titleSearch($params) $searchstring = "^".$searchstring."$"; } } else { - if ($option & 4 or $option & 8) { - global $xmlrpcerruser; - return new xmlrpcresp(0, $xmlrpcerruser + 1, "Invalid option"); - } + if ($option & 4 or $option & 8) { + global $xmlrpcerruser; + return new xmlrpcresp(0, $xmlrpcerruser + 1, "Invalid option"); + } } include_once("lib/TextSearchQuery.php"); $query = new TextSearchQuery($searchstring, $case_exact, $regex ? 'auto' : 'none'); @@ -761,7 +761,7 @@ function getPluginSynopsis($params) $plugin_args = '\n'.str_replace($src, $replace, $desc); $synopsis = ""; // args? } - + return new xmlrpcresp(short_string($synopsis)); } @@ -795,9 +795,9 @@ function callPlugin($params) $pagelist = $p->run($dbi, $plugin_args, $request, $basepage); $list = array(); if (is_object($pagelist) and isa($pagelist, 'PageList')) { - foreach ($pagelist->_pages as $page) { - $list[] = $page->getName(); - } + foreach ($pagelist->_pages as $page) { + $list[] = $page->getName(); + } } return new xmlrpcresp(new xmlrpcval($list, "array")); } @@ -827,14 +827,14 @@ function listRelations($params) $ParamOption = $params->getParam(0); $option = (int) $ParamOption->scalarval(); } else - $option = 1; + $option = 1; $also_attributes = $option & 2; $only_attributes = $option & 2 and !($option & 1); $sorted = !($option & 4); return new xmlrpcresp(new xmlrpcval($dbh->listRelations($also_attributes, - $only_attributes, - $sorted), - "array")); + $only_attributes, + $sorted), + "array")); } /** @@ -859,9 +859,9 @@ Faults but the pingback cannot be acknowledged for some other reaon. 0 - A generic fault code. Servers MAY use this error code instead - of any of the others if they do not have a way of determining - the correct fault code. + A generic fault code. Servers MAY use this error code instead + of any of the others if they do not have a way of determining + the correct fault code. 0x0010 (16) The source URI does not exist. 0x0011 (17) @@ -966,7 +966,7 @@ class XmlRpcServer extends xmlrpc_server xmlrpc_server::service(); $ErrorManager->popErrorHandler(); } - + function _errorHandler ($e) { $msg = htmlspecialchars($e->asString()); // '--' not allowed within xml comment @@ -983,5 +983,5 @@ class XmlRpcServer extends xmlrpc_server // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/config.php b/lib/config.php index 6c0d1dbdb..5917566d3 100644 --- a/lib/config.php +++ b/lib/config.php @@ -20,8 +20,8 @@ define ('_DEBUG_APD', 32); // APD tracing/profiling define ('_DEBUG_LOGIN', 64); // verbose login debug-msg (settings and reason for failure) define ('_DEBUG_SQL', 128); // force check db, force optimize, print some debugging logs define ('_DEBUG_REMOTE', 256); // remote debug into subrequests (xmlrpc, ajax, wikiwyg, ...) - // or test local SearchHighlight. - // internal links have persistent ?start_debug=1 + // or test local SearchHighlight. + // internal links have persistent ?start_debug=1 function isCGI() { return (substr(php_sapi_name(),0,3) == 'cgi' and @@ -98,8 +98,8 @@ function isBrowserOpera($version = false) { */ function guessing_lang ($languages=false) { if (!$languages) { - // make this faster - $languages = array("en","de","es","fr","it","ja","zh","nl","sv"); + // make this faster + $languages = array("en","de","es","fr","it","ja","zh","nl","sv"); } $accept = false; @@ -184,7 +184,7 @@ function guessing_setlocale ($category, $locale) { if (strlen($lang) > 2) { foreach ($alt as $try => $locs) { if (in_array($locale, $locs) or in_array($lang, $locs)) { - //if (empty($GLOBALS['LANG'])) $GLOBALS['LANG'] = $try; + //if (empty($GLOBALS['LANG'])) $GLOBALS['LANG'] = $try; return $try; } } @@ -379,11 +379,11 @@ function getUploadFilePath() { } function getUploadDataPath() { if (defined('UPLOAD_DATA_PATH')) { - return string_ends_with(UPLOAD_DATA_PATH, "/") - ? UPLOAD_DATA_PATH : UPLOAD_DATA_PATH."/"; + return string_ends_with(UPLOAD_DATA_PATH, "/") + ? UPLOAD_DATA_PATH : UPLOAD_DATA_PATH."/"; } return SERVER_URL . (string_ends_with(DATA_PATH, "/") ? '' : "/") - . DATA_PATH . '/uploads/'; + . DATA_PATH . '/uploads/'; } // Local Variables: diff --git a/lib/diff3.php b/lib/diff3.php index ac9f99510..49c88fe68 100644 --- a/lib/diff3.php +++ b/lib/diff3.php @@ -12,7 +12,7 @@ require_once('lib/difflib.php'); class _Diff3_Block { var $type = 'diff3'; - + function _Diff3_Block ($orig = false, $final1 = false, $final2 = false) { $this->orig = $orig ? $orig : array(); $this->final1 = $final1 ? $final1 : array(); @@ -38,10 +38,10 @@ class _Diff3_Block { } } - + class _Diff3_CopyBlock extends _Diff3_Block { var $type = 'copy'; - + function _Diff3_CopyBlock ($lines = false) { $this->orig = $lines ? $lines : array(); $this->final1 = &$this->orig; @@ -51,7 +51,7 @@ class _Diff3_CopyBlock extends _Diff3_Block { function merged() { return $this->orig; } - + function is_conflict () { return false; } @@ -65,12 +65,12 @@ class _Diff3_BlockBuilder { function _init() { $this->orig = $this->final1 = $this->final2 = array(); } - - + + function _append (&$array, $lines) { array_splice($array, sizeof($array), 0, $lines); } - + function input($lines) { if ($lines) $this->_append($this->orig, $lines); @@ -89,7 +89,7 @@ class _Diff3_BlockBuilder { function is_empty() { return !$this->orig && !$this->final1 && !$this->final2; } - + function finish() { if ($this->is_empty()) return false; @@ -121,7 +121,7 @@ class Diff3 { // print_r($e1); // print_r($e2); // echo "====\n"; - + if ($e1 && $e2 && $e1->type == 'copy' && $e2->type == 'copy') { // We have copy blocks from both diffs. This is the (only) // time we want to emit a diff3 copy block. @@ -155,10 +155,10 @@ class Diff3 { array_splice($e2->orig, 0, $norig); $bb->input($orig); } - + if ($e1->type == 'copy') $bb->out1(array_splice($e1->final, 0, $norig)); - + if ($e2->type == 'copy') $bb->out2(array_splice($e2->final, 0, $norig)); } @@ -191,7 +191,7 @@ class Diff3 { array("======="), $block->final2, array(">>>>>>>" . ($label2 ? " $label2" : ''))); - $this->ConflictingBlocks++; + $this->ConflictingBlocks++; } else { $lines = array_merge($lines, $block->merged()); @@ -207,5 +207,5 @@ class Diff3 { // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: -?> \ No newline at end of file +// End: +?> diff --git a/lib/difflib.php b/lib/difflib.php index aebd666fb..9a1c2fb05 100644 --- a/lib/difflib.php +++ b/lib/difflib.php @@ -209,102 +209,102 @@ class _DiffEngine * of the portions it is going to specify. */ function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) { - $flip = false; - - if ($xlim - $xoff > $ylim - $yoff) { - // Things seems faster (I'm not sure I understand why) + $flip = false; + + if ($xlim - $xoff > $ylim - $yoff) { + // Things seems faster (I'm not sure I understand why) // when the shortest sequence in X. $flip = true; - list ($xoff, $xlim, $yoff, $ylim) - = array( $yoff, $ylim, $xoff, $xlim); + list ($xoff, $xlim, $yoff, $ylim) + = array( $yoff, $ylim, $xoff, $xlim); } - if ($flip) - for ($i = $ylim - 1; $i >= $yoff; $i--) - $ymatches[$this->xv[$i]][] = $i; - else - for ($i = $ylim - 1; $i >= $yoff; $i--) - $ymatches[$this->yv[$i]][] = $i; - - $this->lcs = 0; - $this->seq[0]= $yoff - 1; - $this->in_seq = array(); - $ymids[0] = array(); - - $numer = $xlim - $xoff + $nchunks - 1; - $x = $xoff; - for ($chunk = 0; $chunk < $nchunks; $chunk++) { - if ($chunk > 0) - for ($i = 0; $i <= $this->lcs; $i++) - $ymids[$i][$chunk-1] = $this->seq[$i]; - - $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks); - for ( ; $x < $x1; $x++) { + if ($flip) + for ($i = $ylim - 1; $i >= $yoff; $i--) + $ymatches[$this->xv[$i]][] = $i; + else + for ($i = $ylim - 1; $i >= $yoff; $i--) + $ymatches[$this->yv[$i]][] = $i; + + $this->lcs = 0; + $this->seq[0]= $yoff - 1; + $this->in_seq = array(); + $ymids[0] = array(); + + $numer = $xlim - $xoff + $nchunks - 1; + $x = $xoff; + for ($chunk = 0; $chunk < $nchunks; $chunk++) { + if ($chunk > 0) + for ($i = 0; $i <= $this->lcs; $i++) + $ymids[$i][$chunk-1] = $this->seq[$i]; + + $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks); + for ( ; $x < $x1; $x++) { $line = $flip ? $this->yv[$x] : $this->xv[$x]; if (empty($ymatches[$line])) - continue; - $matches = $ymatches[$line]; + continue; + $matches = $ymatches[$line]; reset($matches); - while (list ($junk, $y) = each($matches)) - if (empty($this->in_seq[$y])) { - $k = $this->_lcs_pos($y); - assert($k > 0); - $ymids[$k] = $ymids[$k-1]; - break; + while (list ($junk, $y) = each($matches)) + if (empty($this->in_seq[$y])) { + $k = $this->_lcs_pos($y); + assert($k > 0); + $ymids[$k] = $ymids[$k-1]; + break; } - while (list ($junk, $y) = each($matches)) { - if ($y > $this->seq[$k-1]) { - assert($y < $this->seq[$k]); - // Optimization: this is a common case: - // next match is just replacing previous match. - $this->in_seq[$this->seq[$k]] = false; - $this->seq[$k] = $y; - $this->in_seq[$y] = 1; + while (list ($junk, $y) = each($matches)) { + if ($y > $this->seq[$k-1]) { + assert($y < $this->seq[$k]); + // Optimization: this is a common case: + // next match is just replacing previous match. + $this->in_seq[$this->seq[$k]] = false; + $this->seq[$k] = $y; + $this->in_seq[$y] = 1; } - else if (empty($this->in_seq[$y])) { - $k = $this->_lcs_pos($y); - assert($k > 0); - $ymids[$k] = $ymids[$k-1]; + else if (empty($this->in_seq[$y])) { + $k = $this->_lcs_pos($y); + assert($k > 0); + $ymids[$k] = $ymids[$k-1]; } } } } - $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff); - $ymid = $ymids[$this->lcs]; - for ($n = 0; $n < $nchunks - 1; $n++) { - $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks); - $y1 = $ymid[$n] + 1; - $seps[] = $flip ? array($y1, $x1) : array($x1, $y1); + $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff); + $ymid = $ymids[$this->lcs]; + for ($n = 0; $n < $nchunks - 1; $n++) { + $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks); + $y1 = $ymid[$n] + 1; + $seps[] = $flip ? array($y1, $x1) : array($x1, $y1); } - $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim); + $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim); - return array($this->lcs, $seps); + return array($this->lcs, $seps); } function _lcs_pos ($ypos) { - $end = $this->lcs; - if ($end == 0 || $ypos > $this->seq[$end]) { - $this->seq[++$this->lcs] = $ypos; - $this->in_seq[$ypos] = 1; - return $this->lcs; + $end = $this->lcs; + if ($end == 0 || $ypos > $this->seq[$end]) { + $this->seq[++$this->lcs] = $ypos; + $this->in_seq[$ypos] = 1; + return $this->lcs; } - $beg = 1; - while ($beg < $end) { - $mid = (int)(($beg + $end) / 2); - if ( $ypos > $this->seq[$mid] ) - $beg = $mid + 1; - else - $end = $mid; + $beg = 1; + while ($beg < $end) { + $mid = (int)(($beg + $end) / 2); + if ( $ypos > $this->seq[$mid] ) + $beg = $mid + 1; + else + $end = $mid; } - assert($ypos != $this->seq[$end]); + assert($ypos != $this->seq[$end]); - $this->in_seq[$this->seq[$end]] = false; - $this->seq[$end] = $ypos; - $this->in_seq[$ypos] = 1; - return $end; + $this->in_seq[$this->seq[$end]] = false; + $this->seq[$end] = $ypos; + $this->in_seq[$ypos] = 1; + return $end; } /* Find LCS of two sequences. @@ -319,46 +319,46 @@ class _DiffEngine * All line numbers are origin-0 and discarded lines are not counted. */ function _compareseq ($xoff, $xlim, $yoff, $ylim) { - // Slide down the bottom initial diagonal. - while ($xoff < $xlim && $yoff < $ylim + // Slide down the bottom initial diagonal. + while ($xoff < $xlim && $yoff < $ylim && $this->xv[$xoff] == $this->yv[$yoff]) { - ++$xoff; - ++$yoff; + ++$xoff; + ++$yoff; } - // Slide up the top initial diagonal. - while ($xlim > $xoff && $ylim > $yoff + // Slide up the top initial diagonal. + while ($xlim > $xoff && $ylim > $yoff && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) { - --$xlim; - --$ylim; + --$xlim; + --$ylim; } - if ($xoff == $xlim || $yoff == $ylim) - $lcs = 0; - else { - // This is ad hoc but seems to work well. - //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); - //$nchunks = max(2,min(8,(int)$nchunks)); - $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1; - list ($lcs, $seps) - = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks); + if ($xoff == $xlim || $yoff == $ylim) + $lcs = 0; + else { + // This is ad hoc but seems to work well. + //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); + //$nchunks = max(2,min(8,(int)$nchunks)); + $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1; + list ($lcs, $seps) + = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks); } - if ($lcs == 0) { - // X and Y sequences have no common subsequence: - // mark all changed. - while ($yoff < $ylim) - $this->ychanged[$this->yind[$yoff++]] = 1; - while ($xoff < $xlim) - $this->xchanged[$this->xind[$xoff++]] = 1; + if ($lcs == 0) { + // X and Y sequences have no common subsequence: + // mark all changed. + while ($yoff < $ylim) + $this->ychanged[$this->yind[$yoff++]] = 1; + while ($xoff < $xlim) + $this->xchanged[$this->xind[$xoff++]] = 1; } - else { - // Use the partitions to split this problem into subproblems. - reset($seps); - $pt1 = $seps[0]; - while ($pt2 = next($seps)) { - $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]); - $pt1 = $pt2; + else { + // Use the partitions to split this problem into subproblems. + reset($seps); + $pt1 = $seps[0]; + while ($pt2 = next($seps)) { + $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]); + $pt1 = $pt2; } } } @@ -376,108 +376,108 @@ class _DiffEngine * This is extracted verbatim from analyze.c (GNU diffutils-2.7). */ function _shift_boundaries ($lines, &$changed, $other_changed) { - $i = 0; - $j = 0; - - assert('sizeof($lines) == sizeof($changed)'); - $len = sizeof($lines); - $other_len = sizeof($other_changed); - - while (1) { - /* - * Scan forwards to find beginning of another run of changes. - * Also keep track of the corresponding point in the other file. - * - * Throughout this code, $i and $j are adjusted together so that - * the first $i elements of $changed and the first $j elements - * of $other_changed both contain the same number of zeros - * (unchanged lines). - * Furthermore, $j is always kept so that $j == $other_len or - * $other_changed[$j] == false. - */ - while ($j < $other_len && $other_changed[$j]) - $j++; - - while ($i < $len && ! $changed[$i]) { - assert('$j < $other_len && ! $other_changed[$j]'); - $i++; $j++; - while ($j < $other_len && $other_changed[$j]) - $j++; + $i = 0; + $j = 0; + + assert('sizeof($lines) == sizeof($changed)'); + $len = sizeof($lines); + $other_len = sizeof($other_changed); + + while (1) { + /* + * Scan forwards to find beginning of another run of changes. + * Also keep track of the corresponding point in the other file. + * + * Throughout this code, $i and $j are adjusted together so that + * the first $i elements of $changed and the first $j elements + * of $other_changed both contain the same number of zeros + * (unchanged lines). + * Furthermore, $j is always kept so that $j == $other_len or + * $other_changed[$j] == false. + */ + while ($j < $other_len && $other_changed[$j]) + $j++; + + while ($i < $len && ! $changed[$i]) { + assert('$j < $other_len && ! $other_changed[$j]'); + $i++; $j++; + while ($j < $other_len && $other_changed[$j]) + $j++; } - if ($i == $len) - break; - - $start = $i; - - // Find the end of this run of changes. - while (++$i < $len && $changed[$i]) - continue; - - do { - /* - * Record the length of this run of changes, so that - * we can later determine whether the run has grown. - */ - $runlength = $i - $start; - - /* - * Move the changed region back, so long as the - * previous unchanged line matches the last changed one. - * This merges with previous changed regions. - */ - while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) { - $changed[--$start] = 1; - $changed[--$i] = false; - while ($start > 0 && $changed[$start - 1]) - $start--; - assert('$j > 0'); - while ($other_changed[--$j]) - continue; - assert('$j >= 0 && !$other_changed[$j]'); + if ($i == $len) + break; + + $start = $i; + + // Find the end of this run of changes. + while (++$i < $len && $changed[$i]) + continue; + + do { + /* + * Record the length of this run of changes, so that + * we can later determine whether the run has grown. + */ + $runlength = $i - $start; + + /* + * Move the changed region back, so long as the + * previous unchanged line matches the last changed one. + * This merges with previous changed regions. + */ + while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) { + $changed[--$start] = 1; + $changed[--$i] = false; + while ($start > 0 && $changed[$start - 1]) + $start--; + assert('$j > 0'); + while ($other_changed[--$j]) + continue; + assert('$j >= 0 && !$other_changed[$j]'); } - /* - * Set CORRESPONDING to the end of the changed run, at the last - * point where it corresponds to a changed run in the other file. - * CORRESPONDING == LEN means no such point has been found. - */ - $corresponding = $j < $other_len ? $i : $len; - - /* - * Move the changed region forward, so long as the - * first changed line matches the following unchanged one. - * This merges with following changed regions. - * Do this second, so that if there are no merges, - * the changed region is moved forward as far as possible. - */ - while ($i < $len && $lines[$start] == $lines[$i]) { - $changed[$start++] = false; - $changed[$i++] = 1; - while ($i < $len && $changed[$i]) - $i++; - - assert('$j < $other_len && ! $other_changed[$j]'); - $j++; - if ($j < $other_len && $other_changed[$j]) { - $corresponding = $i; - while ($j < $other_len && $other_changed[$j]) - $j++; + /* + * Set CORRESPONDING to the end of the changed run, at the last + * point where it corresponds to a changed run in the other file. + * CORRESPONDING == LEN means no such point has been found. + */ + $corresponding = $j < $other_len ? $i : $len; + + /* + * Move the changed region forward, so long as the + * first changed line matches the following unchanged one. + * This merges with following changed regions. + * Do this second, so that if there are no merges, + * the changed region is moved forward as far as possible. + */ + while ($i < $len && $lines[$start] == $lines[$i]) { + $changed[$start++] = false; + $changed[$i++] = 1; + while ($i < $len && $changed[$i]) + $i++; + + assert('$j < $other_len && ! $other_changed[$j]'); + $j++; + if ($j < $other_len && $other_changed[$j]) { + $corresponding = $i; + while ($j < $other_len && $other_changed[$j]) + $j++; } } } while ($runlength != $i - $start); - /* - * If possible, move the fully-merged run of changes - * back to a corresponding run in the other file. - */ - while ($corresponding < $i) { - $changed[--$start] = 1; - $changed[--$i] = 0; - assert('$j > 0'); - while ($other_changed[--$j]) - continue; - assert('$j >= 0 && !$other_changed[$j]'); + /* + * If possible, move the fully-merged run of changes + * back to a corresponding run in the other file. + */ + while ($corresponding < $i) { + $changed[--$start] = 1; + $changed[--$i] = 0; + assert('$j > 0'); + while ($other_changed[--$j]) + continue; + assert('$j >= 0 && !$other_changed[$j]'); } } } @@ -515,12 +515,12 @@ class Diff * original diff. */ function reverse () { - $rev = $this; + $rev = $this; $rev->edits = array(); foreach ($this->edits as $edit) { $rev->edits[] = $edit->reverse(); } - return $rev; + return $rev; } /** @@ -544,12 +544,12 @@ class Diff * @return int The length of the LCS. */ function lcs () { - $lcs = 0; + $lcs = 0; foreach ($this->edits as $edit) { if ($edit->type == 'copy') $lcs += sizeof($edit->orig); } - return $lcs; + return $lcs; } /** diff --git a/lib/display.php b/lib/display.php index 3d261af96..5b3cfbba7 100644 --- a/lib/display.php +++ b/lib/display.php @@ -17,7 +17,7 @@ function GleanKeywords ($page) { $links = $page->getPageLinks(); $keywords[] = SplitPagename($page->getName()); while ($link = $links->next()) { - $m = array(); + $m = array(); if (preg_match($KeywordLinkRegexp, $link->getName(), $m)) $keywords[] = SplitPagename($m[0]); } @@ -37,7 +37,7 @@ function RedirectorLink($pagename) { $pagename); } -/* only on ?action= */ +/* only on ?action= */ function actionPage(&$request, $action) { global $WikiTheme; global $robots; @@ -71,7 +71,7 @@ function actionPage(&$request, $action) { $args = array(); if (GOOGLE_LINKS_NOFOLLOW) { $robots = "noindex,nofollow"; - $args = array('ROBOTS_META' => $robots); + $args = array('ROBOTS_META' => $robots); } /* Handle other formats: So far we had html only. @@ -81,83 +81,83 @@ function actionPage(&$request, $action) { rdf and owl are handled by SemanticWeb. */ $format = $request->getArg('format'); - + /* At first the single page formats: html, xml */ if ($pagename == _("LinkDatabase")) { $template = Template('browse', array('CONTENT' => $transformedContent)); - GeneratePage($template, $pagetitle, $revision, $args); + GeneratePage($template, $pagetitle, $revision, $args); } elseif (!$format or $format == 'html' or $format == 'sidebar' or $format == 'contribs') { - $template = Template('browse', array('CONTENT' => $transformedContent)); - GeneratePage($template, $pagetitle, $revision, $args); + $template = Template('browse', array('CONTENT' => $transformedContent)); + GeneratePage($template, $pagetitle, $revision, $args); } elseif ($format == 'xml') { - $request->setArg('format',''); - $template = new Template('browse', $request, + $request->setArg('format',''); + $template = new Template('browse', $request, array('revision' => $revision, 'CONTENT' => $transformedContent, - )); - $html = GeneratePageAsXML($template, $pagename, $revision /*, - array('VALID_LINKS' => $args['VALID_LINKS'])*/); - header("Content-Type: application/xhtml+xml; charset=" . $GLOBALS['charset']); - echo $html; + )); + $html = GeneratePageAsXML($template, $pagename, $revision /*, + array('VALID_LINKS' => $args['VALID_LINKS'])*/); + header("Content-Type: application/xhtml+xml; charset=" . $GLOBALS['charset']); + echo $html; } else { - $pagelist = null; - require_once('lib/WikiPlugin.php'); - // Then the multi-page formats - // rss (if not already handled by RecentChanges) - // Need the pagelist from the first plugin - foreach($transformedContent->_content as $cached_element) { - if (is_a($cached_element, "Cached_PluginInvocation")) { - $loader = new WikiPluginLoader; - $markup = null; - // return the first found pagelist - $pagelist = $loader->expandPI($cached_element->_pi, $request, - $markup, $pagename); - if (is_a($pagelist, 'PageList')) - break; - } - } + $pagelist = null; + require_once('lib/WikiPlugin.php'); + // Then the multi-page formats + // rss (if not already handled by RecentChanges) + // Need the pagelist from the first plugin + foreach($transformedContent->_content as $cached_element) { + if (is_a($cached_element, "Cached_PluginInvocation")) { + $loader = new WikiPluginLoader; + $markup = null; + // return the first found pagelist + $pagelist = $loader->expandPI($cached_element->_pi, $request, + $markup, $pagename); + if (is_a($pagelist, 'PageList')) + break; + } + } if (!$pagelist or !is_a($pagelist, 'PageList')) { - if (!in_array($format, array("rss91","rss2","rss","atom","rdf"))) - trigger_error(sprintf("Format %s requires an actionpage returning a pagelist.", - $format) - ."\n".("Fall back to single page mode"), E_USER_WARNING); - require_once('lib/PageList.php'); - $pagelist = new PageList(); - if ($format == 'pdf') - $pagelist->addPage($page); - } else { + if (!in_array($format, array("rss91","rss2","rss","atom","rdf"))) + trigger_error(sprintf("Format %s requires an actionpage returning a pagelist.", + $format) + ."\n".("Fall back to single page mode"), E_USER_WARNING); + require_once('lib/PageList.php'); + $pagelist = new PageList(); + if ($format == 'pdf') + $pagelist->addPage($page); + } else { foreach ($pagelist->_pages as $page) { - $name = $page->getName(); - if ($name != $pagename and $page->exists()) + $name = $page->getName(); + if ($name != $pagename and $page->exists()) $args['VALID_LINKS'][] = $name; } - } - if ($format == 'pdf') { - require_once("lib/pdf.php"); - array_unshift($args['VALID_LINKS'], $pagename); - ConvertAndDisplayPdfPageList($request, $pagelist, $args); - } - elseif ($format == 'ziphtml') { // need to fix links - require_once('lib/loadsave.php'); - array_unshift($args['VALID_LINKS'], $pagename); - $request->setArg('zipname', FilenameForPage($pagename).".zip"); - $request->setArg('pages', $args['VALID_LINKS']); - $request->setArg('format',''); - MakeWikiZipHtml($request); - } // time-sorted RDF á la RecentChanges - elseif (in_array($format, array("rss91","rss2","rss","atom"))) { + } + if ($format == 'pdf') { + require_once("lib/pdf.php"); + array_unshift($args['VALID_LINKS'], $pagename); + ConvertAndDisplayPdfPageList($request, $pagelist, $args); + } + elseif ($format == 'ziphtml') { // need to fix links + require_once('lib/loadsave.php'); + array_unshift($args['VALID_LINKS'], $pagename); + $request->setArg('zipname', FilenameForPage($pagename).".zip"); + $request->setArg('pages', $args['VALID_LINKS']); + $request->setArg('format',''); + MakeWikiZipHtml($request); + } // time-sorted RDF á la RecentChanges + elseif (in_array($format, array("rss91","rss2","rss","atom"))) { $args = $request->getArgs(); //$request->setArg('format',''); if ($pagename == _("RecentChanges")) { $template->printExpansion($args); - } else { - require_once("lib/plugin/RecentChanges.php"); - $plugin = new WikiPlugin_RecentChanges(); + } else { + require_once("lib/plugin/RecentChanges.php"); + $plugin = new WikiPlugin_RecentChanges(); return $plugin->format($plugin->getChanges($request->_dbi, $args), $args); - } - } elseif ($format == 'json') { // for faster autocompletion on searches - $req_args =& $request->args; - unset($req_args['format']); + } + } elseif ($format == 'json') { // for faster autocompletion on searches + $req_args =& $request->args; + unset($req_args['format']); $json = array('count' => count($pagelist->_pages), 'list' => $args['VALID_LINKS'], 'args' => $req_args, @@ -171,25 +171,25 @@ function actionPage(&$request, $action) { } header("Content-Type: application/json"); die($json_enc); - } elseif ($format == 'rdf') { // all semantic relations and attributes - require_once("lib/SemanticWeb.php"); - $rdf = new RdfWriter($request, $pagelist); - $rdf->format(); - } elseif ($format == 'rdfs') { - require_once("lib/SemanticWeb.php"); - $rdf = new RdfsWriter($request, $pagelist); - $rdf->format(); - } elseif ($format == 'owl') { // or daml? - require_once("lib/SemanticWeb.php"); - $rdf = new OwlWriter($request, $pagelist); - $rdf->format(); - } else { - if (!in_array($pagename, array(_("LinkDatabase")))) - trigger_error(sprintf(_("Unsupported argument: %s=%s"),"format",$format), - E_USER_WARNING); - $template = Template('browse', array('CONTENT' => $transformedContent)); - GeneratePage($template, $pagetitle, $revision, $args); - } + } elseif ($format == 'rdf') { // all semantic relations and attributes + require_once("lib/SemanticWeb.php"); + $rdf = new RdfWriter($request, $pagelist); + $rdf->format(); + } elseif ($format == 'rdfs') { + require_once("lib/SemanticWeb.php"); + $rdf = new RdfsWriter($request, $pagelist); + $rdf->format(); + } elseif ($format == 'owl') { // or daml? + require_once("lib/SemanticWeb.php"); + $rdf = new OwlWriter($request, $pagelist); + $rdf->format(); + } else { + if (!in_array($pagename, array(_("LinkDatabase")))) + trigger_error(sprintf(_("Unsupported argument: %s=%s"),"format",$format), + E_USER_WARNING); + $template = Template('browse', array('CONTENT' => $transformedContent)); + GeneratePage($template, $pagetitle, $revision, $args); + } } $request->checkValidators(); flush(); @@ -208,7 +208,7 @@ function displayPage(&$request, $template=false) { NoSuchRevision($request, $page, $version); /* Tell Google (and others) to ignore old versions of pages */ $robots = "noindex,nofollow"; - $toks['ROBOTS_META'] = $robots; + $toks['ROBOTS_META'] = $robots; } else { $revision = $page->getCurrentRevision(); @@ -221,17 +221,17 @@ function displayPage(&$request, $template=false) { // DOCTYPE html needed to allow unencoded entities like   without !CDATA[] echo '',"\n"; - if ($page->exists()) { - header("Last-Modified: " . Rfc1123DateTime($revision->get('mtime'))); - $request->cacheControl(); - $request->setArg('format',''); + if ($page->exists()) { + header("Last-Modified: " . Rfc1123DateTime($revision->get('mtime'))); + $request->cacheControl(); + $request->setArg('format',''); $page_content = $revision->getTransformedContent(); $page_content->printXML(); $request->_is_buffering_output = false; // avoid wrong Content-Length with errors $request->finish(); } else { - $request->cacheControl(); + $request->cacheControl(); echo('
    '); $request->_is_buffering_output = false; // avoid wrong Content-Length with errors $request->finish(); @@ -275,7 +275,7 @@ function displayPage(&$request, $template=false) { $redirect_message = HTML::span(array('class' => 'redirectfrom'), fmt("(Redirected from %s)", RedirectorLink($redirect_from))); - // abuse the $redirected template var for some status update notice + // abuse the $redirected template var for some status update notice } elseif ($request->getArg('errormsg')) { $redirect_message = $request->getArg('errormsg'); $request->setArg('errormsg', false); @@ -303,8 +303,8 @@ function displayPage(&$request, $template=false) { // On external searchengine (google) referrer, highlight the searchterm and // pass through the Searchhighlight actionpage. if ($result = isExternalReferrer($request)) { - if (!empty($result['query'])) { - if (ENABLE_SEARCHHIGHLIGHT) { + if (!empty($result['query'])) { + if (ENABLE_SEARCHHIGHLIGHT) { $request->_searchhighlight = $result; $request->appendValidators(array('%mtime' => time())); // force no cache(?) // Should be changed to check the engine and search term only @@ -312,9 +312,9 @@ function displayPage(&$request, $template=false) { $page_content = new TransformedText($revision->getPage(), $revision->getPackedContent(), $revision->getMetaData()); - /* Now add the SearchHighlight plugin to the top of the page, in memory only. - You can parametrize this by changing the SearchHighlight action page. - */ + /* Now add the SearchHighlight plugin to the top of the page, in memory only. + You can parametrize this by changing the SearchHighlight action page. + */ if ($actionpage = $request->findActionPage('SearchHighlight')) { $actionpage = $request->getPage($actionpage); $actionrev = $actionpage->getCurrentRevision(); @@ -326,21 +326,21 @@ function displayPage(&$request, $template=false) { $toks['SEARCH_ENGINE'] = $result['engine']; $toks['SEARCH_ENGINE_URL'] = $result['engine_url']; $toks['SEARCH_TERM'] = $result['query']; - //$toks['HEADER'] = HTML($actionpage->getName(),": ",$pageheader); // h1 with backlink + //$toks['HEADER'] = HTML($actionpage->getName(),": ",$pageheader); // h1 with backlink $actioncontent = new TransformedText($actionrev->getPage(), $actionrev->getPackedContent(), $actionrev->getMetaData()); - // prepend the actionpage in front of the hightlighted content - $toks['CONTENT'] = HTML($actioncontent, $page_content); + // prepend the actionpage in front of the hightlighted content + $toks['CONTENT'] = HTML($actioncontent, $page_content); } - } - } else { + } + } else { $page_content = $revision->getTransformedContent(); - } + } } else { $page_content = $revision->getTransformedContent(); } - + /* Check for special pagenames, which are no actionpages. */ /* if ( $pagename == _("RecentVisitors")) { @@ -379,44 +379,44 @@ function displayPage(&$request, $template=false) { /* Only single page versions. rss only if not already handled by RecentChanges. */ if (!$format or $format == 'html' or $format == 'sidebar' or $format == 'contribs') { - $template->printExpansion($toks); + $template->printExpansion($toks); } else { - // No pagelist here. Single page version only - require_once("lib/PageList.php"); - $pagelist = new PageList(); - $pagelist->addPage($page); - if ($format == 'pdf') { - require_once("lib/pdf.php"); - $request->setArg('format',''); - ConvertAndDisplayPdfPageList($request, $pagelist); - // time-sorted rdf a la RecentChanges - } elseif (in_array($format, array("rss91","rss2","rss","atom"))) { - //$request->setArg('format',''); + // No pagelist here. Single page version only + require_once("lib/PageList.php"); + $pagelist = new PageList(); + $pagelist->addPage($page); + if ($format == 'pdf') { + require_once("lib/pdf.php"); + $request->setArg('format',''); + ConvertAndDisplayPdfPageList($request, $pagelist); + // time-sorted rdf a la RecentChanges + } elseif (in_array($format, array("rss91","rss2","rss","atom"))) { + //$request->setArg('format',''); if ($pagename == _("RecentChanges")) $template->printExpansion($toks); - else { - require_once("lib/plugin/RecentChanges.php"); - $plugin = new WikiPlugin_RecentChanges(); + else { + require_once("lib/plugin/RecentChanges.php"); + $plugin = new WikiPlugin_RecentChanges(); $args = $request->getArgs(); return $plugin->format($plugin->getChanges($request->_dbi, $args), $args); } - } elseif ($format == 'rdf') { // all semantic relations and attributes - require_once("lib/SemanticWeb.php"); - $rdf = new RdfWriter($request, $pagelist); - $rdf->format(); - } elseif ($format == 'owl') { // or daml? - require_once("lib/SemanticWeb.php"); - $rdf = new OwlWriter($request, $pagelist); - $rdf->format(); - } elseif ($format == 'json') { // include page content asynchronously - $request->setArg('format',''); - if ($page->exists()) - $content = $page_content->asXML(); + } elseif ($format == 'rdf') { // all semantic relations and attributes + require_once("lib/SemanticWeb.php"); + $rdf = new RdfWriter($request, $pagelist); + $rdf->format(); + } elseif ($format == 'owl') { // or daml? + require_once("lib/SemanticWeb.php"); + $rdf = new OwlWriter($request, $pagelist); + $rdf->format(); + } elseif ($format == 'json') { // include page content asynchronously + $request->setArg('format',''); + if ($page->exists()) + $content = $page_content->asXML(); else $content = ''; - $req_args = $request->args; - unset($req_args['format']); - // no meta-data so far, just the content + $req_args = $request->args; + unset($req_args['format']); + // no meta-data so far, just the content $json = array('content' => $content, 'args' => $req_args, 'phpwiki-version' => PHPWIKI_VERSION); @@ -429,19 +429,19 @@ function displayPage(&$request, $template=false) { } header("Content-Type: application/json"); die($json_enc); - } else { - if (!in_array($pagename, array(_("LinkDatabase")))) - trigger_error(sprintf(_("Unsupported argument: %s=%s"),"format",$format), - E_USER_WARNING); - $template->printExpansion($toks); - } + } else { + if (!in_array($pagename, array(_("LinkDatabase")))) + trigger_error(sprintf(_("Unsupported argument: %s=%s"),"format",$format), + E_USER_WARNING); + $template->printExpansion($toks); } - + } + $page->increaseHitCount(); if ($request->getArg('action') != 'pdf') { $request->checkValidators(); - flush(); + flush(); } return ''; } diff --git a/lib/editpage.php b/lib/editpage.php index 4549b5e36..d297fd798 100644 --- a/lib/editpage.php +++ b/lib/editpage.php @@ -15,14 +15,14 @@ class PageEditor // HACKish short circuit to browse on action=create if ($request->getArg('action') == 'create') { - if (! $this->current->hasDefaultContents()) + if (! $this->current->hasDefaultContents()) $request->redirect(WikiURL($this->page->getName())); // noreturn } - + $this->meta = array('author' => $this->user->getId(), 'author_id' => $this->user->getAuthenticatedId(), 'mtime' => time()); - + $this->tokens = array(); if (ENABLE_WYSIWYG) { @@ -54,9 +54,9 @@ class PageEditor $this->_initializeState(); $this->_initialEdit = true; - // The edit request has specified some initial content from a template + // The edit request has specified some initial content from a template if ( ($template = $request->getArg('template')) - and $request->_dbi->isWikiPage($template)) + and $request->_dbi->isWikiPage($template)) { $page = $request->_dbi->getPage($template); $current = $page->getCurrentRevision(); @@ -87,7 +87,7 @@ class PageEditor and ($r->getPref('editHeight') != $r->args['pref']['editHeight'])) { $r->_prefs->set('editHeight', $r->args['pref']['editHeight']); } - + if ($this->isModerated()) $tokens['PAGE_LOCKED_MESSAGE'] = $this->getModeratedMessage(); @@ -98,9 +98,9 @@ class PageEditor } elseif ($r->getArg('save_and_redirect_to') != "") { if (ENABLE_CAPTCHA && $this->Captcha->Failed()) { - $this->tokens['PAGE_LOCKED_MESSAGE'] = + $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML::p(HTML::h1($this->Captcha->failed_msg)); - } + } elseif ( $this->savePage()) { // noreturn $request->setArg('action', false); @@ -111,9 +111,9 @@ class PageEditor } elseif ($this->editaction == 'save') { if (ENABLE_CAPTCHA && $this->Captcha->Failed()) { - $this->tokens['PAGE_LOCKED_MESSAGE'] = + $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML::p(HTML::h1($this->Captcha->failed_msg)); - } + } elseif ($this->savePage()) { return true; // Page saved. } @@ -121,21 +121,21 @@ class PageEditor $saveFailed = true; } } - // coming from loadfile conflicts + // coming from loadfile conflicts elseif ($this->editaction == 'keep_old') { - // keep old page and do nothing + // keep old page and do nothing $this->_redirectToBrowsePage(); //$r->redirect(WikiURL($r->getArg('save_and_redirect_to'))); - return true; + return true; } - elseif ($this->editaction == 'overwrite') { + elseif ($this->editaction == 'overwrite') { // take the new content without diff - $source = $this->request->getArg('loadfile'); - require_once('lib/loadsave.php'); - $this->request->setArg('loadfile', 1); - $this->request->setArg('overwrite', 1); - $this->request->setArg('merge', 0); - LoadFileOrDir($this->request); + $source = $this->request->getArg('loadfile'); + require_once('lib/loadsave.php'); + $this->request->setArg('loadfile', 1); + $this->request->setArg('overwrite', 1); + $this->request->setArg('merge', 0); + LoadFileOrDir($this->request); $this->_redirectToBrowsePage(); //$r->redirect(WikiURL($r->getArg('save_and_redirect_to'))); return true; @@ -144,7 +144,7 @@ class PageEditor // run plugin UpLoad $plugin = WikiPluginLoader("UpLoad"); $plugin->run(); - // add link to content + // add link to content ; } @@ -167,13 +167,13 @@ class PageEditor $this->_currentVersion = $this->current->getVersion(); $this->version = $this->_currentVersion; $unresolved = $diff->ConflictingBlocks; - $tokens['CONCURRENT_UPDATE_MESSAGE'] + $tokens['CONCURRENT_UPDATE_MESSAGE'] = $this->getConflictMessage($unresolved); } elseif ($saveFailed && !$this->_isSpam) { - $tokens['CONCURRENT_UPDATE_MESSAGE'] = + $tokens['CONCURRENT_UPDATE_MESSAGE'] = HTML(HTML::h2(_("Some internal editing error")), - HTML::p(_("Your are probably trying to edit/create an invalid version of this page.")), - HTML::p(HTML::em(_("&version=-1 might help.")))); + HTML::p(_("Your are probably trying to edit/create an invalid version of this page.")), + HTML::p(HTML::em(_("&version=-1 might help.")))); } if ($this->editaction == 'edit_convert') @@ -216,9 +216,9 @@ class PageEditor //$tokens['PAGE_SOURCE'] = $this->WysiwygEdit->ConvertBefore($this->_content); } $template = Template($template, $this->tokens); - /* Tell google (and others) not to take notice of edit links */ - if (GOOGLE_LINKS_NOFOLLOW) - $args = array('ROBOTS_META' => "noindex,nofollow"); + /* Tell google (and others) not to take notice of edit links */ + if (GOOGLE_LINKS_NOFOLLOW) + $args = array('ROBOTS_META' => "noindex,nofollow"); GeneratePage($template, $title, $rev); return true; } @@ -248,24 +248,24 @@ class PageEditor $this->page->set('locked', (bool)$this->locked); $this->tokens['LOCK_CHANGED_MSG'] .= ($this->locked - ? _("Page now locked.") + ? _("Page now locked.") : _("Page now unlocked.") . " "); $changed = true; } if (ENABLE_PAGE_PUBLIC and (bool)$this->page->get('public') != (bool)$this->public) { $this->page->set('public', (bool)$this->public); $this->tokens['LOCK_CHANGED_MSG'] - .= ($this->public + .= ($this->public ? _("Page now public.") : _("Page now not-public.")); $changed = true; } - - if (ENABLE_EXTERNAL_PAGES) { + + if (ENABLE_EXTERNAL_PAGES) { if ((bool)$this->page->get('external') != (bool)$this->external) { $this->page->set('external', (bool)$this->external); $this->tokens['LOCK_CHANGED_MSG'] - = ($this->external + = ($this->external ? _("Page now external.") : _("Page now not-external.")) . " "; $changed = true; @@ -319,20 +319,20 @@ class PageEditor $meta = $this->selected->getMetaData(); unset($meta['pgsrc_version']); $meta = array_merge($meta, $this->meta); - + // Save new revision $this->_content = $this->getContent(); - $newrevision = $page->save($this->_content, - $this->version == -1 - ? -1 - : $this->_currentVersion + 1, + $newrevision = $page->save($this->_content, + $this->version == -1 + ? -1 + : $this->_currentVersion + 1, // force new? - $meta); + $meta); if (!isa($newrevision, 'WikiDB_PageRevision')) { // Save failed. (Concurrent updates). return false; } - + // New contents successfully saved... $this->updateLock(); @@ -341,17 +341,17 @@ class PageEditor $cleaner = new ArchiveCleaner($GLOBALS['ExpireParams']); $cleaner->cleanPageRevisions($page); - /* generate notification emails done in WikiDB::save to catch + /* generate notification emails done in WikiDB::save to catch all direct calls (admin plugins) */ // look at the errorstack $errors = $GLOBALS['ErrorManager']->_postponed_errors; - $warnings = $GLOBALS['ErrorManager']->getPostponedErrorsAsHTML(); + $warnings = $GLOBALS['ErrorManager']->getPostponedErrorsAsHTML(); $GLOBALS['ErrorManager']->_postponed_errors = $errors; $dbi = $request->getDbh(); $dbi->touch(); - + global $WikiTheme; if (empty($warnings->_content) && ! $WikiTheme->getImageURL('signature')) { // Do redirect to browse page if no signature has @@ -371,7 +371,7 @@ class PageEditor $template->replace('CONTENT', $newrevision->getTransformedContent()); if (!empty($warnings->_content)) { $template->replace('WARNINGS', $warnings); - unset($GLOBALS['ErrorManager']->_postponed_errors); + unset($GLOBALS['ErrorManager']->_postponed_errors); } $pagelink = WikiLink($page); @@ -402,12 +402,12 @@ class PageEditor return $this->_content == $current->getPackedContent(); } - /** + /** * Handle AntiSpam here. How? http://wikiblacklist.blogspot.com/ - * Need to check dynamically some blacklist wikipage settings + * Need to check dynamically some blacklist wikipage settings * (plugin WikiAccessRestrictions) and some static blacklist. - * DONE: - * More than NUM_SPAM_LINKS (default: 20) new external links. + * DONE: + * More than NUM_SPAM_LINKS (default: 20) new external links. * Disabled if NUM_SPAM_LINKS is 0 * ENABLE_SPAMASSASSIN: content patterns by babycart (only php >= 4.3 for now) * ENABLE_SPAMBLOCKLIST: content domain blacklist @@ -428,7 +428,7 @@ class PageEditor { // Allow strictly authenticated users? // TODO: mail the admin? - $this->tokens['PAGE_LOCKED_MESSAGE'] = + $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML($this->getSpamMessage(), HTML::p(HTML::strong(_("Too many external links.")))); return true; @@ -437,13 +437,13 @@ class PageEditor // This will probably prevent from discussing sex or viagra related topics. So beware. if (ENABLE_SPAMASSASSIN) { require_once("lib/spam_babycart.php"); - if ($babycart = check_babycart($newtext, $request->get("REMOTE_ADDR"), + if ($babycart = check_babycart($newtext, $request->get("REMOTE_ADDR"), $this->user->getId())) { // TODO: mail the admin if (is_array($babycart)) - $this->tokens['PAGE_LOCKED_MESSAGE'] = + $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML($this->getSpamMessage(), - HTML::p(HTML::em(_("SpamAssassin reports: "), + HTML::p(HTML::em(_("SpamAssassin reports: "), join("\n", $babycart)))); return true; } @@ -456,26 +456,26 @@ class PageEditor $oldparsed = TransformLinks($oldtext); $oldlinks = array(); foreach ($oldparsed->_content as $link) { - if (isa($link, 'Cached_ExternalLink') and !isa($link, 'Cached_InterwikiLink')) { + if (isa($link, 'Cached_ExternalLink') and !isa($link, 'Cached_InterwikiLink')) { $uri = $link->_getURL($this->page->getName()); $oldlinks[$uri]++; - } + } } unset($oldparsed); foreach ($parsed->_content as $link) { - if (isa($link, 'Cached_ExternalLink') and !isa($link, 'Cached_InterwikiLink')) { + if (isa($link, 'Cached_ExternalLink') and !isa($link, 'Cached_InterwikiLink')) { $uri = $link->_getURL($this->page->getName()); // only check new links, so admins may add blocked links. if (!array_key_exists($uri, $oldlinks) and ($res = IsBlackListed($uri))) { // TODO: mail the admin - $this->tokens['PAGE_LOCKED_MESSAGE'] = + $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML($this->getSpamMessage(), HTML::p(HTML::strong(_("External links contain blocked domains:")), - HTML::ul(HTML::li(sprintf(_("%s is listed at %s with %s"), + HTML::ul(HTML::li(sprintf(_("%s is listed at %s with %s"), $uri." [".$res[2]."]", $res[0], $res[1]))))); return true; } - } + } } unset($oldlinks); unset($parsed); @@ -491,7 +491,7 @@ class PageEditor return substr_count($text, "http://") + substr_count($text, "https://"); } - /** Header of the Anti Spam message + /** Header of the Anti Spam message */ function getSpamMessage () { return @@ -505,7 +505,7 @@ class PageEditor function getPreview () { require_once('lib/PageType.php'); $this->_content = $this->getContent(); - return new TransformedText($this->page, $this->_content, $this->meta); + return new TransformedText($this->page, $this->_content, $this->meta); } function getConvertedPreview () { @@ -513,24 +513,24 @@ class PageEditor $this->_content = $this->getContent(); $this->meta['markup'] = 2.0; $this->_content = ConvertOldMarkup($this->_content); - return new TransformedText($this->page, $this->_content, $this->meta); + return new TransformedText($this->page, $this->_content, $this->meta); } function getDiff () { require_once('lib/diff.php'); - $html = HTML(); - - $diff = new Diff($this->current->getContent(), explode("\n", $this->getContent())); - if ($diff->isEmpty()) { - $html->pushContent(HTML::hr(), - HTML::p('[', _("Versions are identical"), - ']')); - } - else { - // New CSS formatted unified diffs - $fmt = new HtmlUnifiedDiffFormatter; - $html->pushContent($fmt->format($diff)); - } + $html = HTML(); + + $diff = new Diff($this->current->getContent(), explode("\n", $this->getContent())); + if ($diff->isEmpty()) { + $html->pushContent(HTML::hr(), + HTML::p('[', _("Versions are identical"), + ']')); + } + else { + // New CSS formatted unified diffs + $fmt = new HtmlUnifiedDiffFormatter; + $html->pushContent($fmt->format($diff)); + } return $html; } @@ -567,7 +567,7 @@ class PageEditor return HTML(HTML::h2(WikiLink(_("ModeratedPage"))), HTML::p(fmt("You can edit away, but your changes will have to be approved by the defined moderators at the definition in %s", WikiLink(_("ModeratedPage")))), - HTML::p(fmt("The approval has a grace period of 5 days. If you have your E-Mail defined in your %s, you will get a notification of approval or rejection.", + HTML::p(fmt("The approval has a grace period of 5 days. If you have your E-Mail defined in your %s, you will get a notification of approval or rejection.", WikiLink(_("UserPreferences"))))); } function getConflictMessage ($unresolved = false) { @@ -623,7 +623,7 @@ class PageEditor 'readonly' => (bool) $readonly), $this->_content); if (ENABLE_WYSIWYG) { - return $this->WysiwygEdit->Textarea($textarea, $this->_wikicontent, + return $this->WysiwygEdit->Textarea($textarea, $this->_wikicontent, $textarea->getAttr('name')); } else return $textarea; @@ -665,7 +665,7 @@ class PageEditor 'checked' => $this->meta['markup'] < 2.0, 'id' => 'useOldMarkup', 'onclick' => 'showOldMarkupRules(this.checked)')); - $el['OLD_MARKUP_CONVERT'] = ($this->meta['markup'] < 2.0) + $el['OLD_MARKUP_CONVERT'] = ($this->meta['markup'] < 2.0) ? Button('submit:edit[edit_convert]', _("Convert"), 'wikiaction') : ''; $el['LOCKED_CB'] = HTML::input(array('type' => 'checkbox', @@ -681,7 +681,7 @@ class PageEditor 'disabled' => (bool) !$this->user->isAdmin(), 'checked' => (bool) $this->page->get('public'))); } - if (ENABLE_EXTERNAL_PAGES) { + if (ENABLE_EXTERNAL_PAGES) { $el['EXTERNAL_CB'] = HTML::input(array('type' => 'checkbox', 'name' => 'edit[external]', @@ -690,24 +690,24 @@ class PageEditor 'checked' => (bool) $this->page->get('external'))); } if (ENABLE_WYSIWYG) { - if (($this->version == 0) and ($request->getArg('mode') != 'wysiwyg')) { - $el['WYSIWYG_B'] = Button(array("action" => "edit", "mode" => "wysiwyg"), "Wysiwyg Editor"); - } - } + if (($this->version == 0) and ($request->getArg('mode') != 'wysiwyg')) { + $el['WYSIWYG_B'] = Button(array("action" => "edit", "mode" => "wysiwyg"), "Wysiwyg Editor"); + } + } $el['PREVIEW_B'] = Button('submit:edit[preview]', _("Preview"), 'wikiaction', - array('accesskey'=> 'p', + array('accesskey'=> 'p', 'title' => 'Preview the current content [alt-p]')); //if (!$this->isConcurrentUpdate() && $this->canEdit()) $el['SAVE_B'] = Button('submit:edit[save]', _("Save"), 'wikiaction', - array('accesskey'=> 's', + array('accesskey'=> 's', 'title' => 'Save the current content as wikipage [alt-s]')); $el['CHANGES_B'] = Button('submit:edit[diff]', _("Changes"), 'wikiaction', - array('accesskey'=> 'c', + array('accesskey'=> 'c', 'title' => 'Preview the current changes as diff [alt-c]')); $el['UPLOAD_B'] = Button('submit:edit[upload]', _("Upload"), 'wikiaction', @@ -717,7 +717,7 @@ class PageEditor array('title' => 'Check the spelling')); $el['IS_CURRENT'] = $this->version == $this->current->getVersion(); - $el['WIDTH_PREF'] + $el['WIDTH_PREF'] = HTML::input(array('type' => 'text', 'size' => 3, 'maxlength'=> 4, @@ -726,7 +726,7 @@ class PageEditor 'id' => 'pref-editWidth', 'value' => $request->getPref('editWidth'), 'onchange' => 'this.form.submit();')); - $el['HEIGHT_PREF'] + $el['HEIGHT_PREF'] = HTML::input(array('type' => 'text', 'size' => 3, 'maxlength'=> 4, @@ -736,9 +736,9 @@ class PageEditor 'value' => $request->getPref('editHeight'), 'onchange' => 'this.form.submit();')); $el['SEP'] = $WikiTheme->getButtonSeparator(); - $el['AUTHOR_MESSAGE'] = fmt("Author will be logged as %s.", + $el['AUTHOR_MESSAGE'] = fmt("Author will be logged as %s.", HTML::em($this->user->getId())); - + return $el; } @@ -752,8 +752,8 @@ class PageEditor $posted = $request->getArg('edit'); $request->setArg('edit', false); - if (!$posted - || !$request->isPost() + if (!$posted + || !$request->isPost() || !in_array($request->getArg('action'),array('edit','loadfile'))) return false; @@ -776,8 +776,8 @@ class PageEditor $meta['is_minor_edit'] = !empty($posted['minor_edit']); $meta['pagetype'] = !empty($posted['pagetype']) ? $posted['pagetype'] : false; if ( ENABLE_CAPTCHA ) - $meta['captcha_input'] = !empty($posted['captcha_input']) ? - $posted['captcha_input'] : ''; + $meta['captcha_input'] = !empty($posted['captcha_input']) ? + $posted['captcha_input'] : ''; $this->meta = array_merge($this->meta, $meta); $this->locked = !empty($posted['locked']); @@ -786,12 +786,12 @@ class PageEditor if (ENABLE_EXTERNAL_PAGES) $this->external = !empty($posted['external']); - foreach (array('preview','save','edit_convert', - 'keep_old','overwrite','diff','upload') as $o) - { - if (!empty($posted[$o])) - $this->editaction = $o; - } + foreach (array('preview','save','edit_convert', + 'keep_old','overwrite','diff','upload') as $o) + { + if (!empty($posted[$o])) + $this->editaction = $o; + } if (empty($this->editaction)) $this->editaction = 'edit'; @@ -843,13 +843,13 @@ extends PageEditor if (!$this->canEdit()) { if ($this->isInitialEdit()) { return $this->viewSource(); - } + } $tokens['PAGE_LOCKED_MESSAGE'] = $this->getLockedMessage(); } elseif ($this->editaction == 'save') { if ($this->savePage()) { return true; // Page saved. - } + } $saveFailed = true; } @@ -886,29 +886,29 @@ extends PageEditor // FIXME: NOT_CURRENT_MESSAGE? $tokens = array_merge($tokens, $this->getFormElements()); - // we need all GET params for loadfile overwrite - if ($this->request->getArg('action') == 'loadfile') { - - $this->tokens['HIDDEN_INPUTS'] = - HTML(HiddenInputs - (array('source' => $this->request->getArg('source'), - 'merge' => 1)), - $this->tokens['HIDDEN_INPUTS']); - // add two conflict resolution buttons before preview and save. - $tokens['PREVIEW_B'] = HTML( - Button('submit:edit[keep_old]', - _("Keep old"), 'wikiaction'), - $tokens['SEP'], - Button('submit:edit[overwrite]', - _("Overwrite with new"), 'wikiaction'), - $tokens['SEP'], - $tokens['PREVIEW_B']); - } - if (ENABLE_EDIT_TOOLBAR and !ENABLE_WYSIWYG) { + // we need all GET params for loadfile overwrite + if ($this->request->getArg('action') == 'loadfile') { + + $this->tokens['HIDDEN_INPUTS'] = + HTML(HiddenInputs + (array('source' => $this->request->getArg('source'), + 'merge' => 1)), + $this->tokens['HIDDEN_INPUTS']); + // add two conflict resolution buttons before preview and save. + $tokens['PREVIEW_B'] = HTML( + Button('submit:edit[keep_old]', + _("Keep old"), 'wikiaction'), + $tokens['SEP'], + Button('submit:edit[overwrite]', + _("Overwrite with new"), 'wikiaction'), + $tokens['SEP'], + $tokens['PREVIEW_B']); + } + if (ENABLE_EDIT_TOOLBAR and !ENABLE_WYSIWYG) { include_once("lib/EditToolbar.php"); $toolbar = new EditToolbar(); $tokens = array_merge($tokens, $toolbar->getTokens()); - } + } return $this->output('editpage', _("Merge and Edit: %s")); } @@ -927,13 +927,13 @@ extends PageEditor } $title = new FormattedText ($title_fs, $pagelink); - $this->tokens['HEADER'] = $title; - //hack! there's no TITLE in editpage, but in the previous top template - if (empty($this->tokens['PAGE_LOCKED_MESSAGE'])) - $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML::h3($title); - else - $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML(HTML::h3($title), - $this->tokens['PAGE_LOCKED_MESSAGE']); + $this->tokens['HEADER'] = $title; + //hack! there's no TITLE in editpage, but in the previous top template + if (empty($this->tokens['PAGE_LOCKED_MESSAGE'])) + $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML::h3($title); + else + $this->tokens['PAGE_LOCKED_MESSAGE'] = HTML(HTML::h3($title), + $this->tokens['PAGE_LOCKED_MESSAGE']); $template = Template($template, $this->tokens); //GeneratePage($template, $title, $rev); diff --git a/lib/fortune.php b/lib/fortune.php index 689f7338a..941cfc158 100644 --- a/lib/fortune.php +++ b/lib/fortune.php @@ -1,13 +1,13 @@ getRandomQuote($dir . "/" .$files[$i]); + + if ($amount) + while ($quotes[$i] < $index) { + $i++; + } + if (!empty($files)) + return $this->getRandomQuote($dir . "/" .$files[$i]); } return -1; } /* - Reads the number of quotes in the file. + Reads the number of quotes in the file. */ function getNumberOfQuotes($file) { $fd = fopen($file, "rb"); @@ -66,27 +66,27 @@ class Fortune { echo "Input must be a file!
    "; return; } - + if ( ($fd = fopen($file, "rb")) == false ) { - echo "Cannot open $file
    "; + echo "Cannot open $file
    "; return; } fseek($fd, 24 + 4 * $index); - + $phys_index = $this->readLong($fd); - + fclose($fd); - + $quotefile = substr($file, 0, strlen($file) - 4); if ( ($fd = fopen($quotefile, "rb")) == false ) { echo "Cannot find file $quotefile!
    "; - } - + } + $res = $this->getQuote($fd, $phys_index); fclose($fd); - - return $res; + + return $res; } /* @@ -98,7 +98,7 @@ class Fortune { $index = rand(0, $number - 1); return $this->getExactQuote($file, $index); - } + } /* Reads a quote from the specified index. @@ -107,7 +107,7 @@ class Fortune { fseek($fd, $index); $line=""; $res = ""; do { - $res = $res . $line; + $res = $res . $line; $line = fgets($fd, 1024) . "
    "; } while ( ($line[0] != "%") && (!feof($fd)) ); @@ -120,7 +120,7 @@ class Fortune { function getIndices($fd) { fseek($fd, 24, SEEK_SET); $i = 0; - + while ( feof($fd) == FALSE ) { $res[$i] = readLong($fd); $i++; @@ -157,7 +157,7 @@ class Fortune { $i++; if ($length > $longest) $longest = $length; - + if ($length < $shortest) $shortest = $length; diff --git a/lib/fpdf.php b/lib/fpdf.php index 39fc4c23e..f9def489f 100644 --- a/lib/fpdf.php +++ b/lib/fpdf.php @@ -77,51 +77,51 @@ class FPDF * * *******************************************************************************/ function FPDF ($orientation='P', $unit='mm', $format='A4') { - //Some checks - $this->_dochecks(); - //Initialization of properties - $this->page=0; - $this->n=2; - $this->buffer=''; - $this->pages=array(); - $this->OrientationChanges=array(); - $this->state=0; - $this->fonts=array(); - $this->FontFiles=array(); - $this->diffs=array(); - $this->images=array(); - $this->links=array(); - $this->InFooter=false; - $this->lasth=0; - $this->FontFamily=''; - $this->FontStyle=''; - $this->FontSizePt=12; - $this->underline=false; - $this->DrawColor='0 G'; - $this->FillColor='0 g'; - $this->TextColor='0 g'; - $this->ColorFlag=false; - $this->ws=0; - //Standard fonts - $this->CoreFonts=array('japanees'=>'Japanees', + //Some checks + $this->_dochecks(); + //Initialization of properties + $this->page=0; + $this->n=2; + $this->buffer=''; + $this->pages=array(); + $this->OrientationChanges=array(); + $this->state=0; + $this->fonts=array(); + $this->FontFiles=array(); + $this->diffs=array(); + $this->images=array(); + $this->links=array(); + $this->InFooter=false; + $this->lasth=0; + $this->FontFamily=''; + $this->FontStyle=''; + $this->FontSizePt=12; + $this->underline=false; + $this->DrawColor='0 G'; + $this->FillColor='0 g'; + $this->TextColor='0 g'; + $this->ColorFlag=false; + $this->ws=0; + //Standard fonts + $this->CoreFonts=array('japanees'=>'Japanees', 'courier'=>'Courier','courierB'=>'Courier-Bold','courierI'=>'Courier-Oblique','courierBI'=>'Courier-BoldOblique', 'helvetica'=>'Helvetica','helveticaB'=>'Helvetica-Bold','helveticaI'=>'Helvetica-Oblique','helveticaBI'=>'Helvetica-BoldOblique', 'times'=>'Times-Roman','timesB'=>'Times-Bold','timesI'=>'Times-Italic','timesBI'=>'Times-BoldItalic', 'symbol'=>'Symbol','zapfdingbats'=>'ZapfDingbats'); - //Scale factor - if ($unit=='pt') + //Scale factor + if ($unit=='pt') $this->k=1; - elseif ($unit=='mm') + elseif ($unit=='mm') $this->k=72/25.4; - elseif ($unit=='cm') + elseif ($unit=='cm') $this->k=72/2.54; - elseif ($unit=='in') + elseif ($unit=='in') $this->k=72; - else + else $this->Error('Incorrect unit: '.$unit); - //Page format - if (is_string($format)) - { + //Page format + if (is_string($format)) + { $format=strtolower($format); if ($format=='a3') $format=array(841.89,1190.55); @@ -137,176 +137,176 @@ class FPDF $this->Error('Unknown page format: '.$format); $this->fwPt=$format[0]; $this->fhPt=$format[1]; - } - else - { + } + else + { $this->fwPt=$format[0]*$this->k; $this->fhPt=$format[1]*$this->k; - } - $this->fw=$this->fwPt/$this->k; - $this->fh=$this->fhPt/$this->k; - //Page orientation - $orientation=strtolower($orientation); - if ($orientation=='p' or $orientation=='portrait') - { + } + $this->fw=$this->fwPt/$this->k; + $this->fh=$this->fhPt/$this->k; + //Page orientation + $orientation=strtolower($orientation); + if ($orientation=='p' or $orientation=='portrait') + { $this->DefOrientation='P'; $this->wPt=$this->fwPt; $this->hPt=$this->fhPt; - } - elseif ($orientation=='l' or $orientation=='landscape') - { + } + elseif ($orientation=='l' or $orientation=='landscape') + { $this->DefOrientation='L'; $this->wPt=$this->fhPt; $this->hPt=$this->fwPt; - } - else + } + else $this->Error('Incorrect orientation: '.$orientation); - $this->CurOrientation=$this->DefOrientation; - $this->w=$this->wPt/$this->k; - $this->h=$this->hPt/$this->k; - //Page margins (1 cm) - $margin=28.35/$this->k; - $this->SetMargins($margin,$margin); - //Interior cell margin (1 mm) - $this->cMargin=$margin/10; - //Line width (0.2 mm) - $this->LineWidth=.567/$this->k; - //Automatic page break - $this->SetAutoPageBreak(true,2*$margin); - //Full width display mode - $this->SetDisplayMode('fullwidth'); - //Compression - $this->SetCompression(true); + $this->CurOrientation=$this->DefOrientation; + $this->w=$this->wPt/$this->k; + $this->h=$this->hPt/$this->k; + //Page margins (1 cm) + $margin=28.35/$this->k; + $this->SetMargins($margin,$margin); + //Interior cell margin (1 mm) + $this->cMargin=$margin/10; + //Line width (0.2 mm) + $this->LineWidth=.567/$this->k; + //Automatic page break + $this->SetAutoPageBreak(true,2*$margin); + //Full width display mode + $this->SetDisplayMode('fullwidth'); + //Compression + $this->SetCompression(true); } function SetMargins($left,$top,$right=-1) { - //Set left, top and right margins - $this->lMargin=$left; - $this->tMargin=$top; - if ($right==-1) + //Set left, top and right margins + $this->lMargin=$left; + $this->tMargin=$top; + if ($right==-1) $right=$left; - $this->rMargin=$right; + $this->rMargin=$right; } function SetLeftMargin($margin) { - //Set left margin - $this->lMargin=$margin; - if ($this->page>0 and $this->x<$margin) + //Set left margin + $this->lMargin=$margin; + if ($this->page>0 and $this->x<$margin) $this->x=$margin; } function SetTopMargin($margin) { - //Set top margin - $this->tMargin=$margin; + //Set top margin + $this->tMargin=$margin; } function SetRightMargin($margin) { - //Set right margin - $this->rMargin=$margin; + //Set right margin + $this->rMargin=$margin; } function SetAutoPageBreak($auto,$margin=0) { - //Set auto page break mode and triggering margin - $this->AutoPageBreak=$auto; - $this->bMargin=$margin; - $this->PageBreakTrigger=$this->h-$margin; + //Set auto page break mode and triggering margin + $this->AutoPageBreak=$auto; + $this->bMargin=$margin; + $this->PageBreakTrigger=$this->h-$margin; } function SetDisplayMode($zoom,$layout='continuous') { - //Set display mode in viewer - if ($zoom=='fullpage' or $zoom=='fullwidth' or $zoom=='real' or $zoom=='default' or !is_string($zoom)) + //Set display mode in viewer + if ($zoom=='fullpage' or $zoom=='fullwidth' or $zoom=='real' or $zoom=='default' or !is_string($zoom)) $this->ZoomMode=$zoom; - else + else $this->Error('Incorrect zoom display mode: '.$zoom); - if ($layout=='single' or $layout=='continuous' or $layout=='two' or $layout=='default') + if ($layout=='single' or $layout=='continuous' or $layout=='two' or $layout=='default') $this->LayoutMode=$layout; - else + else $this->Error('Incorrect layout display mode: '.$layout); } function SetCompression($compress) { - //Set page compression - if (function_exists('gzcompress')) + //Set page compression + if (function_exists('gzcompress')) $this->compress=$compress; - else + else $this->compress=false; } function SetTitle($title) { - //Title of document - $this->title=$title; + //Title of document + $this->title=$title; } function SetSubject($subject) { - //Subject of document - $this->subject=$subject; + //Subject of document + $this->subject=$subject; } function SetAuthor($author) { - //Author of document - $this->author=$author; + //Author of document + $this->author=$author; } function SetKeywords($keywords) { - //Keywords of document - $this->keywords=$keywords; + //Keywords of document + $this->keywords=$keywords; } function SetCreator($creator) { - //Creator of document - $this->creator=$creator; + //Creator of document + $this->creator=$creator; } function SetProducer($producer) { - //Producer of document - $this->producer=$producer; + //Producer of document + $this->producer=$producer; } function AliasNbPages($alias='{nb}') { - //Define an alias for total number of pages - $this->AliasNbPages=$alias; + //Define an alias for total number of pages + $this->AliasNbPages=$alias; } function Error($msg) { - //Fatal error - die('FPDF error: '.$msg); + //Fatal error + die('FPDF error: '.$msg); } function Open() { - //Begin document - if ($this->state==0) + //Begin document + if ($this->state==0) $this->_begindoc(); } function Close() { - //Terminate document - if ($this->state==3) + //Terminate document + if ($this->state==3) return; - if ($this->page==0) + if ($this->page==0) $this->AddPage(); - //Page footer - $this->InFooter=true; - $this->Footer(); - $this->InFooter=false; - //Close page - $this->_endpage(); - //Close document - $this->_enddoc(); + //Page footer + $this->InFooter=true; + $this->Footer(); + $this->InFooter=false; + //Close page + $this->_endpage(); + //Close document + $this->_enddoc(); } function AddPage($orientation='') { - //Start a new page - if ($this->state==0) + //Start a new page + if ($this->state==0) $this->Open(); - $family=$this->FontFamily; - $style=$this->FontStyle.($this->underline ? 'U' : ''); - $size=$this->FontSizePt; - $lw=$this->LineWidth; - $dc=$this->DrawColor; - $fc=$this->FillColor; - $tc=$this->TextColor; - $cf=$this->ColorFlag; - if ($this->page>0) { + $family=$this->FontFamily; + $style=$this->FontStyle.($this->underline ? 'U' : ''); + $size=$this->FontSizePt; + $lw=$this->LineWidth; + $dc=$this->DrawColor; + $fc=$this->FillColor; + $tc=$this->TextColor; + $cf=$this->ColorFlag; + if ($this->page>0) { //Page footer $this->InFooter=true; $this->Footer(); @@ -314,145 +314,145 @@ class FPDF //Close page $this->_endpage(); } - //Start new page - $this->_beginpage($orientation); - //Set line cap style to square - $this->_out('2 J'); - //Set line width - $this->LineWidth=$lw; - $this->_out(sprintf('%.2f w',$lw*$this->k)); - //Set font - if ($family) + //Start new page + $this->_beginpage($orientation); + //Set line cap style to square + $this->_out('2 J'); + //Set line width + $this->LineWidth=$lw; + $this->_out(sprintf('%.2f w',$lw*$this->k)); + //Set font + if ($family) $this->SetFont($family,$style,$size); - //Set colors - $this->DrawColor=$dc; - if ($dc!='0 G') + //Set colors + $this->DrawColor=$dc; + if ($dc!='0 G') $this->_out($dc); - $this->FillColor=$fc; - if ($fc!='0 g') + $this->FillColor=$fc; + if ($fc!='0 g') $this->_out($fc); - $this->TextColor=$tc; - $this->ColorFlag=$cf; - //Page header - $this->Header(); - //Restore line width - if ($this->LineWidth!=$lw) { + $this->TextColor=$tc; + $this->ColorFlag=$cf; + //Page header + $this->Header(); + //Restore line width + if ($this->LineWidth!=$lw) { $this->LineWidth=$lw; $this->_out(sprintf('%.2f w',$lw*$this->k)); } - //Restore font - if ($family) + //Restore font + if ($family) $this->SetFont($family,$style,$size); - //Restore colors - if ($this->DrawColor!=$dc) { + //Restore colors + if ($this->DrawColor!=$dc) { $this->DrawColor=$dc; $this->_out($dc); } - if ($this->FillColor!=$fc) { + if ($this->FillColor!=$fc) { $this->FillColor=$fc; $this->_out($fc); } - $this->TextColor=$tc; - $this->ColorFlag=$cf; + $this->TextColor=$tc; + $this->ColorFlag=$cf; } function Header() { - //To be implemented in your own inherited class + //To be implemented in your own inherited class } function Footer() { - //To be implemented in your own inherited class + //To be implemented in your own inherited class } function PageNo() { - //Get current page number - return $this->page; + //Get current page number + return $this->page; } function SetDrawColor($r,$g=-1,$b=-1) { - //Set color for all stroking operations - if (($r==0 and $g==0 and $b==0) or $g==-1) + //Set color for all stroking operations + if (($r==0 and $g==0 and $b==0) or $g==-1) $this->DrawColor=sprintf('%.3f G',$r/255); - else + else $this->DrawColor=sprintf('%.3f %.3f %.3f RG',$r/255,$g/255,$b/255); - if ($this->page>0) + if ($this->page>0) $this->_out($this->DrawColor); } function SetFillColor($r,$g=-1,$b=-1) { - //Set color for all filling operations - if (($r==0 and $g==0 and $b==0) or $g==-1) + //Set color for all filling operations + if (($r==0 and $g==0 and $b==0) or $g==-1) $this->FillColor=sprintf('%.3f g',$r/255); - else + else $this->FillColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255); - $this->ColorFlag=($this->FillColor!=$this->TextColor); - if ($this->page>0) + $this->ColorFlag=($this->FillColor!=$this->TextColor); + if ($this->page>0) $this->_out($this->FillColor); } function SetTextColor($r,$g=-1,$b=-1) { - //Set color for text - if (($r==0 and $g==0 and $b==0) or $g==-1) + //Set color for text + if (($r==0 and $g==0 and $b==0) or $g==-1) $this->TextColor=sprintf('%.3f g',$r/255); - else + else $this->TextColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255); - $this->ColorFlag=($this->FillColor!=$this->TextColor); + $this->ColorFlag=($this->FillColor!=$this->TextColor); } function GetStringWidth($s) { - //Get width of a string in the current font - $s=(string)$s; - $cw=&$this->CurrentFont['cw']; - $w=0; - $l=strlen($s); - for($i=0;$i<$l;$i++) + //Get width of a string in the current font + $s=(string)$s; + $cw=&$this->CurrentFont['cw']; + $w=0; + $l=strlen($s); + for($i=0;$i<$l;$i++) $w+=$cw[$s{$i}]; - return $w*$this->FontSize/1000; + return $w*$this->FontSize/1000; } function SetLineWidth($width) { - //Set line width - $this->LineWidth=$width; - if ($this->page>0) + //Set line width + $this->LineWidth=$width; + if ($this->page>0) $this->_out(sprintf('%.2f w',$width*$this->k)); } function Line($x1,$y1,$x2,$y2) { - //Draw a line - $this->_out(sprintf('%.2f %.2f m %.2f %.2f l S',$x1*$this->k,($this->h-$y1)*$this->k,$x2*$this->k,($this->h-$y2)*$this->k)); + //Draw a line + $this->_out(sprintf('%.2f %.2f m %.2f %.2f l S',$x1*$this->k,($this->h-$y1)*$this->k,$x2*$this->k,($this->h-$y2)*$this->k)); } function Rect($x,$y,$w,$h,$style='') { - //Draw a rectangle - if ($style=='F') + //Draw a rectangle + if ($style=='F') $op='f'; - elseif ($style=='FD' or $style=='DF') + elseif ($style=='FD' or $style=='DF') $op='B'; - else + else $op='S'; - $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op)); + $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op)); } function AddFont($family,$style='',$file='') { - //Add a TrueType or Type1 font - $family=strtolower($family); - if ($family=='arial') + //Add a TrueType or Type1 font + $family=strtolower($family); + if ($family=='arial') $family='helvetica'; - $style=strtoupper($style); - if ($style=='IB') + $style=strtoupper($style); + if ($style=='IB') $style='BI'; - if (isset($this->fonts[$family.$style])) + if (isset($this->fonts[$family.$style])) $this->Error('Font already added: '.$family.' '.$style); - if ($file=='') + if ($file=='') $file=str_replace(' ','',$family).strtolower($style).'.php'; - if (defined('FPDF_FONTPATH')) + if (defined('FPDF_FONTPATH')) $file = FPDF_FONTPATH . $file; - include($file); - if (!isset($name)) + include($file); + if (!isset($name)) $this->Error('Could not include font definition file'); - $i=count($this->fonts)+1; - $this->fonts[$family.$style]=array('i'=>$i,'type'=>$type,'name'=>$name,'desc'=>$desc,'up'=>$up,'ut'=>$ut,'cw'=>$cw,'enc'=>$enc,'file'=>$file); - if ($diff) { + $i=count($this->fonts)+1; + $this->fonts[$family.$style]=array('i'=>$i,'type'=>$type,'name'=>$name,'desc'=>$desc,'up'=>$up,'ut'=>$ut,'cw'=>$cw,'enc'=>$enc,'file'=>$file); + if ($diff) { //Search existing encodings $d=0; $nb=count($this->diffs); @@ -467,7 +467,7 @@ class FPDF } $this->fonts[$family.$style]['diff']=$d; } - if ($file) { + if ($file) { if ($type=='TrueType') $this->FontFiles[$file]=array('length1'=>$originalsize); else @@ -476,33 +476,33 @@ class FPDF } function SetFont($family,$style='',$size=0) { - //Select a font; size given in points - global $fpdf_charwidths; + //Select a font; size given in points + global $fpdf_charwidths; - $family=strtolower($family); - if ($family=='') + $family=strtolower($family); + if ($family=='') $family=$this->FontFamily; - if ($family=='arial') + if ($family=='arial') $family='helvetica'; - elseif ($family=='symbol' or $family=='zapfdingbats') + elseif ($family=='symbol' or $family=='zapfdingbats') $style=''; - $style=strtoupper($style); - if (is_int(strpos($style,'U'))) { + $style=strtoupper($style); + if (is_int(strpos($style,'U'))) { $this->underline=true; $style=str_replace('U','',$style); } - else + else $this->underline=false; - if ($style=='IB') + if ($style=='IB') $style='BI'; - if ($size==0) + if ($size==0) $size=$this->FontSizePt; - //Test if font is already selected - if ($this->FontFamily==$family and $this->FontStyle==$style and $this->FontSizePt==$size) + //Test if font is already selected + if ($this->FontFamily==$family and $this->FontStyle==$style and $this->FontSizePt==$size) return; - //Test if used for the first time - $fontkey=$family.$style; - if (!isset($this->fonts[$fontkey])) { + //Test if used for the first time + $fontkey=$family.$style; + if (!isset($this->fonts[$fontkey])) { //Check if one of the standard fonts if (isset($this->CoreFonts[$fontkey])) { if (!isset($fpdf_charwidths[$fontkey])) { @@ -523,66 +523,66 @@ class FPDF else $this->Error('Undefined font: '.$family.' '.$style); } - //Select it - $this->FontFamily=$family; - $this->FontStyle=$style; - $this->FontSizePt=$size; - $this->FontSize=$size/$this->k; - $this->CurrentFont=&$this->fonts[$fontkey]; - if ($this->page>0) + //Select it + $this->FontFamily=$family; + $this->FontStyle=$style; + $this->FontSizePt=$size; + $this->FontSize=$size/$this->k; + $this->CurrentFont=&$this->fonts[$fontkey]; + if ($this->page>0) $this->_out(sprintf('BT /F%d %.2f Tf ET',$this->CurrentFont['i'],$this->FontSizePt)); } function SetFontSize($size) { - //Set font size in points - if ($this->FontSizePt==$size) + //Set font size in points + if ($this->FontSizePt==$size) return; - $this->FontSizePt=$size; - $this->FontSize=$size/$this->k; - if ($this->page>0) + $this->FontSizePt=$size; + $this->FontSize=$size/$this->k; + if ($this->page>0) $this->_out(sprintf('BT /F%d %.2f Tf ET',$this->CurrentFont['i'],$this->FontSizePt)); } function AddLink() { - //Create a new internal link - $n=count($this->links)+1; - $this->links[$n]=array(0,0); - return $n; + //Create a new internal link + $n=count($this->links)+1; + $this->links[$n]=array(0,0); + return $n; } function SetLink($link,$y=0,$page=-1) { - //Set destination of internal link - if ($y==-1) + //Set destination of internal link + if ($y==-1) $y=$this->y; - if ($page==-1) + if ($page==-1) $page=$this->page; - $this->links[$link]=array($page,$y); + $this->links[$link]=array($page,$y); } function Link($x,$y,$w,$h,$link) { - //Put a link on the page - $this->PageLinks[$this->page][]=array($x*$this->k,$this->hPt-$y*$this->k,$w*$this->k,$h*$this->k,$link); + //Put a link on the page + $this->PageLinks[$this->page][]=array($x*$this->k,$this->hPt-$y*$this->k,$w*$this->k,$h*$this->k,$link); } function Text($x,$y,$txt) { - //Output a string - $s=sprintf('BT %.2f %.2f Td (%s) Tj ET',$x*$this->k,($this->h-$y)*$this->k,$this->_escape($txt)); - if ($this->underline and $txt!='') + //Output a string + $s=sprintf('BT %.2f %.2f Td (%s) Tj ET',$x*$this->k,($this->h-$y)*$this->k,$this->_escape($txt)); + if ($this->underline and $txt!='') $s.=' '.$this->_dounderline($x,$y,$txt); - if ($this->ColorFlag) + if ($this->ColorFlag) $s='q '.$this->TextColor.' '.$s.' Q'; - $this->_out($s); + $this->_out($s); } function AcceptPageBreak() { - //Accept automatic page break or not - return $this->AutoPageBreak; + //Accept automatic page break or not + return $this->AutoPageBreak; } function Cell($w,$h=0,$txt='',$border=0,$ln=0,$align='',$fill=0,$link='') { - //Output a cell - $k=$this->k; - if ($this->y+$h>$this->PageBreakTrigger and !$this->InFooter and $this->AcceptPageBreak()) { + //Output a cell + $k=$this->k; + if ($this->y+$h>$this->PageBreakTrigger and !$this->InFooter and $this->AcceptPageBreak()) { //Automatic page break $x=$this->x; $ws=$this->ws; @@ -597,17 +597,17 @@ class FPDF $this->_out(sprintf('%.3f Tw',$ws*$k)); } } - if ($w==0) + if ($w==0) $w=$this->w-$this->rMargin-$this->x; - $s=''; - if ($fill==1 or $border==1) { + $s=''; + if ($fill==1 or $border==1) { if ($fill==1) $op=($border==1) ? 'B' : 'f'; else $op='S'; $s=sprintf('%.2f %.2f %.2f %.2f re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op); } - if (is_string($border)) { + if (is_string($border)) { $x=$this->x; $y=$this->y; if (is_int(strpos($border,'L'))) @@ -619,7 +619,7 @@ class FPDF if (is_int(strpos($border,'B'))) $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k); } - if ($txt!='') { + if ($txt!='') { if ($align=='R') $dx=$w-$this->cMargin-$this->GetStringWidth($txt); elseif ($align=='C') @@ -637,31 +637,31 @@ class FPDF if ($link) $this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$this->GetStringWidth($txt),$this->FontSize,$link); } - if ($s) + if ($s) $this->_out($s); - $this->lasth=$h; - if ($ln>0) { + $this->lasth=$h; + if ($ln>0) { //Go to next line $this->y+=$h; if ($ln==1) $this->x=$this->lMargin; } - else + else $this->x+=$w; } function MultiCell($w,$h,$txt,$border=0,$align='J',$fill=0) { - //Output text with automatic or explicit line breaks - $cw=&$this->CurrentFont['cw']; - if ($w==0) + //Output text with automatic or explicit line breaks + $cw=&$this->CurrentFont['cw']; + if ($w==0) $w=$this->w-$this->rMargin-$this->x; - $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; - $s=str_replace("\r",'',$txt); - $nb=strlen($s); - if ($nb>0 and $s[$nb-1]=="\n") + $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; + $s=str_replace("\r",'',$txt); + $nb=strlen($s); + if ($nb>0 and $s[$nb-1]=="\n") $nb--; - $b=0; - if ($border) { + $b=0; + if ($border) { if ($border==1) { $border='LTRB'; $b='LRT'; @@ -677,13 +677,13 @@ class FPDF $b=is_int(strpos($border,'T')) ? $b2.'T' : $b2; } } - $sep=-1; - $i=0; - $j=0; - $l=0; - $ns=0; - $nl=1; - while ($i<$nb) { + $sep=-1; + $i=0; + $j=0; + $l=0; + $ns=0; + $nl=1; + while ($i<$nb) { //Get next character $c=$s{$i}; if ($c=="\n") { @@ -740,30 +740,30 @@ class FPDF else $i++; } - //Last chunk - if ($this->ws>0) { + //Last chunk + if ($this->ws>0) { $this->ws=0; $this->_out('0 Tw'); } - if ($border and is_int(strpos($border,'B'))) + if ($border and is_int(strpos($border,'B'))) $b.='B'; - $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill); - $this->x=$this->lMargin; + $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill); + $this->x=$this->lMargin; } function Write($h,$txt,$link='') { - //Output text in flowing mode - $cw=&$this->CurrentFont['cw']; - $w=$this->w - $this->rMargin - $this->x; - $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; - $s=str_replace("\r",'',$txt); - $nb=strlen($s); - $sep=-1; - $i=0; - $j=0; - $l=0; - $nl=1; - while($i<$nb) { + //Output text in flowing mode + $cw=&$this->CurrentFont['cw']; + $w=$this->w - $this->rMargin - $this->x; + $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; + $s=str_replace("\r",'',$txt); + $nb=strlen($s); + $sep=-1; + $i=0; + $j=0; + $l=0; + $nl=1; + while($i<$nb) { //Get next character $c=$s{$i}; if ($c=="\n") { @@ -818,14 +818,14 @@ class FPDF else $i++; } - //Last chunk - if ($i!=$j) + //Last chunk + if ($i!=$j) $this->Cell($l/1000*$this->FontSize,$h,substr($s,$j),0,0,'',0,$link); } function Image($file,$x,$y,$w=0,$h=0,$type='',$link='') { - //Put an image on the page - if (!isset($this->images[$file])) { + //Put an image on the page + if (!isset($this->images[$file])) { //First use of image, get info if ($type=='') { $pos=strrpos($file,'.'); @@ -854,77 +854,77 @@ class FPDF $info['i']=count($this->images)+1; $this->images[$file]=$info; } - else + else $info=$this->images[$file]; - //Automatic width and height calculation if needed - if ($w==0 and $h==0) { + //Automatic width and height calculation if needed + if ($w==0 and $h==0) { //Put image at 72 dpi $w=$info['w']/$this->k; $h=$info['h']/$this->k; } - if ($w==0) + if ($w==0) $w=$h*$info['w']/$info['h']; - if ($h==0) + if ($h==0) $h=$w*$info['h']/$info['w']; - $this->_out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q',$w*$this->k,$h*$this->k,$x*$this->k,($this->h-($y+$h))*$this->k,$info['i'])); - if ($link) + $this->_out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q',$w*$this->k,$h*$this->k,$x*$this->k,($this->h-($y+$h))*$this->k,$info['i'])); + if ($link) $this->Link($x,$y,$w,$h,$link); } function Ln($h='') { - //Line feed; default value is last cell height - $this->x=$this->lMargin; - if (is_string($h)) + //Line feed; default value is last cell height + $this->x=$this->lMargin; + if (is_string($h)) $this->y+=$this->lasth; - else + else $this->y+=$h; } function GetX() { - //Get x position - return $this->x; + //Get x position + return $this->x; } function SetX($x) { - //Set x position - if ($x>=0) + //Set x position + if ($x>=0) $this->x=$x; - else + else $this->x=$this->w+$x; } function GetY() { - //Get y position - return $this->y; + //Get y position + return $this->y; } function SetY($y) { - //Set y position and reset x - $this->x=$this->lMargin; - if ($y>=0) + //Set y position and reset x + $this->x=$this->lMargin; + if ($y>=0) $this->y=$y; - else + else $this->y=$this->h+$y; } function SetXY($x,$y) { - //Set x and y positions - $this->SetY($y); - $this->SetX($x); + //Set x and y positions + $this->SetY($y); + $this->SetX($x); } function Output($name='',$dest='') { - //Output PDF to some destination - global $HTTP_SERVER_VARS; + //Output PDF to some destination + global $HTTP_SERVER_VARS; - //Finish document if necessary - if ($this->state<3) + //Finish document if necessary + if ($this->state<3) $this->Close(); - //Normalize parameters - if (is_bool($dest)) + //Normalize parameters + if (is_bool($dest)) $dest = $dest ? 'D' : 'F'; - $dest = strtoupper($dest); - if ($dest=='') { + $dest = strtoupper($dest); + if ($dest=='') { if ($name=='') { $name='doc.pdf'; $dest='I'; @@ -932,7 +932,7 @@ class FPDF else $dest='F'; } - switch($dest) { + switch($dest) { case 'I': //Send to standard output if (isset($HTTP_SERVER_VARS['SERVER_NAME'])) { @@ -971,7 +971,7 @@ class FPDF default: $this->Error('Incorrect output destination: '.$dest); } - return ''; + return ''; } /******************************************************************************* @@ -980,44 +980,44 @@ class FPDF * * *******************************************************************************/ function _dochecks() { - //Check for locale-related bug. we must have "." as comma seperator - $attempts = array("C","en","en_us","English"); - $i = 0; - while (1.1 == 1 and $i++ < count($attempts)) { + //Check for locale-related bug. we must have "." as comma seperator + $attempts = array("C","en","en_us","English"); + $i = 0; + while (1.1 == 1 and $i++ < count($attempts)) { setlocale(LC_NUMERIC,$attempts[$i]); - } - if (1.1 == 1) { + } + if (1.1 == 1) { $this->Error('1.1 == 1: Wrong locale with comma as dot. German? Don\'t alter the locale before including class file'); - } - //Check for decimal separator - if (sprintf('%.1f',1.0)!='1.0') + } + //Check for decimal separator + if (sprintf('%.1f',1.0)!='1.0') setlocale(LC_NUMERIC,'C'); } function _begindoc() { - //Start document - $this->state=1; - $this->_out('%PDF-1.3'); + //Start document + $this->state=1; + $this->_out('%PDF-1.3'); } function _putpages() { - $nb=$this->page; - if (!empty($this->AliasNbPages)) { + $nb=$this->page; + if (!empty($this->AliasNbPages)) { //Replace number of pages for($n=1;$n<=$nb;$n++) $this->pages[$n]=str_replace($this->AliasNbPages,$nb,$this->pages[$n]); } - if ($this->DefOrientation=='P') { + if ($this->DefOrientation=='P') { $wPt=$this->fwPt; $hPt=$this->fhPt; } - else + else { - $wPt=$this->fhPt; - $hPt=$this->fwPt; + $wPt=$this->fhPt; + $hPt=$this->fwPt; } - $filter=($this->compress) ? '/Filter /FlateDecode ' : ''; - for($n=1;$n<=$nb;$n++) { + $filter=($this->compress) ? '/Filter /FlateDecode ' : ''; + for($n=1;$n<=$nb;$n++) { //Page $this->_newobj(); $this->_out('<_putstream($p); $this->_out('endobj'); } - //Pages root - $this->offsets[1]=strlen($this->buffer); - $this->_out('1 0 obj'); - $this->_out('<offsets[1]=strlen($this->buffer); + $this->_out('1 0 obj'); + $this->_out('<_out($kids.']'); - $this->_out('/Count '.$nb); - $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$wPt,$hPt)); - $this->_out('>>'); - $this->_out('endobj'); + $this->_out($kids.']'); + $this->_out('/Count '.$nb); + $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$wPt,$hPt)); + $this->_out('>>'); + $this->_out('endobj'); } function _putfonts() { - $nf=$this->n; - foreach($this->diffs as $diff) { + $nf=$this->n; + foreach($this->diffs as $diff) { //Encodings $this->_newobj(); $this->_out('<>'); $this->_out('endobj'); } - if (!check_php_version(5,3)) { - $mqr=get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - } - foreach($this->FontFiles as $file=>$info) { + if (!check_php_version(5,3)) { + $mqr=get_magic_quotes_runtime(); + set_magic_quotes_runtime(0); + } + foreach($this->FontFiles as $file=>$info) { //Font file embedding $this->_newobj(); $this->FontFiles[$file]['n']=$this->n; @@ -1098,10 +1098,10 @@ class FPDF fclose($f); $this->_out('endobj'); } - if (!check_php_version(5,3)) { - set_magic_quotes_runtime($mqr); - } - foreach($this->fonts as $k=>$font) { + if (!check_php_version(5,3)) { + set_magic_quotes_runtime($mqr); + } + foreach($this->fonts as $k=>$font) { //Font objects $this->fonts[$k]['n']=$this->n+1; $type=$font['type']; @@ -1165,9 +1165,9 @@ class FPDF } function _putimages() { - $filter=($this->compress) ? '/Filter /FlateDecode ' : ''; - reset($this->images); - while(list($file,$info)=each($this->images)) { + $filter=($this->compress) ? '/Filter /FlateDecode ' : ''; + reset($this->images); + while(list($file,$info)=each($this->images)) { $this->_newobj(); $this->images[$file]['n']=$this->n; $this->_out('<_putfonts(); - $this->_putimages(); - //Resource dictionary - $this->offsets[2]=strlen($this->buffer); - $this->_out('2 0 obj'); - $this->_out('<_out('/Font <<'); - foreach($this->fonts as $font) + $this->_putfonts(); + $this->_putimages(); + //Resource dictionary + $this->offsets[2]=strlen($this->buffer); + $this->_out('2 0 obj'); + $this->_out('<_out('/Font <<'); + foreach($this->fonts as $font) $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R'); - $this->_out('>>'); - if (count($this->images)) { + $this->_out('>>'); + if (count($this->images)) { $this->_out('/XObject <<'); foreach($this->images as $image) $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R'); $this->_out('>>'); } - $this->_out('>>'); - $this->_out('endobj'); + $this->_out('>>'); + $this->_out('endobj'); } function _putinfo() { - if (!empty($this->producer)) + if (!empty($this->producer)) $this->_out('/Producer '.$this->_textstring($this->producer)); - if (!empty($this->title)) + if (!empty($this->title)) $this->_out('/Title '.$this->_textstring($this->title)); - if (!empty($this->subject)) + if (!empty($this->subject)) $this->_out('/Subject '.$this->_textstring($this->subject)); - if (!empty($this->author)) + if (!empty($this->author)) $this->_out('/Author '.$this->_textstring($this->author)); - if (!empty($this->keywords)) + if (!empty($this->keywords)) $this->_out('/Keywords '.$this->_textstring($this->keywords)); - if (!empty($this->creator)) + if (!empty($this->creator)) $this->_out('/Creator '.$this->_textstring($this->creator)); - $this->_out('/CreationDate '.$this->_textstring('D:'.date('YmdHis'))); + $this->_out('/CreationDate '.$this->_textstring('D:'.date('YmdHis'))); } function _putcatalog() { - $this->_out('/Type /Catalog'); - $this->_out('/Pages 1 0 R'); - if ($this->ZoomMode=='fullpage') + $this->_out('/Type /Catalog'); + $this->_out('/Pages 1 0 R'); + if ($this->ZoomMode=='fullpage') $this->_out('/OpenAction [3 0 R /Fit]'); - elseif ($this->ZoomMode=='fullwidth') + elseif ($this->ZoomMode=='fullwidth') $this->_out('/OpenAction [3 0 R /FitH null]'); - elseif ($this->ZoomMode=='real') + elseif ($this->ZoomMode=='real') $this->_out('/OpenAction [3 0 R /XYZ null null 1]'); - elseif (!is_string($this->ZoomMode)) + elseif (!is_string($this->ZoomMode)) $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode/100).']'); - if ($this->LayoutMode=='single') + if ($this->LayoutMode=='single') $this->_out('/PageLayout /SinglePage'); - elseif ($this->LayoutMode=='continuous') + elseif ($this->LayoutMode=='continuous') $this->_out('/PageLayout /OneColumn'); - elseif ($this->LayoutMode=='two') + elseif ($this->LayoutMode=='two') $this->_out('/PageLayout /TwoColumnLeft'); } function _puttrailer() { - $this->_out('/Size '.($this->n+1)); - $this->_out('/Root '.$this->n.' 0 R'); - $this->_out('/Info '.($this->n-1).' 0 R'); + $this->_out('/Size '.($this->n+1)); + $this->_out('/Root '.$this->n.' 0 R'); + $this->_out('/Info '.($this->n-1).' 0 R'); } function _enddoc() { - $this->_putpages(); - $this->_putresources(); - //Info - $this->_newobj(); - $this->_out('<<'); - $this->_putinfo(); - $this->_out('>>'); - $this->_out('endobj'); - //Catalog - $this->_newobj(); - $this->_out('<<'); - $this->_putcatalog(); - $this->_out('>>'); - $this->_out('endobj'); - //Cross-ref - $o=strlen($this->buffer); - $this->_out('xref'); - $this->_out('0 '.($this->n+1)); - $this->_out('0000000000 65535 f '); - for($i=1;$i<=$this->n;$i++) + $this->_putpages(); + $this->_putresources(); + //Info + $this->_newobj(); + $this->_out('<<'); + $this->_putinfo(); + $this->_out('>>'); + $this->_out('endobj'); + //Catalog + $this->_newobj(); + $this->_out('<<'); + $this->_putcatalog(); + $this->_out('>>'); + $this->_out('endobj'); + //Cross-ref + $o=strlen($this->buffer); + $this->_out('xref'); + $this->_out('0 '.($this->n+1)); + $this->_out('0000000000 65535 f '); + for($i=1;$i<=$this->n;$i++) $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i])); - //Trailer - $this->_out('trailer'); - $this->_out('<<'); - $this->_puttrailer(); - $this->_out('>>'); - $this->_out('startxref'); - $this->_out($o); - $this->_out('%%EOF'); - $this->state=3; + //Trailer + $this->_out('trailer'); + $this->_out('<<'); + $this->_puttrailer(); + $this->_out('>>'); + $this->_out('startxref'); + $this->_out($o); + $this->_out('%%EOF'); + $this->state=3; } function _beginpage($orientation) { - $this->page++; - $this->pages[$this->page]=''; - $this->state=2; - $this->x=$this->lMargin; - $this->y=$this->tMargin; - $this->FontFamily=''; - //Page orientation - if (!$orientation) + $this->page++; + $this->pages[$this->page]=''; + $this->state=2; + $this->x=$this->lMargin; + $this->y=$this->tMargin; + $this->FontFamily=''; + //Page orientation + if (!$orientation) $orientation=$this->DefOrientation; - else + else { - $orientation=strtoupper($orientation{0}); - if ($orientation!=$this->DefOrientation) + $orientation=strtoupper($orientation{0}); + if ($orientation!=$this->DefOrientation) $this->OrientationChanges[$this->page]=true; } - if ($orientation!=$this->CurOrientation) { + if ($orientation!=$this->CurOrientation) { //Change orientation if ($orientation=='P') { $this->wPt=$this->fwPt; @@ -1339,30 +1339,30 @@ class FPDF } function _endpage() { - //End of page contents - $this->state=1; + //End of page contents + $this->state=1; } function _newobj() { - //Begin a new object - $this->n++; - $this->offsets[$this->n]=strlen($this->buffer); - $this->_out($this->n.' 0 obj'); + //Begin a new object + $this->n++; + $this->offsets[$this->n]=strlen($this->buffer); + $this->_out($this->n.' 0 obj'); } function _dounderline($x,$y,$txt) { - //Underline text - $up=$this->CurrentFont['up']; - $ut=$this->CurrentFont['ut']; - $w=$this->GetStringWidth($txt)+$this->ws*substr_count($txt,' '); - return sprintf('%.2f %.2f %.2f %.2f re f',$x*$this->k,($this->h-($y-$up/1000*$this->FontSize))*$this->k,$w*$this->k,-$ut/1000*$this->FontSizePt); + //Underline text + $up=$this->CurrentFont['up']; + $ut=$this->CurrentFont['ut']; + $w=$this->GetStringWidth($txt)+$this->ws*substr_count($txt,' '); + return sprintf('%.2f %.2f %.2f %.2f re f',$x*$this->k,($this->h-($y-$up/1000*$this->FontSize))*$this->k,$w*$this->k,-$ut/1000*$this->FontSizePt); } - function _parsegif ($file) - { + function _parsegif ($file) + { //Function by Jérôme Fenal //GIF class in pure PHP from Yamasoft (http://www.yamasoft.com/php-gif.zip) - require_once 'lib/gif.php'; + require_once 'lib/gif.php'; $h=0; $w=0; @@ -1370,7 +1370,7 @@ class FPDF if (!$gif->loadFile($file, 0)) $this->Error("GIF parser: unable to open file $file"); - + if ($gif->m_img->m_gih->m_bLocalClr) { $nColors = $gif->m_img->m_gih->m_nTableSize; $pal = $gif->m_img->m_gih->m_colorTable->toString(); @@ -1378,102 +1378,102 @@ class FPDF $bgColor = $this->m_img->m_gih->m_colorTable->colorIndex($bgColor); } $colspace='Indexed'; - } elseif ($gif->m_gfh->m_bGlobalClr) { + } elseif ($gif->m_gfh->m_bGlobalClr) { $nColors = $gif->m_gfh->m_nTableSize; $pal = $gif->m_gfh->m_colorTable->toString(); if ($bgColor != -1) { $bgColor = $gif->m_gfh->m_colorTable->colorIndex($bgColor); } $colspace='Indexed'; - } else { + } else { $nColors = 0; $bgColor = -1; $colspace='DeviceGray'; $pal=''; - } + } - $trns=''; - if ($gif->m_img->m_bTrans && ($nColors > 0)) { + $trns=''; + if ($gif->m_img->m_bTrans && ($nColors > 0)) { $trns=array($gif->m_img->m_nTrans); - } + } - $data=$gif->m_img->m_data; - $w=$gif->m_gfh->m_nWidth; - $h=$gif->m_gfh->m_nHeight; + $data=$gif->m_img->m_data; + $w=$gif->m_gfh->m_nWidth; + $h=$gif->m_gfh->m_nHeight; - if ($colspace=='Indexed' and empty($pal)) + if ($colspace=='Indexed' and empty($pal)) $this->Error('Missing palette in '.$file); - if ($this->compress) { + if ($this->compress) { $data = gzcompress($data); return array( 'w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>8, 'f'=>'FlateDecode', 'pal'=>$pal, 'trns'=>$trns, 'data'=>$data); - } else { + } else { return array( 'w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>8, 'pal'=>$pal, 'trns'=>$trns, 'data'=>$data); - } + } } function _parsejpg($file) { - //Extract info from a JPEG file - $a = GetImageSize($file); - if (!$a) + //Extract info from a JPEG file + $a = GetImageSize($file); + if (!$a) $this->Error('Missing or incorrect image file: '.$file); - if ($a[2]!=2) + if ($a[2]!=2) $this->Error('Not a JPEG file: '.$file); - if (!isset($a['channels']) or $a['channels']==3) + if (!isset($a['channels']) or $a['channels']==3) $colspace='DeviceRGB'; - elseif ($a['channels']==4) + elseif ($a['channels']==4) $colspace='DeviceCMYK'; - else + else $colspace='DeviceGray'; - $bpc=isset($a['bits']) ? $a['bits'] : 8; - //Read whole file - $f=fopen($file,'rb'); - $data=''; - while(!feof($f)) + $bpc=isset($a['bits']) ? $a['bits'] : 8; + //Read whole file + $f=fopen($file,'rb'); + $data=''; + while(!feof($f)) $data.=fread($f,4096); - fclose($f); - return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data); + fclose($f); + return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data); } function _parsepng($file) { - //Extract info from a PNG file - $f=fopen($file,'rb'); - if (!$f) + //Extract info from a PNG file + $f=fopen($file,'rb'); + if (!$f) $this->Error('Can\'t open image file: '.$file); - //Check signature - if (fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) + //Check signature + if (fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) $this->Error('Not a PNG file: '.$file); - //Read header chunk - fread($f,4); - if (fread($f,4)!='IHDR') + //Read header chunk + fread($f,4); + if (fread($f,4)!='IHDR') $this->Error('Incorrect PNG file: '.$file); - $w=$this->_freadint($f); - $h=$this->_freadint($f); - $bpc=ord(fread($f,1)); - if ($bpc>8) + $w=$this->_freadint($f); + $h=$this->_freadint($f); + $bpc=ord(fread($f,1)); + if ($bpc>8) $this->Error('16-bit depth not supported: '.$file); - $ct=ord(fread($f,1)); - if ($ct==0) + $ct=ord(fread($f,1)); + if ($ct==0) $colspace='DeviceGray'; - elseif ($ct==2) + elseif ($ct==2) $colspace='DeviceRGB'; - elseif ($ct==3) + elseif ($ct==3) $colspace='Indexed'; - else + else $this->Error('Alpha channel not supported: '.$file); - if (ord(fread($f,1))!=0) + if (ord(fread($f,1))!=0) $this->Error('Unknown compression method: '.$file); - if (ord(fread($f,1))!=0) + if (ord(fread($f,1))!=0) $this->Error('Unknown filter method: '.$file); - if (ord(fread($f,1))!=0) + if (ord(fread($f,1))!=0) $this->Error('Interlacing not supported: '.$file); - fread($f,4); - $parms='/DecodeParms <>'; - //Scan chunks looking for palette, transparency and image data - $pal=''; - $trns=''; - $data=''; - do { + fread($f,4); + $parms='/DecodeParms <>'; + //Scan chunks looking for palette, transparency and image data + $pal=''; + $trns=''; + $data=''; + do { $n=$this->_freadint($f); $type=fread($f,4); if ($type=='PLTE') { @@ -1505,42 +1505,42 @@ class FPDF else fread($f,$n+4); } while($n); - if ($colspace=='Indexed' and empty($pal)) + if ($colspace=='Indexed' and empty($pal)) $this->Error('Missing palette in '.$file); - fclose($f); - return array('w'=>$w,'h'=>$h,'cs'=>$colspace,'bpc'=>$bpc,'f'=>'FlateDecode','parms'=>$parms,'pal'=>$pal,'trns'=>$trns,'data'=>$data); + fclose($f); + return array('w'=>$w,'h'=>$h,'cs'=>$colspace,'bpc'=>$bpc,'f'=>'FlateDecode','parms'=>$parms,'pal'=>$pal,'trns'=>$trns,'data'=>$data); } function _freadint($f) { - //Read a 4-byte integer from file - $i=ord(fread($f,1))<<24; - $i+=ord(fread($f,1))<<16; - $i+=ord(fread($f,1))<<8; - $i+=ord(fread($f,1)); - return $i; + //Read a 4-byte integer from file + $i=ord(fread($f,1))<<24; + $i+=ord(fread($f,1))<<16; + $i+=ord(fread($f,1))<<8; + $i+=ord(fread($f,1)); + return $i; } function _textstring($s) { - //Format a text string - return '('.$this->_escape($s).')'; + //Format a text string + return '('.$this->_escape($s).')'; } function _escape($s) { - //Add \ before \, ( and ) - return str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$s))); + //Add \ before \, ( and ) + return str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$s))); } function _putstream($s) { - $this->_out('stream'); - $this->_out($s); - $this->_out('endstream'); + $this->_out('stream'); + $this->_out($s); + $this->_out('endstream'); } function _out($s) { - //Add a line to the document - if ($this->state == 2) + //Add a line to the document + if ($this->state == 2) $this->pages[$this->page].=$s."\n"; - else + else $this->buffer.=$s."\n"; } } //End of class @@ -1548,8 +1548,8 @@ class FPDF } //Handle special IE contype request -if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']) and - $HTTP_SERVER_VARS['HTTP_USER_AGENT']=='contype') +if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']) and + $HTTP_SERVER_VARS['HTTP_USER_AGENT']=='contype') { Header('Content-Type: application/pdf'); exit; diff --git a/lib/gif.php b/lib/gif.php index c7317ac34..2df0f4924 100644 --- a/lib/gif.php +++ b/lib/gif.php @@ -81,7 +81,7 @@ function gif_outputAsJpeg($gif, $lpszFileName, $bgColor = -1) if(@fileSize($lpszFileName) > 0) { return true; } - + @unLink($lpszFileName); } } @@ -106,7 +106,7 @@ function gif_getSize($gif, &$width, &$height) else { return false; } - + return true; } @@ -143,7 +143,7 @@ class CGIFLZW while(($iIndex = $this->LZWCommand($data, false)) >= 0) { $ret .= chr($iIndex); } - + $datLen = $stLen - strlen($data); if($iIndex != -2) { @@ -157,7 +157,7 @@ class CGIFLZW if($bInit) { $this->SetCodeSize = ord($data{0}); $data = substr($data, 1); - + $this->CodeSize = $this->SetCodeSize + 1; $this->ClearCode = 1 << $this->SetCodeSize; $this->EndCode = $this->ClearCode + 1; @@ -188,7 +188,7 @@ class CGIFLZW $this->OldCode = $this->FirstCode; } while($this->FirstCode == $this->ClearCode); - + return $this->FirstCode; } @@ -233,7 +233,7 @@ class CGIFLZW while($Code >= $this->ClearCode) { $this->Stack[$this->sp] = $this->Vals[$Code]; $this->sp++; - + if($Code == $this->Next[$Code]) // Circular table entry, big GIF Error! return -1; @@ -282,36 +282,36 @@ class CGIFLZW } return -1; } - + $this->Buf[0] = $this->Buf[$this->LastByte - 2]; $this->Buf[1] = $this->Buf[$this->LastByte - 1]; - + $Count = ord($data{0}); $data = substr($data, 1); - - if($Count) { - for($i = 0; $i < $Count; $i++) { - $this->Buf[2 + $i] = ord($data{$i}); - } - $data = substr($data, $Count); - } - else { - $this->Done = 1; - } - - $this->LastByte = 2 + $Count; - $this->CurBit = ($this->CurBit - $this->LastBit) + 16; - $this->LastBit = (2 + $Count) << 3; - } - - $iRet = 0; - for($i = $this->CurBit, $j = 0; $j < $this->CodeSize; $i++, $j++) { - $iRet |= (($this->Buf[intval($i / 8)] & (1 << ($i % 8))) != 0) << $j; - } - - $this->CurBit += $this->CodeSize; - return $iRet; - } + + if($Count) { + for($i = 0; $i < $Count; $i++) { + $this->Buf[2 + $i] = ord($data{$i}); + } + $data = substr($data, $Count); + } + else { + $this->Done = 1; + } + + $this->LastByte = 2 + $Count; + $this->CurBit = ($this->CurBit - $this->LastBit) + 16; + $this->LastBit = (2 + $Count) << 3; + } + + $iRet = 0; + for($i = $this->CurBit, $j = 0; $j < $this->CodeSize; $i++, $j++) { + $iRet |= (($this->Buf[intval($i / 8)] & (1 << ($i % 8))) != 0) << $j; + } + + $this->CurBit += $this->CodeSize; + return $iRet; + } } class CGIFCOLORTABLE @@ -701,7 +701,7 @@ class CGIF return false; } $data = @fRead($fh, @fileSize($lpszFileName)); - // @fClose($fh); + // @fClose($fh); // $data=fread($fh,filesize($lpszFileName)); while(!feof($fh)) { $data = $data . @fread($fh, 1024); @@ -725,10 +725,10 @@ class CGIF $this->m_bLoaded = true; return true; - } + } - function getSize($lpszFileName, &$width, &$height) - { + function getSize($lpszFileName, &$width, &$height) + { if(!($fh = @fOpen($lpszFileName, "rb"))) { return false; } diff --git a/lib/imagecache.php b/lib/imagecache.php index 0bc7a2df4..568235964 100644 --- a/lib/imagecache.php +++ b/lib/imagecache.php @@ -17,7 +17,7 @@ * You should have received a copy of the GNU General Public License * along with PhpWiki; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ + */ /** * Gets an image from the cache and prints it to the browser. @@ -50,7 +50,7 @@ function deducePagename ($request) { } elseif ($this->isPost()) { global $HTTP_GET_VARS; - if (isset($HTTP_GET_VARS['pagename'])) { + if (isset($HTTP_GET_VARS['pagename'])) { return $HTTP_GET_VARS['pagename']; } } @@ -58,7 +58,7 @@ function deducePagename ($request) { $query_string = $request->get('QUERY_STRING'); if (preg_match('/^[^&=]+$/', $query_string)) return urldecode($query_string); - + return HOME_PAGE; } @@ -70,7 +70,7 @@ function deduceUsername() { return $HTTP_SERVER_VARS['PHP_AUTH_USER']; if (!empty($HTTP_ENV_VARS['REMOTE_USER'])) return $HTTP_ENV_VARS['REMOTE_USER']; - + if ($user = $request->getSessionVar('wiki_user')) { $request->_user = $user; $request->_user->_authhow = 'session'; @@ -88,12 +88,12 @@ function deduceUsername() { /** * Initializes PhpWiki and calls the plugin specified in the url to * produce an image. Furthermore, allow the usage of Apache's - * ErrorDocument mechanism in order to make this file only called when + * ErrorDocument mechanism in order to make this file only called when * image could not be found in the cache. * (see doc/README.phpwiki-cache for further information). */ function mainImageCache() { - $request = new Request; + $request = new Request; // normalize pagename $request->setArg('pagename', deducePagename($request)); $pagename = $request->getArg('pagename'); @@ -102,13 +102,13 @@ function mainImageCache() { $request->_user = new _AnonUser(); $request->_prefs =& $request->_user->_prefs; } else { - $request->_user = new WikiUser($request); + $request->_user = new WikiUser($request); $request->_prefs = new UserPreferences(); } - + // Enable the output of most of the warning messages. // The warnings will screw up zip files and setpref though. - // They will also screw up my images... But I think + // They will also screw up my images... But I think // we should keep them. global $ErrorManager; $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE); @@ -127,24 +127,24 @@ function mainImageCache() { $uri = $request->get('REDIRECT_URL'); $query = $request->get('REDIRECT_QUERY_STRING'); - $uri .= $query ? '?'.$query : ''; + $uri .= $query ? '?'.$query : ''; if (!$uri) { $uri = $request->get('REQUEST_URI'); } if (!$uri) { - $cache->printError( 'png', + $cache->printError( 'png', 'Could not deduce image identifier or creation' . ' parameters. (Neither REQUEST nor REDIRECT' - . ' obtained.)' ); + . ' obtained.)' ); return; - } + } //$cacheparams = $GLOBALS['CacheParams']; if (!preg_match(':^(.*/)?'.PLUGIN_CACHED_FILENAME_PREFIX.'([^\?/]+)\.img(\?args=([^\?&]*))?$:', $uri, $matches)) { $cache->printError('png', "I do not understand this URL: $uri"); return; - } - + } + $request->setArg('id', $matches[2]); if ($matches[4]) { // md5 args? @@ -166,5 +166,5 @@ mainImageCache(); // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/imdb.php b/lib/imdb.php index e034d2e31..256c3946d 100644 --- a/lib/imdb.php +++ b/lib/imdb.php @@ -363,5 +363,5 @@ SELECT m.title, m.date, n.name, c.role // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/install.php b/lib/install.php index 1f8b0a622..05255fe12 100644 --- a/lib/install.php +++ b/lib/install.php @@ -49,7 +49,7 @@ function run_install($part = '') { } // setup default settings if (!$already and !defined("_PHPWIKI_INSTALL_RUNNING")) { - define("_PHPWIKI_INSTALL_RUNNING", true); + define("_PHPWIKI_INSTALL_RUNNING", true); include(dirname(__FILE__)."/../configurator.php"); } $already = 1; diff --git a/lib/loadsave.php b/lib/loadsave.php index f0c38fc72..dc01c2ee7 100644 --- a/lib/loadsave.php +++ b/lib/loadsave.php @@ -217,12 +217,12 @@ function FilenameForPage ($pagename, $action = false) { $enc = rawurlencode($pagename); if (!$action) { - global $request; - $action = $request->getArg('action'); + global $request; + $action = $request->getArg('action'); } if ($action != 'dumpserial') { // zip, ziphtml, dumphtml - // For every %2F we will need to mkdir -p dirname($pagename) - $enc = preg_replace('/%2F/', '/', $enc); + // For every %2F we will need to mkdir -p dirname($pagename) + $enc = preg_replace('/%2F/', '/', $enc); } $enc = preg_replace('/^\./', '%2E', $enc); $enc = preg_replace('/%20/', ' ', $enc); @@ -250,7 +250,7 @@ function MakeWikiZip (&$request) } $include_empty = false; if ($request->getArg('include') == 'empty') { - $include_empty = true; + $include_empty = true; } $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname); @@ -276,8 +276,8 @@ function MakeWikiZip (&$request) $timeout = (! $request->getArg('start_debug')) ? 30 : 240; while ($page = $page_iter->next()) { - $request->args = $request_args; // some plugins might change them (esp. on POST) - longer_timeout($timeout); // Reset watchdog + $request->args = $request_args; // some plugins might change them (esp. on POST) + longer_timeout($timeout); // Reset watchdog $current = $page->getCurrentRevision(); if ($current->getVersion() == 0) @@ -339,7 +339,7 @@ function DumpToDir (&$request) } $include_empty = false; if ($request->getArg('include') == 'empty') { - $include_empty = true; + $include_empty = true; } if ($pages = $request->getArg('pages')) { // which pagenames if ($pages == '[]') // current page @@ -353,8 +353,8 @@ function DumpToDir (&$request) $timeout = (! $request->getArg('start_debug')) ? 30 : 240; while ($page = $page_iter->next()) { - $request->args = $request_args; // some plugins might change them (esp. on POST) - longer_timeout($timeout); // Reset watchdog + $request->args = $request_args; // some plugins might change them (esp. on POST) + longer_timeout($timeout); // Reset watchdog $pagename = $page->getName(); if (!isa($request,'MockRequest')) { @@ -412,16 +412,16 @@ function _copyMsg($page, $smallmsg) { function mkdir_p($pathname, $permission = 0777) { $arr = explode("/", $pathname); if (empty($arr)) { - return mkdir($pathname, $permission); + return mkdir($pathname, $permission); } $s = array_shift($arr); $ok = TRUE; foreach ($arr as $p) { - $curr = "$s/$p"; - if (!is_dir($curr)) - $ok = mkdir($curr, $permission); - $s = $curr; - if (!$ok) return FALSE; + $curr = "$s/$p"; + if (!is_dir($curr)) + $ok = mkdir($curr, $permission); + $s = $curr; + if (!$ok) return FALSE; } return TRUE; } @@ -531,12 +531,12 @@ function _DumpHtmlToDir ($target, $page_iter, $exclude = false) global $WikiTheme, $request, $ErrorManager; $silent = true; $zip = false; $directory = false; if ($WikiTheme->DUMP_MODE == 'HTML') { - $directory = $target; - $silent = false; + $directory = $target; + $silent = false; } elseif ($WikiTheme->DUMP_MODE == 'PDFHTML') { - $directory = $target; + $directory = $target; } elseif (is_object($target)) { // $WikiTheme->DUMP_MODE == 'ZIPHTML' - $zip = $target; + $zip = $target; } $request->_TemplatesProcessed = array(); @@ -547,11 +547,11 @@ function _DumpHtmlToDir ($target, $page_iter, $exclude = false) } $WikiTheme->VALID_LINKS = array(); if ($request->getArg('format')) { // pagelist - $page_iter_sav = $page_iter; - foreach ($page_iter_sav->asArray() as $handle) { - $WikiTheme->VALID_LINKS[] = is_string($handle) ? $handle : $handle->getName(); - } - $page_iter_sav->reset(); + $page_iter_sav = $page_iter; + foreach ($page_iter_sav->asArray() as $handle) { + $WikiTheme->VALID_LINKS[] = is_string($handle) ? $handle : $handle->getName(); + } + $page_iter_sav->reset(); } if (defined('HTML_DUMP_SUFFIX')) @@ -564,159 +564,159 @@ function _DumpHtmlToDir ($target, $page_iter, $exclude = false) // check if the dumped file will be accessible from outside $doc_root = $request->get("DOCUMENT_ROOT"); if ($WikiTheme->DUMP_MODE == 'HTML') { - $ldir = NormalizeLocalFileName($directory); - $wikiroot = NormalizeLocalFileName(''); - if (string_starts_with($ldir, $doc_root)) { - $link_prefix = substr($directory, strlen($doc_root))."/"; - } elseif (string_starts_with($ldir, $wikiroot)) { - $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot)))."/"; - } else { - $prefix = ''; - if (isWindows()) { - $prefix = '/'; // . substr($doc_root,0,2); // add drive where apache is installed - } - $link_prefix = "file://".$prefix.$directory."/"; - } + $ldir = NormalizeLocalFileName($directory); + $wikiroot = NormalizeLocalFileName(''); + if (string_starts_with($ldir, $doc_root)) { + $link_prefix = substr($directory, strlen($doc_root))."/"; + } elseif (string_starts_with($ldir, $wikiroot)) { + $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot)))."/"; + } else { + $prefix = ''; + if (isWindows()) { + $prefix = '/'; // . substr($doc_root,0,2); // add drive where apache is installed + } + $link_prefix = "file://".$prefix.$directory."/"; + } } else { - $link_prefix = ""; + $link_prefix = ""; } $request_args = $request->args; $timeout = (! $request->getArg('start_debug')) ? 60 : 240; if ($directory) { - if (isWindows()) - $directory = str_replace("\\", "/", $directory); // no Win95 support. - @mkdir("$directory/images"); + if (isWindows()) + $directory = str_replace("\\", "/", $directory); // no Win95 support. + @mkdir("$directory/images"); } $already = array(); $outfiles = array(); $already_images = array(); while ($page = $page_iter->next()) { - if (is_string($page)) { + if (is_string($page)) { $pagename = $page; $page = $request->_dbi->getPage($pagename); - } else { + } else { $pagename = $page->getName(); - } - if (empty($firstpage)) $firstpage = $pagename; - if (array_key_exists($pagename, $already)) - continue; - $already[$pagename] = 1; + } + if (empty($firstpage)) $firstpage = $pagename; + if (array_key_exists($pagename, $already)) + continue; + $already[$pagename] = 1; $current = $page->getCurrentRevision(); //if ($current->getVersion() == 0) // continue; - $request->args = $request_args; // some plugins might change them (esp. on POST) - longer_timeout($timeout); // Reset watchdog + $request->args = $request_args; // some plugins might change them (esp. on POST) + longer_timeout($timeout); // Reset watchdog - if ($zip) { - $attrib = array('mtime' => $current->get('mtime'), + if ($zip) { + $attrib = array('mtime' => $current->get('mtime'), 'is_ascii' => 1); - if ($page->get('locked')) - $attrib['write_protected'] = 1; - } elseif (!$silent) { - if (!isa($request,'MockRequest')) { - PrintXML(HTML::br(), $pagename, ' ... '); - flush(); - } + if ($page->get('locked')) + $attrib['write_protected'] = 1; + } elseif (!$silent) { + if (!isa($request,'MockRequest')) { + PrintXML(HTML::br(), $pagename, ' ... '); + flush(); + } } if (in_array($pagename, $excludeList)) { - if (!$silent and !isa($request,'MockRequest')) { - PrintXML(_("Skipped.")); - flush(); - } + if (!$silent and !isa($request,'MockRequest')) { + PrintXML(_("Skipped.")); + flush(); + } continue; } $relative_base = ''; if ($WikiTheme->DUMP_MODE == 'PDFHTML') - $request->setArg('action', 'pdf'); // to omit cache headers + $request->setArg('action', 'pdf'); // to omit cache headers $request->setArg('pagename', $pagename); // Template::_basepage fix $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX; - $args = array('revision' => $current, - 'CONTENT' => $current->getTransformedContent(), + $args = array('revision' => $current, + 'CONTENT' => $current->getTransformedContent(), 'relative_base' => $relative_base); - // For every %2F will need to mkdir -p dirname($pagename) - if (preg_match("/(%2F|\/)/", $filename)) { - // mkdir -p and set relative base for subdir pages - $filename = preg_replace("/%2F/", "/", $filename); - $count = substr_count($filename, "/"); - $dirname = dirname($filename); - if ($directory) - mkdir_p($directory."/".$dirname); - // Fails with "XX / YY", "XX" is created, "XX / YY" cannot be written - // if (isWindows()) // interesting Windows bug: cannot mkdir "bla " - // Since dumps needs to be copied, we have to disallow this for all platforms. - $filename = preg_replace("/ \//", "/", $filename); - $relative_base = "../"; - while ($count > 1) { - $relative_base .= "../"; - $count--; - } - $args['relative_base'] = $relative_base; - } + // For every %2F will need to mkdir -p dirname($pagename) + if (preg_match("/(%2F|\/)/", $filename)) { + // mkdir -p and set relative base for subdir pages + $filename = preg_replace("/%2F/", "/", $filename); + $count = substr_count($filename, "/"); + $dirname = dirname($filename); + if ($directory) + mkdir_p($directory."/".$dirname); + // Fails with "XX / YY", "XX" is created, "XX / YY" cannot be written + // if (isWindows()) // interesting Windows bug: cannot mkdir "bla " + // Since dumps needs to be copied, we have to disallow this for all platforms. + $filename = preg_replace("/ \//", "/", $filename); + $relative_base = "../"; + while ($count > 1) { + $relative_base .= "../"; + $count--; + } + $args['relative_base'] = $relative_base; + } $msg = HTML(); $DUMP_MODE = $WikiTheme->DUMP_MODE; $data = GeneratePageasXML(new Template('browse', $request, $args), - $pagename, $current, $args); + $pagename, $current, $args); $WikiTheme->DUMP_MODE = $DUMP_MODE; - if (preg_match_all("/addSrcFile($target, $src); - } - } - } - } - - if ($directory) { - $outfile = $directory."/".$filename; - if ( !($fd = fopen($outfile, "wb")) ) { - $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing", - $outfile))); - $request->finish($msg); - } - $len = strlen($data); - $num = fwrite($fd, $data, $len); - if ($pagename != $filename) { - $link = LinkURL($link_prefix.$filename, $filename); - $msg->pushContent(HTML::small(_("saved as "), $link, " ... ")); - } - $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n")); - if (!$silent) { - if (!isa($request, 'MockRequest')) { - PrintXML($msg); - } - flush(); - $request->chunkOutput(); - } - assert($num == $len); - fclose($fd); - $outfiles[] = $outfile; - } else { - $zip->addRegularFile($filename, $data, $attrib); - } + if (preg_match_all("/addSrcFile($target, $src); + } + } + } + } + + if ($directory) { + $outfile = $directory."/".$filename; + if ( !($fd = fopen($outfile, "wb")) ) { + $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing", + $outfile))); + $request->finish($msg); + } + $len = strlen($data); + $num = fwrite($fd, $data, $len); + if ($pagename != $filename) { + $link = LinkURL($link_prefix.$filename, $filename); + $msg->pushContent(HTML::small(_("saved as "), $link, " ... ")); + } + $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n")); + if (!$silent) { + if (!isa($request, 'MockRequest')) { + PrintXML($msg); + } + flush(); + $request->chunkOutput(); + } + assert($num == $len); + fclose($fd); + $outfiles[] = $outfile; + } else { + $zip->addRegularFile($filename, $data, $attrib); + } if (USECACHE) { $request->_dbi->_cache->invalidate_cache($pagename); @@ -729,10 +729,10 @@ function _DumpHtmlToDir ($target, $page_iter, $exclude = false) unset($msg); unset($current->_transformedContent); unset($current); - if (!empty($template)) { - unset($template->_request); - unset($template); - } + if (!empty($template)) { + unset($template->_request); + unset($template); + } unset($data); } $page_iter->free(); @@ -741,28 +741,28 @@ function _DumpHtmlToDir ($target, $page_iter, $exclude = false) if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) { // @mkdir("$directory/images"); foreach ($WikiTheme->dumped_images as $img_file) { - if (array_key_exists($img_file, $already_images)) - continue; - $already_images[$img_file] = 1; + if (array_key_exists($img_file, $already_images)) + continue; + $already_images[$img_file] = 1; if ($img_file and ($from = $WikiTheme->_findFile($img_file, true)) and basename($from)) { - if ($directory) { - $target = "$directory/images/".basename($from); - if ($silent) - copy($WikiTheme->_path . $from, $target); - else { - if (copy($WikiTheme->_path . $from, $target)) { - _copyMsg($from, fmt("... copied to %s", $target)); - } else { - _copyMsg($from, fmt("... not copied to %s", $target)); - } - } - } else { - $target = "images/".basename($from); - $zip->addSrcFile($target, $WikiTheme->_path . $from); - } + if ($directory) { + $target = "$directory/images/".basename($from); + if ($silent) + copy($WikiTheme->_path . $from, $target); + else { + if (copy($WikiTheme->_path . $from, $target)) { + _copyMsg($from, fmt("... copied to %s", $target)); + } else { + _copyMsg($from, fmt("... not copied to %s", $target)); + } + } + } else { + $target = "images/".basename($from); + $zip->addSrcFile($target, $WikiTheme->_path . $from); + } } elseif (!$silent) { _copyMsg($from, _("... not found")); } @@ -772,32 +772,32 @@ function _DumpHtmlToDir ($target, $page_iter, $exclude = false) if (!empty($WikiTheme->dumped_buttons) and is_array($WikiTheme->dumped_buttons)) { - // Buttons also - if ($directory) - @mkdir("$directory/images/buttons"); + // Buttons also + if ($directory) + @mkdir("$directory/images/buttons"); foreach ($WikiTheme->dumped_buttons as $text => $img_file) { if (array_key_exists($img_file, $already_images)) - continue; - $already_images[$img_file] = 1; + continue; + $already_images[$img_file] = 1; if ($img_file and ($from = $WikiTheme->_findFile($img_file, true)) and basename($from)) { - if ($directory) { - $target = "$directory/images/buttons/".basename($from); - if ($silent) - copy($WikiTheme->_path . $from, $target); - else { - if (copy($WikiTheme->_path . $from, $target)) { - _copyMsg($from, fmt("... copied to %s", $target)); - } else { - _copyMsg($from, fmt("... not copied to %s", $target)); - } - } - } else { - $target = "images/buttons/".basename($from); - $zip->addSrcFile($target, $WikiTheme->_path . $from); - } + if ($directory) { + $target = "$directory/images/buttons/".basename($from); + if ($silent) + copy($WikiTheme->_path . $from, $target); + else { + if (copy($WikiTheme->_path . $from, $target)) { + _copyMsg($from, fmt("... copied to %s", $target)); + } else { + _copyMsg($from, fmt("... not copied to %s", $target)); + } + } + } else { + $target = "images/buttons/".basename($from); + $zip->addSrcFile($target, $WikiTheme->_path . $from); + } } elseif (!$silent) { _copyMsg($from, _("... not found")); } @@ -806,29 +806,29 @@ function _DumpHtmlToDir ($target, $page_iter, $exclude = false) if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) { foreach ($WikiTheme->dumped_css as $css_file) { if (array_key_exists($css_file, $already_images)) - continue; - $already_images[$css_file] = 1; + continue; + $already_images[$css_file] = 1; if ($css_file and ($from = $WikiTheme->_findFile(basename($css_file), true)) and basename($from)) { - // TODO: fix @import url(main.css); - if ($directory) { - $target = "$directory/" . basename($css_file); - if ($silent) - copy($WikiTheme->_path . $from, $target); - else { - if (copy($WikiTheme->_path . $from, $target)) { - _copyMsg($from, fmt("... copied to %s", $target)); - } else { - _copyMsg($from, fmt("... not copied to %s", $target)); - } - } - } else { - //$attrib = array('is_ascii' => 0); - $target = basename($css_file); - $zip->addSrcFile($target, $WikiTheme->_path . $from); - } + // TODO: fix @import url(main.css); + if ($directory) { + $target = "$directory/" . basename($css_file); + if ($silent) + copy($WikiTheme->_path . $from, $target); + else { + if (copy($WikiTheme->_path . $from, $target)) { + _copyMsg($from, fmt("... copied to %s", $target)); + } else { + _copyMsg($from, fmt("... not copied to %s", $target)); + } + } + } else { + //$attrib = array('is_ascii' => 0); + $target = basename($css_file); + $zip->addSrcFile($target, $WikiTheme->_path . $from); + } } elseif (!$silent) { _copyMsg($from, _("... not found")); } @@ -836,37 +836,37 @@ function _DumpHtmlToDir ($target, $page_iter, $exclude = false) } if ($zip) - $zip->finish(); + $zip->finish(); if ($WikiTheme->DUMP_MODE == 'PDFHTML') { - if (USE_EXTERNAL_HTML2PDF and $outfiles) { - $cmd = EXTERNAL_HTML2PDF_PAGELIST.' "'.join('" "', $outfiles).'"'; - $filename = FilenameForPage($firstpage); - if (DEBUG) { - $tmpfile = $directory . "/createpdf.bat"; - $fp = fopen($tmpfile, "wb"); - fwrite($fp, $cmd . " > $filename.pdf"); - fclose($fp); - } - if (!headers_sent()) { - Header('Content-Type: application/pdf'); - passthru($cmd); - } - else { - $tmpdir = getUploadFilePath(); - $s = passthru($cmd . " > $tmpdir/$filename.pdf"); - $errormsg = "
    \nGenerated Upload:$filename.pdf\n"; - $errormsg .= $s; - echo $errormsg; - } - if (!DEBUG) { - foreach($outfiles as $f) unlink($f); - } - } - if (!empty($errormsg)) { - $request->discardOutput(); - $GLOBALS['ErrorManager']->_postponed_errors = array(); - } + if (USE_EXTERNAL_HTML2PDF and $outfiles) { + $cmd = EXTERNAL_HTML2PDF_PAGELIST.' "'.join('" "', $outfiles).'"'; + $filename = FilenameForPage($firstpage); + if (DEBUG) { + $tmpfile = $directory . "/createpdf.bat"; + $fp = fopen($tmpfile, "wb"); + fwrite($fp, $cmd . " > $filename.pdf"); + fclose($fp); + } + if (!headers_sent()) { + Header('Content-Type: application/pdf'); + passthru($cmd); + } + else { + $tmpdir = getUploadFilePath(); + $s = passthru($cmd . " > $tmpdir/$filename.pdf"); + $errormsg = "
    \nGenerated Upload:$filename.pdf\n"; + $errormsg .= $s; + echo $errormsg; + } + if (!DEBUG) { + foreach($outfiles as $f) unlink($f); + } + } + if (!empty($errormsg)) { + $request->discardOutput(); + $GLOBALS['ErrorManager']->_postponed_errors = array(); + } } $ErrorManager->popErrorHandler(); @@ -933,14 +933,14 @@ function SavePage (&$request, &$pageinfo, $source, $filename) $skip = false; $edit = $request->getArg('edit'); if ($merging) { - if (isset($edit['keep_old'])) { + if (isset($edit['keep_old'])) { $merging = false; $skip = true; - } - elseif (isset($edit['overwrite'])) { + } + elseif (isset($edit['overwrite'])) { $merging = false; $overwrite = true; - } + } elseif ( $current and (! $current->hasDefaultContents()) && ($current->getPackedContent() != $content) ) { @@ -966,8 +966,8 @@ function SavePage (&$request, &$pageinfo, $source, $filename) $mesg->pushContent(' ', fmt("from %s", $source)); if (!$current) { - //FIXME: This should not happen! (empty vdata, corrupt cache or db) - $current = $page->getCurrentRevision(); + //FIXME: This should not happen! (empty vdata, corrupt cache or db) + $current = $page->getCurrentRevision(); } if ($current->getVersion() == 0) { $versiondata['author'] = ADMIN_USER; @@ -988,12 +988,12 @@ function SavePage (&$request, &$pageinfo, $source, $filename) } } else { - if (isset($edit['keep_old'])) { - $mesg->pushContent(' ', fmt("keep old")); - } else { - $mesg->pushContent(' ', fmt("has edit conflicts - skipped")); - $needs_merge = true; // hackish, to display the buttons - } + if (isset($edit['keep_old'])) { + $mesg->pushContent(' ', fmt("keep old")); + } else { + $mesg->pushContent(' ', fmt("has edit conflicts - skipped")); + $needs_merge = true; // hackish, to display the buttons + } $skip = true; } } @@ -1008,9 +1008,9 @@ function SavePage (&$request, &$pageinfo, $source, $filename) } if (! $skip ) { - // in case of failures print the culprit: + // in case of failures print the culprit: if (!isa($request,'MockRequest')) { - PrintXML(HTML::p(WikiLink($pagename))); flush(); + PrintXML(HTML::p(WikiLink($pagename))); flush(); } $new = $page->save($content, WIKIDB_FORCE_CREATE, $versiondata); $dbi->touch(); @@ -1284,8 +1284,8 @@ function LoadFile (&$request, $filename, $text = false, $mtime = false) $default_pagename = rawurldecode($basename); if ( ($parts = ParseMimeifiedPages($text)) ) { - if (count($parts) > 1) - $overwrite = $request->getArg('overwrite'); + if (count($parts) > 1) + $overwrite = $request->getArg('overwrite'); usort($parts, 'SortByPageVersion'); foreach ($parts as $pageinfo) { // force overwrite @@ -1298,7 +1298,7 @@ function LoadFile (&$request, $filename, $text = false, $mtime = false) if ($overwrite) $request->setArg('overwrite', $overwrite); else - unset($request->_args['overwrite']); + unset($request->_args['overwrite']); } else if ( ($pageinfo = ParseSerializedPage($text, $default_pagename, $request->getUser())) ) { @@ -1343,7 +1343,7 @@ function LoadZip (&$request, $zipfile, $files = false, $exclude = false) { flush(); continue; } - longer_timeout($timeout); // longer timeout per page + longer_timeout($timeout); // longer timeout per page LoadFile($request, $fn, $data, $attrib['mtime']); } } @@ -1368,7 +1368,7 @@ function LoadDir (&$request, $dirname, $files = false, $exclude = false) { } $timeout = (! $request->getArg('start_debug')) ? 20 : 120; foreach ($files as $file) { - longer_timeout($timeout); // longer timeout per page + longer_timeout($timeout); // longer timeout per page if (substr($file,-1,1) != '~') // refuse to load backup files LoadFile($request, "$dirname/$file"); } @@ -1476,8 +1476,8 @@ function LoadFileOrDir (&$request) $source = $request->getArg('source'); $finder = new FileFinder; $source = $finder->slashifyPath($source); - StartLoadDump($request, - sprintf(_("Loading '%s'"), $source)); + StartLoadDump($request, + sprintf(_("Loading '%s'"), $source)); LoadAny($request, $source); EndLoadDump($request); } diff --git a/lib/main.php b/lib/main.php index f0bb2499a..c774ae2c2 100644 --- a/lib/main.php +++ b/lib/main.php @@ -67,12 +67,12 @@ class WikiRequest extends Request { // UserPreferences POST Update doesn't reach this. foreach ($GLOBALS['USER_AUTH_ORDER'] as $method) { include_once("lib/WikiUser/$method.php"); - if ($method == 'Db') - switch( DATABASE_TYPE ) { - case 'SQL' : include_once("lib/WikiUser/PearDb.php"); break; - case 'ADODB': include_once("lib/WikiUser/AdoDb.php"); break; + if ($method == 'Db') + switch( DATABASE_TYPE ) { + case 'SQL' : include_once("lib/WikiUser/PearDb.php"); break; + case 'ADODB': include_once("lib/WikiUser/AdoDb.php"); break; case 'PDO' : include_once("lib/WikiUser/PdoDb.php"); break; - } + } } unset($method); } @@ -95,7 +95,7 @@ class WikiRequest extends Request { $this->setArg('action', $this->_deduceAction()); if ((DEBUG & _DEBUG_SQL) - or (DATABASE_OPTIMISE_FREQUENCY > 0 and + or (DATABASE_OPTIMISE_FREQUENCY > 0 and (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) { if ($this->_dbi->_backend->optimize()) trigger_error(_("Optimizing database"), E_USER_NOTICE); @@ -119,27 +119,27 @@ class WikiRequest extends Request { { $this->_user = WikiUser($userid, $this->_user->_prefs); } - // revive other db handle - if (isset($this->_user->_prefs->_method) + // revive other db handle + if (isset($this->_user->_prefs->_method) and ($this->_user->_prefs->_method == 'SQL' or $this->_user->_prefs->_method == 'ADODB' or $this->_user->_prefs->_method == 'PDO' or $this->_user->_prefs->_method == 'HomePage')) { - $this->_user->_HomePagehandle = $this->getPage($userid); - } - // need to update the lockfile filehandle - if ( isa($this->_user, '_FilePassUser') + $this->_user->_HomePagehandle = $this->getPage($userid); + } + // need to update the lockfile filehandle + if ( isa($this->_user, '_FilePassUser') and $this->_user->_file->lockfile and !$this->_user->_file->fplock ) - { - //$level = $this->_user->_level; - $this->_user = UpgradeUser($this->_user, - new _FilePassUser($userid, + { + //$level = $this->_user->_level; + $this->_user = UpgradeUser($this->_user, + new _FilePassUser($userid, $this->_user->_prefs, $this->_user->_file->filename)); //$this->_user->_level = $level; } - $this->_prefs = & $this->_user->_prefs; + $this->_prefs = & $this->_user->_prefs; } else { $user = WikiUser($userid); $this->_user = & $user; @@ -170,11 +170,11 @@ class WikiRequest extends Request { function initializeTheme ($when = 'default') { global $WikiTheme; - // if when = 'default', then first time init (default theme, ...) - // if when = 'login', then check some callbacks - // and maybe the theme changed (other theme defined in pref) - // if when = 'logout', then check other callbacks - // and maybe the theme changed (back to default theme) + // if when = 'default', then first time init (default theme, ...) + // if when = 'login', then check some callbacks + // and maybe the theme changed (other theme defined in pref) + // if when = 'logout', then check other callbacks + // and maybe the theme changed (back to default theme) // Load non-default theme (when = login) if (!empty($this->_prefs->_prefs['theme'])) { @@ -201,12 +201,12 @@ class WikiRequest extends Request { } if (empty($WikiTheme) and $user_theme) { if (strcspn($user_theme,"./\x00]") != strlen($user_theme)) { - trigger_error(sprintf("invalid theme '%s': Invalid characters detected", + trigger_error(sprintf("invalid theme '%s': Invalid characters detected", $user_theme), - E_USER_WARNING); + E_USER_WARNING); $user_theme = "default"; } - if (!$user_theme) $user_theme = "default"; + if (!$user_theme) $user_theme = "default"; include_once("themes/$user_theme/themeinfo.php"); } if (empty($WikiTheme) and defined('THEME')) @@ -215,27 +215,27 @@ class WikiRequest extends Request { include_once("themes/default/themeinfo.php"); assert(!empty($WikiTheme)); - // Do not execute global init code anymore - - // WikiTheme callbacks - if ($when == 'login') { - $WikiTheme->CbUserLogin($this, $this->_user->_userid); - if (!$this->_user->hasHomePage()) { // NewUser - $WikiTheme->CbNewUserLogin($this, $this->_user->_userid); - if (in_array($this->getArg('action'), array('edit','create'))) - $WikiTheme->CbNewUserEdit($this, $this->_user->_userid); - } - } - elseif ($when == 'logout') { - $WikiTheme->CbUserLogout($this, $this->_user->_userid); - } - elseif ($when == 'default') { - $WikiTheme->load(); - if ($this->_user->_level > 0 and !$this->_user->hasHomePage()) { // NewUser - if (in_array($this->getArg('action'), array('edit','create'))) - $WikiTheme->CbNewUserEdit($this, $this->_user->_userid); - } - } + // Do not execute global init code anymore + + // WikiTheme callbacks + if ($when == 'login') { + $WikiTheme->CbUserLogin($this, $this->_user->_userid); + if (!$this->_user->hasHomePage()) { // NewUser + $WikiTheme->CbNewUserLogin($this, $this->_user->_userid); + if (in_array($this->getArg('action'), array('edit','create'))) + $WikiTheme->CbNewUserEdit($this, $this->_user->_userid); + } + } + elseif ($when == 'logout') { + $WikiTheme->CbUserLogout($this, $this->_user->_userid); + } + elseif ($when == 'default') { + $WikiTheme->load(); + if ($this->_user->_level > 0 and !$this->_user->hasHomePage()) { // NewUser + if (in_array($this->getArg('action'), array('edit','create'))) + $WikiTheme->CbNewUserEdit($this, $this->_user->_userid); + } + } } // This really maybe should be part of the constructor, but since it @@ -266,9 +266,9 @@ class WikiRequest extends Request { // Save preferences in session and cookie if ((defined('WIKI_XMLRPC') and !WIKI_XMLRPC) or $action != 'xmlrpc') { if (isset($this->_user) and $this->_user->_userid) { - if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') { + if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') { $this->_user->setPreferences($this->_prefs, true); - } + } } $tmpuser = $this->_user; // clone it $this->setSessionVar('wiki_user', $tmpuser); @@ -278,13 +278,13 @@ class WikiRequest extends Request { // Ensure user has permissions for action // HACK ALERT: We may not set the request arg to create, // since the pageeditor has an ugly logic for action == create. - if ($action == 'edit' or $action == 'create') { + if ($action == 'edit' or $action == 'create') { $page = $this->getPage(); if (! $page->exists() ) $action = 'create'; else $action = 'edit'; - } + } if (! ENABLE_PAGEPERM) { // Bug #1438392 by Matt Brown $require_level = $this->requiredAuthority($action); if (! $this->_user->hasAuthority($require_level)) @@ -311,7 +311,7 @@ class WikiRequest extends Request { if (isset($this->_user) and isset($this->_user->_group)) return $this->_user->_group; else { - // Debug Strict: Only variable references should be returned by reference + // Debug Strict: Only variable references should be returned by reference $this->_user->_group = WikiGroup::getGroup(); return $this->_user->_group; } @@ -442,10 +442,10 @@ class WikiRequest extends Request { if (defined('MAIN_setUser')) return; // don't set cookies twice $this->setCookieVar(getCookieName(), $user->getAuthenticatedId(), COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN); - $isSignedIn = $user->isSignedIn(); + $isSignedIn = $user->isSignedIn(); if ($isSignedIn) { $user->_authhow = 'signin'; - } + } // Save userid to prefs.. if ( empty($this->_user->_prefs)) { @@ -468,9 +468,9 @@ class WikiRequest extends Request { /* Permission system */ function getLevelDescription($level) { - static $levels = false; - if (!$levels) // This looks like a Visual Basic hack. For the very same reason. "0" - $levels = array('x-1' => _("FORBIDDEN"), + static $levels = false; + if (!$levels) // This looks like a Visual Basic hack. For the very same reason. "0" + $levels = array('x-1' => _("FORBIDDEN"), 'x0' => _("ANON"), 'x1' => _("BOGO"), 'x2' => _("USER"), @@ -502,17 +502,17 @@ class WikiRequest extends Request { $pass_required = ($require_level >= WIKIAUTH_USER); if ($require_level == WIKIAUTH_UNOBTAINABLE) { global $DisabledActions; - if ($DisabledActions and in_array($action, $DisabledActions)) { - $msg = fmt("%s is disallowed on this wiki.", + if ($DisabledActions and in_array($action, $DisabledActions)) { + $msg = fmt("%s is disallowed on this wiki.", $this->getDisallowedActionDescription($this->getArg('action'))); - $this->finish(); - return; - } - // Is the reason a missing ACL or just wrong user or password? + $this->finish(); + return; + } + // Is the reason a missing ACL or just wrong user or password? if (class_exists('PagePermission')) { $user =& $this->_user; - $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated"); - $msg = fmt("%s %s %s is disallowed on this wiki for %s user '%s' (level: %s).", + $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated"); + $msg = fmt("%s %s %s is disallowed on this wiki for %s user '%s' (level: %s).", _("Missing PagePermission:"), action2access($this->getArg('action')), $this->getArg('pagename'), @@ -520,34 +520,34 @@ class WikiRequest extends Request { // TODO: add link to action=setacl $user->PrintLoginForm($this, compact('pass_required'), $msg); $this->finish(); - return; + return; } else { - $msg = fmt("%s is disallowed on this wiki.", + $msg = fmt("%s is disallowed on this wiki.", $this->getDisallowedActionDescription($this->getArg('action'))); $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg); - $this->finish(); - return; + $this->finish(); + return; } } elseif ($require_level == WIKIAUTH_BOGO) $msg = fmt("You must sign in to %s.", $what); elseif ($require_level == WIKIAUTH_USER) { - // LoginForm should display the relevant messages... - $msg = ""; - /*if (!ALLOW_ANON_USER) - $msg = fmt("You must log in first to %s", $what); - else + // LoginForm should display the relevant messages... + $msg = ""; + /*if (!ALLOW_ANON_USER) + $msg = fmt("You must log in first to %s", $what); + else $msg = fmt("You must log in to %s.", $what); - */ + */ } elseif ($require_level == WIKIAUTH_ANON) $msg = fmt("Access for you is forbidden to %s.", $what); else $msg = fmt("You must be an administrator to %s.", $what); $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), - $msg); - if (!$GLOBALS['WikiTheme']->DUMP_MODE) - $this->finish(); // NORETURN + $msg); + if (!$GLOBALS['WikiTheme']->DUMP_MODE) + $this->finish(); // NORETURN } // Fixme: for PagePermissions we'll need other strings, @@ -589,9 +589,9 @@ class WikiRequest extends Request { if ($DisabledActions and in_array($action, $DisabledActions)) return WIKIAUTH_UNOBTAINABLE; - if (ENABLE_PAGEPERM and class_exists("PagePermission")) { - return requiredAuthorityForPage($action); - + if (ENABLE_PAGEPERM and class_exists("PagePermission")) { + return requiredAuthorityForPage($action); + => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO). */ function getDisallowedActionDescription($action) { @@ -653,9 +653,9 @@ class WikiRequest extends Request { if ($DisabledActions and in_array($action, $DisabledActions)) return WIKIAUTH_UNOBTAINABLE; - if (ENABLE_PAGEPERM and class_exists("PagePermission")) { - return requiredAuthorityForPage($action); - } else { + if (ENABLE_PAGEPERM and class_exists("PagePermission")) { + return requiredAuthorityForPage($action); + } else { // FIXME: clean up. switch ($action) { case 'browse': @@ -673,20 +673,20 @@ class WikiRequest extends Request { case 'soap': case 'dumphtml': if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost()) - return WIKIAUTH_ADMIN; - return WIKIAUTH_ANON; + return WIKIAUTH_ADMIN; + return WIKIAUTH_ANON; case 'ziphtml': if (ZIPDUMP_AUTH) return WIKIAUTH_ADMIN; if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost()) - return WIKIAUTH_ADMIN; - return WIKIAUTH_ANON; + return WIKIAUTH_ADMIN; + return WIKIAUTH_ANON; case 'dumpserial': if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost()) - return WIKIAUTH_ANON; - return WIKIAUTH_ADMIN; + return WIKIAUTH_ANON; + return WIKIAUTH_ADMIN; case 'zip': if (ZIPDUMP_AUTH) @@ -781,8 +781,8 @@ class WikiRequest extends Request { require_once("lib/WikiPlugin.php"); $loader = new WikiPluginLoader(); $plugin = $loader->getPlugin("ModeratedPage"); - if ($plugin->handler($this, $page)) { - $CONTENT = HTML::div + if ($plugin->handler($this, $page)) { + $CONTENT = HTML::div ( array('class' => 'wiki-edithelp'), fmt("%s: action forwarded to a moderator.", @@ -796,11 +796,11 @@ class WikiRequest extends Request { _("You must wait for moderator approval.")); else $plugin->_tokens['CONTENT'] = $CONTENT; - $title = WikiLink($page->getName()); - $title->pushContent(' : ', WikiLink(_("ModeratedPage"))); - GeneratePage(Template('browse', $plugin->_tokens), - $title, - $page->getCurrentRevision()); + $title = WikiLink($page->getName()); + $title->pushContent(' : ', WikiLink(_("ModeratedPage"))); + GeneratePage(Template('browse', $plugin->_tokens), + $title, + $page->getCurrentRevision()); $this->finish(); } } @@ -842,7 +842,7 @@ class WikiRequest extends Request { unset($this->_user->_auth_dbi); unset($this->_user->_dbi); unset($this->_user->_request); - } + } Request::finish(); exit; } @@ -965,7 +965,7 @@ class WikiRequest extends Request { } } - // Sessions override http auth + // Sessions override http auth if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER'])) return $HTTP_SERVER_VARS['PHP_AUTH_USER']; // pubcookie et al @@ -982,8 +982,8 @@ class WikiRequest extends Request { } if ($this->getArg('action') == 'xmlrpc') { // how about SOAP? - if (empty($GLOBALS['HTTP_RAW_POST_DATA'])) - trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR); + if (empty($GLOBALS['HTTP_RAW_POST_DATA'])) + trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR); // wiki.putPage has special otional userid/passwd arguments. check that later. $userid = ''; if (isset($HTTP_SERVER_VARS['REMOTE_USER'])) @@ -1026,7 +1026,7 @@ class WikiRequest extends Request { require_once("lib/plugin/_WikiTranslation.php"); $trans = new WikiPlugin__WikiTranslation(); $trans->lang = $LANG; - $default = $trans->translate_to_en($action, $LANG); + $default = $trans->translate_to_en($action, $LANG); if ($default and isActionPage($default)) return $cache[$action] = $default; } else { @@ -1113,23 +1113,23 @@ class WikiRequest extends Request { } function action_search () { - // Decide between title or fulltextsearch (e.g. both buttons available). + // Decide between title or fulltextsearch (e.g. both buttons available). // Reformulate URL and redirect. - $searchtype = $this->getArg('searchtype'); - $args = array('s' => $this->getArg('searchterm') - ? $this->getArg('searchterm') - : $this->getArg('s')); + $searchtype = $this->getArg('searchtype'); + $args = array('s' => $this->getArg('searchterm') + ? $this->getArg('searchterm') + : $this->getArg('s')); if ($searchtype == 'full' or $searchtype == 'fulltext') { $search_page = _("FullTextSearch"); } elseif ($searchtype == 'external') { $s = $args['s']; - $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega + $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega $this->redirect($link->url); } else { $search_page = _("TitleSearch"); - $args['auto_redirect'] = 1; + $args['auto_redirect'] = 1; } $this->redirect(WikiURL($search_page, $args, 'absolute_url')); } @@ -1209,12 +1209,12 @@ class WikiRequest extends Request { } function action_soap () { - if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded - return; - /* - allow VIRTUAL_PATH or action=soap SOAP access - */ - include_once("SOAP.php"); + if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded + return; + /* + allow VIRTUAL_PATH or action=soap SOAP access + */ + include_once("SOAP.php"); } function action_revert () { @@ -1262,8 +1262,8 @@ class WikiRequest extends Request { } function action_pdf () { - include_once("lib/pdf.php"); - ConvertAndDisplayPdf($this); + include_once("lib/pdf.php"); + ConvertAndDisplayPdf($this); } function action_captcha () { @@ -1279,11 +1279,11 @@ class WikiRequest extends Request { } function action_setpref () { - $what = $this->getArg('pref'); - $value = $this->getArg('value'); - $prefs =& $this->_user->_prefs; - $prefs->set($what, $value); - $num = $this->_user->setPreferences($prefs); + $what = $this->getArg('pref'); + $value = $this->getArg('value'); + $prefs =& $this->_user->_prefs; + $prefs->set($what, $value); + $num = $this->_user->setPreferences($prefs); } } @@ -1351,9 +1351,9 @@ function main () { $action = $request->getArg('action'); if (substr($action, 0, 3) != 'zip') { - if ($action == 'pdf') - $ErrorManager->setPostponedErrorMask(-1); // everything - //else // reject postponing of warnings + if ($action == 'pdf') + $ErrorManager->setPostponedErrorMask(-1); // everything + //else // reject postponing of warnings // $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE); } @@ -1404,7 +1404,7 @@ function main () { // to go the paranoid route here pending further study and testing.) // access hits and edit stats in the footer violate strong ETags also. if (1 or DEBUG) { - $validators['%weak'] = true; + $validators['%weak'] = true; } $request->setValidators($validators); diff --git a/lib/pdf.php b/lib/pdf.php index d8c0728de..bab5809a2 100644 --- a/lib/pdf.php +++ b/lib/pdf.php @@ -20,7 +20,7 @@ * You should have received a copy of the GNU General Public License * along with PhpWiki; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ + */ //define("USE_EXTERNAL_HTML2PDF", "htmldoc --quiet --format pdf14 --jpeg --webpage --no-toc --no-title %s"); /** @@ -45,13 +45,13 @@ function ConvertAndDisplayPdfPageList (&$request, $pagelist, $args = array()) { $cache = new WikiPluginCached; $cache->newCache(); $tmpfile = $cache->tempnam(); - $tmpdir = dirname($tmpfile); + $tmpdir = dirname($tmpfile); unlink ($tmpfile); $WikiTheme->DUMP_MODE = 'PDFHTML'; - _DumpHtmlToDir($tmpdir, - new WikiDB_Array_generic_iter($pagelist->_pages), - $request->getArg('exclude')); + _DumpHtmlToDir($tmpdir, + new WikiDB_Array_generic_iter($pagelist->_pages), + $request->getArg('exclude')); $WikiTheme->DUMP_MODE = false; return; } @@ -75,7 +75,7 @@ function ConvertAndDisplayPdf (&$request) { displayPage($request, new Template('htmldump', $request)); $html = ob_get_contents(); $WikiTheme->DUMP_MODE = false; - + // check hook for external converters if (defined('USE_EXTERNAL_HTML2PDF') and USE_EXTERNAL_HTML2PDF) @@ -97,7 +97,7 @@ function ConvertAndDisplayPdf (&$request) { // clean the hints errors global $ErrorManager; $ErrorManager->destroyPostponedErrors(); - + if (!empty($errormsg)) { $request->discardOutput(); } diff --git a/lib/prepend.php b/lib/prepend.php index 5a98273ab..46c1d3e2a 100644 --- a/lib/prepend.php +++ b/lib/prepend.php @@ -34,9 +34,9 @@ foreach (array('SERVER','REQUEST','GET','POST','SESSION','ENV','COOKIE') as $k) // A new php-5.1.x feature: Turn off php-5.1.x auto_globals_jit = On, or use this mess below. if (empty($GLOBALS['HTTP_SERVER_VARS'])) { $GLOBALS['HTTP_SERVER_VARS'] =& $_SERVER; - $GLOBALS['HTTP_ENV_VARS'] =& $_ENV; - $GLOBALS['HTTP_GET_VARS'] =& $_GET; - $GLOBALS['HTTP_POST_VARS'] =& $_POST; + $GLOBALS['HTTP_ENV_VARS'] =& $_ENV; + $GLOBALS['HTTP_GET_VARS'] =& $_GET; + $GLOBALS['HTTP_POST_VARS'] =& $_POST; $GLOBALS['HTTP_SESSION_VARS'] =& $_SESSION; $GLOBALS['HTTP_COOKIE_VARS'] =& $_COOKIE; $GLOBALS['HTTP_REQUEST_VARS'] =& $_REQUEST; @@ -64,7 +64,7 @@ if (defined('DEBUG') and (DEBUG & 8) and extension_loaded("xdebug")) { } if (defined('DEBUG') and (DEBUG & 32) and extension_loaded("apd")) { apd_set_pprof_trace(); - /* FUNCTION_TRACE 1 + /* FUNCTION_TRACE 1 ARGS_TRACE 2 ASSIGNMENT_TRACE 4 STATEMENT_TRACE 8 @@ -110,7 +110,7 @@ class DebugTimer { $this->getTime('utime', $now), $this->getTime('stime', $now)); } - + function _CLK_TCK() { // FIXME: this is clearly not always right. // But how to figure out the right value? @@ -125,7 +125,7 @@ class DebugTimer { $RUNTIMER = new DebugTimer; /* if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5? - error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT + error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT else error_reporting(E_ALL); // php4 //echo " prepend: ", error_reporting(); @@ -144,12 +144,12 @@ function ExitWiki($errormsg = false) if ($in_exit) exit; - + $in_exit = true; global $ErrorManager; $ErrorManager->flushPostponedErrors(); - + if(!empty($errormsg)) { PrintXML(HTML::br(), $errormsg); print "\n"; @@ -169,5 +169,5 @@ if (!defined('DEBUG') or (defined('DEBUG') and DEBUG > 2)) { // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/lib/spam_babycart.php b/lib/spam_babycart.php index 89eaef93b..e54e2ea19 100644 --- a/lib/spam_babycart.php +++ b/lib/spam_babycart.php @@ -5,7 +5,7 @@ * Proof-of-concept PHP fragment to flag blog/wiki spam * * URL: -* INSTALL: +* INSTALL: * cpan Blog::SpamAssassin * copy contrib/babycart to /usr/local/bin/ */ @@ -27,10 +27,10 @@ function check_babycart(&$text, $ip, $user_id='') { $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $process = proc_open(BABYCART_PATH, $descriptorspec, $pipes); if (is_resource($process)) { - // $pipes now looks like this: - // 0 => writeable handle connected to child stdin - // 1 => readable handle connected to child stdout - // Any error output will be appended to $pipes[2] + // $pipes now looks like this: + // 0 => writeable handle connected to child stdin + // 1 => readable handle connected to child stdout + // Any error output will be appended to $pipes[2] // Send comment out for analysis fwrite($pipes[0], $comment); @@ -55,7 +55,7 @@ function check_babycart(&$text, $ip, $user_id='') { $return_value = proc_close($process); // Interpret results and yield judgment - + // print "Response: $response\n"; // split into status, note, score, rules... if ($response) { @@ -66,7 +66,7 @@ function check_babycart(&$text, $ip, $user_id='') { 0 - verdict (OK or SUSPICIOUS) 1 - note (additional info on verdict, whether tests ran, etc.) 2 - numeric score; anything greater than 5-7 is suspect - 3 - comma-delimited list of rules hit (may be empty) + 3 - comma-delimited list of rules hit (may be empty) */ return explode(',', $response, 4); } diff --git a/lib/stdlib.php b/lib/stdlib.php index 32669df93..d3e518fce 100644 --- a/lib/stdlib.php +++ b/lib/stdlib.php @@ -36,7 +36,7 @@ ConvertOldMarkup ($content, $markup_type = "block") MangleXmlIdentifier($str) UnMangleXmlIdentifier($str) - + class Stack { push($item), pop(), cnt(), top() } class Alert { show() } class WikiPageName {getParent(),isValid(),getWarnings() } @@ -108,7 +108,7 @@ if (defined('_PHPWIKI_STDLIB_LOADED')) return; else define('_PHPWIKI_STDLIB_LOADED', true); define('MAX_PAGENAME_LENGTH', 100); - + /** * Convert string to a valid XML identifier. * @@ -135,7 +135,7 @@ define('MAX_PAGENAME_LENGTH', 100); function MangleXmlIdentifier($str) { if (!$str) return 'empty.'; - + return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e', "'x' . sprintf('%02x', ord('\\0')) . '.'", $str); @@ -152,8 +152,8 @@ function UnMangleXmlIdentifier($str) { /** * Generates a valid URL for a given Wiki pagename. * @param mixed $pagename If a string this will be the name of the Wiki page to link to. - * If a WikiDB_Page object function will extract the name to link to. - * If a WikiDB_PageRevision object function will extract the name to link to. + * If a WikiDB_Page object function will extract the name to link to. + * If a WikiDB_PageRevision object function will extract the name to link to. * @param array $args * @param boolean $get_abs_url Default value is false. * @return string The absolute URL to the page passed as $pagename. @@ -180,21 +180,21 @@ function WikiURL($pagename, $args = '', $get_abs_url = false) { } } if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) { - if (!$args) - $args = 'start_debug=' . $request->getArg('start_debug'); - elseif (is_array($args)) - $args['start_debug'] = $request->getArg('start_debug'); - else - $args .= '&start_debug=' . $request->getArg('start_debug'); + if (!$args) + $args = 'start_debug=' . $request->getArg('start_debug'); + elseif (is_array($args)) + $args['start_debug'] = $request->getArg('start_debug'); + else + $args .= '&start_debug=' . $request->getArg('start_debug'); } if (is_array($args)) { $enc_args = array(); foreach ($args as $key => $val) { // avoid default args if (USE_PATH_INFO and $key == 'pagename') - ; + ; elseif ($key == 'action' and $val == 'browse') - ; + ; elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars $enc_args[] = urlencode($key) . '=' . urlencode($val); } @@ -203,23 +203,23 @@ function WikiURL($pagename, $args = '', $get_abs_url = false) { if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) { $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : ""; - $base = preg_replace('/%2f/i', '/', rawurlencode($pagename)); - $url .= $base; + $base = preg_replace('/%2f/i', '/', rawurlencode($pagename)); + $url .= $base; if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) { - if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') { - if (!in_array($pagename, $WikiTheme->VALID_LINKS)) - $url = ''; - else - $url = $base . $WikiTheme->HTML_DUMP_SUFFIX; - } else { - $url .= $WikiTheme->HTML_DUMP_SUFFIX; - if ($args) - $url .= "?$args"; - } + if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') { + if (!in_array($pagename, $WikiTheme->VALID_LINKS)) + $url = ''; + else + $url = $base . $WikiTheme->HTML_DUMP_SUFFIX; } else { - if ($args) - $url .= "?$args"; - } + $url .= $WikiTheme->HTML_DUMP_SUFFIX; + if ($args) + $url .= "?$args"; + } + } else { + if ($args) + $url .= "?$args"; + } } else { $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME); @@ -467,8 +467,8 @@ function LinkImage($url, $alt = "") { } // Correct silently the most common error if ($url != $ori_url and empty($arr) and !preg_match("/^http/",$url)) { - // space belongs to the path - $file = NormalizeLocalFileName($ori_url); + // space belongs to the path + $file = NormalizeLocalFileName($ori_url); if (file_exists($file)) { $link = HTML::img(array('src' => $ori_url)); trigger_error( @@ -478,7 +478,7 @@ function LinkImage($url, $alt = "") { $file = substr($file, strlen(getUploadDataPath())); $path = getUploadFilePath().$file; if (file_exists($path)) { - trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."), + trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."), $url, $ori_url), E_USER_WARNING); $link->setAttr('src', getUploadDataPath() . $file); $url = $ori_url; @@ -584,29 +584,29 @@ function LinkImage($url, $alt = "") { function ImgObject($img, $url) { // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300" $params = explode(",","data,classid,archive,codebase,name,usemap,type,". - "codetype,standby,tabindex,declare"); + "codetype,standby,tabindex,declare"); if (is_array($url)) { - $args = $url; - $found = array(); + $args = $url; + $found = array(); foreach ($args as $attr => $value) { - foreach ($params as $param) { - if ($param == $attr) { - $img->setAttr($param, $value); - if (isset($found[$param])) $found[$param]++; - else $found[$param] = 1; - break; - } - } + foreach ($params as $param) { + if ($param == $attr) { + $img->setAttr($param, $value); + if (isset($found[$param])) $found[$param]++; + else $found[$param] = 1; + break; + } + } } - // now all remaining args are added as to the object - $params = array(); + // now all remaining args are added as to the object + $params = array(); foreach ($args as $attr => $value) { - if (!isset($found[$attr])) { - $params[] = HTML::param(array('name' => $attr, + if (!isset($found[$attr])) { + $params[] = HTML::param(array('name' => $attr, 'value' => $value)); - } - } - $url = $img->getAttr('src'); + } + } + $url = $img->getAttr('src'); $force_img = "png|jpg|gif|jpeg|bmp"; if (!preg_match("/\.(".$force_img.")/i", $url)) { $img->setAttr('src', false); @@ -617,23 +617,23 @@ function ImgObject($img, $url) { $url = array_shift($args); $found = array(); foreach ($args as $attr) { - foreach ($params as $param) { - if (preg_match("/^$param=(\S+)$/i",$attr,$m)) { - $img->setAttr($param, $m[1]); - if (isset($found[$param])) $found[$param]++; - else $found[$param] = 1; - break; - } - } + foreach ($params as $param) { + if (preg_match("/^$param=(\S+)$/i",$attr,$m)) { + $img->setAttr($param, $m[1]); + if (isset($found[$param])) $found[$param]++; + else $found[$param] = 1; + break; + } } - // now all remaining args are added as to the object - $params = array(); + } + // now all remaining args are added as to the object + $params = array(); foreach ($args as $attr) { - if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) { - $params[] = HTML::param(array('name' => $m[1], + if (!isset($found[$attr]) and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) { + $params[] = HTML::param(array('name' => $m[1], 'value' => $m[2])); - } - } + } + } } } $type = $img->getAttr('type'); @@ -644,10 +644,10 @@ function ImgObject($img, $url) { } $object = HTML::object(array_merge($img->_attr, array('type' => $type)), //'src' => $url - $img->_content); + $img->_content); $object->setAttr('class', 'inlineobject'); if ($params) { - foreach ($params as $param) $object->pushContent($param); + foreach ($params as $param) $object->pushContent($param); } if (isBrowserSafari() and !isBrowserSafari(532)) { // recent chrome can do OBJECT return HTML::embed($object->_attr, $object->_content); @@ -669,7 +669,7 @@ class Stack { $this->size++; return true; } - + function pop() { if ($this->size == 0) { return false; // stack is empty @@ -677,18 +677,18 @@ class Stack { $this->size--; return $this->items[$this->size]; } - + function cnt() { return $this->size; } - + function top() { if($this->size) return $this->items[$this->size - 1]; else return ''; } - + } // end class definition @@ -705,7 +705,7 @@ function SplitQueryArgs ($query_args = '') function LinkPhpwikiURL($url, $text = '', $basepage = false) { $args = array(); - + if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) { return HTML::span(array('class' => 'error'), _("BAD phpwiki: URL")); } @@ -713,7 +713,7 @@ function LinkPhpwikiURL($url, $text = '', $basepage = false) { if ($m[1]) $pagename = urldecode($m[1]); $qargs = $m[2]; - + if (empty($pagename) && preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) { // Convert old style links (to not break diff links in @@ -730,7 +730,7 @@ function LinkPhpwikiURL($url, $text = '', $basepage = false) { if (isset($args['action']) && $args['action'] == 'browse') unset($args['action']); - + /*FIXME: if (empty($args['action'])) $class = 'wikilink'; @@ -748,7 +748,7 @@ function LinkPhpwikiURL($url, $text = '', $basepage = false) { HTML::u(_("Lock page to enable link"))); $class = 'wikiadmin'; } - + if (!$text) $text = HTML::span(array('class' => 'rawurl'), $url); @@ -757,7 +757,7 @@ function LinkPhpwikiURL($url, $text = '', $basepage = false) { global $WikiTheme; return $WikiTheme->linkBadWikiWord($wikipage, $url); } - + return HTML::a(array('href' => WikiURL($pagename, $args), 'class' => $class), $text); @@ -783,13 +783,13 @@ class WikiPageName * This is the full name of the page (without anchor). */ //var $name; - + /** The anchor. * * This is the referenced anchor within the page, or the empty string. */ //var $anchor; - + /** Constructor * * @param mixed $name Page name. @@ -807,7 +807,7 @@ class WikiPageName $this->shortName = $name; if (strstr($name, ':')) { list($moniker, $shortName) = explode (":", $name, 2); - $map = getInterwikiMap(); // allow overrides to custom maps + $map = getInterwikiMap(); // allow overrides to custom maps if (isset($map->_map[$moniker])) { $url = $map->_map[$moniker]; if (strstr($url, '%s')) @@ -826,17 +826,17 @@ class WikiPageName } if (strstr($shortName, '?')) { list($shortName, $dummy) = explode("\?", $shortName, 2); - } + } $this->shortName = $shortName; } } - // FIXME: We should really fix the cause for "/PageName" in the WikiDB + // FIXME: We should really fix the cause for "/PageName" in the WikiDB if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) { if ($basename) $name = $this->_pagename($basename) . $name; else { $name = $this->_normalize_bad_pagename($name); - $this->shortName = $name; + $this->shortName = $name; } } } @@ -850,9 +850,9 @@ class WikiPageName } function getName() { - return $this->name; + return $this->name; } - + function getParent() { $name = $this->name; if (!($tail = strrchr($name, SUBPAGE_SEPARATOR))) @@ -874,26 +874,26 @@ class WikiPageName $warnings = array_merge($warnings, $this->_errors); if (!$warnings) return false; - + return sprintf(_("'%s': Bad page name: %s"), $this->shortName, join(', ', $warnings)); } - + function _pagename($page) { - if (isa($page, 'WikiDB_Page')) - return $page->getName(); + if (isa($page, 'WikiDB_Page')) + return $page->getName(); elseif (isa($page, 'WikiDB_PageRevision')) - return $page->getPageName(); + return $page->getPageName(); elseif (isa($page, 'WikiPageName')) - return $page->name; + return $page->name; // '0' or e.g. '1984' should be allowed though if (!is_string($page) and !is_integer($page)) { trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)", $page, gettype($page), get_class($page)), E_USER_NOTICE); } - //assert(is_string($page)); - return $page; + //assert(is_string($page)); + return $page; } function _normalize_bad_pagename($name) { @@ -921,7 +921,7 @@ class WikiPageName $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename); if ($pagename != $orig) $this->_warnings[] = _("White space converted to single space"); - + // Delete any control characters. if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') { $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename); @@ -943,7 +943,7 @@ class WikiPageName $this->_warnings[] = _("';' is deprecated"); $pagename = str_replace(';', '', $pagename); }*/ - + // not only for SQL, also to restrict url length if (strlen($pagename) > MAX_PAGENAME_LENGTH) { $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH); @@ -960,7 +960,7 @@ class WikiPageName $pagename = str_replace('..', '', $pagename); $pagename = str_replace(':', '', $pagename); } - + return $pagename; } } @@ -991,7 +991,7 @@ function ConvertOldMarkup ($text, $markup_type = "block") { static $subs; static $block_re; - + // FIXME: // Trying to detect why the 2nd paragraph of OldTextFormattingRules or // AnciennesR%E8glesDeFormatage crashes. @@ -1002,9 +1002,9 @@ function ConvertOldMarkup ($text, $markup_type = "block") { if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi')) and preg_match("/plugin CreateToc/", $text)) { - trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ") - ._("Please remove the CreateToc line to be able to reformat this page to old markup. ") - ._("Skipped."), E_USER_WARNING); + trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ") + ._("Please remove the CreateToc line to be able to reformat this page to old markup. ") + ._("Skipped."), E_USER_WARNING); $debug_skip = true; //if (!DEBUG) return $text; return $text; @@ -1044,7 +1044,7 @@ function ConvertOldMarkup ($text, $markup_type = "block") { // Escape '<'s //$orig[] = '/<(?!\?plugin)|(?~[[\\1|#ftnt_\\1]~]'; @@ -1058,7 +1058,7 @@ function ConvertOldMarkup ($text, $markup_type = "block") { // Escape nestled markup. $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m'; $repl[] = '~\\0'; - + // in old markup headings only allowed at beginning of line $orig[] = '/!/'; $repl[] = '~!'; @@ -1094,15 +1094,15 @@ function ConvertOldMarkup ($text, $markup_type = "block") { // Section Title $blockpats[] = '!{1,3}[^!]'; /* - removed .|\n in the anchor not to crash on /m because with /m "." already includes \n - this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only) - */ + removed .|\n in the anchor not to crash on /m because with /m "." already includes \n + this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only) + */ $block_re = ( '/\A((?:.|\n)*?)(^(?:' . join("|", $blockpats) . ').*$)\n?/m' ); - + } - + if ($markup_type != "block") { list ($orig, $repl) = $subs[$markup_type]; return preg_replace($orig, $repl, $text); @@ -1110,15 +1110,15 @@ function ConvertOldMarkup ($text, $markup_type = "block") { else { list ($orig, $repl) = $subs['inline']; $out = ''; - //FIXME: - // php crashes here in the 2nd paragraph of OldTextFormattingRules, - // AnciennesR%E8glesDeFormatage and more - // See http://www.pcre.org/pcre.txt LIMITATIONS - while (preg_match($block_re, $text, $m)) { + //FIXME: + // php crashes here in the 2nd paragraph of OldTextFormattingRules, + // AnciennesR%E8glesDeFormatage and more + // See http://www.pcre.org/pcre.txt LIMITATIONS + while (preg_match($block_re, $text, $m)) { $text = substr($text, strlen($m[0])); list (,$leading_text, $block) = $m; $suffix = "\n"; - + if (strchr(" \t", $block[0])) { // Indented block $prefix = "
    \n";
    @@ -1134,7 +1134,7 @@ function ConvertOldMarkup ($text, $markup_type = "block") {
                     preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
                     list (,$ind,$bullet) = $m;
                     $block = substr($block, strlen($m[0]));
    -              
    +
                     $indent = str_repeat('     ', strlen($ind));
                     if ($bullet[0] == ';') {
                         //$term = ltrim(substr($bullet, 1));
    @@ -1212,10 +1212,10 @@ function expand_tabs($str, $tab_width = 8) {
      * @return string The split name.
      */
     function SplitPagename ($page) {
    -  
    +
         if (preg_match("/\s/", $page))
             return $page;           // Already split --- don't split any more.
    -  
    +
         // This algorithm is specialized for several languages.
         // (Thanks to Pierrick MEIGNEN)
         // Improvements for other languages welcome.
    @@ -1235,7 +1235,7 @@ function SplitPagename ($page) {
                 $RE[] = '/([[:lower:]])((? count($args))
    @@ -1520,7 +1520,7 @@ function __vsprintf ($fmt, $args) {
             }
             $args = $newargs;
         }
    -  
    +
         // Not all PHP's have vsprintf, so...
         array_unshift($args, $fmt);
         return call_user_func_array('sprintf', $args);
    @@ -1624,22 +1624,22 @@ class fileSet {
     class ListRegexExpand {
         //var $match, $list, $index, $case_sensitive;
         function ListRegexExpand (&$list, $match, $case_sensitive = true) {
    -    	$this->match = $match;
    -    	$this->list = &$list;
    -    	$this->case_sensitive = $case_sensitive;
    +        $this->match = $match;
    +        $this->list = &$list;
    +        $this->case_sensitive = $case_sensitive;
             //$this->index = false;
         }
         function listMatchCallback ($item, $key) {
             $quoted = str_replace('/','\/',$item);
    -    	if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
    +        if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'),
                            $quoted)) {
    -	    unset($this->list[$this->index]);
    +        unset($this->list[$this->index]);
                 $this->list[] = $item;
             }
         }
         function expandRegex ($index, &$pages) {
    -    	$this->index = $index;
    -    	array_walk($pages, array($this, 'listMatchCallback'));
    +        $this->index = $index;
    +        array_walk($pages, array($this, 'listMatchCallback'));
             return $this->list;
         }
     }
    @@ -1694,10 +1694,10 @@ function explodeList($input, $allnames, $glob_style = true, $case_sensitive = tr
             for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
                 $f = $list[$i];
                 if (preg_match('/[\?\*]/',$f)) {
    -            	reset($allnames);
    -            	$expand = new ListRegexExpand($list,
    +                reset($allnames);
    +                $expand = new ListRegexExpand($list,
                         $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
    -            	$expand->expandRegex($i, $allnames);
    +                $expand->expandRegex($i, $allnames);
                 }
             }
         }
    @@ -1706,7 +1706,7 @@ function explodeList($input, $allnames, $glob_style = true, $case_sensitive = tr
     
     // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
     function explodePageList($input, $include_empty=false, $sortby='pagename',
    -			 $limit='', $exclude='') {
    +             $limit='', $exclude='') {
         include_once("lib/PageList.php");
         return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
     }
    @@ -1763,8 +1763,8 @@ function function_usable($function_name) {
                  and ! isset($disabled[strtolower($function_name)])
                  );
     }
    -  
    -  
    +
    +
     /** Hash a value.
      *
      * This is used for generating ETags.
    @@ -1773,7 +1773,7 @@ function wikihash ($x) {
         if (is_scalar($x)) {
             return $x;
         }
    -    elseif (is_array($x)) {          
    +    elseif (is_array($x)) {
             ksort($x);
             return md5(serialize($x));
         }
    @@ -1899,13 +1899,13 @@ class Alert {
             if ($buttons === false)
                 $buttons = array();
     
    -	if (is_array($body)) {
    -	    $html = HTML::ol();
    -	    foreach ($body as $li) {
    -		$html->pushContent(HTML::li($li));
    -	    }
    -	    $body = $html;
    -	}
    +    if (is_array($body)) {
    +        $html = HTML::ol();
    +        foreach ($body as $li) {
    +        $html->pushContent(HTML::li($li));
    +        }
    +        $body = $html;
    +    }
             $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
             $this->_buttons = $buttons;
         }
    @@ -1918,7 +1918,7 @@ class Alert {
     
             $tokens = $this->_tokens;
             $tokens['BUTTONS'] = $this->_getButtons();
    -      
    +
             $request->discardOutput();
             $tmpl = new Template('dialog', $request, $tokens);
             $tmpl->printXML();
    @@ -1932,7 +1932,7 @@ class Alert {
             $buttons = $this->_buttons;
             if (!$buttons)
                 $buttons = array(_("Okay") => $request->getURLtoSelf());
    -      
    +
             global $WikiTheme;
             foreach ($buttons as $label => $url)
                 print "$label $url\n";
    @@ -2036,7 +2036,7 @@ function fixTitleEncoding( $s ) {
         $locharset = strtolower($charset);
     
         if( $locharset != "utf-8" and $ishigh and $isutf )
    -	$s = charset_convert('UTF-8', $locharset, $s);
    +    $s = charset_convert('UTF-8', $locharset, $s);
         if ($locharset == "utf-8" and $ishigh and !$isutf )
             return utf8_encode( $s );
     
    @@ -2107,9 +2107,9 @@ function GenerateId($name) {
     // content: string or array of strings
     function firstNWordsOfContent( $n, $content ) {
         if ($content and $n > 0) {
    -    	if (is_array($content)) {
    -    	    // fixme: return a list of lines then?
    -    	    //$content = join("\n", $content);
    +        if (is_array($content)) {
    +            // fixme: return a list of lines then?
    +            //$content = join("\n", $content);
                 //$return_array = true;
                 $wordcount = 0;
                 foreach ($content as $line) {
    @@ -2195,8 +2195,8 @@ function extractSections ($sections, $content, $page, $quiet = false, $sectionhe
     // use this faster version: only load ExternalReferrer if we came from an external referrer
     function isExternalReferrer(&$request) {
         if ($referrer = $request->get('HTTP_REFERER')) {
    -    	$home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
    -    	if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
    +        $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
    +        if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
             require_once("lib/ExternalReferrer.php");
             $se = new SearchEngines();
             return $se->parseSearchQuery($referrer);
    @@ -2210,10 +2210,10 @@ function isExternalReferrer(&$request) {
      */
     function loadPhpExtension($extension) {
         if (!extension_loaded($extension)) {
    -	$isWindows = (substr(PHP_OS,0,3) == 'WIN');
    +    $isWindows = (substr(PHP_OS,0,3) == 'WIN');
             $soname = ($isWindows ? 'php_' : '')
    -	        . $extension
    -	        . ($isWindows ? '.dll' : '.so');
    +            . $extension
    +            . ($isWindows ? '.dll' : '.so');
             if (!@dl($soname))
                 return false;
         }
    @@ -2225,18 +2225,18 @@ function charset_convert($from, $to, $data) {
         //$wikicharset = strtolower($CHARSET);
         //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
         if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
    -	return utf8_decode($data);
    +    return utf8_decode($data);
         if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
    -	return utf8_encode($data);
    +    return utf8_encode($data);
     
         if (loadPhpExtension("iconv")) {
    -	$tmpdata = iconv($from, $to, $data);
    -	if (!$tmpdata)
    -	    trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
    -	else
    -	    $data = $tmpdata;
    +    $tmpdata = iconv($from, $to, $data);
    +    if (!$tmpdata)
    +        trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
    +    else
    +        $data = $tmpdata;
         } else {
    -	trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
    +    trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
         }
         return $data;
     }
    @@ -2268,15 +2268,15 @@ function printSimpleTrace($bt) {
         //print_r($bt);
         echo "\nTraceback:\n";
         if (function_exists('debug_print_backtrace')) { // >= 5
    -	debug_print_backtrace();
    +    debug_print_backtrace();
         } else {
    -	foreach ($bt as $i => $elem) {
    -	    if (!array_key_exists('file', $elem)) {
    -		continue;
    -	    }
    -	    //echo join(" ",array_values($elem)),"\n";
    -	    echo "  ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
    -	}
    +    foreach ($bt as $i => $elem) {
    +        if (!array_key_exists('file', $elem)) {
    +        continue;
    +        }
    +        //echo join(" ",array_values($elem)),"\n";
    +        echo "  ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
    +    }
         }
     }
     
    @@ -2295,18 +2295,18 @@ function getMemoryUsage() {
             // what we want is the process memory only: apache or php (if CGI)
             $pid = getmypid();
             $memstr = '';
    -	// win32_ps_stat_proc, win32_ps_stat_mem
    - 	if (function_exists('win32_ps_list_procs')) {
    -	    $info = win32_ps_stat_proc($pid);
    -	    $memstr = $info['mem']['working_set_size'];
    -	} elseif(0) {
    -	    // This works only if it's a cygwin process (apache or php).
    -	    // Requires a newer cygwin
    -	    $memstr = exec("cat /proc/$pid/statm |cut -f1");
    -
    -	    // if it's native windows use something like this:
    -	    //   (requires pslist from sysinternals.com, grep, sed and perl)
    -	    //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
    +    // win32_ps_stat_proc, win32_ps_stat_mem
    +     if (function_exists('win32_ps_list_procs')) {
    +        $info = win32_ps_stat_proc($pid);
    +        $memstr = $info['mem']['working_set_size'];
    +    } elseif(0) {
    +        // This works only if it's a cygwin process (apache or php).
    +        // Requires a newer cygwin
    +        $memstr = exec("cat /proc/$pid/statm |cut -f1");
    +
    +        // if it's native windows use something like this:
    +        //   (requires pslist from sysinternals.com, grep, sed and perl)
    +        //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
             }
             return (integer) trim($memstr);
         } elseif (1) {
    @@ -2332,7 +2332,7 @@ function getMemoryUsage() {
     function binary_search($needle, $haystack) {
         $high = count($haystack);
         $low = 0;
    - 
    +
         while (($high - $low) > 1) {
             $probe = floor(($high + $low) / 2);
             if ($haystack[$probe] < $needle) {
    @@ -2353,8 +2353,8 @@ function binary_search($needle, $haystack) {
     
     function is_localhost($url = false) {
         if (!$url) {
    -    	global $HTTP_SERVER_VARS;
    -    	return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
    +        global $HTTP_SERVER_VARS;
    +        return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
         }
     }
     
    @@ -2435,7 +2435,7 @@ function parse_attributes($line) {
         }
     
         $options[$attribute] = $value;
    -  
    +
         $line = substr($line, $i+1);
         $line = trim ($line);
         $line = trim ($line, ",");
    @@ -2491,5 +2491,5 @@ function strip_accents($text) {
     // c-basic-offset: 4
     // c-hanging-comment-ender-p: nil
     // indent-tabs-mode: nil
    -// End: 
    +// End:
     ?>
    diff --git a/lib/upgrade.php b/lib/upgrade.php
    index 1376b0920..0e368d2e8 100644
    --- a/lib/upgrade.php
    +++ b/lib/upgrade.php
    @@ -52,96 +52,96 @@ require_once("lib/loadsave.php");
     class Upgrade {
     
         function Upgrade (&$request) {
    -	$this->request =& $request;
    -	$this->dbi =& $request->_dbi; // no reference for dbadmin ?
    -	$this->phpwiki_version = $this->current_db_version = phpwiki_version();
    -	//$this->current_db_version = 1030.13; // should be stored in the db. should be phpwiki_version
    +    $this->request =& $request;
    +    $this->dbi =& $request->_dbi; // no reference for dbadmin ?
    +    $this->phpwiki_version = $this->current_db_version = phpwiki_version();
    +    //$this->current_db_version = 1030.13; // should be stored in the db. should be phpwiki_version
     
    -	$this->db_version = $this->dbi->get_db_version();
    -	$this->isSQL = $this->dbi->_backend->isSQL();
    +    $this->db_version = $this->dbi->get_db_version();
    +    $this->isSQL = $this->dbi->_backend->isSQL();
         }
     
         /**
          * TODO: check for the pgsrc_version number, not the revision mtime only
          */
         function doPgsrcUpdate($pagename, $path, $filename) {
    -	// don't ever update the HomePage
    -	if ((defined(HOME_PAGE) and ($pagename == HOME_PAGE))
    -	    or ($pagename == _("HomePage"))
    -	    or ($pagename == "HomePage")) {
    -	    echo "$path/$pagename: ",_("always skip the HomePage."),
    -	    _(" Skipped"),".
    \n"; + // don't ever update the HomePage + if ((defined(HOME_PAGE) and ($pagename == HOME_PAGE)) + or ($pagename == _("HomePage")) + or ($pagename == "HomePage")) { + echo "$path/$pagename: ",_("always skip the HomePage."), + _(" Skipped"),".
    \n"; return; - } + } - $page = $this->dbi->getPage($pagename); - if ($page->exists()) { - // check mtime: update automatically if pgsrc is newer - $rev = $page->getCurrentRevision(); - $page_mtime = $rev->get('mtime'); - $data = implode("", file($path."/".$filename)); - if (($parts = ParseMimeifiedPages($data))) { - usort($parts, 'SortByPageVersion'); - reset($parts); - $pageinfo = $parts[0]; - $stat = stat($path."/".$filename); - $new_mtime = 0; - if (isset($pageinfo['versiondata']['mtime'])) - $new_mtime = $pageinfo['versiondata']['mtime']; - if (!$new_mtime and isset($pageinfo['versiondata']['lastmodified'])) - $new_mtime = $pageinfo['versiondata']['lastmodified']; - if (!$new_mtime and isset($pageinfo['pagedata']['date'])) - $new_mtime = $pageinfo['pagedata']['date']; - if (!$new_mtime) - $new_mtime = $stat[9]; - if ($new_mtime > $page_mtime) { - echo "$path/$pagename: ",_("newer than the existing page."), - _(" replace "),"($new_mtime > $page_mtime)","
    \n"; - LoadAny($this->request, $path."/".$filename); - echo "
    \n"; - } else { - echo "$path/$pagename: ",_("older than the existing page."), - _(" Skipped"),".
    \n"; - } - } else { - echo "$path/$pagename: ",("unknown format."), + $page = $this->dbi->getPage($pagename); + if ($page->exists()) { + // check mtime: update automatically if pgsrc is newer + $rev = $page->getCurrentRevision(); + $page_mtime = $rev->get('mtime'); + $data = implode("", file($path."/".$filename)); + if (($parts = ParseMimeifiedPages($data))) { + usort($parts, 'SortByPageVersion'); + reset($parts); + $pageinfo = $parts[0]; + $stat = stat($path."/".$filename); + $new_mtime = 0; + if (isset($pageinfo['versiondata']['mtime'])) + $new_mtime = $pageinfo['versiondata']['mtime']; + if (!$new_mtime and isset($pageinfo['versiondata']['lastmodified'])) + $new_mtime = $pageinfo['versiondata']['lastmodified']; + if (!$new_mtime and isset($pageinfo['pagedata']['date'])) + $new_mtime = $pageinfo['pagedata']['date']; + if (!$new_mtime) + $new_mtime = $stat[9]; + if ($new_mtime > $page_mtime) { + echo "$path/$pagename: ",_("newer than the existing page."), + _(" replace "),"($new_mtime > $page_mtime)","
    \n"; + LoadAny($this->request, $path."/".$filename); + echo "
    \n"; + } else { + echo "$path/$pagename: ",_("older than the existing page."), + _(" Skipped"),".
    \n"; + } + } else { + echo "$path/$pagename: ",("unknown format."), _(" Skipped"),".
    \n"; - } - } else { - echo sprintf(_("%s does not exist"),$pagename),"
    \n"; - LoadAny($this->request, $path."/".$filename); - echo "
    \n"; - } + } + } else { + echo sprintf(_("%s does not exist"),$pagename),"
    \n"; + LoadAny($this->request, $path."/".$filename); + echo "
    \n"; + } } function CheckActionPageUpdate() { - echo "

    ",sprintf(_("Check for necessary %s updates"), - _("ActionPage")),"

    \n"; - // 1.3.13 before we pull in all missing pages, we rename existing ones - $this->_rename_page_helper(_("_AuthInfo"), _("DebugAuthInfo")); - // this is in some templates. so we keep the old name - //$this->_rename_page_helper($this->dbi, _("DebugInfo"), _("DebugBackendInfo")); - $this->_rename_page_helper(_("_GroupInfo"), _("GroupAuthInfo")); //never officially existed - $this->_rename_page_helper("InterWikiKarte", "InterWikiListe"); // german only + echo "

    ",sprintf(_("Check for necessary %s updates"), + _("ActionPage")),"

    \n"; + // 1.3.13 before we pull in all missing pages, we rename existing ones + $this->_rename_page_helper(_("_AuthInfo"), _("DebugAuthInfo")); + // this is in some templates. so we keep the old name + //$this->_rename_page_helper($this->dbi, _("DebugInfo"), _("DebugBackendInfo")); + $this->_rename_page_helper(_("_GroupInfo"), _("GroupAuthInfo")); //never officially existed + $this->_rename_page_helper("InterWikiKarte", "InterWikiListe"); // german only - $path = FindFile('pgsrc'); - $pgsrc = new fileSet($path); - // most actionpages have the same name as the plugin - $loc_path = FindLocalizedFile('pgsrc'); - foreach ($pgsrc->getFiles() as $filename) { - if (substr($filename,-1,1) == '~') continue; - if (substr($filename,-5,5) == '.orig') continue; - $pagename = urldecode($filename); - if (isActionPage($pagename)) { - $translation = gettext($pagename); - if ($translation == $pagename) - $this->doPgsrcUpdate($pagename, $path, $filename); - elseif (FindLocalizedFile('pgsrc/'.urlencode($translation),1)) - $this->doPgsrcUpdate($translation, $loc_path, urlencode($translation)); - else - $this->doPgsrcUpdate($pagename, $path, $filename); - } - } + $path = FindFile('pgsrc'); + $pgsrc = new fileSet($path); + // most actionpages have the same name as the plugin + $loc_path = FindLocalizedFile('pgsrc'); + foreach ($pgsrc->getFiles() as $filename) { + if (substr($filename,-1,1) == '~') continue; + if (substr($filename,-5,5) == '.orig') continue; + $pagename = urldecode($filename); + if (isActionPage($pagename)) { + $translation = gettext($pagename); + if ($translation == $pagename) + $this->doPgsrcUpdate($pagename, $path, $filename); + elseif (FindLocalizedFile('pgsrc/'.urlencode($translation),1)) + $this->doPgsrcUpdate($translation, $loc_path, urlencode($translation)); + else + $this->doPgsrcUpdate($pagename, $path, $filename); + } + } } // see loadsave.php for saving new pages. @@ -189,23 +189,23 @@ class Upgrade { } function _rename_page_helper($oldname, $pagename) { - echo sprintf(_("rename %s to %s"), $oldname, $pagename)," ..."; - if ($this->dbi->isWikiPage($oldname) and !$this->dbi->isWikiPage($pagename)) { - if ($this->dbi->_backend->rename_page($oldname, $pagename)) - echo _("OK"),"
    \n"; - else - echo " ", _("FAILED"), "", - "
    \n"; - } else { - echo _(" Skipped"),"
    \n"; - } + echo sprintf(_("rename %s to %s"), $oldname, $pagename)," ..."; + if ($this->dbi->isWikiPage($oldname) and !$this->dbi->isWikiPage($pagename)) { + if ($this->dbi->_backend->rename_page($oldname, $pagename)) + echo _("OK"),"
    \n"; + else + echo " ", _("FAILED"), "", + "
    \n"; + } else { + echo _(" Skipped"),"
    \n"; + } } function _rename_to_help_page($pagename) { - $newprefix = _("Help") . "/"; - if (substr($pagename,0,strlen($newprefix)) != $newprefix) return; - $oldname = substr($pagename,strlen($newprefix)); - $this->_rename_page_helper($oldname, $pagename); + $newprefix = _("Help") . "/"; + if (substr($pagename,0,strlen($newprefix)) != $newprefix) return; + $oldname = substr($pagename,strlen($newprefix)); + $this->_rename_page_helper($oldname, $pagename); } /** @@ -214,90 +214,90 @@ class Upgrade { * Supported: mysql and generic SQL, for ADODB and PearDB. */ function installTable($table, $backend_type) { - global $DBParams; - if (!$this->isSQL) return; - echo _("MISSING")," ... \n"; - $backend = &$this->dbi->_backend->_dbh; - /* - $schema = findFile("schemas/${backend_type}.sql"); - if (!$schema) { - echo " ",_("FAILED"),": ",sprintf(_("no schema %s found"), - "schemas/${backend_type}.sql")," ...
    \n"; - return false; - } - */ - extract($this->dbi->_backend->_table_names); - $prefix = isset($DBParams['prefix']) ? $DBParams['prefix'] : ''; - switch ($table) { - case 'session': - assert($session_tbl); - if ($backend_type == 'mysql') { - $this->dbi->genericSqlQuery(" + global $DBParams; + if (!$this->isSQL) return; + echo _("MISSING")," ... \n"; + $backend = &$this->dbi->_backend->_dbh; + /* + $schema = findFile("schemas/${backend_type}.sql"); + if (!$schema) { + echo " ",_("FAILED"),": ",sprintf(_("no schema %s found"), + "schemas/${backend_type}.sql")," ...
    \n"; + return false; + } + */ + extract($this->dbi->_backend->_table_names); + $prefix = isset($DBParams['prefix']) ? $DBParams['prefix'] : ''; + switch ($table) { + case 'session': + assert($session_tbl); + if ($backend_type == 'mysql') { + $this->dbi->genericSqlQuery(" CREATE TABLE $session_tbl ( - sess_id CHAR(32) NOT NULL DEFAULT '', - sess_data BLOB NOT NULL, - sess_date INT UNSIGNED NOT NULL, - sess_ip CHAR(15) NOT NULL, - PRIMARY KEY (sess_id), - INDEX (sess_date) + sess_id CHAR(32) NOT NULL DEFAULT '', + sess_data BLOB NOT NULL, + sess_date INT UNSIGNED NOT NULL, + sess_ip CHAR(15) NOT NULL, + PRIMARY KEY (sess_id), + INDEX (sess_date) )"); - } else { - $this->dbi->genericSqlQuery(" + } else { + $this->dbi->genericSqlQuery(" CREATE TABLE $session_tbl ( - sess_id CHAR(32) NOT NULL DEFAULT '', - sess_data ".($backend_type == 'pgsql'?'TEXT':'BLOB')." NOT NULL, - sess_date INT, - sess_ip CHAR(15) NOT NULL + sess_id CHAR(32) NOT NULL DEFAULT '', + sess_data ".($backend_type == 'pgsql'?'TEXT':'BLOB')." NOT NULL, + sess_date INT, + sess_ip CHAR(15) NOT NULL )"); - $this->dbi->genericSqlQuery("CREATE UNIQUE INDEX sess_id ON $session_tbl (sess_id)"); - } - $this->dbi->genericSqlQuery("CREATE INDEX sess_date on session (sess_date)"); - echo " ",_("CREATED"); - break; - case 'pref': - $pref_tbl = $prefix.'pref'; - if ($backend_type == 'mysql') { - $this->dbi->genericSqlQuery(" + $this->dbi->genericSqlQuery("CREATE UNIQUE INDEX sess_id ON $session_tbl (sess_id)"); + } + $this->dbi->genericSqlQuery("CREATE INDEX sess_date on session (sess_date)"); + echo " ",_("CREATED"); + break; + case 'pref': + $pref_tbl = $prefix.'pref'; + if ($backend_type == 'mysql') { + $this->dbi->genericSqlQuery(" CREATE TABLE $pref_tbl ( - userid CHAR(48) BINARY NOT NULL UNIQUE, - prefs TEXT NULL DEFAULT '', - PRIMARY KEY (userid) + userid CHAR(48) BINARY NOT NULL UNIQUE, + prefs TEXT NULL DEFAULT '', + PRIMARY KEY (userid) )"); - } else { - $this->dbi->genericSqlQuery(" + } else { + $this->dbi->genericSqlQuery(" CREATE TABLE $pref_tbl ( - userid CHAR(48) NOT NULL, - prefs TEXT NULL DEFAULT '' + userid CHAR(48) NOT NULL, + prefs TEXT NULL DEFAULT '' )"); - $this->dbi->genericSqlQuery("CREATE UNIQUE INDEX userid ON $pref_tbl (userid)"); - } - echo " ",_("CREATED"); - break; - case 'member': - $member_tbl = $prefix.'member'; - if ($backend_type == 'mysql') { - $this->dbi->genericSqlQuery(" + $this->dbi->genericSqlQuery("CREATE UNIQUE INDEX userid ON $pref_tbl (userid)"); + } + echo " ",_("CREATED"); + break; + case 'member': + $member_tbl = $prefix.'member'; + if ($backend_type == 'mysql') { + $this->dbi->genericSqlQuery(" CREATE TABLE $member_tbl ( - userid CHAR(48) BINARY NOT NULL, - groupname CHAR(48) BINARY NOT NULL DEFAULT 'users', - INDEX (userid), - INDEX (groupname) + userid CHAR(48) BINARY NOT NULL, + groupname CHAR(48) BINARY NOT NULL DEFAULT 'users', + INDEX (userid), + INDEX (groupname) )"); - } else { - $this->dbi->genericSqlQuery(" + } else { + $this->dbi->genericSqlQuery(" CREATE TABLE $member_tbl ( - userid CHAR(48) NOT NULL, - groupname CHAR(48) NOT NULL DEFAULT 'users' + userid CHAR(48) NOT NULL, + groupname CHAR(48) NOT NULL DEFAULT 'users' )"); - $this->dbi->genericSqlQuery("CREATE INDEX userid ON $member_tbl (userid)"); - $this->dbi->genericSqlQuery("CREATE INDEX groupname ON $member_tbl (groupname)"); - } - echo " ",_("CREATED"); - break; - case 'rating': - $rating_tbl = $prefix.'rating'; - if ($backend_type == 'mysql') { - $this->dbi->genericSqlQuery(" + $this->dbi->genericSqlQuery("CREATE INDEX userid ON $member_tbl (userid)"); + $this->dbi->genericSqlQuery("CREATE INDEX groupname ON $member_tbl (groupname)"); + } + echo " ",_("CREATED"); + break; + case 'rating': + $rating_tbl = $prefix.'rating'; + if ($backend_type == 'mysql') { + $this->dbi->genericSqlQuery(" CREATE TABLE $rating_tbl ( dimension INT(4) NOT NULL, raterpage INT(11) NOT NULL, @@ -307,8 +307,8 @@ CREATE TABLE $rating_tbl ( tstamp TIMESTAMP(14) NOT NULL, PRIMARY KEY (dimension, raterpage, rateepage) )"); - } else { - $this->dbi->genericSqlQuery(" + } else { + $this->dbi->genericSqlQuery(" CREATE TABLE $rating_tbl ( dimension INT(4) NOT NULL, raterpage INT(11) NOT NULL, @@ -317,59 +317,59 @@ CREATE TABLE $rating_tbl ( rateeversion INT(11) NOT NULL, tstamp TIMESTAMP(14) NOT NULL )"); - $this->dbi->genericSqlQuery("CREATE UNIQUE INDEX rating" - ." ON $rating_tbl (dimension, raterpage, rateepage)"); - } - echo " ",_("CREATED"); - break; - case 'accesslog': - $log_tbl = $prefix.'accesslog'; - // fields according to http://www.outoforder.cc/projects/apache/mod_log_sql/docs-2.0/#id2756178 - /* - A User Agent agent varchar(255) Mozilla/4.0 (compat; MSIE 6.0; Windows) - a CGi request arguments request_args varchar(255) user=Smith&cart=1231&item=532 - b Bytes transfered bytes_sent int unsigned 32561 - c??? Text of cookie cookie varchar(255) Apache=sdyn.fooonline.net 1300102700823 - f Local filename requested request_file varchar(255) /var/www/html/books-cycroad.html - H HTTP request_protocol request_protocol varchar(10) HTTP/1.1 - h Name of remote host remote_host varchar(50) blah.foobar.com - I Request ID (from modd_unique_id) id char(19) POlFcUBRH30AAALdBG8 - l Ident user info remote_logname varcgar(50) bobby - M Machine ID??? machine_id varchar(25) web01 - m HTTP request method request_method varchar(10) GET - P httpd cchild PID child_pid smallint unsigned 3215 - p http port server_port smallint unsigned 80 - R Referer referer varchar(255) http://www.biglinks4u.com/linkpage.html - r Request in full form request_line varchar(255) GET /books-cycroad.html HTTP/1.1 - S Time of request in UNIX time_t format time_stamp int unsigned 1005598029 - T Seconds to service request request_duration smallint unsigned 2 - t Time of request in human format request_time char(28) [02/Dec/2001:15:01:26 -0800] - U Request in simple form request_uri varchar(255) /books-cycroad.html - u User info from HTTP auth remote_user varchar(50) bobby - v Virtual host servicing the request virtual_host varchar(255) - */ - $this->dbi->genericSqlQuery(" + $this->dbi->genericSqlQuery("CREATE UNIQUE INDEX rating" + ." ON $rating_tbl (dimension, raterpage, rateepage)"); + } + echo " ",_("CREATED"); + break; + case 'accesslog': + $log_tbl = $prefix.'accesslog'; + // fields according to http://www.outoforder.cc/projects/apache/mod_log_sql/docs-2.0/#id2756178 + /* + A User Agent agent varchar(255) Mozilla/4.0 (compat; MSIE 6.0; Windows) + a CGi request arguments request_args varchar(255) user=Smith&cart=1231&item=532 + b Bytes transfered bytes_sent int unsigned 32561 + c??? Text of cookie cookie varchar(255) Apache=sdyn.fooonline.net 1300102700823 + f Local filename requested request_file varchar(255) /var/www/html/books-cycroad.html + H HTTP request_protocol request_protocol varchar(10) HTTP/1.1 + h Name of remote host remote_host varchar(50) blah.foobar.com + I Request ID (from modd_unique_id) id char(19) POlFcUBRH30AAALdBG8 + l Ident user info remote_logname varcgar(50) bobby + M Machine ID??? machine_id varchar(25) web01 + m HTTP request method request_method varchar(10) GET + P httpd cchild PID child_pid smallint unsigned 3215 + p http port server_port smallint unsigned 80 + R Referer referer varchar(255) http://www.biglinks4u.com/linkpage.html + r Request in full form request_line varchar(255) GET /books-cycroad.html HTTP/1.1 + S Time of request in UNIX time_t format time_stamp int unsigned 1005598029 + T Seconds to service request request_duration smallint unsigned 2 + t Time of request in human format request_time char(28) [02/Dec/2001:15:01:26 -0800] + U Request in simple form request_uri varchar(255) /books-cycroad.html + u User info from HTTP auth remote_user varchar(50) bobby + v Virtual host servicing the request virtual_host varchar(255) + */ + $this->dbi->genericSqlQuery(" CREATE TABLE $log_tbl ( time_stamp int unsigned, - remote_host varchar(100), - remote_user varchar(50), + remote_host varchar(100), + remote_user varchar(50), request_method varchar(10), - request_line varchar(255), - request_args varchar(255), - request_uri varchar(255), - request_time char(28), - status smallint unsigned, - bytes_sent smallint unsigned, + request_line varchar(255), + request_args varchar(255), + request_uri varchar(255), + request_time char(28), + status smallint unsigned, + bytes_sent smallint unsigned, referer varchar(255), - agent varchar(255), - request_duration float + agent varchar(255), + request_duration float )"); - $this->dbi->genericSqlQuery("CREATE INDEX log_time ON $log_tbl (time_stamp)"); - $this->dbi->genericSqlQuery("CREATE INDEX log_host ON $log_tbl (remote_host)"); - echo " ",_("CREATED"); - break; - } - echo "
    \n"; + $this->dbi->genericSqlQuery("CREATE INDEX log_time ON $log_tbl (time_stamp)"); + $this->dbi->genericSqlQuery("CREATE INDEX log_host ON $log_tbl (remote_host)"); + echo " ",_("CREATED"); + break; + } + echo "
    \n"; } /** @@ -379,19 +379,19 @@ CREATE TABLE $log_tbl ( * people should export/import their pages if using that old versions. */ function CheckDatabaseUpdate() { - global $DBAuthParams, $DBParams; + global $DBAuthParams, $DBParams; - echo "

    ",sprintf(_("Check for necessary %s updates"), - _("database")), - " - ", DATABASE_TYPE,"

    \n"; - $dbadmin = $this->request->getArg('dbadmin'); - if ($this->isSQL) { - $this->_db_init(); - if (isset($dbadmin['cancel'])) { - echo _("CANCEL"),"
    \n"; - return; - } - } + echo "

    ",sprintf(_("Check for necessary %s updates"), + _("database")), + " - ", DATABASE_TYPE,"

    \n"; + $dbadmin = $this->request->getArg('dbadmin'); + if ($this->isSQL) { + $this->_db_init(); + if (isset($dbadmin['cancel'])) { + echo _("CANCEL"),"
    \n"; + return; + } + } echo "db version: we want ", $this->current_db_version, "\n
    "; echo "db version: we have ", $this->db_version, "\n
    "; if ($this->db_version >= $this->current_db_version) { @@ -399,301 +399,301 @@ CREATE TABLE $log_tbl ( return; } - $backend_type = $this->dbi->_backend->backendType(); - if ($this->isSQL) { - echo "

    ",_("Backend type: "),$backend_type,"

    \n"; - $prefix = isset($DBParams['prefix']) ? $DBParams['prefix'] : ''; - $tables = $this->dbi->_backend->listOfTables(); - foreach (explode(':','session:pref:member') as $table) { - echo sprintf(_("Check for table %s"), $table)," ..."; - if (!in_array($prefix.$table, $tables)) { - $this->installTable($table, $backend_type); - } else { - echo _("OK"),"
    \n"; - } - } - } + $backend_type = $this->dbi->_backend->backendType(); + if ($this->isSQL) { + echo "

    ",_("Backend type: "),$backend_type,"

    \n"; + $prefix = isset($DBParams['prefix']) ? $DBParams['prefix'] : ''; + $tables = $this->dbi->_backend->listOfTables(); + foreach (explode(':','session:pref:member') as $table) { + echo sprintf(_("Check for table %s"), $table)," ..."; + if (!in_array($prefix.$table, $tables)) { + $this->installTable($table, $backend_type); + } else { + echo _("OK"),"
    \n"; + } + } + } - if ($this->phpwiki_version >= 1030.12200612 and $this->db_version < 1030.13) { - if ($this->isSQL and preg_match("/(pgsql|postgres)/", $backend_type)) { - trigger_error("You need to upgrade to schema/psql-initialize.sql manually!", - E_USER_WARNING); - // $this->_upgrade_psql_tsearch2(); - } - $this->_upgrade_relation_links(); - } + if ($this->phpwiki_version >= 1030.12200612 and $this->db_version < 1030.13) { + if ($this->isSQL and preg_match("/(pgsql|postgres)/", $backend_type)) { + trigger_error("You need to upgrade to schema/psql-initialize.sql manually!", + E_USER_WARNING); + // $this->_upgrade_psql_tsearch2(); + } + $this->_upgrade_relation_links(); + } - if (ACCESS_LOG_SQL and $this->isSQL) { - $table = "accesslog"; - echo sprintf(_("Check for table %s"), $table)," ..."; - if (!in_array($prefix.$table, $tables)) { - $this->installTable($table, $backend_type); - } else { - echo _("OK"),"
    \n"; - } - } - if ($this->isSQL and (class_exists("RatingsUserFactory") or $this->dbi->isWikiPage(_("RateIt")))) { - $table = "rating"; - echo sprintf(_("Check for table %s"), $table)," ..."; - if (!in_array($prefix.$table, $tables)) { - $this->installTable($table, $backend_type); - } else { - echo _("OK"),"
    \n"; - } - } - $backend = &$this->dbi->_backend->_dbh; - if ($this->isSQL) - extract($this->dbi->_backend->_table_names); + if (ACCESS_LOG_SQL and $this->isSQL) { + $table = "accesslog"; + echo sprintf(_("Check for table %s"), $table)," ..."; + if (!in_array($prefix.$table, $tables)) { + $this->installTable($table, $backend_type); + } else { + echo _("OK"),"
    \n"; + } + } + if ($this->isSQL and (class_exists("RatingsUserFactory") or $this->dbi->isWikiPage(_("RateIt")))) { + $table = "rating"; + echo sprintf(_("Check for table %s"), $table)," ..."; + if (!in_array($prefix.$table, $tables)) { + $this->installTable($table, $backend_type); + } else { + echo _("OK"),"
    \n"; + } + } + $backend = &$this->dbi->_backend->_dbh; + if ($this->isSQL) + extract($this->dbi->_backend->_table_names); - // 1.3.8 added session.sess_ip - if ($this->isSQL and $this->phpwiki_version >= 1030.08 and USE_DB_SESSION - and isset($this->request->_dbsession)) - { - echo _("Check for new session.sess_ip column")," ... "; - $database = $this->dbi->_backend->database(); - assert(!empty($DBParams['db_session_table'])); - $session_tbl = $prefix . $DBParams['db_session_table']; - $sess_fields = $this->dbi->_backend->listOfFields($database, $session_tbl); - if (!$sess_fields) { - echo _("SKIP"); - } elseif (!strstr(strtolower(join(':', $sess_fields)), "sess_ip")) { - // TODO: postgres test (should be able to add columns at the end, but not in between) - echo "",_("ADDING"),""," ... "; - $this->dbi->genericSqlQuery("ALTER TABLE $session_tbl ADD sess_ip CHAR(15) NOT NULL"); - $this->dbi->genericSqlQuery("CREATE INDEX sess_date ON $session_tbl (sess_date)"); - } else { - echo _("OK"); - } - echo "
    \n"; - if (substr($backend_type,0,5) == 'mysql') { - // upgrade to 4.1.8 destroyed my session table: - // sess_id => varchar(10), sess_data => varchar(5). For others obviously also. - echo _("Check for mysql session.sess_id sanity")," ... "; - $result = $this->dbi->genericSqlQuery("DESCRIBE $session_tbl"); - if (DATABASE_TYPE == 'SQL') { - $iter = new WikiDB_backend_PearDB_generic_iter($backend, $result); - } elseif (DATABASE_TYPE == 'ADODB') { - $iter = new WikiDB_backend_ADODB_generic_iter($backend, $result, - array("Field", "Type", "Null", "Key", "Default", "Extra")); - } elseif (DATABASE_TYPE == 'PDO') { - $iter = new WikiDB_backend_PDO_generic_iter($backend, $result); - } - while ($col = $iter->next()) { - if ($col["Field"] == 'sess_id' and !strstr(strtolower($col["Type"]), 'char(32)')) { - $this->dbi->genericSqlQuery("ALTER TABLE $session_tbl CHANGE sess_id" - ." sess_id CHAR(32) NOT NULL"); - echo "sess_id ", $col["Type"], " ", _("fixed"), " => CHAR(32) "; - } - if ($col["Field"] == 'sess_ip' and !strstr(strtolower($col["Type"]), 'char(15)')) { - $this->dbi->genericSqlQuery("ALTER TABLE $session_tbl CHANGE sess_ip" - ." sess_ip CHAR(15) NOT NULL"); - echo "sess_ip ", $col["Type"], " ", _("fixed"), " => CHAR(15) "; - } - } - echo _("OK"), "
    \n"; - } - } + // 1.3.8 added session.sess_ip + if ($this->isSQL and $this->phpwiki_version >= 1030.08 and USE_DB_SESSION + and isset($this->request->_dbsession)) + { + echo _("Check for new session.sess_ip column")," ... "; + $database = $this->dbi->_backend->database(); + assert(!empty($DBParams['db_session_table'])); + $session_tbl = $prefix . $DBParams['db_session_table']; + $sess_fields = $this->dbi->_backend->listOfFields($database, $session_tbl); + if (!$sess_fields) { + echo _("SKIP"); + } elseif (!strstr(strtolower(join(':', $sess_fields)), "sess_ip")) { + // TODO: postgres test (should be able to add columns at the end, but not in between) + echo "",_("ADDING"),""," ... "; + $this->dbi->genericSqlQuery("ALTER TABLE $session_tbl ADD sess_ip CHAR(15) NOT NULL"); + $this->dbi->genericSqlQuery("CREATE INDEX sess_date ON $session_tbl (sess_date)"); + } else { + echo _("OK"); + } + echo "
    \n"; + if (substr($backend_type,0,5) == 'mysql') { + // upgrade to 4.1.8 destroyed my session table: + // sess_id => varchar(10), sess_data => varchar(5). For others obviously also. + echo _("Check for mysql session.sess_id sanity")," ... "; + $result = $this->dbi->genericSqlQuery("DESCRIBE $session_tbl"); + if (DATABASE_TYPE == 'SQL') { + $iter = new WikiDB_backend_PearDB_generic_iter($backend, $result); + } elseif (DATABASE_TYPE == 'ADODB') { + $iter = new WikiDB_backend_ADODB_generic_iter($backend, $result, + array("Field", "Type", "Null", "Key", "Default", "Extra")); + } elseif (DATABASE_TYPE == 'PDO') { + $iter = new WikiDB_backend_PDO_generic_iter($backend, $result); + } + while ($col = $iter->next()) { + if ($col["Field"] == 'sess_id' and !strstr(strtolower($col["Type"]), 'char(32)')) { + $this->dbi->genericSqlQuery("ALTER TABLE $session_tbl CHANGE sess_id" + ." sess_id CHAR(32) NOT NULL"); + echo "sess_id ", $col["Type"], " ", _("fixed"), " => CHAR(32) "; + } + if ($col["Field"] == 'sess_ip' and !strstr(strtolower($col["Type"]), 'char(15)')) { + $this->dbi->genericSqlQuery("ALTER TABLE $session_tbl CHANGE sess_ip" + ." sess_ip CHAR(15) NOT NULL"); + echo "sess_ip ", $col["Type"], " ", _("fixed"), " => CHAR(15) "; + } + } + echo _("OK"), "
    \n"; + } + } - /* TODO: - ALTER TABLE link ADD relation INT DEFAULT 0; - CREATE INDEX linkrelation ON link (relation); - */ + /* TODO: + ALTER TABLE link ADD relation INT DEFAULT 0; + CREATE INDEX linkrelation ON link (relation); + */ - // mysql >= 4.0.4 requires LOCK TABLE privileges - if (substr($backend_type,0,5) == 'mysql') { - echo _("Check for mysql LOCK TABLE privilege")," ..."; - $mysql_version = $this->dbi->_backend->_serverinfo['version']; - if ($mysql_version > 400.40) { - if (!empty($this->dbi->_backend->_parsedDSN)) - $parseDSN = $this->dbi->_backend->_parsedDSN; - elseif (function_exists('parseDSN')) // ADODB or PDO - $parseDSN = parseDSN($DBParams['dsn']); - else // pear - $parseDSN = DB::parseDSN($DBParams['dsn']); - $username = $this->dbi->_backend->qstr($parseDSN['username']); - // on db level - $query = "SELECT lock_tables_priv FROM mysql.db WHERE user='$username'"; - //mysql_select_db("mysql", $this->dbi->_backend->connection()); - $db_fields = $this->dbi->_backend->listOfFields("mysql", "db"); - if (!strstr(strtolower(join(':', $db_fields)), "lock_tables_priv")) { - echo join(':', $db_fields); - die("lock_tables_priv missing. The DB Admin must run mysql_fix_privilege_tables"); - } - $row = $this->dbi->_backend->getRow($query); - if (isset($row[0]) and $row[0] == 'N') { - $this->dbi->genericSqlQuery("UPDATE mysql.db SET lock_tables_priv='Y'" - ." WHERE mysql.user='$username'"); - $this->dbi->genericSqlQuery("FLUSH PRIVILEGES"); - echo "mysql.db user='$username'", _("fixed"), "
    \n"; - } elseif (!$row) { - // or on user level - $query = "SELECT lock_tables_priv FROM mysql.user WHERE user='$username'"; - $row = $this->dbi->_backend->getRow($query); - if ($row and $row[0] == 'N') { - $this->dbi->genericSqlQuery("UPDATE mysql.user SET lock_tables_priv='Y'" - ." WHERE mysql.user='$username'"); - $this->dbi->genericSqlQuery("FLUSH PRIVILEGES"); - echo "mysql.user user='$username'", _("fixed"), "
    \n"; - } elseif (!$row) { - echo " ", _("FAILED"), ": ", - "Neither mysql.db nor mysql.user has a user='$username'" - ." or the lock_tables_priv field", - "
    \n"; - } else { - echo _("OK"), "
    \n"; - } - } else { - echo _("OK"), "
    \n"; - } - //mysql_select_db($this->dbi->_backend->database(), $this->dbi->_backend->connection()); - } else { - echo sprintf(_("version %s not affected"), $mysql_version),"
    \n"; - } - } + // mysql >= 4.0.4 requires LOCK TABLE privileges + if (substr($backend_type,0,5) == 'mysql') { + echo _("Check for mysql LOCK TABLE privilege")," ..."; + $mysql_version = $this->dbi->_backend->_serverinfo['version']; + if ($mysql_version > 400.40) { + if (!empty($this->dbi->_backend->_parsedDSN)) + $parseDSN = $this->dbi->_backend->_parsedDSN; + elseif (function_exists('parseDSN')) // ADODB or PDO + $parseDSN = parseDSN($DBParams['dsn']); + else // pear + $parseDSN = DB::parseDSN($DBParams['dsn']); + $username = $this->dbi->_backend->qstr($parseDSN['username']); + // on db level + $query = "SELECT lock_tables_priv FROM mysql.db WHERE user='$username'"; + //mysql_select_db("mysql", $this->dbi->_backend->connection()); + $db_fields = $this->dbi->_backend->listOfFields("mysql", "db"); + if (!strstr(strtolower(join(':', $db_fields)), "lock_tables_priv")) { + echo join(':', $db_fields); + die("lock_tables_priv missing. The DB Admin must run mysql_fix_privilege_tables"); + } + $row = $this->dbi->_backend->getRow($query); + if (isset($row[0]) and $row[0] == 'N') { + $this->dbi->genericSqlQuery("UPDATE mysql.db SET lock_tables_priv='Y'" + ." WHERE mysql.user='$username'"); + $this->dbi->genericSqlQuery("FLUSH PRIVILEGES"); + echo "mysql.db user='$username'", _("fixed"), "
    \n"; + } elseif (!$row) { + // or on user level + $query = "SELECT lock_tables_priv FROM mysql.user WHERE user='$username'"; + $row = $this->dbi->_backend->getRow($query); + if ($row and $row[0] == 'N') { + $this->dbi->genericSqlQuery("UPDATE mysql.user SET lock_tables_priv='Y'" + ." WHERE mysql.user='$username'"); + $this->dbi->genericSqlQuery("FLUSH PRIVILEGES"); + echo "mysql.user user='$username'", _("fixed"), "
    \n"; + } elseif (!$row) { + echo " ", _("FAILED"), ": ", + "Neither mysql.db nor mysql.user has a user='$username'" + ." or the lock_tables_priv field", + "
    \n"; + } else { + echo _("OK"), "
    \n"; + } + } else { + echo _("OK"), "
    \n"; + } + //mysql_select_db($this->dbi->_backend->database(), $this->dbi->_backend->connection()); + } else { + echo sprintf(_("version %s not affected"), $mysql_version),"
    \n"; + } + } - // 1.3.10 mysql requires page.id auto_increment - // mysql, mysqli or mysqlt - if ($this->phpwiki_version >= 1030.099 and substr($backend_type,0,5) == 'mysql' - and DATABASE_TYPE != 'PDO') + // 1.3.10 mysql requires page.id auto_increment + // mysql, mysqli or mysqlt + if ($this->phpwiki_version >= 1030.099 and substr($backend_type,0,5) == 'mysql' + and DATABASE_TYPE != 'PDO') { - echo _("Check for mysql page.id auto_increment flag")," ..."; - assert(!empty($page_tbl)); - $database = $this->dbi->_backend->database(); - $fields = mysql_list_fields($database, $page_tbl, $this->dbi->_backend->connection()); - $columns = mysql_num_fields($fields); - for ($i = 0; $i < $columns; $i++) { - if (mysql_field_name($fields, $i) == 'id') { - $flags = mysql_field_flags($fields, $i); - //DONE: something was wrong with ADODB here. - if (!strstr(strtolower($flags), "auto_increment")) { - echo "",_("ADDING"),""," ... "; - // MODIFY col_def valid since mysql 3.22.16, - // older mysql's need CHANGE old_col col_def - $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl CHANGE id" - ." id INT NOT NULL AUTO_INCREMENT"); - $fields = mysql_list_fields($database, $page_tbl); - if (!strstr(strtolower(mysql_field_flags($fields, $i)), "auto_increment")) - echo " ", _("FAILED"), "
    \n"; - else - echo _("OK"), "
    \n"; - } else { - echo _("OK"), "
    \n"; - } - break; - } - } - mysql_free_result($fields); - } + echo _("Check for mysql page.id auto_increment flag")," ..."; + assert(!empty($page_tbl)); + $database = $this->dbi->_backend->database(); + $fields = mysql_list_fields($database, $page_tbl, $this->dbi->_backend->connection()); + $columns = mysql_num_fields($fields); + for ($i = 0; $i < $columns; $i++) { + if (mysql_field_name($fields, $i) == 'id') { + $flags = mysql_field_flags($fields, $i); + //DONE: something was wrong with ADODB here. + if (!strstr(strtolower($flags), "auto_increment")) { + echo "",_("ADDING"),""," ... "; + // MODIFY col_def valid since mysql 3.22.16, + // older mysql's need CHANGE old_col col_def + $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl CHANGE id" + ." id INT NOT NULL AUTO_INCREMENT"); + $fields = mysql_list_fields($database, $page_tbl); + if (!strstr(strtolower(mysql_field_flags($fields, $i)), "auto_increment")) + echo " ", _("FAILED"), "
    \n"; + else + echo _("OK"), "
    \n"; + } else { + echo _("OK"), "
    \n"; + } + break; + } + } + mysql_free_result($fields); + } - // Check for mysql 4.1.x/5.0.0a binary search problem. - // http://bugs.mysql.com/bug.php?id=4398 - // "select * from page where LOWER(pagename) like '%search%'" does not apply LOWER! - // Confirmed for 4.1.0alpha,4.1.3-beta,5.0.0a; not yet tested for 4.1.2alpha, - // On windows only, though utf8 would be useful elsewhere also. - // Illegal mix of collations (latin1_bin,IMPLICIT) and - // (utf8_general_ci, COERCIBLE) for operation '=']) - if (isWindows() and substr($backend_type,0,5) == 'mysql') { - echo _("Check for mysql 4.1.x/5.0.0 binary search on windows problem")," ..."; - $mysql_version = $this->dbi->_backend->_serverinfo['version']; - if ($mysql_version < 401.0) { - echo sprintf(_("version %s"), $mysql_version)," ", - _("not affected"),"
    \n"; - } elseif ($mysql_version >= 401.6) { // FIXME: since which version? - $row = $this->dbi->_backend->getRow("SHOW CREATE TABLE $page_tbl"); - $result = join(" ", $row); - if (strstr(strtolower($result), "character set") - and strstr(strtolower($result), "collate")) - { - echo _("OK"), "
    \n"; - } else { - //SET CHARACTER SET latin1 - $charset = CHARSET; - if ($charset == 'iso-8859-1') $charset = 'latin1'; - $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl CHANGE pagename " - ."pagename VARCHAR(100) " - ."CHARACTER SET '$charset' COLLATE '$charset"."_bin' NOT NULL"); - echo sprintf(_("version %s"), $mysql_version), - " ",_("FIXED"),"", - "
    \n"; - } - } elseif (DATABASE_TYPE != 'PDO') { - // check if already fixed - extract($this->dbi->_backend->_table_names); - assert(!empty($page_tbl)); - $database = $this->dbi->_backend->database(); - $fields = mysql_list_fields($database, $page_tbl, $this->dbi->_backend->connection()); - $columns = mysql_num_fields($fields); - for ($i = 0; $i < $columns; $i++) { - if (mysql_field_name($fields, $i) == 'pagename') { - $flags = mysql_field_flags($fields, $i); - // I think it was fixed with 4.1.6, but I tested it only with 4.1.8 - if ($mysql_version > 401.0 and $mysql_version < 401.6) { - // remove the binary flag - if (strstr(strtolower($flags), "binary")) { - // FIXME: on duplicate pagenames this will fail! - $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl CHANGE pagename" - ." pagename VARCHAR(100) NOT NULL"); - echo sprintf(_("version %s"), $mysql_version), - "",_("FIXED"),"" - ,"
    \n"; - } - } - break; - } - } - } - } - if ($this->isSQL and ACCESS_LOG_SQL & 2) { - echo _("Check for ACCESS_LOG_SQL passwords in POST requests")," ..."; - // Don't display passwords in POST requests (up to 2005-02-04 12:03:20) - $res = $this->dbi->genericSqlIter("SELECT time_stamp, remote_host, " . - "request_args FROM ${prefix}accesslog WHERE request_args LIKE " . - "'%s:6:\"passwd\"%' AND request_args NOT LIKE '%s:6:\"passwd\";" . - "s:15:\"\"%'"); - $count = 0; - while ($row = $res->next()) { - $args = preg_replace("/(s:6:\"passwd\";s:15:\").*(\")/", - "$1$2", $row["request_args"]); - $ts = $row["time_stamp"]; - $rh = $row["remote_host"]; - $this->dbi->genericSqlQuery("UPDATE ${prefix}accesslog SET " . - "request_args='$args' WHERE time_stamp=$ts AND " . - "remote_host='$rh'"); - $count++; - } - if ($count > 0) - echo "",_("FIXED"),"", "
    \n"; - else - echo _("OK"),"
    \n"; + // Check for mysql 4.1.x/5.0.0a binary search problem. + // http://bugs.mysql.com/bug.php?id=4398 + // "select * from page where LOWER(pagename) like '%search%'" does not apply LOWER! + // Confirmed for 4.1.0alpha,4.1.3-beta,5.0.0a; not yet tested for 4.1.2alpha, + // On windows only, though utf8 would be useful elsewhere also. + // Illegal mix of collations (latin1_bin,IMPLICIT) and + // (utf8_general_ci, COERCIBLE) for operation '=']) + if (isWindows() and substr($backend_type,0,5) == 'mysql') { + echo _("Check for mysql 4.1.x/5.0.0 binary search on windows problem")," ..."; + $mysql_version = $this->dbi->_backend->_serverinfo['version']; + if ($mysql_version < 401.0) { + echo sprintf(_("version %s"), $mysql_version)," ", + _("not affected"),"
    \n"; + } elseif ($mysql_version >= 401.6) { // FIXME: since which version? + $row = $this->dbi->_backend->getRow("SHOW CREATE TABLE $page_tbl"); + $result = join(" ", $row); + if (strstr(strtolower($result), "character set") + and strstr(strtolower($result), "collate")) + { + echo _("OK"), "
    \n"; + } else { + //SET CHARACTER SET latin1 + $charset = CHARSET; + if ($charset == 'iso-8859-1') $charset = 'latin1'; + $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl CHANGE pagename " + ."pagename VARCHAR(100) " + ."CHARACTER SET '$charset' COLLATE '$charset"."_bin' NOT NULL"); + echo sprintf(_("version %s"), $mysql_version), + " ",_("FIXED"),"", + "
    \n"; + } + } elseif (DATABASE_TYPE != 'PDO') { + // check if already fixed + extract($this->dbi->_backend->_table_names); + assert(!empty($page_tbl)); + $database = $this->dbi->_backend->database(); + $fields = mysql_list_fields($database, $page_tbl, $this->dbi->_backend->connection()); + $columns = mysql_num_fields($fields); + for ($i = 0; $i < $columns; $i++) { + if (mysql_field_name($fields, $i) == 'pagename') { + $flags = mysql_field_flags($fields, $i); + // I think it was fixed with 4.1.6, but I tested it only with 4.1.8 + if ($mysql_version > 401.0 and $mysql_version < 401.6) { + // remove the binary flag + if (strstr(strtolower($flags), "binary")) { + // FIXME: on duplicate pagenames this will fail! + $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl CHANGE pagename" + ." pagename VARCHAR(100) NOT NULL"); + echo sprintf(_("version %s"), $mysql_version), + "",_("FIXED"),"" + ,"
    \n"; + } + } + break; + } + } + } + } + if ($this->isSQL and ACCESS_LOG_SQL & 2) { + echo _("Check for ACCESS_LOG_SQL passwords in POST requests")," ..."; + // Don't display passwords in POST requests (up to 2005-02-04 12:03:20) + $res = $this->dbi->genericSqlIter("SELECT time_stamp, remote_host, " . + "request_args FROM ${prefix}accesslog WHERE request_args LIKE " . + "'%s:6:\"passwd\"%' AND request_args NOT LIKE '%s:6:\"passwd\";" . + "s:15:\"\"%'"); + $count = 0; + while ($row = $res->next()) { + $args = preg_replace("/(s:6:\"passwd\";s:15:\").*(\")/", + "$1$2", $row["request_args"]); + $ts = $row["time_stamp"]; + $rh = $row["remote_host"]; + $this->dbi->genericSqlQuery("UPDATE ${prefix}accesslog SET " . + "request_args='$args' WHERE time_stamp=$ts AND " . + "remote_host='$rh'"); + $count++; + } + if ($count > 0) + echo "",_("FIXED"),"", "
    \n"; + else + echo _("OK"),"
    \n"; - if ($this->phpwiki_version >= 1030.13) { - echo _("Check for ACCESS_LOG_SQL remote_host varchar(50)")," ..."; - $database = $this->dbi->_backend->database(); - $accesslog_tbl = $prefix . 'accesslog'; - $fields = $this->dbi->_backend->listOfFields($database, $accesslog_tbl); - if (!$fields) { - echo _("SKIP"); - } elseif (strstr(strtolower(join(':', $sess_fields)), "remote_host")) { - // TODO: how to check size, already done? - echo "",_("FIXING"),"remote_host"," ... "; - $this->dbi->genericSqlQuery("ALTER TABLE $accesslog_tbl CHANGE remote_host VARCHAR(100)"); - } else { - echo _("FAIL"); - } - echo "
    \n"; - } - } - $this->_upgrade_cached_html(); + if ($this->phpwiki_version >= 1030.13) { + echo _("Check for ACCESS_LOG_SQL remote_host varchar(50)")," ..."; + $database = $this->dbi->_backend->database(); + $accesslog_tbl = $prefix . 'accesslog'; + $fields = $this->dbi->_backend->listOfFields($database, $accesslog_tbl); + if (!$fields) { + echo _("SKIP"); + } elseif (strstr(strtolower(join(':', $sess_fields)), "remote_host")) { + // TODO: how to check size, already done? + echo "",_("FIXING"),"remote_host"," ... "; + $this->dbi->genericSqlQuery("ALTER TABLE $accesslog_tbl CHANGE remote_host VARCHAR(100)"); + } else { + echo _("FAIL"); + } + echo "
    \n"; + } + } + $this->_upgrade_cached_html(); - if ($this->db_version < $this->current_db_version) { - $this->dbi->set_db_version($this->current_db_version); - $this->db_version = $this->dbi->get_db_version(); + if ($this->db_version < $this->current_db_version) { + $this->dbi->set_db_version($this->current_db_version); + $this->db_version = $this->dbi->get_db_version(); echo "db version: upgrade to ", $this->db_version," "; echo _("OK"), "
    \n"; flush(); - } + } - return; + return; } /** @@ -704,98 +704,98 @@ CREATE TABLE $log_tbl ( * @access private */ function _dbpermission_filter($err) { - if ( $err->isWarning() ) { - global $ErrorManager; - $this->error_caught = 1; - $ErrorManager->_postponed_errors[] = $err; - return true; - } - return false; + if ( $err->isWarning() ) { + global $ErrorManager; + $this->error_caught = 1; + $ErrorManager->_postponed_errors[] = $err; + return true; + } + return false; } function _try_dbadmin_user ($user, $passwd) { - global $DBParams, $DBAuthParams; - $AdminParams = $DBParams; - if (DATABASE_TYPE == 'SQL') - $dsn = DB::parseDSN($AdminParams['dsn']); - else { - $dsn = parseDSN($AdminParams['dsn']); - } - $AdminParams['dsn'] = sprintf("%s://%s:%s@%s/%s", - $dsn['phptype'], - $user, - $passwd, - $dsn['hostspec'], - $dsn['database']); - $AdminParams['_tryroot_from_upgrade'] = 1; - // add error handler to warn about missing permissions for DBADMIN_USER - global $ErrorManager; - $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_dbpermission_filter')); - $this->error_caught = 0; - $this->dbi = WikiDB::open($AdminParams); - if (!$this->error_caught) return true; - // FAILED: redo our connection with the wikiuser - $this->dbi = WikiDB::open($DBParams); - $ErrorManager->flushPostponedErrors(); - $ErrorManager->popErrorHandler(); - return false; + global $DBParams, $DBAuthParams; + $AdminParams = $DBParams; + if (DATABASE_TYPE == 'SQL') + $dsn = DB::parseDSN($AdminParams['dsn']); + else { + $dsn = parseDSN($AdminParams['dsn']); + } + $AdminParams['dsn'] = sprintf("%s://%s:%s@%s/%s", + $dsn['phptype'], + $user, + $passwd, + $dsn['hostspec'], + $dsn['database']); + $AdminParams['_tryroot_from_upgrade'] = 1; + // add error handler to warn about missing permissions for DBADMIN_USER + global $ErrorManager; + $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_dbpermission_filter')); + $this->error_caught = 0; + $this->dbi = WikiDB::open($AdminParams); + if (!$this->error_caught) return true; + // FAILED: redo our connection with the wikiuser + $this->dbi = WikiDB::open($DBParams); + $ErrorManager->flushPostponedErrors(); + $ErrorManager->popErrorHandler(); + return false; } function _db_init () { - if (!$this->isSQL) return; + if (!$this->isSQL) return; - /* SQLite never needs admin params */ - $backend_type = $this->dbi->_backend->backendType(); - if (substr($backend_type,0,6)=="sqlite") { - return; - } - $dbadmin_user = 'root'; - if ($dbadmin = $this->request->getArg('dbadmin')) { - $dbadmin_user = $dbadmin['user']; - if (isset($dbadmin['cancel'])) { - return; - } elseif (!empty($dbadmin_user)) { - if ($this->_try_dbadmin_user($dbadmin['user'], $dbadmin['passwd'])) - return; - } - } elseif (DBADMIN_USER) { - if ($this->_try_dbadmin_user(DBADMIN_USER, DBADMIN_PASSWD)) - return true; - } - // Check if the privileges are enough. Need CREATE and ALTER perms. - // And on windows: SELECT FROM mysql, possibly: UPDATE mysql. - $form = HTML::form(array("method" => "post", - "action" => $this->request->getPostURL(), - "accept-charset"=>$GLOBALS['charset']), - HTML::p(_("Upgrade requires database privileges to CREATE and ALTER the phpwiki database."), - HTML::br(), - _("And on windows at least the privilege to SELECT FROM mysql, and possibly UPDATE mysql")), - HiddenInputs(array('action' => 'upgrade', - 'overwrite' => $this->request->getArg('overwrite'))), - HTML::table(array("cellspacing"=>4), - HTML::tr(HTML::td(array('align'=>'right'), - _("DB admin user:")), - HTML::td(HTML::input(array('name'=>"dbadmin[user]", - 'size'=>12, - 'maxlength'=>256, - 'value'=>$dbadmin_user)))), - HTML::tr(HTML::td(array('align'=>'right'), - _("DB admin password:")), - HTML::td(HTML::input(array('name'=>"dbadmin[passwd]", - 'type'=>'password', - 'size'=>12, - 'maxlength'=>256)))), - HTML::tr(HTML::td(array('align'=>'center', 'colspan' => 2), - Button("submit:", _("Submit"), 'wikiaction'), - HTML::raw(' '), - Button("submit:dbadmin[cancel]", _("Cancel"), - 'button'))))); - $form->printXml(); - echo "
    \n"; - echo asXML(Template("bottom")); - echo "\n"; - $this->request->finish(); - exit(); + /* SQLite never needs admin params */ + $backend_type = $this->dbi->_backend->backendType(); + if (substr($backend_type,0,6)=="sqlite") { + return; + } + $dbadmin_user = 'root'; + if ($dbadmin = $this->request->getArg('dbadmin')) { + $dbadmin_user = $dbadmin['user']; + if (isset($dbadmin['cancel'])) { + return; + } elseif (!empty($dbadmin_user)) { + if ($this->_try_dbadmin_user($dbadmin['user'], $dbadmin['passwd'])) + return; + } + } elseif (DBADMIN_USER) { + if ($this->_try_dbadmin_user(DBADMIN_USER, DBADMIN_PASSWD)) + return true; + } + // Check if the privileges are enough. Need CREATE and ALTER perms. + // And on windows: SELECT FROM mysql, possibly: UPDATE mysql. + $form = HTML::form(array("method" => "post", + "action" => $this->request->getPostURL(), + "accept-charset"=>$GLOBALS['charset']), + HTML::p(_("Upgrade requires database privileges to CREATE and ALTER the phpwiki database."), + HTML::br(), + _("And on windows at least the privilege to SELECT FROM mysql, and possibly UPDATE mysql")), + HiddenInputs(array('action' => 'upgrade', + 'overwrite' => $this->request->getArg('overwrite'))), + HTML::table(array("cellspacing"=>4), + HTML::tr(HTML::td(array('align'=>'right'), + _("DB admin user:")), + HTML::td(HTML::input(array('name'=>"dbadmin[user]", + 'size'=>12, + 'maxlength'=>256, + 'value'=>$dbadmin_user)))), + HTML::tr(HTML::td(array('align'=>'right'), + _("DB admin password:")), + HTML::td(HTML::input(array('name'=>"dbadmin[passwd]", + 'type'=>'password', + 'size'=>12, + 'maxlength'=>256)))), + HTML::tr(HTML::td(array('align'=>'center', 'colspan' => 2), + Button("submit:", _("Submit"), 'wikiaction'), + HTML::raw(' '), + Button("submit:dbadmin[cancel]", _("Cancel"), + 'button'))))); + $form->printXml(); + echo "\n"; + echo asXML(Template("bottom")); + echo "\n"; + $this->request->finish(); + exit(); } /** @@ -807,38 +807,38 @@ CREATE TABLE $log_tbl ( * but was extracetd for every simple page iteration. */ function _upgrade_cached_html ( $verbose=true ) { - global $DBParams; - if (!$this->isSQL) return; - $count = 0; - if ($this->phpwiki_version >= 1030.10) { - if ($verbose) - echo _("Check for extra page.cached_html column")," ... "; - $database = $this->dbi->_backend->database(); - extract($this->dbi->_backend->_table_names); - $fields = $this->dbi->_backend->listOfFields($database, $page_tbl); - if (!$fields) { - echo _("SKIP"), "
    \n"; - return 0; - } - if (!strstr(strtolower(join(':', $fields)), "cached_html")) { - if ($verbose) - echo "",_("ADDING"),""," ... "; - $backend_type = $this->dbi->_backend->backendType(); - if (substr($backend_type,0,5) == 'mysql') - $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl ADD cached_html MEDIUMBLOB"); - else - $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl ADD cached_html BLOB"); - if ($verbose) - echo "",_("CONVERTING"),""," ... "; - $count = _convert_cached_html(); - if ($verbose) - echo $count, " ", _("OK"), "
    \n"; - } else { - if ($verbose) - echo _("OK"), "
    \n"; - } - } - return $count; + global $DBParams; + if (!$this->isSQL) return; + $count = 0; + if ($this->phpwiki_version >= 1030.10) { + if ($verbose) + echo _("Check for extra page.cached_html column")," ... "; + $database = $this->dbi->_backend->database(); + extract($this->dbi->_backend->_table_names); + $fields = $this->dbi->_backend->listOfFields($database, $page_tbl); + if (!$fields) { + echo _("SKIP"), "
    \n"; + return 0; + } + if (!strstr(strtolower(join(':', $fields)), "cached_html")) { + if ($verbose) + echo "",_("ADDING"),""," ... "; + $backend_type = $this->dbi->_backend->backendType(); + if (substr($backend_type,0,5) == 'mysql') + $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl ADD cached_html MEDIUMBLOB"); + else + $this->dbi->genericSqlQuery("ALTER TABLE $page_tbl ADD cached_html BLOB"); + if ($verbose) + echo "",_("CONVERTING"),""," ... "; + $count = _convert_cached_html(); + if ($verbose) + echo $count, " ", _("OK"), "
    \n"; + } else { + if ($verbose) + echo _("OK"), "
    \n"; + } + } + return $count; } /** @@ -846,28 +846,28 @@ CREATE TABLE $log_tbl ( * decoupled from action=upgrade, so that it can be used by a WikiAdminUtils button also. */ function _convert_cached_html () { - global $DBParams; - if (!$this->isSQL) return; - //if (!in_array(DATABASE_TYPE, array('SQL','ADODB'))) return; + global $DBParams; + if (!$this->isSQL) return; + //if (!in_array(DATABASE_TYPE, array('SQL','ADODB'))) return; - $pages = $this->dbi->getAllPages(); - $cache =& $this->dbi->_cache; - $count = 0; - extract($this->dbi->_backend->_table_names); - while ($page = $pages->next()) { - $pagename = $page->getName(); - $data = $this->dbi->_backend->get_pagedata($pagename); - if (!empty($data['_cached_html'])) { - $cached_html = $data['_cached_html']; - $data['_cached_html'] = ''; - $cache->update_pagedata($pagename, $data); - // store as blob, not serialized - $this->dbi->genericSqlQuery("UPDATE $page_tbl SET cached_html=? WHERE pagename=?", - array($cached_html, $pagename)); - $count++; - } - } - return $count; + $pages = $this->dbi->getAllPages(); + $cache =& $this->dbi->_cache; + $count = 0; + extract($this->dbi->_backend->_table_names); + while ($page = $pages->next()) { + $pagename = $page->getName(); + $data = $this->dbi->_backend->get_pagedata($pagename); + if (!empty($data['_cached_html'])) { + $cached_html = $data['_cached_html']; + $data['_cached_html'] = ''; + $cache->update_pagedata($pagename, $data); + // store as blob, not serialized + $this->dbi->genericSqlQuery("UPDATE $page_tbl SET cached_html=? WHERE pagename=?", + array($cached_html, $pagename)); + $count++; + } + } + return $count; } /** @@ -890,59 +890,59 @@ CREATE TABLE $log_tbl ( } echo "
    \n"; } - if ($this->phpwiki_version >= 1030.12200610) { - echo _("Rebuild entire database to upgrade relation links")," ... "; - if (DATABASE_TYPE == 'dba') { - echo "",_("CONVERTING")," dba linktable","(~2 min, max 4 min) ... "; - flush(); - longer_timeout(240); - $this->dbi->_backend->_linkdb->rebuild(); - } else { - flush(); - longer_timeout(180); - $this->dbi->_backend->rebuild(); - } - echo _("OK"), "
    \n"; - } + if ($this->phpwiki_version >= 1030.12200610) { + echo _("Rebuild entire database to upgrade relation links")," ... "; + if (DATABASE_TYPE == 'dba') { + echo "",_("CONVERTING")," dba linktable","(~2 min, max 4 min) ... "; + flush(); + longer_timeout(240); + $this->dbi->_backend->_linkdb->rebuild(); + } else { + flush(); + longer_timeout(180); + $this->dbi->_backend->rebuild(); + } + echo _("OK"), "
    \n"; + } } function CheckPluginUpdate() { - return; - - echo "

    ",sprintf(_("Check for necessary %s updates"), - _("plugin argument")),"

    \n"; + return; - $this->_configUpdates = array(); - $this->_configUpdates[] = new UpgradePluginEntry - ($this, array('key' => 'plugin_randompage_numpages', - 'fixed_with' => 1012.0, - //'header' => _("change RandomPage pages => numpages"), - //'notice' =>_("found RandomPage plugin"), - 'check_args' => array("plugin RandomPage pages", + echo "

    ",sprintf(_("Check for necessary %s updates"), + _("plugin argument")),"

    \n"; + + $this->_configUpdates = array(); + $this->_configUpdates[] = new UpgradePluginEntry + ($this, array('key' => 'plugin_randompage_numpages', + 'fixed_with' => 1012.0, + //'header' => _("change RandomPage pages => numpages"), + //'notice' =>_("found RandomPage plugin"), + 'check_args' => array("plugin RandomPage pages", "/(<\?\s*plugin\s+ RandomPage\s+)pages/", "\\1numpages"))); - $this->_configUpdates[] = new UpgradePluginEntry - ($this, array('key' => 'plugin_createtoc_position', - 'fixed_with' => 1013.0, - //'header' => _("change CreateToc align => position"), - //'notice' =>_("found CreateToc plugin"), - 'check_args' => array("plugin CreateToc align", + $this->_configUpdates[] = new UpgradePluginEntry + ($this, array('key' => 'plugin_createtoc_position', + 'fixed_with' => 1013.0, + //'header' => _("change CreateToc align => position"), + //'notice' =>_("found CreateToc plugin"), + 'check_args' => array("plugin CreateToc align", "/(<\?\s*plugin\s+ CreateToc[^\?]+)align/", "\\1position"))); - if (empty($this->_configUpdates)) return; + if (empty($this->_configUpdates)) return; foreach ($this->_configUpdates as $update) { $pages = $this->dbi->fullSearch($this->check_args[0]); while ($page = $allpages->next()) { $current = $page->getCurrentRevision(); $pagetext = $current->getPackedContent(); - $update->check($this->check_args[1], $this->check_args[2], $pagetext, $page, $current); - } - } - free($allpages); - unset($pagetext); - unset($current); - unset($page); + $update->check($this->check_args[1], $this->check_args[2], $pagetext, $page, $current); + } + } + free($allpages); + unset($pagetext); + unset($current); + unset($page); } /** @@ -950,90 +950,90 @@ CREATE TABLE $log_tbl ( * Only line-orientated matches possible. */ function fixLocalFile($match, $replace, $filename) { - $o_filename = $filename; - if (!file_exists($filename)) - $filename = FindFile($filename); - if (!file_exists($filename)) - return array(false, sprintf(_("file %s not found"), $o_filename)); - $found = false; - if (is_writable($filename)) { - $in = fopen($filename, "rb"); - $out = fopen($tmp = tempnam(getUploadFilePath(),"cfg"), "wb"); - if (isWindows()) - $tmp = str_replace("/","\\",$tmp); - // Detect the existing linesep at first line. fgets strips it even if 'rb'. - // Before we simply assumed \r\n on windows local files. - $s = fread($in, 1024); - rewind($in); - $linesep = (substr_count($s, "\r\n") > substr_count($s, "\n")) ? "\r\n" : "\n"; - //$linesep = isWindows() ? "\r\n" : "\n"; - while ($s = fgets($in)) { - // =>php-5.0.1 can fill count - //$new = preg_replace($match, $replace, $s, -1, $count); - $new = preg_replace($match, $replace, $s); - if ($new != $s) { - $s = $new . $linesep; - $found = true; - } - fputs($out, $s); - } - fclose($in); - fclose($out); - if (!$found) { - // todo: skip - $reason = sprintf(_("%s not found in %s"), $match, $filename); - unlink($out); - return array($found, $reason); - } else { - @unlink("$file.bak"); - @rename($file,"$file.bak"); - if (!rename($tmp, $file)) - return array(false, sprintf(_("couldn't move %s to %s"), $tmp, $filename)); - return true; - } - } else { - return array(false, sprintf(_("file %s is not writable"), $filename)); - } + $o_filename = $filename; + if (!file_exists($filename)) + $filename = FindFile($filename); + if (!file_exists($filename)) + return array(false, sprintf(_("file %s not found"), $o_filename)); + $found = false; + if (is_writable($filename)) { + $in = fopen($filename, "rb"); + $out = fopen($tmp = tempnam(getUploadFilePath(),"cfg"), "wb"); + if (isWindows()) + $tmp = str_replace("/","\\",$tmp); + // Detect the existing linesep at first line. fgets strips it even if 'rb'. + // Before we simply assumed \r\n on windows local files. + $s = fread($in, 1024); + rewind($in); + $linesep = (substr_count($s, "\r\n") > substr_count($s, "\n")) ? "\r\n" : "\n"; + //$linesep = isWindows() ? "\r\n" : "\n"; + while ($s = fgets($in)) { + // =>php-5.0.1 can fill count + //$new = preg_replace($match, $replace, $s, -1, $count); + $new = preg_replace($match, $replace, $s); + if ($new != $s) { + $s = $new . $linesep; + $found = true; + } + fputs($out, $s); + } + fclose($in); + fclose($out); + if (!$found) { + // todo: skip + $reason = sprintf(_("%s not found in %s"), $match, $filename); + unlink($out); + return array($found, $reason); + } else { + @unlink("$file.bak"); + @rename($file,"$file.bak"); + if (!rename($tmp, $file)) + return array(false, sprintf(_("couldn't move %s to %s"), $tmp, $filename)); + return true; + } + } else { + return array(false, sprintf(_("file %s is not writable"), $filename)); + } } function CheckConfigUpdate () { - echo "

    ",sprintf(_("Check for necessary %s updates"), - "config.ini"),"

    \n"; - $entry = new UpgradeConfigEntry - ($this, array('key' => 'cache_control_none', - 'fixed_with' => 1012.0, - 'header' => sprintf(_("Check for %s"),"CACHE_CONTROL = NONE"), - 'applicable_args' => 'CACHE_CONTROL', - 'notice' => _("CACHE_CONTROL is set to 'NONE', and must be changed to 'NO_CACHE'"), - 'check_args' => array("/^\s*CACHE_CONTROL\s*=\s*NONE/", "CACHE_CONTROL = NO_CACHE"))); - $entry->setApplicableCb(new WikiMethodCb($entry, '_applicable_defined_and_empty')); - $this->_configUpdates[] = $entry; + echo "

    ",sprintf(_("Check for necessary %s updates"), + "config.ini"),"

    \n"; + $entry = new UpgradeConfigEntry + ($this, array('key' => 'cache_control_none', + 'fixed_with' => 1012.0, + 'header' => sprintf(_("Check for %s"),"CACHE_CONTROL = NONE"), + 'applicable_args' => 'CACHE_CONTROL', + 'notice' => _("CACHE_CONTROL is set to 'NONE', and must be changed to 'NO_CACHE'"), + 'check_args' => array("/^\s*CACHE_CONTROL\s*=\s*NONE/", "CACHE_CONTROL = NO_CACHE"))); + $entry->setApplicableCb(new WikiMethodCb($entry, '_applicable_defined_and_empty')); + $this->_configUpdates[] = $entry; - $entry = new UpgradeConfigEntry - ($this, array('key' => 'group_method_none', - 'fixed_with' => 1012.0, - 'header' => sprintf(_("Check for %s"), "GROUP_METHOD = NONE"), - 'applicable_args' => 'GROUP_METHOD', - 'notice' =>_("GROUP_METHOD is set to NONE, and must be changed to \"NONE\""), - 'check_args' => array("/^\s*GROUP_METHOD\s*=\s*NONE/", "GROUP_METHOD = \"NONE\""))); - $entry->setApplicableCb(new WikiMethodCb($entry, '_applicable_defined_and_empty')); - $this->_configUpdates[] = $entry; + $entry = new UpgradeConfigEntry + ($this, array('key' => 'group_method_none', + 'fixed_with' => 1012.0, + 'header' => sprintf(_("Check for %s"), "GROUP_METHOD = NONE"), + 'applicable_args' => 'GROUP_METHOD', + 'notice' =>_("GROUP_METHOD is set to NONE, and must be changed to \"NONE\""), + 'check_args' => array("/^\s*GROUP_METHOD\s*=\s*NONE/", "GROUP_METHOD = \"NONE\""))); + $entry->setApplicableCb(new WikiMethodCb($entry, '_applicable_defined_and_empty')); + $this->_configUpdates[] = $entry; - $entry = new UpgradeConfigEntry - ($this, array('key' => 'blog_empty_default_prefix', - 'fixed_with' => 1013.0, - 'header' => sprintf(_("Check for %s"), "BLOG_EMPTY_DEFAULT_PREFIX"), - 'applicable_args' => 'BLOG_EMPTY_DEFAULT_PREFIX', - 'notice' =>_("fix BLOG_EMPTY_DEFAULT_PREFIX into BLOG_DEFAULT_EMPTY_PREFIX"), - 'check_args' => array("/BLOG_EMPTY_DEFAULT_PREFIX\s*=/","BLOG_DEFAULT_EMPTY_PREFIX ="))); - $entry->setApplicableCb(new WikiMethodCb($entry, '_applicable_defined')); - $this->_configUpdates[] = $entry; + $entry = new UpgradeConfigEntry + ($this, array('key' => 'blog_empty_default_prefix', + 'fixed_with' => 1013.0, + 'header' => sprintf(_("Check for %s"), "BLOG_EMPTY_DEFAULT_PREFIX"), + 'applicable_args' => 'BLOG_EMPTY_DEFAULT_PREFIX', + 'notice' =>_("fix BLOG_EMPTY_DEFAULT_PREFIX into BLOG_DEFAULT_EMPTY_PREFIX"), + 'check_args' => array("/BLOG_EMPTY_DEFAULT_PREFIX\s*=/","BLOG_DEFAULT_EMPTY_PREFIX ="))); + $entry->setApplicableCb(new WikiMethodCb($entry, '_applicable_defined')); + $this->_configUpdates[] = $entry; - // TODO: find extra file updates - if (empty($this->_configUpdates)) return; - foreach ($this->_configUpdates as $update) { - $update->check(); - } + // TODO: find extra file updates + if (empty($this->_configUpdates)) return; + foreach ($this->_configUpdates as $update) { + $update->check(); + } } } // class Upgrade @@ -1053,17 +1053,17 @@ class UpgradeEntry * //param All other args are passed to $method */ function UpgradeEntry(&$parent, $params) { - $this->parent =& $parent; // get the properties db_version - foreach (array('key' => 'required', - // the wikidb stores the version when we actually fixed that. - 'fixed_with' => 'required', - 'header' => '', // always printed - 'applicable_cb' => null, // method to check if applicable - 'applicable_args' => array(), // might be the config name - 'notice' => '', - 'check_cb' => null, // method to apply - 'check_args' => array()) - as $k => $v) + $this->parent =& $parent; // get the properties db_version + foreach (array('key' => 'required', + // the wikidb stores the version when we actually fixed that. + 'fixed_with' => 'required', + 'header' => '', // always printed + 'applicable_cb' => null, // method to check if applicable + 'applicable_args' => array(), // might be the config name + 'notice' => '', + 'check_cb' => null, // method to apply + 'check_args' => array()) + as $k => $v) { if (!isset($params[$k])) { // default if ($v == 'required') trigger_error("Required arg $k missing", E_USER_ERROR); @@ -1072,97 +1072,97 @@ class UpgradeEntry $this->{$k} = $params[$k]; } } - if (!is_array($this->applicable_args)) // single arg convenience shortcut - $this->applicable_args = array($this->applicable_args); - if (!is_array($this->check_args)) // single arg convenience shortcut - $this->check_args = array($this->check_args); - if ($this->notice === '' and count($this->applicable_args) > 0) - $this->notice = 'Check for '.join(', ', $this->applicable_args); - $this->_db_key = "_upgrade"; - $this->upgrade = $this->parent->dbi->get($this->_db_key); + if (!is_array($this->applicable_args)) // single arg convenience shortcut + $this->applicable_args = array($this->applicable_args); + if (!is_array($this->check_args)) // single arg convenience shortcut + $this->check_args = array($this->check_args); + if ($this->notice === '' and count($this->applicable_args) > 0) + $this->notice = 'Check for '.join(', ', $this->applicable_args); + $this->_db_key = "_upgrade"; + $this->upgrade = $this->parent->dbi->get($this->_db_key); } /* needed ? */ function setApplicableCb($object) { - $this->applicable_cb =& $object; + $this->applicable_cb =& $object; } function _check_if_already_fixed() { - // not yet fixed? - if (!isset($this->upgrade['name'])) return false; - // override with force? - if ($this->parent->request->getArg('force')) return false; - // already fixed and with an ok version - if ($this->upgrade['name'] >= $this->fixed_with) return $this->upgrade['name']; - // already fixed but with an older version. do it again. - return false; + // not yet fixed? + if (!isset($this->upgrade['name'])) return false; + // override with force? + if ($this->parent->request->getArg('force')) return false; + // already fixed and with an ok version + if ($this->upgrade['name'] >= $this->fixed_with) return $this->upgrade['name']; + // already fixed but with an older version. do it again. + return false; } function pass() { - // store in db no to fix again - $this->upgrade['name'] = $this->parent->phpwiki_version; - $this->parent->dbi->set($this->_db_key, $this->upgrade); - echo "",_("FIXED"),""; - if (isset($this->reason)) - echo _(": "), $this->reason; - echo "
    \n"; - flush(); - return true; + // store in db no to fix again + $this->upgrade['name'] = $this->parent->phpwiki_version; + $this->parent->dbi->set($this->_db_key, $this->upgrade); + echo "",_("FIXED"),""; + if (isset($this->reason)) + echo _(": "), $this->reason; + echo "
    \n"; + flush(); + return true; } function fail() { - echo " ", _("FAILED"), ""; - if (isset($this->reason)) - echo _(": "), $this->reason; - echo "
    \n"; - flush(); - return false; + echo " ", _("FAILED"), ""; + if (isset($this->reason)) + echo _(": "), $this->reason; + echo "
    \n"; + flush(); + return false; } function skip() { // not applicable if (isset($this->silent_skip)) return true; - echo _(" Skipped"),".
    \n"; - flush(); - return true; + echo _(" Skipped"),".
    \n"; + flush(); + return true; } function check($args = null) { - if ($this->header) echo $this->header, ' ... '; - if ($when = $this->_check_if_already_fixed()) { - // be totally silent if no header is defined. - if ($this->header) echo _("fixed with")," ",$when,"
    \n"; - flush(); - return true; - } - if (is_object($this->applicable_cb)) { - if (!$this->applicable_cb->call_array($this->applicable_args)) - return $this->skip(); - } - if ($this->notice) { - if ($this->header) - echo "
    \n"; - echo $this->notice," "; - flush(); - } - if (!is_null($args)) $this->check_args =& $args; - if (is_object($this->check_cb)) - $do = $this->method_cb->call_array($this->check_args); - else - $do = $this->default_method($this->check_args); - if (is_array($do)) { - $this->reason = $do[1]; - $do = $do[0]; - } - return $do ? $this->pass() : $this->fail(); + if ($this->header) echo $this->header, ' ... '; + if ($when = $this->_check_if_already_fixed()) { + // be totally silent if no header is defined. + if ($this->header) echo _("fixed with")," ",$when,"
    \n"; + flush(); + return true; + } + if (is_object($this->applicable_cb)) { + if (!$this->applicable_cb->call_array($this->applicable_args)) + return $this->skip(); + } + if ($this->notice) { + if ($this->header) + echo "
    \n"; + echo $this->notice," "; + flush(); + } + if (!is_null($args)) $this->check_args =& $args; + if (is_object($this->check_cb)) + $do = $this->method_cb->call_array($this->check_args); + else + $do = $this->default_method($this->check_args); + if (is_array($do)) { + $this->reason = $do[1]; + $do = $do[0]; + } + return $do ? $this->pass() : $this->fail(); } } // class UpgradeEntry class UpgradeConfigEntry extends UpgradeEntry { function _applicable_defined() { - return (boolean)defined($this->applicable_args[0]); + return (boolean)defined($this->applicable_args[0]); } function _applicable_defined_and_empty() { - $const = $this->applicable_args[0]; - return (boolean)(defined($const) and !constant($const)); + $const = $this->applicable_args[0]; + return (boolean)(defined($const) and !constant($const)); } function default_method ($args) { - $match = $args[0]; - $replace = $args[1]; - return $this->parent->fixLocalFile($match, $replace, "config/config.ini"); + $match = $args[0]; + $replace = $args[1]; + return $this->parent->fixLocalFile($match, $replace, "config/config.ini"); } } // class UpdateConfigEntry @@ -1175,22 +1175,22 @@ class UpgradePluginEntry extends UpgradeEntry { var $silent_skip = 1; function default_method (&$args) { - $match = $args[0]; - $replace = $args[1]; - $pagetext =& $args[2]; - $page =& $args[3]; - $current =& $args[4]; - if (preg_match($match, $pagetext)) { - echo $page->getName()," ",$this->notice," ... "; - if ($newtext = preg_replace($match, $replace, $pagetext)) { - $meta = $current->_data; - $meta['summary'] = "upgrade: ".$this->header; - $page->save($newtext, $current->getVersion() + 1, $meta); - $this->pass(); - } else { - $this->fail(); - } - } + $match = $args[0]; + $replace = $args[1]; + $pagetext =& $args[2]; + $page =& $args[3]; + $current =& $args[4]; + if (preg_match($match, $pagetext)) { + echo $page->getName()," ",$this->notice," ... "; + if ($newtext = preg_replace($match, $replace, $pagetext)) { + $meta = $current->_data; + $meta['summary'] = "upgrade: ".$this->header; + $page->save($newtext, $current->getVersion() + 1, $meta); + $this->pass(); + } else { + $this->fail(); + } + } } } // class UpdatePluginEntry @@ -1201,32 +1201,32 @@ class UpgradePluginEntry extends UpgradeEntry { class UpgradeThemeEntry extends UpgradeEntry { function default_method (&$args) { - $match = $args[0]; - $replace = $args[1]; - $template = $args[2]; + $match = $args[0]; + $replace = $args[1]; + $template = $args[2]; } function fixThemeTemplate($match, $new, $template) { - // for all custom themes - $ourthemes = explode(":","blog:Crao:default:Hawaiian:MacOSX:MonoBook:Portland:shamino_com:SpaceWiki:wikilens:Wordpress"); - $themedir = NormalizeLocalFileName("themes"); - $dh = opendir($themedir); - while ($r = readdir($dh)) { - if (filetype($r) == 'dir' and $r[0] != '.' and !is_array($r, $ourthemes)) - $customthemes[] = $r; - } - $success = true; - $errors = ''; - foreach ($customthemes as $customtheme) { - $template = FindFile("themes/$customtheme/templates/$template"); - $do = $this->parent->fixLocalFile($match, $new, template); - if (!$do[0]) { - $success = false; - $errors .= $do[1]." "; - echo $do[1]; - } - } - return array($success, $errors); + // for all custom themes + $ourthemes = explode(":","blog:Crao:default:Hawaiian:MacOSX:MonoBook:Portland:shamino_com:SpaceWiki:wikilens:Wordpress"); + $themedir = NormalizeLocalFileName("themes"); + $dh = opendir($themedir); + while ($r = readdir($dh)) { + if (filetype($r) == 'dir' and $r[0] != '.' and !is_array($r, $ourthemes)) + $customthemes[] = $r; + } + $success = true; + $errors = ''; + foreach ($customthemes as $customtheme) { + $template = FindFile("themes/$customtheme/templates/$template"); + $do = $this->parent->fixLocalFile($match, $new, template); + if (!$do[0]) { + $success = false; + $errors .= $do[1]." "; + echo $do[1]; + } + } + return array($success, $errors); } } @@ -1260,18 +1260,18 @@ function DoUpgrade(&$request) { //if (!$request->getArg('noindex')) // CheckOldIndexUpdate($request); // index.php => config.ini to upgrade from < 1.3.10 if (!$request->getArg('nodb')) - $upgrade->CheckDatabaseUpdate($request); // first check cached_html and friends + $upgrade->CheckDatabaseUpdate($request); // first check cached_html and friends if (!$request->getArg('nopgsrc')) { - $upgrade->CheckPgsrcUpdate($request); - $upgrade->CheckActionPageUpdate($request); + $upgrade->CheckPgsrcUpdate($request); + $upgrade->CheckActionPageUpdate($request); } if (!$request->getArg('noplugin')) - $upgrade->CheckPluginUpdate($request); + $upgrade->CheckPluginUpdate($request); if (!$request->getArg('noconfig')) - $upgrade->CheckConfigUpdate($request); + $upgrade->CheckConfigUpdate($request); // This is optional and should be linked. In EndLoadDump or PhpWikiAdministration? //if ($request->getArg('theme')) - // $upgrade->CheckThemeUpdate($request); + // $upgrade->CheckThemeUpdate($request); EndLoadDump($request); } diff --git a/lib/ziplib.php b/lib/ziplib.php index 7c4f1a08d..0bc475da3 100644 --- a/lib/ziplib.php +++ b/lib/ziplib.php @@ -12,14 +12,14 @@ */ function gzip_cleanup () { global $gzip_tmpfile; - + if ($gzip_tmpfile) @unlink($gzip_tmpfile); } function gzip_tempnam () { global $gzip_tmpfile; - + if (!$gzip_tmpfile) { //FIXME: does this work on non-unix machines? if (is_writable("/tmp")) @@ -59,7 +59,7 @@ function gzip_uncompress ($data) { fwrite($fp, $data, strlen($data)); if (!fclose($fp)) trigger_error(sprintf("%s failed", 'fclose'), E_USER_ERROR); - + if (!($fp = gzopen($filename, "rb"))) trigger_error(sprintf("%s failed", 'gzopen'), E_USER_ERROR); $unz = ''; @@ -67,7 +67,7 @@ function gzip_uncompress ($data) { $unz .= $buf; if (!gzclose($fp)) trigger_error(sprintf("%s failed", 'gzclose'), E_USER_ERROR); - + unlink($filename); return $unz; } @@ -79,7 +79,7 @@ function gzip_uncompress ($data) { function zip_crc32 ($str, $crc = 0) { static $zip_crc_table; - + if (empty($zip_crc_table)) { /* NOTE: The range of PHP ints seems to be -0x80000000 to 0x7fffffff. * So, had to munge these constants. @@ -138,7 +138,7 @@ function zip_crc32 ($str, $crc = 0) 0x5d681b02, 0x2a6f2b94, -0x4bf441c9, -0x3cf3715f, 0x5a05df1b, 0x2d02ef8d); } - + $crc = ~$crc; for ($i = 0; $i < strlen($str); $i++) { $crc = ( $zip_crc_table[($crc ^ ord($str[$i])) & 0xff] @@ -157,11 +157,11 @@ function zip_deflate ($content) $z = gzencode($content); else $z = gzip_compress($content); - + // Suck OS type byte from gzip header. FIXME: this smells bad. - + extract(unpack("a2magic/Ccomp_type/Cflags/@9/Cos_type", $z)); - + if ($magic != GZIP_MAGIC) trigger_error(sprintf("Bad %s", "gzip magic"), E_USER_ERROR); if ($comp_type != GZIP_DEFLATE) @@ -169,17 +169,17 @@ function zip_deflate ($content) if (($flags & 0x3e) != 0) trigger_error(sprintf("Bad %s", sprintf("flags (0x%02x)", $flags)), E_USER_ERROR); - + $gz_header_len = 10; $gz_data_len = strlen($z) - $gz_header_len - 8; if ($gz_data_len < 0) trigger_error("not enough gzip output?", E_USER_ERROR); - + extract(unpack("Vcrc32", substr($z, $gz_header_len + $gz_data_len))); - + return array(substr($z, $gz_header_len, $gz_data_len), // gzipped data - $crc32, // crc - $os_type // OS type + $crc32, // crc + $os_type // OS type ); } @@ -200,15 +200,15 @@ function zip_inflate ($data, $crc32, $uncomp_size) trigger_error("CRC32 mismatch: calculated=$zcrc32, expected=$crc32", E_USER_ERROR); return $data; } - + if (!function_exists('gzopen')) { global $request; $request->finish(_("Can't inflate data: zlib support not enabled in this PHP")); } - + // Reconstruct gzip header and ungzip the data. - $mtime = time(); //(Bogus mtime) - + $mtime = time(); //(Bogus mtime) + return gzip_uncompress( pack("a2CxV@10", GZIP_MAGIC, GZIP_DEFLATE, $mtime) . $data . pack("VV", $crc32, $uncomp_size) ); @@ -216,17 +216,17 @@ function zip_inflate ($data, $crc32, $uncomp_size) function unixtime2dostime ($unix_time) { if ($unix_time % 1) - $unix_time++; // Round up to even seconds. + $unix_time++; // Round up to even seconds. list ($year,$month,$mday,$hour,$min,$sec) = explode(" ", date("Y n j G i s", $unix_time)); - + if ($year < 1980) list ($year,$month,$mday,$hour,$min,$sec) = array(1980, 1, 1, 0, 0, 0); - + $dosdate = (($year - 1980) << 9) | ($month << 5) | $mday; $dostime = ($hour << 11) | ($min << 5) | ($sec >> 1); - + return array($dosdate, $dostime); } @@ -234,11 +234,11 @@ function dostime2unixtime ($dosdate, $dostime) { $mday = $dosdate & 0x1f; $month = ($dosdate >> 5) & 0x0f; $year = 1980 + (($dosdate >> 9) & 0x7f); - + $sec = ($dostime & 0x1f) * 2; $min = ($dostime >> 5) & 0x3f; $hour = ($dostime >> 11) & 0x1f; - + return mktime($hour, $min, $sec, $month, $mday, $year); } @@ -257,33 +257,33 @@ class ZipWriter function ZipWriter ($comment = "", $zipname = "archive.zip") { $this->comment = $comment; $this->nfiles = 0; - $this->dir = ""; // "Central directory block" - $this->offset = 0; // Current file position. - + $this->dir = ""; // "Central directory block" + $this->offset = 0; // Current file position. + $zipname = addslashes($zipname); header("Content-Type: application/zip; name=\"$zipname\""); header("Content-Disposition: attachment; filename=\"$zipname\""); } - + function addSrcFile ($target, $src, $attrib = false) { - if (empty($attrib['mtime'])) - $attrib = array('mtime' => filemtime($src), 'is_ascii' => 0); - $this->addRegularFile($target, file_get_contents($src), $attrib); + if (empty($attrib['mtime'])) + $attrib = array('mtime' => filemtime($src), 'is_ascii' => 0); + $this->addRegularFile($target, file_get_contents($src), $attrib); } - + function addRegularFile ($filename, $content, $attrib = false) { if (!$attrib) $attrib = array(); - + $size = strlen($content); if (function_exists('gzopen')) { list ($data, $crc32, $os_type) = zip_deflate($content); if (strlen($data) < $size) { - $content = $data; // Use compressed data. + $content = $data; // Use compressed data. $comp_type = ZIP_DEFLATE; } else - unset($crc32); // force plain store. + unset($crc32); // force plain store. } else { // Punt: @@ -295,29 +295,29 @@ class ZipWriter $comp_type = ZIP_STORE; $crc32 = zip_crc32($content); } - + if (!empty($attrib['write_protected'])) $atx = (0100444 << 16) | 1; // S_IFREG + read permissions to // everybody. else $atx = (0100644 << 16); // Add owner write perms. - + $ati = $attrib['is_ascii'] ? 1 : 0; - + if (empty($attrib['mtime'])) $attrib['mtime'] = time(); list ($mod_date, $mod_time) = unixtime2dostime($attrib['mtime']); - + // Construct parts common to "Local file header" and "Central // directory file header." if (!isset($attrib['extra_field'])) $attrib['extra_field'] = ''; if (!isset($attrib['file_comment'])) $attrib['file_comment'] = ''; - + $head = pack("vvvvvVVVvv", - 20, // Version needed to extract (FIXME: is this right?) - 0, // Gen purp bit flag + 20, // Version needed to extract (FIXME: is this right?) + 0, // Gen purp bit flag $comp_type, $mod_time, $mod_date, @@ -326,47 +326,47 @@ class ZipWriter $size, strlen($filename), strlen($attrib['extra_field'])); - + // Construct the "Local file header" $lheader = ZIP_LOCHEAD_MAGIC . $head . $filename . $attrib['extra_field']; - + // Construct the "central directory file header" $this->dir .= pack("a4CC", ZIP_CENTHEAD_MAGIC, - 23, // Version made by (FIXME: is this right?) + 23, // Version made by (FIXME: is this right?) $os_type); $this->dir .= $head; $this->dir .= pack("vvvVV", strlen($attrib['file_comment']), 0, // Disk number start - $ati, // Internal file attributes - $atx, // External file attributes + $ati, // Internal file attributes + $atx, // External file attributes $this->offset); // Relative offset of local header $this->dir .= $filename . $attrib['extra_field'] . $attrib['file_comment']; - + // Output the "Local file header" and file contents. echo $lheader; echo $content; - + $this->offset += strlen($lheader) + strlen($content); $this->nfiles++; } - + function finish () { // Output the central directory echo $this->dir; - + // Construct the "End of central directory record" echo ZIP_ENDDIR_MAGIC; echo pack("vvvvVVv", 0, // Number of this disk. 0, // Number of disk with start of c dir $this->nfiles, // Number entries on this disk - $this->nfiles, // Number entries + $this->nfiles, // Number entries strlen($this->dir), // Size of central directory - $this->offset, // Offset of central directory + $this->offset, // Offset of central directory strlen($this->comment)); echo $this->comment; } @@ -396,12 +396,12 @@ class ZipReader $this->fp = $zipfile; $zipfile = NULL; } elseif (((ord($zipfile[0]) * 256 + ord($zipfile[1])) % 31 == 0) // buffer - and (substr($zipfile,0,2) == "\037\213") - or (substr($zipfile,0,2) == "x\332")) { // 120, 218 - $this->fp = NULL; - $this->buf = $zipfile; + and (substr($zipfile,0,2) == "\037\213") + or (substr($zipfile,0,2) == "x\332")) { // 120, 218 + $this->fp = NULL; + $this->buf = $zipfile; $zipfile = NULL; - } + } if ($zipfile) { $this->zipfile = $zipfile; if (!($this->fp = fopen($zipfile, "rb"))) { @@ -410,44 +410,44 @@ class ZipReader } } } - + function _read ($nbytes) { - if ($this->fp) { + if ($this->fp) { $chunk = fread($this->fp, $nbytes); if (strlen($chunk) != $nbytes) trigger_error(_("Unexpected EOF in zip file"), E_USER_ERROR); return $chunk; - } elseif ($this->buf) { - if (strlen($this->buf) < $nbytes) - trigger_error(_("Unexpected EOF in zip file"), E_USER_ERROR); - $chunk = substr($this->buf, 0, $nbytes); - $this->buf = substr($this->buf, $nbytes); - return $chunk; - } - } - + } elseif ($this->buf) { + if (strlen($this->buf) < $nbytes) + trigger_error(_("Unexpected EOF in zip file"), E_USER_ERROR); + $chunk = substr($this->buf, 0, $nbytes); + $this->buf = substr($this->buf, $nbytes); + return $chunk; + } + } + function done () { - if ($this->fp) + if ($this->fp) fclose($this->fp); - else - $this->buf = ''; + else + $this->buf = ''; return false; } - + function readFile () { $head = $this->_read(30); // FIXME: This is bad for gzip compressed buffers - + extract(unpack("a4magic/vreq_version/vflags/vcomp_type" . "/vmod_time/vmod_date" . "/Vcrc32/Vcomp_size/Vuncomp_size" . "/vfilename_len/vextrafld_len", $head)); - + if ($magic != ZIP_LOCHEAD_MAGIC) { // maybe gzip? //$x = substr($magic,0,3); if (substr($magic,0,3) == "\037\213\225") - //and (substr($magic,3,1) & 0x3e) == 0) + //and (substr($magic,3,1) & 0x3e) == 0) { if ($this->fp) { fclose($this->fp); @@ -470,15 +470,15 @@ class ZipReader if (($flags & 0x08) != 0) // FIXME: better message? ExitWiki("Postponed CRC not yet supported."); - + $filename = $this->_read($filename_len); //FIXME: we should probably check $req_version. $attrib['mtime'] = dostime2unixtime($mod_date, $mod_time); if ($extrafld_len != 0) $attrib['extra_field'] = $this->_read($extrafld_len); - + $data = $this->_read($comp_size); - + if ($comp_type == ZIP_DEFLATE) { $data = zip_inflate($data, $crc32, $uncomp_size); } @@ -490,11 +490,11 @@ class ZipReader else ExitWiki(sprintf("Compression method %s unsupported", $comp_method)); - + if (strlen($data) != $uncomp_size) ExitWiki(sprintf("Uncompressed size mismatch %d != %d", strlen($data), $uncomp_size)); - + return array($filename, $data, $attrib); } } @@ -549,18 +549,18 @@ function MimeContentTypeHeader ($type, $subtype, $params) return "$header\r\n"; } -function MimeMultipart ($parts) +function MimeMultipart ($parts) { global $mime_multipart_count; - + // The string "=_" can not occur in quoted-printable encoded data. $boundary = "=_multipart_boundary_" . ++$mime_multipart_count; - + $head = MimeContentTypeHeader('multipart', 'mixed', array('boundary' => $boundary)); - + $sep = "\r\n--$boundary\r\n"; - + return $head . $sep . implode($sep, $parts) . "\r\n--${boundary}--\r\n"; } @@ -588,14 +588,14 @@ function MimeMultipart ($parts) function MimeifyPageRevision (&$page, &$revision) { // $wikidb =& $revision->_wikidb; // $page = $wikidb->getPage($revision->getName()); - // FIXME: add 'hits' to $params + // FIXME: add 'hits' to $params $params = array('pagename' => $page->getName(), 'flags' => "", 'author' => $revision->get('author'), 'owner' => $page->getOwner(), 'version' => $revision->getVersion(), 'lastmodified' => $revision->get('mtime')); - + if ($page->get('mtime')) $params['created'] = $page->get('mtime'); if ($page->get('locked')) @@ -615,7 +615,7 @@ function MimeifyPageRevision (&$page, &$revision) { if ($page->get('perm') and class_exists('PagePermission')) { $acl = getPagePermissions($page); $params['acl'] = $acl->asAclLines(); - //TODO: convert to multiple lines? acl-view => groups,...; acl-edit => groups,... + //TODO: convert to multiple lines? acl-view => groups,...; acl-edit => groups,... } $params['charset'] = $GLOBALS['charset']; @@ -624,17 +624,17 @@ function MimeifyPageRevision (&$page, &$revision) { // special handling) --- so we urlencode all parameter values. foreach ($params as $key => $val) $params[$key] = rawurlencode($val); - if (isset($params['acl'])) + if (isset($params['acl'])) // default: "view:_EVERY; edit:_AUTHENTICATED; create:_AUTHENTICATED,_BOGOUSER; ". // "list:_EVERY; remove:_ADMIN,_OWNER; change:_ADMIN,_OWNER; dump:_EVERY; " $params['acl'] = str_replace(array("%3A","%3B%20","%2C"),array(":","; ",","),$params['acl']); - + $out = MimeContentTypeHeader('application', 'x-phpwiki', $params); $out .= sprintf("Content-Transfer-Encoding: %s\r\n", STRICT_MAILABLE_PAGEDUMPS ? 'quoted-printable' : 'binary'); $out .= "\r\n"; - + foreach ($revision->getContent() as $line) { // This is a dirty hack to allow saving binary text files. See above. $line = rtrim($line); @@ -654,7 +654,7 @@ function ParseRFC822Headers (&$string) $headers['from '] = preg_replace('/^\s+|\s+$/', '', $match[1]); $string = substr($string, strlen($match[0])); } - + while (preg_match('/^([!-9;-~]+) [ \t]* : [ \t]* ' . '( .* \r?\n (?: [ \t] .* \r?\n)* )/x', $string, $match)) @@ -663,7 +663,7 @@ function ParseRFC822Headers (&$string) = preg_replace('/^\s+|\s+$/', '', $match[2]); $string = substr($string, strlen($match[0])); } - + if (empty($headers)) return false; @@ -674,7 +674,7 @@ function ParseRFC822Headers (&$string) } $string = substr($string, strlen($match[0])); } - + return $headers; } @@ -682,18 +682,18 @@ function ParseRFC822Headers (&$string) function ParseMimeContentType ($string) { // FIXME: Remove (RFC822 style comments). - + // Get type/subtype if (!preg_match(':^\s*(' . MIME_TOKEN_REGEXP . ')\s*' . '/' . '\s*(' . MIME_TOKEN_REGEXP . ')\s*:x', $string, $match)) ExitWiki(sprintf("Bad %s",'MIME content-type')); - + $type = strtolower($match[1]); $subtype = strtolower($match[2]); $string = substr($string, strlen($match[0])); - + $param = array(); while (preg_match('/^;\s*(' . MIME_TOKEN_REGEXP . ')\s*=\s*' . '(?:(' . MIME_TOKEN_REGEXP . ')|"((?:[^"\\\\]|\\.)*)") \s*/sx', @@ -703,12 +703,12 @@ function ParseMimeContentType ($string) $val = $match[2]; else $val = preg_replace('/[\\\\](.)/s', '\\1', $match[3]); - + $param[strtolower($match[1])] = $val; - + $string = substr($string, strlen($match[0])); } - + return array($type, $subtype, $param); } @@ -716,9 +716,9 @@ function ParseMimeMultipart($data, $boundary) { if (!$boundary) ExitWiki("No boundary?"); - + $boundary = preg_quote($boundary); - + while (preg_match("/^(|.*?\n)--$boundary((?:--)?)[^\n]*\n/s", $data, $match)) { @@ -730,9 +730,9 @@ function ParseMimeMultipart($data, $boundary) for (reset($content); $p = current($content); next($content)) $parts[] = $p; } - + if ($match[2]) - return $parts; // End boundary found. + return $parts; // End boundary found. } ExitWiki("No end boundary?"); } @@ -746,7 +746,7 @@ function GenerateFootnotesFromRefs($params) $footnotes[$m[1]] = sprintf(_("[%d] See [%s]"), $m[1], rawurldecode($reference)); } - + if (sizeof($footnotes) > 0) { ksort($footnotes); return "-----\n" @@ -793,7 +793,7 @@ function ParseMimeifiedPages ($data) return false; } $typeheader = $headers['content-type']; - + if (!(list ($type, $subtype, $params) = ParseMimeContentType($typeheader))) { trigger_error( sprintf("Can't parse %s: (%s)", 'content-type', $typeheader), @@ -808,13 +808,13 @@ function ParseMimeifiedPages ($data) E_USER_WARNING ); return false; } - + // FIXME: more sanity checking? $page = array(); $pagedata = array(); $versiondata = array(); if (isset($headers['date'])) - $pagedata['date'] = strtotime($headers['date']); + $pagedata['date'] = strtotime($headers['date']); //DONE: support owner and acl foreach ($params as $key => $value) { @@ -855,7 +855,7 @@ function ParseMimeifiedPages ($data) break; } } - + // FIXME: do we need to try harder to find a pagename if we // haven't got one yet? if (!isset($versiondata['author'])) { @@ -865,7 +865,7 @@ function ParseMimeifiedPages ($data) $versiondata['author'] = $user->getId(); //FIXME:? } } - + $encoding = strtolower($headers['content-transfer-encoding']); if ($encoding == 'quoted-printable') $data = QuotedPrintableDecode($data); @@ -877,19 +877,19 @@ function ParseMimeifiedPages ($data) // compare to target charset if (strtolower($params['charset']) != strtolower($GLOBALS['charset'])) { - $data = charset_convert($params['charset'], $GLOBALS['charset'], $data); - //$page['pagename'] = charset_convert($params['charset'], $GLOBALS['charset'], $page['pagename']); - if (isset($versiondata['summary'])) - $versiondata['summary'] = charset_convert($params['charset'], $GLOBALS['charset'], $versiondata['summary']); + $data = charset_convert($params['charset'], $GLOBALS['charset'], $data); + //$page['pagename'] = charset_convert($params['charset'], $GLOBALS['charset'], $page['pagename']); + if (isset($versiondata['summary'])) + $versiondata['summary'] = charset_convert($params['charset'], $GLOBALS['charset'], $versiondata['summary']); } - + $data .= GenerateFootnotesFromRefs($params); - + $page['content'] = preg_replace('/[ \t\r]*\n/', "\n", chop($data)); $page['pagedata'] = $pagedata; $page['versiondata'] = $versiondata; - + return array($page); } @@ -899,5 +899,5 @@ function ParseMimeifiedPages ($data) // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/tests/CompatInfo.php b/tests/CompatInfo.php index 238547d37..a99ac58ef 100644 --- a/tests/CompatInfo.php +++ b/tests/CompatInfo.php @@ -47,7 +47,7 @@ $dir = preg_replace('/\/'.basename(dirname(__FILE__)).'$/', '', $dir); $debug = !empty($_GET['debug']); $detail = !empty($_GET['detail']); // echo $dir; -$options = array('file_ext' => array('php'), +$options = array('file_ext' => array('php'), 'ignore_files' => array(__FILE__), 'recurse_dir' => true, 'ignore_functions' => array(), @@ -102,7 +102,7 @@ foreach ($r as $key => $info) { $const = array_shift($info['constants']); } out_row(array($file, $info['version'], $ext, $const)); - + if (is_array($info['extensions']) and sizeof($info['extensions']) >= sizeof($info['constants'])) { foreach ($info['extensions'] as $i => $ext) { @@ -158,5 +158,5 @@ if ($debug) { // c-basic-offset: 4 // c-hanging-comment-ender-p: nil // indent-tabs-mode: nil -// End: +// End: ?> diff --git a/tests/unit_test_backend_cvs.php b/tests/unit_test_backend_cvs.php index 18edbadb6..415a3bc16 100644 --- a/tests/unit_test_backend_cvs.php +++ b/tests/unit_test_backend_cvs.php @@ -24,7 +24,7 @@ require_once( 'lib/WikiDB/backend/cvs.php' ); $db_params = array(); /** - * These are the parameters required by the backend. + * These are the parameters required by the backend. */ $db_params[CVS_PAGE_SOURCE] = "../pgsrc"; $db_params[CVS_CHECK_FOR_REPOSITORY] = true; @@ -44,12 +44,12 @@ $d = opendir( $db_params[CVS_PAGE_SOURCE] ); while ( $entry = readdir( $d ) ) { exec( "grep 'Checking in $entry' " . $db_params[CVS_DEBUG_FILE], $cmdOutput, $cmdRetval ); - + if ( !is_dir( $db_params[CVS_PAGE_SOURCE] . "/" . $entry )) { $allPageNames[] = $entry; - + if ( $cmdRetval ) { - print "*** Error: [$entry] was not checked in -- view " + print "*** Error: [$entry] was not checked in -- view " . $db_params[CVS_DEBUG_FILE] . " for details\n"; $REMOVE_DEBUG = false; } @@ -60,7 +60,7 @@ closedir( $d ); // // Check that the meta data files were created // -function get_pagedata( $page_name, $key, &$cvsdb ) +function get_pagedata( $page_name, $key, &$cvsdb ) { global $REMOVE_DEBUG; $pageHash = $cvsdb->get_pagedata( $page_name ); diff --git a/uploads/index.php b/uploads/index.php index af6be592e..81c8c3d8d 100644 --- a/uploads/index.php +++ b/uploads/index.php @@ -1,4 +1,4 @@ - -- 2.45.0