diff options
185 files changed, 8366 insertions, 6933 deletions
diff --git a/_cs/DokuWiki/Sniffs/Functions/OpeningFunctionBraceSniff.php b/_cs/DokuWiki/Sniffs/Functions/OpeningFunctionBraceSniff.php deleted file mode 100644 index 6c582b3af..000000000 --- a/_cs/DokuWiki/Sniffs/Functions/OpeningFunctionBraceSniff.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php -/** - * Generic_Sniffs_Functions_OpeningFunctionBraceKernighanRitchieSniff. - */ - -class DokuWiki_Sniffs_Functions_OpeningFunctionBraceSniff implements PHP_CodeSniffer_Sniff { - - - /** - * Registers the tokens that this sniff wants to listen for. - * - * @return void - */ - public function register() - { - return array(T_FUNCTION); - - }//end register() - - - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token in the - * stack passed in $tokens. - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); - - if (isset($tokens[$stackPtr]['scope_opener']) === false) { - return; - } - - $openingBrace = $tokens[$stackPtr]['scope_opener']; - - // The end of the function occurs at the end of the argument list. Its - // like this because some people like to break long function declarations - // over multiple lines. - $functionLine = $tokens[$tokens[$stackPtr]['parenthesis_closer']]['line']; - $braceLine = $tokens[$openingBrace]['line']; - - $lineDifference = ($braceLine - $functionLine); - - if ($lineDifference > 0) { - $error = 'Opening brace should be on the same line as the declaration'; - $phpcsFile->addError($error, $openingBrace); - return; - } - - // Checks that the closing parenthesis and the opening brace are - // separated by a whitespace character. - $closerColumn = $tokens[$tokens[$stackPtr]['parenthesis_closer']]['column']; - $braceColumn = $tokens[$openingBrace]['column']; - - $columnDifference = ($braceColumn - $closerColumn); - - if ($columnDifference > 2) { - $error = 'Expected 0 or 1 space between the closing parenthesis and the opening brace; found '.($columnDifference - 1).'.'; - $phpcsFile->addError($error, $openingBrace); - return; - } - - // Check that a tab was not used instead of a space. - $spaceTokenPtr = ($tokens[$stackPtr]['parenthesis_closer'] + 1); - $spaceContent = $tokens[$spaceTokenPtr]['content']; - if ($columnDifference == 2 && $spaceContent !== ' ') { - $error = 'Expected a none or a single space character between closing parenthesis and opening brace; found "'.$spaceContent.'".'; - $phpcsFile->addError($error, $openingBrace); - return; - } - - }//end process() - - -}//end class - -?> diff --git a/_cs/DokuWiki/Sniffs/NamingConventions/ConstructorNameSniff.php b/_cs/DokuWiki/Sniffs/NamingConventions/ConstructorNameSniff.php deleted file mode 100644 index 7dd6d9366..000000000 --- a/_cs/DokuWiki/Sniffs/NamingConventions/ConstructorNameSniff.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php -/** - * Generic_Sniffs_NamingConventions_ConstructorNameSniff. - * - * PHP version 5 - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood <gsherwood@squiz.net> - * @author Leif Wickland <lwickland@rightnow.com> - * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer - */ - -if (class_exists('PHP_CodeSniffer_Standards_AbstractScopeSniff', true) === false) { - $error = 'Class PHP_CodeSniffer_Standards_AbstractScopeSniff not found'; - throw new PHP_CodeSniffer_Exception($error); -} - -/** - * Generic_Sniffs_NamingConventions_ConstructorNameSniff. - * - * Favor PHP 5 constructor syntax, which uses "function __construct()". - * Avoid PHP 4 constructor syntax, which uses "function ClassName()". - * - * @category PHP - * @package PHP_CodeSniffer - * @author Leif Wickland <lwickland@rightnow.com> - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.3.3 - * @link http://pear.php.net/package/PHP_CodeSniffer - */ -class DokuWiki_Sniffs_NamingConventions_ConstructorNameSniff extends Generic_Sniffs_NamingConventions_ConstructorNameSniff -{ - /** - * Processes this test when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The current file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * @param int $currScope A pointer to the start of the scope. - * - * @return void - */ - protected function processTokenWithinScope( - PHP_CodeSniffer_File $phpcsFile, - $stackPtr, - $currScope - ) { - $className = $phpcsFile->getDeclarationName($currScope); - $methodName = $phpcsFile->getDeclarationName($stackPtr); - - if (strcasecmp($methodName, $className) === 0) { - $error = 'PHP4 style constructors are discouraged; use "__construct()" instead'; - $phpcsFile->addWarning($error, $stackPtr, 'OldStyle'); - } else if (strcasecmp($methodName, '__construct') !== 0) { - // Not a constructor. - return; - } - - $tokens = $phpcsFile->getTokens(); - - $parentClassName = $phpcsFile->findExtendedClassName($currScope); - if ($parentClassName === false) { - return; - } - - $endFunctionIndex = $tokens[$stackPtr]['scope_closer']; - $startIndex = $stackPtr; - while ($doubleColonIndex = $phpcsFile->findNext(array(T_DOUBLE_COLON), $startIndex, $endFunctionIndex)) { - if ($tokens[($doubleColonIndex + 1)]['code'] === T_STRING - && $tokens[($doubleColonIndex + 1)]['content'] === $parentClassName - ) { - $error = 'PHP4 style calls to parent constructors are discouraged; use "parent::__construct()" instead'; - $phpcsFile->addWarning($error, ($doubleColonIndex + 1), 'OldStyleCall'); - } - - $startIndex = ($doubleColonIndex + 1); - } - - }//end processTokenWithinScope() - - -}//end class diff --git a/_cs/DokuWiki/Sniffs/PHP/DeprecatedFunctionsSniff.php b/_cs/DokuWiki/Sniffs/PHP/DeprecatedFunctionsSniff.php deleted file mode 100644 index c15a5be02..000000000 --- a/_cs/DokuWiki/Sniffs/PHP/DeprecatedFunctionsSniff.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * DokuWiki_Sniffs_PHP_DiscouragedFunctionsSniff. - * - * PHP version 5 - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood <gsherwood@squiz.net> - * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version CVS: $Id: DiscouragedFunctionsSniff.php 265110 2008-08-19 06:36:11Z squiz $ - * @link http://pear.php.net/package/PHP_CodeSniffer - */ - -if (class_exists('Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true) === false) { - throw new PHP_CodeSniffer_Exception('Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found'); -} - -/** - * DokuWiki_Sniffs_PHP_DiscouragedFunctionsSniff. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood <gsherwood@squiz.net> - * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.2.2 - * @link http://pear.php.net/package/PHP_CodeSniffer - */ -class DokuWiki_Sniffs_PHP_DeprecatedFunctionsSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff -{ - - /** - * A list of forbidden functions with their alternatives. - * - * The value is NULL if no alternative exists. IE, the - * function should just not be used. - * - * @var array(string => string|null) - */ - public $forbiddenFunctions = array( - 'setCorrectLocale' => null, - 'html_attbuild' => 'buildAttributes', - 'io_runcmd' => null, - 'p_wiki_xhtml_summary' => 'p_cached_output', - 'search_callback' => 'call_user_func_array', - 'search_backlinks' => 'ft_backlinks', - 'search_fulltext' => 'Fulltext Indexer', - 'search_regex' => 'Fulltext Indexer', - 'tpl_getFavicon' => 'tpl_getMediaFile', - 'p_cached_xhtml' => 'p_cached_output', - ); - - /** - * If true, an error will be thrown; otherwise a warning. - * - * @var bool - */ - public $error = true; - -}//end class diff --git a/_cs/DokuWiki/Sniffs/PHP/DiscouragedFunctionsSniff.php b/_cs/DokuWiki/Sniffs/PHP/DiscouragedFunctionsSniff.php deleted file mode 100644 index bd51b1166..000000000 --- a/_cs/DokuWiki/Sniffs/PHP/DiscouragedFunctionsSniff.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * DokuWiki_Sniffs_PHP_DiscouragedFunctionsSniff. - * - * PHP version 5 - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood <gsherwood@squiz.net> - * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version CVS: $Id: DiscouragedFunctionsSniff.php 265110 2008-08-19 06:36:11Z squiz $ - * @link http://pear.php.net/package/PHP_CodeSniffer - */ - -if (class_exists('Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true) === false) { - throw new PHP_CodeSniffer_Exception('Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found'); -} - -/** - * DokuWiki_Sniffs_PHP_DiscouragedFunctionsSniff. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood <gsherwood@squiz.net> - * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.2.2 - * @link http://pear.php.net/package/PHP_CodeSniffer - */ -class DokuWiki_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff -{ - - /** - * A list of forbidden functions with their alternatives. - * - * The value is NULL if no alternative exists. IE, the - * function should just not be used. - * - * @var array(string => string|null) - */ - public $forbiddenFunctions = array( - 'date' => 'dformat', - 'strftime' => 'dformat', - ); - - /** - * If true, an error will be thrown; otherwise a warning. - * - * @var bool - */ - public $error = false; - -}//end class diff --git a/_cs/DokuWiki/Sniffs/WhiteSpace/ScopeIndentSniff.php b/_cs/DokuWiki/Sniffs/WhiteSpace/ScopeIndentSniff.php deleted file mode 100644 index 72064bda0..000000000 --- a/_cs/DokuWiki/Sniffs/WhiteSpace/ScopeIndentSniff.php +++ /dev/null @@ -1,319 +0,0 @@ -<?php -/** - * DokuWiki_Sniffs_Whitespace_ScopeIndentSniff based on - * Generic_Sniffs_Whitespace_ScopeIndentSniff. - * - * PHP version 5 - * - * @category PHP - * @package PHP_CodeSniffer - * @author Andreas Gohr <andi@splitbrain.org> - * @author Greg Sherwood <gsherwood@squiz.net> - * @author Marc McIntyre <mmcintyre@squiz.net> - * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version CVS: $Id: ScopeIndentSniff.php 270281 2008-12-02 02:38:34Z squiz $ - * @link http://pear.php.net/package/PHP_CodeSniffer - */ - -/** - * Generic_Sniffs_Whitespace_ScopeIndentSniff. - * - * Checks that control structures are structured correctly, and their content - * is indented correctly. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood <gsherwood@squiz.net> - * @author Marc McIntyre <mmcintyre@squiz.net> - * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.2.0 - * @link http://pear.php.net/package/PHP_CodeSniffer - */ -class DokuWiki_Sniffs_WhiteSpace_ScopeIndentSniff implements PHP_CodeSniffer_Sniff -{ - - /** - * The number of spaces code should be indented. - * - * @var int - */ - protected $indent = 4; - - /** - * Does the indent need to be exactly right. - * - * If TRUE, indent needs to be exactly $ident spaces. If FALSE, - * indent needs to be at least $ident spaces (but can be more). - * - * @var bool - */ - protected $exact = false; - - /** - * Any scope openers that should not cause an indent. - * - * @var array(int) - */ - protected $nonIndentingScopes = array(); - - - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() - { - return PHP_CodeSniffer_Tokens::$scopeOpeners; - - }//end register() - - - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile All the tokens found in the document. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); - - // If this is an inline condition (ie. there is no scope opener), then - // return, as this is not a new scope. - if (isset($tokens[$stackPtr]['scope_opener']) === false) { - return; - } - - if ($tokens[$stackPtr]['code'] === T_ELSE) { - $next = $phpcsFile->findNext( - PHP_CodeSniffer_Tokens::$emptyTokens, - ($stackPtr + 1), - null, - true - ); - - // We will handle the T_IF token in another call to process. - if ($tokens[$next]['code'] === T_IF) { - return; - } - } - - // Find the first token on this line. - $firstToken = $stackPtr; - for ($i = $stackPtr; $i >= 0; $i--) { - // Record the first code token on the line. - if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$emptyTokens) === false) { - $firstToken = $i; - } - - // It's the start of the line, so we've found our first php token. - if ($tokens[$i]['column'] === 1) { - break; - } - } - - // Based on the conditions that surround this token, determine the - // indent that we expect this current content to be. - $expectedIndent = $this->calculateExpectedIndent($tokens, $firstToken); - - if ($tokens[$firstToken]['column'] !== $expectedIndent) { - if($this->exact || $tokens[$firstToken]['column'] < $expectedIndent){ - $error = 'Line indented incorrectly; expected '; - $error .= ($expectedIndent - 1).' spaces, found '; - $error .= ($tokens[$firstToken]['column'] - 1); - $phpcsFile->addError($error, $stackPtr); - }elseif((($tokens[$firstToken]['column'] - 1) % $this->indent)){ - $error = 'Line indented not by multiple of '.$this->indent.'; expected '; - $error .= ($expectedIndent - 1).' spaces, found '; - $error .= ($tokens[$firstToken]['column'] - 1); - $phpcsFile->addError($error, $stackPtr); - } - } - - $scopeOpener = $tokens[$stackPtr]['scope_opener']; - $scopeCloser = $tokens[$stackPtr]['scope_closer']; - - // Some scopes are expected not to have indents. - if (in_array($tokens[$firstToken]['code'], $this->nonIndentingScopes) === false) { - $indent = ($expectedIndent + $this->indent); - } else { - $indent = $expectedIndent; - } - - $newline = false; - $commentOpen = false; - $inHereDoc = false; - - // Only loop over the content beween the opening and closing brace, not - // the braces themselves. - for ($i = ($scopeOpener + 1); $i < $scopeCloser; $i++) { - - // If this token is another scope, skip it as it will be handled by - // another call to this sniff. - if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$scopeOpeners) === true) { - if (isset($tokens[$i]['scope_opener']) === true) { - $i = $tokens[$i]['scope_closer']; - } else { - // If this token does not have a scope_opener indice, then - // it's probably an inline scope, so let's skip to the next - // semicolon. Inline scopes include inline if's, abstract - // methods etc. - $nextToken = $phpcsFile->findNext(T_SEMICOLON, $i, $scopeCloser); - if ($nextToken !== false) { - $i = $nextToken; - } - } - - continue; - } - - // If this is a HEREDOC then we need to ignore it as the - // whitespace before the contents within the HEREDOC are - // considered part of the content. - if ($tokens[$i]['code'] === T_START_HEREDOC) { - $inHereDoc = true; - continue; - } else if ($inHereDoc === true) { - if ($tokens[$i]['code'] === T_END_HEREDOC) { - $inHereDoc = false; - } - - continue; - } - - if ($tokens[$i]['column'] === 1) { - // We started a newline. - $newline = true; - } - - if ($newline === true && $tokens[$i]['code'] !== T_WHITESPACE) { - // If we started a newline and we find a token that is not - // whitespace, then this must be the first token on the line that - // must be indented. - $newline = false; - $firstToken = $i; - - $column = $tokens[$firstToken]['column']; - - // Special case for non-PHP code. - if ($tokens[$firstToken]['code'] === T_INLINE_HTML) { - $trimmedContentLength - = strlen(ltrim($tokens[$firstToken]['content'])); - if ($trimmedContentLength === 0) { - continue; - } - - $contentLength = strlen($tokens[$firstToken]['content']); - $column = ($contentLength - $trimmedContentLength + 1); - } - - // Check to see if this constant string spans multiple lines. - // If so, then make sure that the strings on lines other than the - // first line are indented appropriately, based on their whitespace. - if (in_array($tokens[$firstToken]['code'], PHP_CodeSniffer_Tokens::$stringTokens) === true) { - if (in_array($tokens[($firstToken - 1)]['code'], PHP_CodeSniffer_Tokens::$stringTokens) === true) { - // If we find a string that directly follows another string - // then its just a string that spans multiple lines, so we - // don't need to check for indenting. - continue; - } - } - - // This is a special condition for T_DOC_COMMENT and C-style - // comments, which contain whitespace between each line. - $comments = array( - T_COMMENT, - T_DOC_COMMENT - ); - - if (in_array($tokens[$firstToken]['code'], $comments) === true) { - $content = trim($tokens[$firstToken]['content']); - if (preg_match('|^/\*|', $content) !== 0) { - // Check to see if the end of the comment is on the same line - // as the start of the comment. If it is, then we don't - // have to worry about opening a comment. - if (preg_match('|\*/$|', $content) === 0) { - // We don't have to calculate the column for the - // start of the comment as there is a whitespace - // token before it. - $commentOpen = true; - } - } else if ($commentOpen === true) { - if ($content === '') { - // We are in a comment, but this line has nothing on it - // so let's skip it. - continue; - } - - $contentLength = strlen($tokens[$firstToken]['content']); - $trimmedContentLength - = strlen(ltrim($tokens[$firstToken]['content'])); - - $column = ($contentLength - $trimmedContentLength + 1); - if (preg_match('|\*/$|', $content) !== 0) { - $commentOpen = false; - } - }//end if - }//end if - - // The token at the start of the line, needs to have its' column - // greater than the relative indent we set above. If it is less, - // an error should be shown. - if ($column !== $indent) { - if ($this->exact === true || $column < $indent) { - $error = 'Line indented incorrectly; expected '; - if ($this->exact === false) { - $error .= 'at least '; - } - - $error .= ($indent - 1).' spaces, found '; - $error .= ($column - 1); - $phpcsFile->addError($error, $firstToken); - } - } - }//end if - }//end for - - }//end process() - - - /** - * Calculates the expected indent of a token. - * - * @param array $tokens The stack of tokens for this file. - * @param int $stackPtr The position of the token to get indent for. - * - * @return int - */ - protected function calculateExpectedIndent(array $tokens, $stackPtr) - { - $conditionStack = array(); - - // Empty conditions array (top level structure). - if (empty($tokens[$stackPtr]['conditions']) === true) { - return 1; - } - - $tokenConditions = $tokens[$stackPtr]['conditions']; - foreach ($tokenConditions as $id => $condition) { - // If it's an indenting scope ie. it's not in our array of - // scopes that don't indent, add it to our condition stack. - if (in_array($condition, $this->nonIndentingScopes) === false) { - $conditionStack[$id] = $condition; - } - } - - return ((count($conditionStack) * $this->indent) + 1); - - }//end calculateExpectedIndent() - - -}//end class - -?> diff --git a/_cs/DokuWiki/ruleset.xml b/_cs/DokuWiki/ruleset.xml deleted file mode 100644 index 3ee7fb667..000000000 --- a/_cs/DokuWiki/ruleset.xml +++ /dev/null @@ -1,69 +0,0 @@ -<?xml version="1.0"?> -<ruleset name="DokuWiki"> - <description>DokuWiki Coding Standard</description> - - <!-- ignore 3rd party libraries (that we haven't adopted) --> - <exclude-pattern>*/inc/blowfish.php</exclude-pattern> - <exclude-pattern>*/inc/lessc.inc.php</exclude-pattern> - <exclude-pattern>*/inc/phpseclib/*</exclude-pattern> - <exclude-pattern>*/lib/plugins/authad/adLDAP/*</exclude-pattern> - <exclude-pattern>*/lib/scripts/fileuploader.js</exclude-pattern> - <exclude-pattern>*/lib/scripts/jquery/*</exclude-pattern> - <exclude-pattern>*/EmailAddressValidator.php</exclude-pattern> - <exclude-pattern>*/feedcreator.class.php</exclude-pattern> - <exclude-pattern>*/SimplePie.php</exclude-pattern> - <exclude-pattern>*/geshi.php</exclude-pattern> - <exclude-pattern>*/geshi/*</exclude-pattern> - <exclude-pattern>*/JSON.php</exclude-pattern> - - <!-- ignore devel only parts --> - <exclude-pattern>*/_test/*</exclude-pattern> - <exclude-pattern>*/_cs/*</exclude-pattern> - - <rule ref="Generic.Classes.DuplicateClassName" /> - <rule ref="Generic.CodeAnalysis.JumbledIncrementer" /> - <rule ref="Generic.CodeAnalysis.UnnecessaryFinalModifier" /> - <rule ref="Generic.CodeAnalysis.UnconditionalIfStatement" /> - <rule ref="Generic.CodeAnalysis.ForLoopShouldBeWhileLoop" /> - <rule ref="Generic.CodeAnalysis.ForLoopWithTestFunctionCall" /> - <rule ref="Generic.CodeAnalysis.UnusedFunctionParameter" /> - <rule ref="Generic.CodeAnalysis.EmptyStatement" /> - <rule ref="Generic.CodeAnalysis.UselessOverridingMethod" /> - <rule ref="Generic.Commenting.Todo" /> - <rule ref="Generic.Files.ByteOrderMark" /> - <rule ref="Generic.Files.LineEndings" /> - <rule ref="Generic.Formatting.DisallowMultipleStatements" /> - <rule ref="Generic.Metrics.NestingLevel"> - <properties> - <property name="nestingLevel" value="6" /> - </properties> - </rule> - <rule ref="Generic.NamingConventions.UpperCaseConstantName" /> - <rule ref="Generic.PHP.LowerCaseConstant" /> - <rule ref="Generic.PHP.DeprecatedFunctions.php" /> - <rule ref="Generic.PHP.DisallowShortOpenTag" /> - <rule ref="Generic.PHP.ForbiddenFunctions" /> - <rule ref="Generic.WhiteSpace.DisallowTabIndent" /> - <rule ref="Generic.Classes.DuplicateClassName" /> - <rule ref="Generic.Functions.CallTimePassByReference" /> - <rule ref="Zend.Files.ClosingTag" /> - <rule ref="PEAR.Functions.ValidDefaultValue" /> - <rule ref="Squiz.PHP.Eval" /> - <rule ref="Squiz.WhiteSpace.SuperfluousWhitespace" /> - <rule ref="Squiz.CSS.LowercaseStyleDefinition" /> - <rule ref="Squiz.CSS.MissingColon" /> - <rule ref="Squiz.CSS.DisallowMultipleStyleDefinitions" /> - <rule ref="Squiz.CSS.ColonSpacing" /> - <rule ref="Squiz.CSS.ClassDefinitionClosingBraceSpace" /> - <rule ref="Squiz.CSS.SemicolonSpacing" /> - <rule ref="Squiz.CSS.Indentation" /> - <rule ref="Squiz.CSS.EmptyClassDefinition" /> - <rule ref="Squiz.CSS.ClassDefinitionNameSpacing" /> - <rule ref="Squiz.CSS.EmptyStyleDefinition" /> - <rule ref="Squiz.CSS.Opacity" /> - <rule ref="Squiz.CSS.ColourDefinition" /> - <rule ref="Squiz.CSS.DuplicateClassDefinition" /> - <rule ref="Squiz.CSS.ClassDefinitionOpeningBraceSpace" /> - <rule ref="Squiz.Commenting.DocCommentAlignment" /> - -</ruleset> diff --git a/_cs/README b/_cs/README deleted file mode 100644 index 7aac73161..000000000 --- a/_cs/README +++ /dev/null @@ -1,18 +0,0 @@ -This directory contains the Coding Standard tests to be used with PHP -CodeSniffer on DokuWiki's code. - -1. Install PHP CodeSniffer: - - #> pear install PHP_CodeSniffer - -2. Link the Coding Standard to the CodeSniffer directory: - - #> ln -s /path/to/dokuwiki/_cs/DokuWiki /usr/share/pear/PHP/CodeSniffer/Standards/DokuWiki - -3. Set DokuWiki to be the default standard: - - #> phpcs --config-set default_standard DokuWiki - - - -The coding standard is work in progress. diff --git a/_test/core/DokuWikiTest.php b/_test/core/DokuWikiTest.php index dbaf29eda..8935e0d01 100644 --- a/_test/core/DokuWikiTest.php +++ b/_test/core/DokuWikiTest.php @@ -191,4 +191,41 @@ abstract class DokuWikiTest extends PHPUnit_Framework_TestCase { $method->setAccessible(true); return $method->invokeArgs($obj, $args); } + + /** + * Allow for reading inaccessible properties (private or protected) + * + * This makes it easier to check internals of tested objects. This should generally + * be avoided. + * + * @param object $obj Object on which to access the property + * @param string $prop name of the property to access + * @return mixed + * @throws ReflectionException when the given obj/prop does not exist + */ + protected static function getInaccessibleProperty($obj, $prop) { + $class = new \ReflectionClass($obj); + $property = $class->getProperty($prop); + $property->setAccessible(true); + return $property->getValue($obj); + } + + /** + * Allow for reading inaccessible properties (private or protected) + * + * This makes it easier to set internals of tested objects. This should generally + * be avoided. + * + * @param object $obj Object on which to access the property + * @param string $prop name of the property to access + * @param mixed $value new value to set the property to + * @return void + * @throws ReflectionException when the given obj/prop does not exist + */ + protected static function setInaccessibleProperty($obj, $prop, $value) { + $class = new \ReflectionClass($obj); + $property = $class->getProperty($prop); + $property->setAccessible(true); + $property->setValue($obj, $value); + } } diff --git a/_test/mock/DokuWiki_Auth_Plugin.php b/_test/mock/DokuWiki_Auth_Plugin.php new file mode 100644 index 000000000..9014b020f --- /dev/null +++ b/_test/mock/DokuWiki_Auth_Plugin.php @@ -0,0 +1,10 @@ +<?php + +namespace dokuwiki\test\mock; + +/** + * Class DokuWiki_Auth_Plugin + */ +class DokuWiki_Auth_Plugin extends \DokuWiki_Auth_Plugin { + +} diff --git a/_test/mock/Doku_Renderer.php b/_test/mock/Doku_Renderer.php new file mode 100644 index 000000000..350346101 --- /dev/null +++ b/_test/mock/Doku_Renderer.php @@ -0,0 +1,11 @@ +<?php + +namespace dokuwiki\test\mock; + +class Doku_Renderer extends \Doku_Renderer { + + /** @inheritdoc */ + public function getFormat() { + return 'none'; + } +} diff --git a/_test/phpcs.xml b/_test/phpcs.xml new file mode 100644 index 000000000..f9fbe985d --- /dev/null +++ b/_test/phpcs.xml @@ -0,0 +1,75 @@ +<?xml version="1.0"?> +<ruleset name="DokuWiki Coding Standard Standard" namespace="DokuWiki\CS\Standard"> + <description>Coding Standard used for DokuWiki</description> + + <!-- default config --> + <arg name="colors"/> + <arg value="sp"/> + <arg name="extensions" value="php"/> + + <!-- where to look --> + <file>../inc</file> + <file>../lib</file> + <file>../bin</file> + <file>../doku.php</file> + <file>../index.php</file> + <file>../feed.php</file> + <file>../install.php</file> + + <!-- skip these completely --> + <exclude-pattern>*/lang/*/lang.php</exclude-pattern> + <exclude-pattern>*/lang/*/settings.php</exclude-pattern> + <exclude-pattern>*/_test/*</exclude-pattern> + + <!-- 3rd party libs, these should be moved to composer some day --> + <exclude-pattern>*/inc/DifferenceEngine.php</exclude-pattern> + <exclude-pattern>*/inc/IXR_Library.php</exclude-pattern> + <exclude-pattern>*/inc/JSON.php</exclude-pattern> + <exclude-pattern>*/inc/JpegMeta.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/authad/adLDAP</exclude-pattern> + + <!-- rules on top of PSR-2 --> + <rule ref="PSR2"> + <!-- the following rule is not in PSR-2 and breaks the guardian pattern --> + <exclude name="Generic.ControlStructures.InlineControlStructure.NotAllowed"/> + + <!-- we have lots of legacy classes without name spaces --> + <exclude name="PSR1.Classes.ClassDeclaration.MissingNamespace"/> + </rule> + + <!-- disable some rules for certain paths, for legacy support --> + <rule ref="Squiz.Classes.ValidClassName.NotCamelCaps"> + <exclude-pattern>*/inc/parser/*</exclude-pattern> + + <exclude-pattern>*/inc/Plugin.php</exclude-pattern> + <exclude-pattern>*/inc/PluginInterface.php</exclude-pattern> + + <exclude-pattern>*/lib/plugins/*.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/action.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/action/*.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/admin.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/admin/*.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/auth.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/auth/*.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/cli.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/cli/*.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/helper.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/helper/*.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/remote.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/remote/*.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/syntax.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/syntax/*.php</exclude-pattern> + </rule> + + <!-- underscore skips exposing public methods to remote api --> + <rule ref="PSR2.Methods.MethodDeclaration.Underscore"> + <exclude-pattern>*/lib/plugins/remote.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/remote.php</exclude-pattern> + <exclude-pattern>*/lib/plugins/*/remote/*.php</exclude-pattern> + </rule> + + <rule ref="PSR1.Methods.CamelCapsMethodName.NotCamelCaps"> + <exclude-pattern>*/inc/parser/*</exclude-pattern> + </rule> + +</ruleset> diff --git a/_test/tests/inc/auth_aclcheck.test.php b/_test/tests/inc/auth_aclcheck.test.php index 8c9b37536..4f1103ff2 100644 --- a/_test/tests/inc/auth_aclcheck.test.php +++ b/_test/tests/inc/auth_aclcheck.test.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\test\mock\DokuWiki_Auth_Plugin; + class auth_acl_test extends DokuWikiTest { protected $oldAuthAcl; diff --git a/_test/tests/inc/auth_admincheck.test.php b/_test/tests/inc/auth_admincheck.test.php index 087be3810..c4aa78ce5 100644 --- a/_test/tests/inc/auth_admincheck.test.php +++ b/_test/tests/inc/auth_admincheck.test.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\test\mock\DokuWiki_Auth_Plugin; + class auth_admin_test_AuthInSensitive extends DokuWiki_Auth_Plugin { function isCaseSensitive(){ return false; diff --git a/_test/tests/inc/httpclient_http.test.php b/_test/tests/inc/httpclient_http.test.php index 3061f7e33..80ef2793b 100644 --- a/_test/tests/inc/httpclient_http.test.php +++ b/_test/tests/inc/httpclient_http.test.php @@ -301,6 +301,9 @@ class httpclient_http_test extends DokuWikiTest { $this->assertTrue($data !== false, $http->errorInfo()); } + /** + * @throws ReflectionException + */ function test_postencode(){ $http = new HTTPMockClient(); @@ -312,7 +315,7 @@ class httpclient_http_test extends DokuWikiTest { ); $this->assertEquals( '%C3%B6%C3%A4%3F=%C3%B6%C3%A4%3F&foo=bang', - $http->_postEncode($data), + $this->callInaccessibleMethod($http, '_postEncode', [$data]), 'simple' ); @@ -323,7 +326,7 @@ class httpclient_http_test extends DokuWikiTest { ); $this->assertEquals( 'foo=bang&%C3%A4rr%5B0%5D=%C3%B6&%C3%A4rr%5B1%5D=b&%C3%A4rr%5B2%5D=c', - $http->_postEncode($data), + $this->callInaccessibleMethod($http, '_postEncode', [$data]), 'onelevelnum' ); @@ -334,7 +337,7 @@ class httpclient_http_test extends DokuWikiTest { ); $this->assertEquals( 'foo=bang&%C3%A4rr%5B%C3%B6%5D=%C3%A4&%C3%A4rr%5Bb%5D=c', - $http->_postEncode($data), + $this->callInaccessibleMethod($http, '_postEncode', [$data]), 'onelevelassoc' ); @@ -346,7 +349,7 @@ class httpclient_http_test extends DokuWikiTest { ); $this->assertEquals( 'foo=bang&%C3%A4rr%5B%C3%B6%5D=%C3%A4&%C3%A4rr%5B%C3%A4%5D%5B%C3%B6%5D=%C3%A4', - $http->_postEncode($data), + $this->callInaccessibleMethod($http, '_postEncode', [$data]), 'twolevelassoc' ); } diff --git a/_test/tests/inc/pageutils_findnearest.test.php b/_test/tests/inc/pageutils_findnearest.test.php index c2815a06c..6aa6d449c 100644 --- a/_test/tests/inc/pageutils_findnearest.test.php +++ b/_test/tests/inc/pageutils_findnearest.test.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\test\mock\DokuWiki_Auth_Plugin; + class pageutils_findnearest_test extends DokuWikiTest { protected $oldAuthAcl; diff --git a/_test/tests/inc/parser/lexer.test.php b/_test/tests/inc/parser/lexer.test.php index 50b6548a4..412bee75b 100644 --- a/_test/tests/inc/parser/lexer.test.php +++ b/_test/tests/inc/parser/lexer.test.php @@ -5,10 +5,9 @@ * @subpackage Tests */ -/** -* Includes -*/ -require_once DOKU_INC . 'inc/parser/lexer.php'; +use dokuwiki\Parsing\Lexer\Lexer; +use dokuwiki\Parsing\Lexer\ParallelRegex; +use dokuwiki\Parsing\Lexer\StateStack; /** * @package Doku @@ -17,24 +16,24 @@ require_once DOKU_INC . 'inc/parser/lexer.php'; class TestOfLexerParallelRegex extends DokuWikiTest { function testNoPatterns() { - $regex = new Doku_LexerParallelRegex(false); + $regex = new ParallelRegex(false); $this->assertFalse($regex->match("Hello", $match)); $this->assertEquals($match, ""); } function testNoSubject() { - $regex = new Doku_LexerParallelRegex(false); + $regex = new ParallelRegex(false); $regex->addPattern(".*"); $this->assertTrue($regex->match("", $match)); $this->assertEquals($match, ""); } function testMatchAll() { - $regex = new Doku_LexerParallelRegex(false); + $regex = new ParallelRegex(false); $regex->addPattern(".*"); $this->assertTrue($regex->match("Hello", $match)); $this->assertEquals($match, "Hello"); } function testCaseSensitive() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("abc"); $this->assertTrue($regex->match("abcdef", $match)); $this->assertEquals($match, "abc"); @@ -42,7 +41,7 @@ class TestOfLexerParallelRegex extends DokuWikiTest { $this->assertEquals($match, "abc"); } function testCaseInsensitive() { - $regex = new Doku_LexerParallelRegex(false); + $regex = new ParallelRegex(false); $regex->addPattern("abc"); $this->assertTrue($regex->match("abcdef", $match)); $this->assertEquals($match, "abc"); @@ -50,7 +49,7 @@ class TestOfLexerParallelRegex extends DokuWikiTest { $this->assertEquals($match, "ABC"); } function testMatchMultiple() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("abc"); $regex->addPattern("ABC"); $this->assertTrue($regex->match("abcdef", $match)); @@ -60,7 +59,7 @@ class TestOfLexerParallelRegex extends DokuWikiTest { $this->assertFalse($regex->match("Hello", $match)); } function testPatternLabels() { - $regex = new Doku_LexerParallelRegex(false); + $regex = new ParallelRegex(false); $regex->addPattern("abc", "letter"); $regex->addPattern("123", "number"); $this->assertEquals($regex->match("abcdef", $match), "letter"); @@ -69,7 +68,7 @@ class TestOfLexerParallelRegex extends DokuWikiTest { $this->assertEquals($match, "123"); } function testMatchMultipleWithLookaheadNot() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("abc"); $regex->addPattern("ABC"); $regex->addPattern("a(?!\n).{1}"); @@ -82,37 +81,37 @@ class TestOfLexerParallelRegex extends DokuWikiTest { $this->assertFalse($regex->match("Hello", $match)); } function testMatchSetOptionCaseless() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("a(?i)b(?i)c"); $this->assertTrue($regex->match("aBc", $match)); $this->assertEquals($match, "aBc"); } function testMatchSetOptionUngreedy() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("(?U)\w+"); $this->assertTrue($regex->match("aaaaaa", $match)); $this->assertEquals($match, "a"); } function testMatchLookaheadEqual() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("\w(?=c)"); $this->assertTrue($regex->match("xbyczd", $match)); $this->assertEquals($match, "y"); } function testMatchLookaheadNot() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("\w(?!b|c)"); $this->assertTrue($regex->match("xbyczd", $match)); $this->assertEquals($match, "b"); } function testMatchLookbehindEqual() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("(?<=c)\w"); $this->assertTrue($regex->match("xbyczd", $match)); $this->assertEquals($match, "z"); } function testMatchLookbehindNot() { - $regex = new Doku_LexerParallelRegex(true); + $regex = new ParallelRegex(true); $regex->addPattern("(?<!\A|x|b)\w"); $this->assertTrue($regex->match("xbyczd", $match)); $this->assertEquals($match, "c"); @@ -122,15 +121,15 @@ class TestOfLexerParallelRegex extends DokuWikiTest { class TestOfLexerStateStack extends DokuWikiTest { function testStartState() { - $stack = new Doku_LexerStateStack("one"); + $stack = new StateStack("one"); $this->assertEquals($stack->getCurrent(), "one"); } function testExhaustion() { - $stack = new Doku_LexerStateStack("one"); + $stack = new StateStack("one"); $this->assertFalse($stack->leave()); } function testStateMoves() { - $stack = new Doku_LexerStateStack("one"); + $stack = new StateStack("one"); $stack->enter("two"); $this->assertEquals($stack->getCurrent(), "two"); $stack->enter("three"); @@ -160,13 +159,13 @@ class TestOfLexer extends DokuWikiTest { function testNoPatterns() { $handler = $this->createMock('TestParser'); $handler->expects($this->never())->method('accept'); - $lexer = new Doku_Lexer($handler); + $lexer = new Lexer($handler); $this->assertFalse($lexer->parse("abcdef")); } function testEmptyPage() { $handler = $this->createMock('TestParser'); $handler->expects($this->never())->method('accept'); - $lexer = new Doku_Lexer($handler); + $lexer = new Lexer($handler); $lexer->addPattern("a+"); $this->assertTrue($lexer->parse("")); } @@ -189,7 +188,7 @@ class TestOfLexer extends DokuWikiTest { $handler->expects($this->at(7))->method('accept') ->with("z", DOKU_LEXER_UNMATCHED, 13)->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler); + $lexer = new Lexer($handler); $lexer->addPattern("a+"); $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); } @@ -201,7 +200,7 @@ class TestOfLexer extends DokuWikiTest { $handler->expects($this->at($i))->method('accept') ->with($target[$i], $this->anything(), $positions[$i])->will($this->returnValue(true)); } - $lexer = new Doku_Lexer($handler); + $lexer = new Lexer($handler); $lexer->addPattern("a+"); $lexer->addPattern("b+"); $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); @@ -227,7 +226,7 @@ class TestOfLexerModes extends DokuWikiTest { ->with("aaaa", DOKU_LEXER_MATCHED,11)->will($this->returnValue(true)); $handler->expects($this->at(7))->method('a') ->with("x", DOKU_LEXER_UNMATCHED,15)->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "a"); + $lexer = new Lexer($handler, "a"); $lexer->addPattern("a+", "a"); $lexer->addPattern("b+", "b"); $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); @@ -261,7 +260,7 @@ class TestOfLexerModes extends DokuWikiTest { $handler->expects($this->at(12))->method('b') ->with("a", DOKU_LEXER_UNMATCHED,18)->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "a"); + $lexer = new Lexer($handler, "a"); $lexer->addPattern("a+", "a"); $lexer->addEntryPattern(":", "a", "b"); $lexer->addPattern("b+", "b"); @@ -293,7 +292,7 @@ class TestOfLexerModes extends DokuWikiTest { ->with("b", DOKU_LEXER_UNMATCHED,15)->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "a"); + $lexer = new Lexer($handler, "a"); $lexer->addPattern("a+", "a"); $lexer->addEntryPattern("(", "a", "b"); $lexer->addPattern("b+", "b"); @@ -314,7 +313,7 @@ class TestOfLexerModes extends DokuWikiTest { ->with("bbb", DOKU_LEXER_SPECIAL,7)->will($this->returnValue(true)); $handler->expects($this->at(5))->method('a') ->with("xx", DOKU_LEXER_UNMATCHED,10)->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "a"); + $lexer = new Lexer($handler, "a"); $lexer->addPattern("a+", "a"); $lexer->addSpecialPattern("b+", "a", "b"); $this->assertTrue($lexer->parse("aabaaxxbbbxx")); @@ -326,7 +325,7 @@ class TestOfLexerModes extends DokuWikiTest { $handler->expects($this->at(1))->method('a') ->with(")", DOKU_LEXER_EXIT,2)->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "a"); + $lexer = new Lexer($handler, "a"); $lexer->addPattern("a+", "a"); $lexer->addExitPattern(")", "a"); $this->assertFalse($lexer->parse("aa)aa")); @@ -351,7 +350,7 @@ class TestOfLexerHandlers extends DokuWikiTest { $handler->expects($this->at(6))->method('a') ->with("b", DOKU_LEXER_UNMATCHED,9)->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "mode_a"); + $lexer = new Lexer($handler, "mode_a"); $lexer->addPattern("a+", "mode_a"); $lexer->addEntryPattern("(", "mode_a", "mode_b"); $lexer->addPattern("b+", "mode_b"); @@ -389,7 +388,7 @@ class TestOfLexerByteIndices extends DokuWikiTest { $handler->expects($this->at(5))->method('caught') ->with("</file>", DOKU_LEXER_EXIT, strpos($doc,'</file>'))->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "ignore"); + $lexer = new Lexer($handler, "ignore"); $lexer->addEntryPattern("<file>", "ignore", "caught"); $lexer->addExitPattern("</file>", "caught"); $lexer->addSpecialPattern('b','caught','special'); @@ -415,7 +414,7 @@ class TestOfLexerByteIndices extends DokuWikiTest { $handler->expects($this->at(5))->method('caught') ->with("</file>", DOKU_LEXER_EXIT, strpos($doc,'</file>'))->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "ignore"); + $lexer = new Lexer($handler, "ignore"); $lexer->addEntryPattern('<file>(?=.*</file>)', "ignore", "caught"); $lexer->addExitPattern("</file>", "caught"); $lexer->addSpecialPattern('b','caught','special'); @@ -441,7 +440,7 @@ class TestOfLexerByteIndices extends DokuWikiTest { $handler->expects($this->at(5))->method('caught') ->with("</file>", DOKU_LEXER_EXIT, strpos($doc,'</file>'))->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "ignore"); + $lexer = new Lexer($handler, "ignore"); $lexer->addEntryPattern('<file>(?!foo)', "ignore", "caught"); $lexer->addExitPattern("</file>", "caught"); $lexer->addSpecialPattern('b','caught','special'); @@ -467,7 +466,7 @@ class TestOfLexerByteIndices extends DokuWikiTest { $handler->expects($this->at(5))->method('caught') ->with("</file>", DOKU_LEXER_EXIT, strpos($doc,'</file>'))->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "ignore"); + $lexer = new Lexer($handler, "ignore"); $lexer->addEntryPattern('<file>', "ignore", "caught"); $lexer->addExitPattern("(?<=d)</file>", "caught"); $lexer->addSpecialPattern('b','caught','special'); @@ -493,7 +492,7 @@ class TestOfLexerByteIndices extends DokuWikiTest { $handler->expects($this->at(5))->method('caught') ->with("</file>", DOKU_LEXER_EXIT, strpos($doc,'</file>'))->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, 'ignore'); + $lexer = new Lexer($handler, 'ignore'); $lexer->addEntryPattern('<file>', 'ignore', 'caught'); $lexer->addExitPattern('(?<!c)</file>', 'caught'); $lexer->addSpecialPattern('b','caught','special'); @@ -520,7 +519,7 @@ class TestOfLexerByteIndices extends DokuWikiTest { $handler->expects($this->once())->method('caught') ->with("FOO", DOKU_LEXER_SPECIAL, $matches[0][1])->will($this->returnValue(true)); - $lexer = new Doku_Lexer($handler, "ignore"); + $lexer = new Lexer($handler, "ignore"); $lexer->addSpecialPattern($pattern,'ignore','caught'); $this->assertTrue($lexer->parse($doc)); diff --git a/_test/tests/inc/parser/parser.inc.php b/_test/tests/inc/parser/parser.inc.php index c73f8d137..153f67b26 100644 --- a/_test/tests/inc/parser/parser.inc.php +++ b/_test/tests/inc/parser/parser.inc.php @@ -1,20 +1,22 @@ <?php +use dokuwiki\Parsing\Parser; + require_once DOKU_INC . 'inc/parser/parser.php'; require_once DOKU_INC . 'inc/parser/handler.php'; +if (!defined('DOKU_PARSER_EOL')) define('DOKU_PARSER_EOL', "\n"); // add this to make handling test cases simpler abstract class TestOfDoku_Parser extends DokuWikiTest { - /** @var Doku_Parser */ + /** @var Parser */ protected $P; /** @var Doku_Handler */ protected $H; function setUp() { parent::setUp(); - $this->P = new Doku_Parser(); $this->H = new Doku_Handler(); - $this->P->Handler = $this->H; + $this->P = new Parser($this->H); } function tearDown() { diff --git a/_test/tests/inc/parser/parser_code.test.php b/_test/tests/inc/parser/parser_code.test.php index df8225f4e..961db7dd2 100644 --- a/_test/tests/inc/parser/parser_code.test.php +++ b/_test/tests/inc/parser/parser_code.test.php @@ -1,4 +1,7 @@ <?php + +use dokuwiki\Parsing\ParserMode\Code; + require_once 'parser.inc.php'; /** @@ -10,7 +13,7 @@ class TestOfDoku_Parser_Code extends TestOfDoku_Parser { function setUp() { parent::setUp(); - $this->P->addMode('code',new Doku_Parser_Mode_Code()); + $this->P->addMode('code',new Code()); } function testCode() { diff --git a/_test/tests/inc/parser/parser_eol.test.php b/_test/tests/inc/parser/parser_eol.test.php index 6264f8b55..ae5e9cce5 100644 --- a/_test/tests/inc/parser/parser_eol.test.php +++ b/_test/tests/inc/parser/parser_eol.test.php @@ -1,10 +1,14 @@ <?php + +use dokuwiki\Parsing\ParserMode\Eol; +use dokuwiki\Parsing\ParserMode\Linebreak; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Eol extends TestOfDoku_Parser { function testEol() { - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('eol',new Eol()); $this->P->parse("Foo\nBar"); $calls = array ( array('document_start',array()), @@ -17,7 +21,7 @@ class TestOfDoku_Parser_Eol extends TestOfDoku_Parser { } function testEolMultiple() { - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('eol',new Eol()); $this->P->parse("Foo\n\nbar\nFoo"); $calls = array ( array('document_start',array()), @@ -33,7 +37,7 @@ class TestOfDoku_Parser_Eol extends TestOfDoku_Parser { } function testWinEol() { - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('eol',new Eol()); $this->P->parse("Foo\r\nBar"); $calls = array ( array('document_start',array()), @@ -46,7 +50,7 @@ class TestOfDoku_Parser_Eol extends TestOfDoku_Parser { } function testLinebreak() { - $this->P->addMode('linebreak',new Doku_Parser_Mode_Linebreak()); + $this->P->addMode('linebreak',new Linebreak()); $this->P->parse('Foo\\\\ Bar'); $calls = array ( array('document_start',array()), @@ -61,8 +65,8 @@ class TestOfDoku_Parser_Eol extends TestOfDoku_Parser { } function testLinebreakPlusEol() { - $this->P->addMode('linebreak',new Doku_Parser_Mode_Linebreak()); - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('linebreak',new Linebreak()); + $this->P->addMode('eol',new Eol()); $this->P->parse('Foo\\\\'."\n\n".'Bar'); $calls = array ( @@ -80,7 +84,7 @@ class TestOfDoku_Parser_Eol extends TestOfDoku_Parser { } function testLinebreakInvalid() { - $this->P->addMode('linebreak',new Doku_Parser_Mode_Linebreak()); + $this->P->addMode('linebreak',new Linebreak()); $this->P->parse('Foo\\\\Bar'); $calls = array ( array('document_start',array()), diff --git a/_test/tests/inc/parser/parser_file.test.php b/_test/tests/inc/parser/parser_file.test.php index 39bda8a58..407b04a48 100644 --- a/_test/tests/inc/parser/parser_file.test.php +++ b/_test/tests/inc/parser/parser_file.test.php @@ -1,11 +1,14 @@ <?php + +use dokuwiki\Parsing\ParserMode\File; + require_once 'parser.inc.php'; class TestOfDoku_Parser_File extends TestOfDoku_Parser { function setUp() { parent::setUp(); - $this->P->addMode('file',new Doku_Parser_Mode_File()); + $this->P->addMode('file',new File()); } function testFile() { diff --git a/_test/tests/inc/parser/parser_footnote.test.php b/_test/tests/inc/parser/parser_footnote.test.php index 2457fb031..96d7a8407 100644 --- a/_test/tests/inc/parser/parser_footnote.test.php +++ b/_test/tests/inc/parser/parser_footnote.test.php @@ -1,11 +1,24 @@ <?php + +use dokuwiki\Parsing\Handler\Lists; +use dokuwiki\Parsing\ParserMode\Code; +use dokuwiki\Parsing\ParserMode\Eol; +use dokuwiki\Parsing\ParserMode\Footnote; +use dokuwiki\Parsing\ParserMode\Formatting; +use dokuwiki\Parsing\ParserMode\Hr; +use dokuwiki\Parsing\ParserMode\Listblock; +use dokuwiki\Parsing\ParserMode\Preformatted; +use dokuwiki\Parsing\ParserMode\Quote; +use dokuwiki\Parsing\ParserMode\Table; +use dokuwiki\Parsing\ParserMode\Unformatted; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { function setUp() { parent::setUp(); - $this->P->addMode('footnote',new Doku_Parser_Mode_Footnote()); + $this->P->addMode('footnote',new Footnote()); } function testFootnote() { @@ -39,7 +52,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteLinefeed() { - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('eol',new Eol()); $this->P->parse("Foo (( testing\ntesting )) Bar"); $calls = array ( array('document_start',array()), @@ -76,7 +89,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteEol() { - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('eol',new Eol()); $this->P->parse("Foo \nX(( test\ning ))Y\n Bar"); $calls = array ( array('document_start',array()), @@ -95,7 +108,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteStrong() { - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); + $this->P->addMode('strong',new Formatting('strong')); $this->P->parse('Foo (( **testing** )) Bar'); $calls = array ( array('document_start',array()), @@ -118,7 +131,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteHr() { - $this->P->addMode('hr',new Doku_Parser_Mode_HR()); + $this->P->addMode('hr',new Hr()); $this->P->parse("Foo (( \n ---- \n )) Bar"); $calls = array ( array('document_start',array()), @@ -139,7 +152,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteCode() { - $this->P->addMode('code',new Doku_Parser_Mode_Code()); + $this->P->addMode('code',new Code()); $this->P->parse("Foo (( <code>Test</code> )) Bar"); $calls = array ( array('document_start',array()), @@ -160,7 +173,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnotePreformatted() { - $this->P->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); + $this->P->addMode('preformatted',new Preformatted()); $this->P->parse("Foo (( \n Test\n )) Bar"); $calls = array ( array('document_start',array()), @@ -181,8 +194,8 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnotePreformattedEol() { - $this->P->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('preformatted',new Preformatted()); + $this->P->addMode('eol',new Eol()); $this->P->parse("Foo (( \n Test\n )) Bar"); $calls = array ( array('document_start',array()), @@ -204,7 +217,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteUnformatted() { - $this->P->addMode('unformatted',new Doku_Parser_Mode_Unformatted()); + $this->P->addMode('unformatted',new Unformatted()); $this->P->parse("Foo (( <nowiki>Test</nowiki> )) Bar"); $calls = array ( array('document_start',array()), @@ -225,7 +238,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteNotHeader() { - $this->P->addMode('unformatted',new Doku_Parser_Mode_Unformatted()); + $this->P->addMode('unformatted',new Unformatted()); $this->P->parse("Foo (( \n====Test====\n )) Bar"); $calls = array ( array('document_start',array()), @@ -244,7 +257,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteTable() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse("Foo (( | Row 0 Col 1 | Row 0 Col 2 | Row 0 Col 3 | | Row 1 Col 1 | Row 1 Col 2 | Row 1 Col 3 | @@ -290,7 +303,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteList() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->P->addMode('listblock',new ListBlock()); $this->P->parse("Foo (( *A * B @@ -303,7 +316,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { array('nest', array ( array ( array('footnote_open',array()), array('listu_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('cdata',array("A")), array('listcontent_close',array()), @@ -332,7 +345,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteQuote() { - $this->P->addMode('quote',new Doku_Parser_Mode_Quote()); + $this->P->addMode('quote',new Quote()); $this->P->parse("Foo (( > def >>ghi @@ -361,7 +374,7 @@ class TestOfDoku_Parser_Footnote extends TestOfDoku_Parser { } function testFootnoteNesting() { - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); + $this->P->addMode('strong',new Formatting('strong')); $this->P->parse("(( a ** (( b )) ** c ))"); $calls = array( diff --git a/_test/tests/inc/parser/parser_headers.test.php b/_test/tests/inc/parser/parser_headers.test.php index a1bf7d2ba..d061899dd 100644 --- a/_test/tests/inc/parser/parser_headers.test.php +++ b/_test/tests/inc/parser/parser_headers.test.php @@ -1,10 +1,14 @@ <?php + +use dokuwiki\Parsing\ParserMode\Eol; +use dokuwiki\Parsing\ParserMode\Header; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { function testHeader1() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n ====== Header ====== \n def"); $calls = array ( array('document_start',array()), @@ -23,7 +27,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeader2() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n ===== Header ===== \n def"); $calls = array ( array('document_start',array()), @@ -42,7 +46,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeader3() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n ==== Header ==== \n def"); $calls = array ( array('document_start',array()), @@ -61,7 +65,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeader4() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n === Header === \n def"); $calls = array ( array('document_start',array()), @@ -80,7 +84,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeader5() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n == Header == \n def"); $calls = array ( array('document_start',array()), @@ -99,7 +103,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeader2UnevenSmaller() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n ===== Header == \n def"); $calls = array ( array('document_start',array()), @@ -118,7 +122,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeader2UnevenBigger() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n ===== Header =========== \n def"); $calls = array ( array('document_start',array()), @@ -137,7 +141,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeaderLarge() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n ======= Header ======= \n def"); $calls = array ( array('document_start',array()), @@ -156,7 +160,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeaderSmall() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n= Header =\n def"); $calls = array ( array('document_start',array()), @@ -170,7 +174,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { function testHeader1Mixed() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n====== == Header == ======\n def"); $calls = array ( array('document_start',array()), @@ -189,7 +193,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeader5Mixed() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n== ====== Header ====== ==\n def"); $calls = array ( array('document_start',array()), @@ -208,7 +212,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeaderMultiline() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n== ====== Header\n ====== ==\n def"); $calls = array ( array('document_start',array()), @@ -227,14 +231,14 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } # function testNoToc() { -# $this->P->addMode('notoc',new Doku_Parser_Mode_NoToc()); +# $this->P->addMode('notoc',new NoToc()); # $this->P->parse('abc ~~NOTOC~~ def'); # $this->assertFalse($this->H->meta['toc']); # } function testHeader1Eol() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('header',new Header()); + $this->P->addMode('eol',new Eol()); $this->P->parse("abc \n ====== Header ====== \n def"); $calls = array ( array('document_start',array()), @@ -254,7 +258,7 @@ class TestOfDoku_Parser_Headers extends TestOfDoku_Parser { } function testHeaderMulti2() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("abc \n ====== Header ====== \n def abc \n ===== Header2 ===== \n def"); $calls = array ( array('document_start',array()), diff --git a/_test/tests/inc/parser/parser_i18n.test.php b/_test/tests/inc/parser/parser_i18n.test.php index 096f2e227..b10bd9f3e 100644 --- a/_test/tests/inc/parser/parser_i18n.test.php +++ b/_test/tests/inc/parser/parser_i18n.test.php @@ -1,4 +1,11 @@ <?php + +use dokuwiki\Parsing\ParserMode\Acronym; +use dokuwiki\Parsing\ParserMode\Formatting; +use dokuwiki\Parsing\ParserMode\Header; +use dokuwiki\Parsing\ParserMode\Internallink; +use dokuwiki\Parsing\ParserMode\Table; + require_once 'parser.inc.php'; class TestOfDoku_Parser_i18n extends TestOfDoku_Parser { @@ -9,7 +16,7 @@ class TestOfDoku_Parser_i18n extends TestOfDoku_Parser { 'subscript', 'superscript', 'deleted', ); foreach ( $formats as $format ) { - $this->P->addMode($format,new Doku_Parser_Mode_Formatting($format)); + $this->P->addMode($format,new Formatting($format)); } $this->P->parse("I**ñ**t__ë__r//n//â<sup>t</sup>i<sub>ô</sub>n''à''liz<del>æ</del>tiøn"); $calls = array ( @@ -51,7 +58,7 @@ class TestOfDoku_Parser_i18n extends TestOfDoku_Parser { } function testHeader() { - $this->P->addMode('header',new Doku_Parser_Mode_Header()); + $this->P->addMode('header',new Header()); $this->P->parse("Foo\n ==== Iñtërnâtiônàlizætiøn ==== \n Bar"); $calls = array ( array('document_start',array()), @@ -70,7 +77,7 @@ class TestOfDoku_Parser_i18n extends TestOfDoku_Parser { } function testTable() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc | Row 0 Col 1 | Iñtërnâtiônàlizætiøn | Row 0 Col 3 | @@ -115,7 +122,7 @@ def'); function testAcronym() { $t = array('Iñtërnâtiônàlizætiøn'); - $this->P->addMode('acronym',new Doku_Parser_Mode_Acronym($t)); + $this->P->addMode('acronym',new Acronym($t)); $this->P->parse("Foo Iñtërnâtiônàlizætiøn Bar"); $calls = array ( array('document_start',array()), @@ -130,7 +137,7 @@ def'); } function testInterwiki() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new InternalLink()); $this->P->parse("Foo [[wp>Iñtërnâtiônàlizætiøn|Iñtërnâtiônàlizætiøn]] Bar"); $calls = array ( array('document_start',array()), @@ -145,7 +152,7 @@ def'); } function testInternalLink() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new InternalLink()); $this->P->parse("Foo [[x:Iñtërnâtiônàlizætiøn:y:foo_bar:z|Iñtërnâtiônàlizætiøn]] Bar"); $calls = array ( array('document_start',array()), diff --git a/_test/tests/inc/parser/parser_links.test.php b/_test/tests/inc/parser/parser_links.test.php index ee001e73a..cbcfcb87b 100644 --- a/_test/tests/inc/parser/parser_links.test.php +++ b/_test/tests/inc/parser/parser_links.test.php @@ -1,4 +1,13 @@ <?php + +use dokuwiki\Parsing\ParserMode\Camelcaselink; +use dokuwiki\Parsing\ParserMode\Emaillink; +use dokuwiki\Parsing\ParserMode\Externallink; +use dokuwiki\Parsing\ParserMode\Filelink; +use dokuwiki\Parsing\ParserMode\Internallink; +use dokuwiki\Parsing\ParserMode\Media; +use dokuwiki\Parsing\ParserMode\Windowssharelink; + require_once 'parser.inc.php'; /** @@ -9,7 +18,7 @@ require_once 'parser.inc.php'; class TestOfDoku_Parser_Links extends TestOfDoku_Parser { function testExternalLinkSimple() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo http://www.google.com Bar"); $calls = array ( array('document_start',array()), @@ -24,7 +33,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalLinkCase() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo HTTP://WWW.GOOGLE.COM Bar"); $calls = array ( array('document_start',array()), @@ -39,7 +48,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalIPv4() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo http://123.123.3.21/foo Bar"); $calls = array ( array('document_start',array()), @@ -54,7 +63,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalIPv6() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo http://[3ffe:2a00:100:7031::1]/foo Bar"); $calls = array ( array('document_start',array()), @@ -96,8 +105,8 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { $name = $title; } $this->setup(); - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('internallink',new Internallink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo $source Bar"); $calls = array ( array('document_start',array()), @@ -117,7 +126,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalLinkJavascript() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo javascript:alert('XSS'); Bar"); $calls = array ( array('document_start',array()), @@ -130,7 +139,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalWWWLink() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo www.google.com Bar"); $calls = array ( array('document_start',array()), @@ -145,7 +154,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalWWWLinkInPath() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); // See issue #936. Should NOT generate a link! $this->P->parse("Foo /home/subdir/www/www.something.de/somedir/ Bar"); $calls = array ( @@ -159,7 +168,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalWWWLinkFollowingPath() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo /home/subdir/www/ www.something.de/somedir/ Bar"); $calls = array ( array('document_start',array()), @@ -174,7 +183,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalFTPLink() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo ftp.sunsite.com Bar"); $calls = array ( array('document_start',array()), @@ -189,7 +198,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalFTPLinkInPath() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); // See issue #936. Should NOT generate a link! $this->P->parse("Foo /home/subdir/www/ftp.something.de/somedir/ Bar"); $calls = array ( @@ -203,7 +212,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalFTPLinkFollowingPath() { - $this->P->addMode('externallink',new Doku_Parser_Mode_ExternalLink()); + $this->P->addMode('externallink',new Externallink()); $this->P->parse("Foo /home/subdir/www/ ftp.something.de/somedir/ Bar"); $calls = array ( array('document_start',array()), @@ -218,7 +227,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testEmail() { - $this->P->addMode('emaillink',new Doku_Parser_Mode_Emaillink()); + $this->P->addMode('emaillink',new Emaillink()); $this->P->parse("Foo <bugs@php.net> Bar"); $calls = array ( array('document_start',array()), @@ -233,7 +242,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testEmailRFC2822() { - $this->P->addMode('emaillink',new Doku_Parser_Mode_Emaillink()); + $this->P->addMode('emaillink',new Emaillink()); $this->P->parse("Foo <~fix+bug's.for/ev{e}r@php.net> Bar"); $calls = array ( array('document_start',array()), @@ -248,7 +257,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testEmailCase() { - $this->P->addMode('emaillink',new Doku_Parser_Mode_Emaillink()); + $this->P->addMode('emaillink',new Emaillink()); $this->P->parse("Foo <bugs@pHp.net> Bar"); $calls = array ( array('document_start',array()), @@ -264,7 +273,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { function testInternalLinkOneChar() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[l]] Bar"); $calls = array ( array('document_start',array()), @@ -279,7 +288,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testInternalLinkNoChar() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[]] Bar"); $calls = array ( array('document_start',array()), @@ -294,7 +303,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testInternalLinkNamespaceNoTitle() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[foo:bar]] Bar"); $calls = array ( array('document_start',array()), @@ -309,7 +318,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testInternalLinkNamespace() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[x:1:y:foo_bar:z|Test]] Bar"); $calls = array ( array('document_start',array()), @@ -324,7 +333,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testInternalLinkSectionRef() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[wiki:syntax#internal|Syntax]] Bar"); $calls = array ( array('document_start',array()), @@ -339,7 +348,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testInternalLinkCodeFollows() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[wiki:internal:link|Test]] Bar <code>command [arg1 [arg2 [arg3]]]</code>"); $calls = array ( array('document_start',array()), @@ -354,7 +363,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testInternalLinkCodeFollows2() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[wiki:internal:link|[Square brackets in title] Test]] Bar <code>command [arg1 [arg2 [arg3]]]</code>"); $calls = array ( array('document_start',array()), @@ -369,7 +378,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalInInternalLink() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[http://www.google.com|Google]] Bar"); $calls = array ( array('document_start',array()), @@ -384,7 +393,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalInInternalLink2() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[http://www.google.com?test[]=squarebracketsinurl|Google]] Bar"); $calls = array ( array('document_start',array()), @@ -399,7 +408,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testExternalInInternalLink2CodeFollows() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[http://www.google.com?test[]=squarebracketsinurl|Google]] Bar <code>command [arg1 [arg2 [arg3]]]</code>"); $calls = array ( array('document_start',array()), @@ -414,7 +423,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testTwoInternalLinks() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[foo:bar|one]] and [[bar:foo|two]] Bar"); $calls = array ( array('document_start',array()), @@ -432,7 +441,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { function testInterwikiLink() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[iw>somepage|Some Page]] Bar"); $calls = array ( array('document_start',array()), @@ -447,7 +456,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testInterwikiLinkCase() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[IW>somepage|Some Page]] Bar"); $calls = array ( array('document_start',array()), @@ -462,7 +471,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testInterwikiPedia() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[wp>Callback_(computer_science)|callbacks]] Bar"); $calls = array ( array('document_start',array()), @@ -477,7 +486,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testCamelCase() { - $this->P->addMode('camelcaselink',new Doku_Parser_Mode_CamelCaseLink()); + $this->P->addMode('camelcaselink',new Camelcaselink()); $this->P->parse("Foo FooBar Bar"); $calls = array ( array('document_start',array()), @@ -492,7 +501,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testFileLink() { - $this->P->addMode('filelink',new Doku_Parser_Mode_FileLink()); + $this->P->addMode('filelink',new FileLink()); $this->P->parse('Foo file://temp/file.txt Bar'); $calls = array ( array('document_start',array()), @@ -507,7 +516,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testFileLinkInternal() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse('Foo [[file://temp/file.txt|Some File]] Bar'); $calls = array ( array('document_start',array()), @@ -522,7 +531,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testWindowsShareLink() { - $this->P->addMode('windowssharelink',new Doku_Parser_Mode_WindowsShareLink()); + $this->P->addMode('windowssharelink',new Windowssharelink()); $this->P->parse('Foo \\\server\share Bar'); $calls = array ( array('document_start',array()), @@ -537,7 +546,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testWindowsShareLinkHyphen() { - $this->P->addMode('windowssharelink',new Doku_Parser_Mode_WindowsShareLink()); + $this->P->addMode('windowssharelink',new Windowssharelink()); $this->P->parse('Foo \\\server\share-hyphen Bar'); $calls = array ( array('document_start',array()), @@ -552,7 +561,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testWindowsShareLinkInternal() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse('Foo [[\\\server\share|My Documents]] Bar'); $calls = array ( array('document_start',array()), @@ -567,7 +576,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInternal() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{img.gif}} Bar'); $calls = array ( array('document_start',array()), @@ -582,7 +591,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInternalLinkOnly() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{img.gif?linkonly}} Bar'); $calls = array ( array('document_start',array()), @@ -597,7 +606,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaNotImage() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{foo.txt?10x10|Some File}} Bar'); $calls = array ( array('document_start',array()), @@ -612,7 +621,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInternalLAlign() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{img.gif }} Bar'); $calls = array ( array('document_start',array()), @@ -627,7 +636,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInternalRAlign() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{ img.gif}} Bar'); $calls = array ( array('document_start',array()), @@ -642,7 +651,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInternalCenter() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{ img.gif }} Bar'); $calls = array ( array('document_start',array()), @@ -657,7 +666,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInternalParams() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{img.gif?50x100nocache}} Bar'); $calls = array ( array('document_start',array()), @@ -672,7 +681,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInternalTitle() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{img.gif?50x100|Some Image}} Bar'); $calls = array ( array('document_start',array()), @@ -687,7 +696,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaExternal() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{http://www.google.com/img.gif}} Bar'); $calls = array ( array('document_start',array()), @@ -702,7 +711,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaExternalParams() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{http://www.google.com/img.gif?50x100nocache}} Bar'); $calls = array ( array('document_start',array()), @@ -717,7 +726,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaExternalTitle() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{http://www.google.com/img.gif?50x100|Some Image}} Bar'); $calls = array ( array('document_start',array()), @@ -733,7 +742,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInInternalLink() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[x:1:y:foo_bar:z|{{img.gif?10x20nocache|Some Image}}]] Bar"); $image = array( @@ -760,7 +769,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaNoImageInInternalLink() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[x:1:y:foo_bar:z|{{foo.txt?10x20nocache|Some Image}}]] Bar"); $image = array( @@ -787,7 +796,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testMediaInEmailLink() { - $this->P->addMode('internallink',new Doku_Parser_Mode_InternalLink()); + $this->P->addMode('internallink',new Internallink()); $this->P->parse("Foo [[foo@example.com|{{img.gif?10x20nocache|Some Image}}]] Bar"); $image = array( @@ -814,7 +823,7 @@ class TestOfDoku_Parser_Links extends TestOfDoku_Parser { } function testNestedMedia() { - $this->P->addMode('media',new Doku_Parser_Mode_Media()); + $this->P->addMode('media',new Media()); $this->P->parse('Foo {{img.gif|{{foo.gif|{{bar.gif|Bar}}}}}} Bar'); $calls = array ( array('document_start',array()), diff --git a/_test/tests/inc/parser/parser_lists.test.php b/_test/tests/inc/parser/parser_lists.test.php index 6acaff637..2176af76d 100644 --- a/_test/tests/inc/parser/parser_lists.test.php +++ b/_test/tests/inc/parser/parser_lists.test.php @@ -1,10 +1,19 @@ <?php + +use dokuwiki\Parsing\Handler\Lists; +use dokuwiki\Parsing\ParserMode\Eol; +use dokuwiki\Parsing\ParserMode\Footnote; +use dokuwiki\Parsing\ParserMode\Formatting; +use dokuwiki\Parsing\ParserMode\Linebreak; +use dokuwiki\Parsing\ParserMode\Listblock; +use dokuwiki\Parsing\ParserMode\Unformatted; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { function testUnorderedList() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->P->addMode('listblock',new Listblock()); $this->P->parse(' *A * B @@ -13,7 +22,7 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { $calls = array ( array('document_start',array()), array('listu_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('cdata',array("A")), array('listcontent_close',array()), @@ -37,7 +46,7 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { } function testOrderedList() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->P->addMode('listblock',new Listblock()); $this->P->parse(' -A - B @@ -46,7 +55,7 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { $calls = array ( array('document_start',array()), array('listo_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('cdata',array("A")), array('listcontent_close',array()), @@ -71,7 +80,7 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { function testMixedList() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->P->addMode('listblock',new Listblock()); $this->P->parse(' -A * B @@ -80,7 +89,7 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { $calls = array ( array('document_start',array()), array('listo_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('cdata',array("A")), array('listcontent_close',array()), @@ -102,14 +111,14 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + function testUnorderedListWinEOL() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->P->addMode('listblock',new Listblock()); $this->P->parse("\r\n *A\r\n * B\r\n * C\r\n"); $calls = array ( array('document_start',array()), array('listu_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('cdata',array("A")), array('listcontent_close',array()), @@ -131,14 +140,14 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + function testOrderedListWinEOL() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->P->addMode('listblock',new Listblock()); $this->P->parse("\r\n -A\r\n - B\r\n - C\r\n"); $calls = array ( array('document_start',array()), array('listo_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('cdata',array("A")), array('listcontent_close',array()), @@ -160,9 +169,9 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + function testNotAList() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->P->addMode('listblock',new Listblock()); $this->P->parse("Foo -bar *foo Bar"); $calls = array ( array('document_start',array()), @@ -173,10 +182,10 @@ class TestOfDoku_Parser_Lists extends TestOfDoku_Parser { ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + function testUnorderedListParagraph() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('listblock',new Listblock()); + $this->P->addMode('eol',new Eol()); $this->P->parse('Foo *A * B @@ -188,7 +197,7 @@ Bar'); array('cdata',array("Foo")), array('p_close',array()), array('listu_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('cdata',array("A")), array('listcontent_close',array()), @@ -213,12 +222,12 @@ Bar'); ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + // This is really a failing test - formatting able to spread across list items // Problem is fixing it would mean a major rewrite of lists function testUnorderedListStrong() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); + $this->P->addMode('listblock',new Listblock()); + $this->P->addMode('strong',new Formatting('strong')); $this->P->parse(' ***A** *** B @@ -227,7 +236,7 @@ Bar'); $calls = array ( array('document_start',array()), array('listu_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('strong_open',array()), array('cdata',array("A")), @@ -248,12 +257,12 @@ Bar'); ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + // This is really a failing test - unformatted able to spread across list items // Problem is fixing it would mean a major rewrite of lists function testUnorderedListUnformatted() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); - $this->P->addMode('unformatted',new Doku_Parser_Mode_Unformatted()); + $this->P->addMode('listblock',new Listblock()); + $this->P->addMode('unformatted',new Unformatted()); $this->P->parse(' *%%A%% *%% B @@ -262,7 +271,7 @@ Bar'); $calls = array ( array('document_start',array()), array('listu_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('unformatted',array("A")), array('listcontent_close',array()), @@ -279,10 +288,10 @@ Bar'); ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + function testUnorderedListLinebreak() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); - $this->P->addMode('linebreak',new Doku_Parser_Mode_Linebreak()); + $this->P->addMode('listblock',new Listblock()); + $this->P->addMode('linebreak',new Linebreak()); $this->P->parse(' *A\\\\ D * B @@ -291,7 +300,7 @@ Bar'); $calls = array ( array('document_start',array()), array('listu_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('cdata',array("A")), array('linebreak',array()), @@ -315,10 +324,10 @@ Bar'); ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + function testUnorderedListLinebreak2() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); - $this->P->addMode('linebreak',new Doku_Parser_Mode_Linebreak()); + $this->P->addMode('listblock',new Listblock()); + $this->P->addMode('linebreak',new Linebreak()); $this->P->parse(' *A\\\\ * B @@ -342,10 +351,10 @@ Bar'); ); $this->assertEquals(array_map('stripbyteindex',$this->H->calls),$calls); } - + function testUnorderedListFootnote() { - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); - $this->P->addMode('footnote',new Doku_Parser_Mode_Footnote()); + $this->P->addMode('listblock',new Listblock()); + $this->P->addMode('footnote',new Footnote()); $this->P->parse(' *((A)) *(( B @@ -355,7 +364,7 @@ Bar'); $calls = array ( array('document_start',array()), array('listu_open',array()), - array('listitem_open',array(1,Doku_Handler_List::NODE)), + array('listitem_open',array(1,Lists::NODE)), array('listcontent_open',array()), array('nest', array( array( array('footnote_open',array()), diff --git a/_test/tests/inc/parser/parser_preformatted.test.php b/_test/tests/inc/parser/parser_preformatted.test.php index f7a01a7e5..ad99f2916 100644 --- a/_test/tests/inc/parser/parser_preformatted.test.php +++ b/_test/tests/inc/parser/parser_preformatted.test.php @@ -1,10 +1,20 @@ <?php + +use dokuwiki\Parsing\ParserMode\Code; +use dokuwiki\Parsing\ParserMode\Eol; +use dokuwiki\Parsing\ParserMode\File; +use dokuwiki\Parsing\ParserMode\Header; +use dokuwiki\Parsing\ParserMode\Html; +use dokuwiki\Parsing\ParserMode\Listblock; +use dokuwiki\Parsing\ParserMode\Php; +use dokuwiki\Parsing\ParserMode\Preformatted; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { function testFile() { - $this->P->addMode('file',new Doku_Parser_Mode_File()); + $this->P->addMode('file',new File()); $this->P->parse('Foo <file>testing</file> Bar'); $calls = array ( array('document_start',array()), @@ -22,7 +32,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { } function testCode() { - $this->P->addMode('code',new Doku_Parser_Mode_Code()); + $this->P->addMode('code',new Code()); $this->P->parse('Foo <code>testing</code> Bar'); $calls = array ( array('document_start',array()), @@ -39,7 +49,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { } function testCodeWhitespace() { - $this->P->addMode('code',new Doku_Parser_Mode_Code()); + $this->P->addMode('code',new Code()); $this->P->parse("Foo <code \n>testing</code> Bar"); $calls = array ( array('document_start',array()), @@ -56,7 +66,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { } function testCodeLang() { - $this->P->addMode('code',new Doku_Parser_Mode_Code()); + $this->P->addMode('code',new Code()); $this->P->parse("Foo <code php>testing</code> Bar"); $calls = array ( array('document_start',array()), @@ -73,7 +83,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { } function testPreformatted() { - $this->P->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); + $this->P->addMode('preformatted',new Preformatted()); $this->P->parse("F oo\n x \n y \nBar\n"); $calls = array ( array('document_start',array()), @@ -90,7 +100,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { } function testPreformattedWinEOL() { - $this->P->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); + $this->P->addMode('preformatted',new Preformatted()); $this->P->parse("F oo\r\n x \r\n y \r\nBar\r\n"); $calls = array ( array('document_start',array()), @@ -107,7 +117,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { } function testPreformattedTab() { - $this->P->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); + $this->P->addMode('preformatted',new Preformatted()); $this->P->parse("F oo\n\tx\t\n\t\ty\t\nBar\n"); $calls = array ( array('document_start',array()), @@ -124,7 +134,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { } function testPreformattedTabWinEOL() { - $this->P->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); + $this->P->addMode('preformatted',new Preformatted()); $this->P->parse("F oo\r\n\tx\t\r\n\t\ty\t\r\nBar\r\n"); $calls = array ( array('document_start',array()), @@ -141,8 +151,8 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { } function testPreformattedList() { - $this->P->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); - $this->P->addMode('listblock',new Doku_Parser_Mode_ListBlock()); + $this->P->addMode('preformatted',new Preformatted()); + $this->P->addMode('listblock',new Listblock()); $this->P->parse(" - x \n * y \nF oo\n x \n y \n -X\n *Y\nBar\n"); $calls = array ( array('document_start',array()), @@ -175,7 +185,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { // test for php function testPHP() { - $this->P->addMode('php',new Doku_Parser_Mode_PHP()); + $this->P->addMode('php',new Php()); $this->P->parse('Foo <php>testing</php> Bar'); $calls = array ( array('document_start',array()), @@ -192,7 +202,7 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { // test with for HTML function testHTML() { - $this->P->addMode('html',new Doku_Parser_Mode_HTML()); + $this->P->addMode('html',new Html()); $this->P->parse('Foo <html>testing</html> Bar'); $calls = array ( array('document_start',array()), @@ -210,9 +220,9 @@ class TestOfDoku_Parser_Preformatted extends TestOfDoku_Parser { function testPreformattedPlusHeaderAndEol() { // Note that EOL must come after preformatted! - $this->P->addMode('preformatted',new Doku_Parser_Mode_Preformatted()); - $this->P->addMode('header',new Doku_Parser_Mode_Header()); - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('preformatted',new Preformatted()); + $this->P->addMode('header',new Header()); + $this->P->addMode('eol',new Eol()); $this->P->parse("F oo\n ==Test==\n y \nBar\n"); $calls = array ( array('document_start',array()), diff --git a/_test/tests/inc/parser/parser_quote.test.php b/_test/tests/inc/parser/parser_quote.test.php index ae14671c1..190f18cc1 100644 --- a/_test/tests/inc/parser/parser_quote.test.php +++ b/_test/tests/inc/parser/parser_quote.test.php @@ -1,10 +1,14 @@ <?php + +use dokuwiki\Parsing\ParserMode\Eol; +use dokuwiki\Parsing\ParserMode\Quote; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Quote extends TestOfDoku_Parser { function testQuote() { - $this->P->addMode('quote',new Doku_Parser_Mode_Quote()); + $this->P->addMode('quote',new Quote()); $this->P->parse("abc\n> def\n>>ghi\nklm"); $calls = array ( array('document_start',array()), @@ -27,7 +31,7 @@ class TestOfDoku_Parser_Quote extends TestOfDoku_Parser { } function testQuoteWinCr() { - $this->P->addMode('quote',new Doku_Parser_Mode_Quote()); + $this->P->addMode('quote',new Quote()); $this->P->parse("abc\r\n> def\r\n>>ghi\r\nklm"); $calls = array ( array('document_start',array()), @@ -50,7 +54,7 @@ class TestOfDoku_Parser_Quote extends TestOfDoku_Parser { } function testQuoteMinumumContext() { - $this->P->addMode('quote',new Doku_Parser_Mode_Quote()); + $this->P->addMode('quote',new Quote()); $this->P->parse("\n> def\n>>ghi\n "); $calls = array ( array('document_start',array()), @@ -67,8 +71,8 @@ class TestOfDoku_Parser_Quote extends TestOfDoku_Parser { } function testQuoteEol() { - $this->P->addMode('quote',new Doku_Parser_Mode_Quote()); - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('quote',new Quote()); + $this->P->addMode('eol',new Eol()); $this->P->parse("abc\n> def\n>>ghi\nklm"); $calls = array ( array('document_start',array()), diff --git a/_test/tests/inc/parser/parser_quotes.test.php b/_test/tests/inc/parser/parser_quotes.test.php index 6f174ddae..fb192d21f 100644 --- a/_test/tests/inc/parser/parser_quotes.test.php +++ b/_test/tests/inc/parser/parser_quotes.test.php @@ -1,4 +1,7 @@ <?php + +use dokuwiki\Parsing\ParserMode\Quotes; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { @@ -11,7 +14,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testSingleQuoteOpening() { $raw = "Foo 'hello Bar"; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -29,7 +32,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testSingleQuoteOpeningSpecial() { $raw = "Foo said:'hello Bar"; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -47,7 +50,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testSingleQuoteClosing() { $raw = "Foo hello' Bar"; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -65,7 +68,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testSingleQuoteClosingSpecial() { $raw = "Foo hello') Bar"; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -83,7 +86,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testSingleQuotes() { $raw = "Foo 'hello' Bar"; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -103,7 +106,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testApostrophe() { $raw = "hey it's fine weather today"; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -122,7 +125,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testSingleQuotesSpecial() { $raw = "Foo ('hello') Bar"; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -142,7 +145,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testDoubleQuoteOpening() { $raw = 'Foo "hello Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -160,7 +163,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testDoubleQuoteOpeningSpecial() { $raw = 'Foo said:"hello Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -178,8 +181,13 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testDoubleQuoteClosing() { $raw = 'Foo hello" Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); - $this->H->status['doublequote'] = 1; + $this->P->addMode('quotes',new Quotes()); + + /** @noinspection PhpUnhandledExceptionInspection */ + $status = $this->getInaccessibleProperty($this->H, 'status'); + $status['doublequote'] = 1; + /** @noinspection PhpUnhandledExceptionInspection */ + $this->setInaccessibleProperty($this->H, 'status', $status); $this->P->parse($raw); $calls = array ( @@ -197,8 +205,13 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testDoubleQuoteClosingSpecial() { $raw = 'Foo hello") Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); - $this->H->status['doublequote'] = 1; + $this->P->addMode('quotes',new Quotes()); + /** @noinspection PhpUnhandledExceptionInspection */ + $status = $this->getInaccessibleProperty($this->H, 'status'); + $status['doublequote'] = 1; + /** @noinspection PhpUnhandledExceptionInspection */ + $this->setInaccessibleProperty($this->H, 'status', $status); + $this->P->parse($raw); $calls = array ( @@ -215,8 +228,13 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { } function testDoubleQuoteClosingSpecial2() { $raw = 'Foo hello") Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); - $this->H->status['doublequote'] = 0; + $this->P->addMode('quotes',new Quotes()); + /** @noinspection PhpUnhandledExceptionInspection */ + $status = $this->getInaccessibleProperty($this->H, 'status'); + $status['doublequote'] = 0; + /** @noinspection PhpUnhandledExceptionInspection */ + $this->setInaccessibleProperty($this->H, 'status', $status); + $this->P->parse($raw); $calls = array ( @@ -234,7 +252,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testDoubleQuotes() { $raw = 'Foo "hello" Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -254,7 +272,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testDoubleQuotesSpecial() { $raw = 'Foo ("hello") Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -274,7 +292,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testDoubleQuotesEnclosingBrackets() { $raw = 'Foo "{hello}" Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -294,7 +312,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testDoubleQuotesEnclosingLink() { $raw = 'Foo "[[www.domain.com]]" Bar'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( @@ -315,7 +333,7 @@ class TestOfDoku_Parser_Quotes extends TestOfDoku_Parser { function testAllQuotes() { $raw = 'There was written "He thought \'It\'s a man\'s world\'".'; - $this->P->addMode('quotes',new Doku_Parser_Mode_Quotes()); + $this->P->addMode('quotes',new Quotes()); $this->P->parse($raw); $calls = array ( diff --git a/_test/tests/inc/parser/parser_replacements.test.php b/_test/tests/inc/parser/parser_replacements.test.php index f0367dac0..d910dba9e 100644 --- a/_test/tests/inc/parser/parser_replacements.test.php +++ b/_test/tests/inc/parser/parser_replacements.test.php @@ -1,10 +1,18 @@ <?php + +use dokuwiki\Parsing\ParserMode\Acronym; +use dokuwiki\Parsing\ParserMode\Entity; +use dokuwiki\Parsing\ParserMode\Hr; +use dokuwiki\Parsing\ParserMode\Multiplyentity; +use dokuwiki\Parsing\ParserMode\Smiley; +use dokuwiki\Parsing\ParserMode\Wordblock; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { function testSingleAcronym() { - $this->P->addMode('acronym',new Doku_Parser_Mode_Acronym(array('FOOBAR'))); + $this->P->addMode('acronym',new Acronym(array('FOOBAR'))); $this->P->parse('abc FOOBAR xyz'); $calls = array ( @@ -21,7 +29,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testAlmostAnAcronym() { - $this->P->addMode('acronym',new Doku_Parser_Mode_Acronym(array('FOOBAR'))); + $this->P->addMode('acronym',new Acronym(array('FOOBAR'))); $this->P->parse('abcFOOBARxyz'); $calls = array ( @@ -36,7 +44,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testPickAcronymCorrectly() { - $this->P->addMode('acronym',new Doku_Parser_Mode_Acronym(array('FOO'))); + $this->P->addMode('acronym',new Acronym(array('FOO'))); $this->P->parse('FOOBAR FOO'); $calls = array ( @@ -53,7 +61,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testMultipleAcronyms() { - $this->P->addMode('acronym',new Doku_Parser_Mode_Acronym(array('FOO','BAR'))); + $this->P->addMode('acronym',new Acronym(array('FOO','BAR'))); $this->P->parse('abc FOO def BAR xyz'); $calls = array ( @@ -73,7 +81,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testMultipleAcronymsWithSubset1() { - $this->P->addMode('acronym',new Doku_Parser_Mode_Acronym(array('FOO','A.FOO','FOO.1','A.FOO.1'))); + $this->P->addMode('acronym',new Acronym(array('FOO','A.FOO','FOO.1','A.FOO.1'))); $this->P->parse('FOO A.FOO FOO.1 A.FOO.1'); $calls = array ( @@ -96,7 +104,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testMultipleAcronymsWithSubset2() { - $this->P->addMode('acronym',new Doku_Parser_Mode_Acronym(array('A.FOO.1','FOO.1','A.FOO','FOO'))); + $this->P->addMode('acronym',new Acronym(array('A.FOO.1','FOO.1','A.FOO','FOO'))); $this->P->parse('FOO A.FOO FOO.1 A.FOO.1'); $calls = array ( @@ -119,7 +127,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testSingleSmileyFail() { - $this->P->addMode('smiley',new Doku_Parser_Mode_Smiley(array(':-)'))); + $this->P->addMode('smiley',new Smiley(array(':-)'))); $this->P->parse('abc:-)xyz'); $calls = array ( @@ -134,7 +142,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testSingleSmiley() { - $this->P->addMode('smiley',new Doku_Parser_Mode_Smiley(array(':-)'))); + $this->P->addMode('smiley',new Smiley(array(':-)'))); $this->P->parse('abc :-) xyz'); $calls = array ( @@ -151,7 +159,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testMultipleSmileysFail() { - $this->P->addMode('smiley',new Doku_Parser_Mode_Smiley(array(':-)','^_^'))); + $this->P->addMode('smiley',new Smiley(array(':-)','^_^'))); $this->P->parse('abc:-)x^_^yz'); $calls = array ( @@ -166,7 +174,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testMultipleSmileys() { - $this->P->addMode('smiley',new Doku_Parser_Mode_Smiley(array(':-)','^_^'))); + $this->P->addMode('smiley',new Smiley(array(':-)','^_^'))); $this->P->parse('abc :-) x ^_^ yz'); $calls = array ( @@ -186,7 +194,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { function testBackslashSmileyFail() { // This smiley is really :-\\ but escaping makes like interesting - $this->P->addMode('smiley',new Doku_Parser_Mode_Smiley(array(':-\\\\'))); + $this->P->addMode('smiley',new Smiley(array(':-\\\\'))); $this->P->parse('abc:-\\\xyz'); $calls = array ( @@ -202,7 +210,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { function testBackslashSmiley() { // This smiley is really :-\\ but escaping makes like interesting - $this->P->addMode('smiley',new Doku_Parser_Mode_Smiley(array(':-\\\\'))); + $this->P->addMode('smiley',new Smiley(array(':-\\\\'))); $this->P->parse('abc :-\\\ xyz'); $calls = array ( @@ -219,7 +227,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testSingleWordblock() { - $this->P->addMode('wordblock',new Doku_Parser_Mode_Wordblock(array('CAT'))); + $this->P->addMode('wordblock',new Wordblock(array('CAT'))); $this->P->parse('abc CAT xyz'); $calls = array ( @@ -236,7 +244,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testWordblockCase() { - $this->P->addMode('wordblock',new Doku_Parser_Mode_Wordblock(array('CAT'))); + $this->P->addMode('wordblock',new Wordblock(array('CAT'))); $this->P->parse('abc cat xyz'); $calls = array ( @@ -253,7 +261,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testMultipleWordblock() { - $this->P->addMode('wordblock',new Doku_Parser_Mode_Wordblock(array('CAT','dog'))); + $this->P->addMode('wordblock',new Wordblock(array('CAT','dog'))); $this->P->parse('abc cat x DOG yz'); $calls = array ( @@ -272,7 +280,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testSingleEntity() { - $this->P->addMode('entity',new Doku_Parser_Mode_Entity(array('->'))); + $this->P->addMode('entity',new Entity(array('->'))); $this->P->parse('x -> y'); $calls = array ( @@ -289,7 +297,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testMultipleEntities() { - $this->P->addMode('entity',new Doku_Parser_Mode_Entity(array('->','<-'))); + $this->P->addMode('entity',new Entity(array('->','<-'))); $this->P->parse('x -> y <- z'); $calls = array ( @@ -308,7 +316,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testMultiplyEntity() { - $this->P->addMode('multiplyentity',new Doku_Parser_Mode_MultiplyEntity()); + $this->P->addMode('multiplyentity',new Multiplyentity()); $this->P->parse('Foo 10x20 Bar'); $calls = array ( @@ -326,7 +334,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { function testMultiplyEntityHex() { // the multiply entity pattern should not match hex numbers, eg. 0x123 - $this->P->addMode('multiplyentity',new Doku_Parser_Mode_MultiplyEntity()); + $this->P->addMode('multiplyentity',new Multiplyentity()); $this->P->parse('Foo 0x123 Bar'); $calls = array ( @@ -341,7 +349,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testHR() { - $this->P->addMode('hr',new Doku_Parser_Mode_HR()); + $this->P->addMode('hr',new Hr()); $this->P->parse("Foo \n ---- \n Bar"); $calls = array ( @@ -359,7 +367,7 @@ class TestOfDoku_Parser_Replacements extends TestOfDoku_Parser { } function testHREol() { - $this->P->addMode('hr',new Doku_Parser_Mode_HR()); + $this->P->addMode('hr',new Hr()); $this->P->parse("Foo \n----\n Bar"); $calls = array ( diff --git a/_test/tests/inc/parser/parser_table.test.php b/_test/tests/inc/parser/parser_table.test.php index f05dd29aa..c233a4072 100644 --- a/_test/tests/inc/parser/parser_table.test.php +++ b/_test/tests/inc/parser/parser_table.test.php @@ -1,10 +1,18 @@ <?php + +use dokuwiki\Parsing\ParserMode\Eol; +use dokuwiki\Parsing\ParserMode\Footnote; +use dokuwiki\Parsing\ParserMode\Formatting; +use dokuwiki\Parsing\ParserMode\Linebreak; +use dokuwiki\Parsing\ParserMode\Table; +use dokuwiki\Parsing\ParserMode\Unformatted; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Table extends TestOfDoku_Parser { function testTable() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc | Row 0 Col 1 | Row 0 Col 2 | Row 0 Col 3 | @@ -48,7 +56,7 @@ def'); } function testTableWinEOL() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse("\r\nabc\r\n| Row 0 Col 1 | Row 0 Col 2 | Row 0 Col 3 |\r\n| Row 1 Col 1 | Row 1 Col 2 | Row 1 Col 3 |\r\ndef"); $calls = array ( array('document_start',array()), @@ -88,7 +96,7 @@ def'); } function testEmptyTable() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc | @@ -113,7 +121,7 @@ def'); } function testTableHeaders() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc ^ X | Y ^ Z | @@ -148,7 +156,7 @@ def'); } function testTableHead() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc ^ X ^ Y ^ Z ^ @@ -197,7 +205,7 @@ def'); } function testTableHeadOneRowTable() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc ^ X ^ Y ^ Z ^ @@ -232,7 +240,7 @@ def'); } function testTableHeadMultiline() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc ^ X1 ^ Y1 ^ Z1 ^ @@ -293,7 +301,7 @@ def'); } function testCellAlignment() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc | X | Y ^ Z | @@ -327,7 +335,7 @@ def'); } function testCellSpan() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc | d || e | @@ -369,7 +377,7 @@ def'); } function testCellRowSpan() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc | a | c:::|| @@ -417,7 +425,7 @@ def'); } function testCellRowSpanFirstRow() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc |::: ^ d:::^:::| ::: | @@ -475,7 +483,7 @@ def'); } function testRowSpanTableHead() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc ^ X1 ^ Y1 ^ Z1 ^ @@ -533,7 +541,7 @@ def'); } function testRowSpanAcrossTableHeadBoundary() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse(' abc ^ X1 ^ Y1 ^ Z1 ^ @@ -600,8 +608,8 @@ def'); } function testCellAlignmentFormatting() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); + $this->P->addMode('table',new Table()); + $this->P->addMode('strong',new Formatting('strong')); $this->P->parse(' abc | **X** | Y ^ Z | @@ -640,8 +648,8 @@ def'); } function testTableEol() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); - $this->P->addMode('eol',new Doku_Parser_Mode_Eol()); + $this->P->addMode('table',new Table()); + $this->P->addMode('eol',new Eol()); $this->P->parse(' abc | Row 0 Col 1 | Row 0 Col 2 | Row 0 Col 3 | @@ -687,8 +695,8 @@ def'); // This is really a failing test - formatting able to spread across cols // Problem is fixing it would mean a major rewrite of table handling function testTableStrong() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); - $this->P->addMode('strong',new Doku_Parser_Mode_Formatting('strong')); + $this->P->addMode('table',new Table()); + $this->P->addMode('strong',new Formatting('strong')); $this->P->parse(' abc | **Row 0 Col 1** | **Row 0 Col 2 | Row 0 Col 3** | @@ -742,8 +750,8 @@ def'); // This is really a failing test - unformatted able to spread across cols // Problem is fixing it would mean a major rewrite of table handling function testTableUnformatted() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); - $this->P->addMode('unformatted',new Doku_Parser_Mode_Unformatted()); + $this->P->addMode('table',new Table()); + $this->P->addMode('unformatted',new Unformatted()); $this->P->parse(' abc | <nowiki>Row 0 Col 1</nowiki> | <nowiki>Row 0 Col 2 | Row 0 Col 3</nowiki> | @@ -791,8 +799,8 @@ def'); } function testTableLinebreak() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); - $this->P->addMode('linebreak',new Doku_Parser_Mode_Linebreak()); + $this->P->addMode('table',new Table()); + $this->P->addMode('linebreak',new Linebreak()); $this->P->parse(' abc | Row 0\\\\ Col 1 | Row 0 Col 2 | Row 0 Col 3 | @@ -841,8 +849,8 @@ def'); // This is really a failing test - footnote able to spread across cols // Problem is fixing it would mean a major rewrite of table handling function testTableFootnote() { - $this->P->addMode('table',new Doku_Parser_Mode_Table()); - $this->P->addMode('footnote',new Doku_Parser_Mode_Footnote()); + $this->P->addMode('table',new Table()); + $this->P->addMode('footnote',new Footnote()); $this->P->parse(' abc | ((Row 0 Col 1)) | ((Row 0 Col 2 | Row 0 Col 3)) | @@ -899,7 +907,7 @@ def'); function testTable_FS1833() { $syntax = " \n| Row 0 Col 1 |\n"; - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse($syntax); $calls = array ( array('document_start',array()), @@ -920,7 +928,7 @@ def'); */ function testTable_CellFix() { $syntax = "\n| r1c1 | r1c2 | r1c3 |\n| r2c1 |\n"; - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse($syntax); $calls = array ( array('document_start',array()), @@ -961,7 +969,7 @@ def'); */ function testTable_CellFix2() { $syntax = "\n| r1c1 |\n| r2c1 | r2c2 | r2c3 |\n"; - $this->P->addMode('table',new Doku_Parser_Mode_Table()); + $this->P->addMode('table',new Table()); $this->P->parse($syntax); $calls = array ( array('document_start',array()), diff --git a/_test/tests/inc/parser/parser_unformatted.test.php b/_test/tests/inc/parser/parser_unformatted.test.php index f20ba5e8b..32c83fcce 100644 --- a/_test/tests/inc/parser/parser_unformatted.test.php +++ b/_test/tests/inc/parser/parser_unformatted.test.php @@ -1,10 +1,13 @@ <?php + +use dokuwiki\Parsing\ParserMode\Unformatted; + require_once 'parser.inc.php'; class TestOfDoku_Parser_Unformatted extends TestOfDoku_Parser { function testNowiki() { - $this->P->addMode('unformatted',new Doku_Parser_Mode_Unformatted()); + $this->P->addMode('unformatted',new Unformatted()); $this->P->parse("Foo <nowiki>testing</nowiki> Bar"); $calls = array ( array('document_start',array()), @@ -21,7 +24,7 @@ class TestOfDoku_Parser_Unformatted extends TestOfDoku_Parser { } function testDoublePercent() { - $this->P->addMode('unformatted',new Doku_Parser_Mode_Unformatted()); + $this->P->addMode('unformatted',new Unformatted()); $this->P->parse("Foo %%testing%% Bar"); $calls = array ( array('document_start',array()), diff --git a/_test/tests/inc/parser/renderer_resolveinterwiki.test.php b/_test/tests/inc/parser/renderer_resolveinterwiki.test.php index 822c41af8..2cd23dfaa 100644 --- a/_test/tests/inc/parser/renderer_resolveinterwiki.test.php +++ b/_test/tests/inc/parser/renderer_resolveinterwiki.test.php @@ -1,6 +1,6 @@ <?php -require_once DOKU_INC . 'inc/parser/renderer.php'; +use dokuwiki\test\mock\Doku_Renderer; /** * Tests for Doku_Renderer::_resolveInterWiki() diff --git a/_test/tests/inc/parser/renderer_xhtml.test.php b/_test/tests/inc/parser/renderer_xhtml.test.php index f7be39a1b..828c6dff6 100644 --- a/_test/tests/inc/parser/renderer_xhtml.test.php +++ b/_test/tests/inc/parser/renderer_xhtml.test.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\Parsing\Handler\Lists; + /** * Class renderer_xhtml_test */ @@ -123,7 +125,7 @@ class renderer_xhtml_test extends DokuWikiTest { $this->R->document_start(); $this->R->listo_open(); - $this->R->listitem_open(1, Doku_Handler_List::NODE); + $this->R->listitem_open(1, Lists::NODE); $this->R->listcontent_open(); $this->R->cdata('item1'); $this->R->listcontent_close(); @@ -145,7 +147,7 @@ class renderer_xhtml_test extends DokuWikiTest { $this->R->listcontent_close(); $this->R->listitem_close(); - $this->R->listitem_open(1, Doku_Handler_List::NODE); + $this->R->listitem_open(1, Lists::NODE); $this->R->listcontent_open(); $this->R->cdata('item3'); $this->R->listcontent_close(); @@ -188,7 +190,7 @@ class renderer_xhtml_test extends DokuWikiTest { $this->R->document_start(); $this->R->listu_open(); - $this->R->listitem_open(1, Doku_Handler_List::NODE); + $this->R->listitem_open(1, Lists::NODE); $this->R->listcontent_open(); $this->R->cdata('item1'); $this->R->listcontent_close(); @@ -210,7 +212,7 @@ class renderer_xhtml_test extends DokuWikiTest { $this->R->listcontent_close(); $this->R->listitem_close(); - $this->R->listitem_open(1, Doku_Handler_List::NODE); + $this->R->listitem_open(1, Lists::NODE); $this->R->listcontent_open(); $this->R->cdata('item3'); $this->R->listcontent_close(); diff --git a/_test/tests/inc/remote.test.php b/_test/tests/inc/remote.test.php index ee040f09a..acc9e7cc8 100644 --- a/_test/tests/inc/remote.test.php +++ b/_test/tests/inc/remote.test.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\Remote\Api; + class MockAuth extends DokuWiki_Auth_Plugin { function isCaseSensitive() { return true; } } @@ -131,7 +133,7 @@ class remote_test extends DokuWikiTest { protected $userinfo; - /** @var RemoteAPI */ + /** @var Api */ protected $remote; function setUp() { @@ -162,7 +164,7 @@ class remote_test extends DokuWikiTest { $conf['useacl'] = 0; $this->userinfo = $USERINFO; - $this->remote = new RemoteAPI(); + $this->remote = new Api(); $auth = new MockAuth(); } @@ -206,7 +208,7 @@ class remote_test extends DokuWikiTest { } /** - * @expectedException RemoteAccessDeniedException + * @expectedException dokuwiki\Remote\AccessDeniedException */ function test_hasAccessFail() { global $conf; @@ -260,7 +262,7 @@ class remote_test extends DokuWikiTest { } /** - * @expectedException RemoteException + * @expectedException dokuwiki\Remote\RemoteException */ function test_forceAccessFail() { global $conf; @@ -275,7 +277,7 @@ class remote_test extends DokuWikiTest { $conf['remoteuser'] = ''; $conf['useacl'] = 1; $USERINFO['grps'] = array('grp'); - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); $this->assertEquals($remoteApi->call('wiki.stringTestMethod'), 'success'); @@ -287,12 +289,12 @@ class remote_test extends DokuWikiTest { } /** - * @expectedException RemoteException + * @expectedException dokuwiki\Remote\RemoteException */ function test_generalCoreFunctionOnArgumentMismatch() { global $conf; $conf['remote'] = 1; - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); $remoteApi->call('wiki.voidTestMethod', array('something')); @@ -305,7 +307,7 @@ class remote_test extends DokuWikiTest { $conf['remoteuser'] = ''; $conf['useacl'] = 1; - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); $this->assertEquals($remoteApi->call('wiki.oneStringArgMethod', array('string')), 'string'); @@ -321,7 +323,7 @@ class remote_test extends DokuWikiTest { $conf['remoteuser'] = ''; $conf['useacl'] = 1; - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $this->assertEquals($remoteApi->call('plugin.testplugin.method1'), null); $this->assertEquals($remoteApi->call('plugin.testplugin.method2', array('string', 7)), array('string', 7, false)); $this->assertEquals($remoteApi->call('plugin.testplugin.method2ext', array('string', 7, true)), array('string', 7, true)); @@ -329,20 +331,20 @@ class remote_test extends DokuWikiTest { } /** - * @expectedException RemoteException + * @expectedException dokuwiki\Remote\RemoteException */ function test_notExistingCall() { global $conf; $conf['remote'] = 1; - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $remoteApi->call('dose not exist'); } function test_publicCallCore() { global $conf; $conf['useacl'] = 1; - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); $this->assertTrue($remoteApi->call('wiki.publicCall')); } @@ -350,28 +352,28 @@ class remote_test extends DokuWikiTest { function test_publicCallPlugin() { global $conf; $conf['useacl'] = 1; - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $this->assertTrue($remoteApi->call('plugin.testplugin.publicCall')); } /** - * @expectedException RemoteAccessDeniedException + * @expectedException dokuwiki\Remote\AccessDeniedException */ function test_publicCallCoreDeny() { global $conf; $conf['useacl'] = 1; - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $remoteApi->getCoreMethods(new RemoteAPICoreTest()); $remoteApi->call('wiki.stringTestMethod'); } /** - * @expectedException RemoteAccessDeniedException + * @expectedException dokuwiki\Remote\AccessDeniedException */ function test_publicCallPluginDeny() { global $conf; $conf['useacl'] = 1; - $remoteApi = new RemoteApi(); + $remoteApi = new Api(); $remoteApi->call('plugin.testplugin.methodString'); } @@ -384,7 +386,7 @@ class remote_test extends DokuWikiTest { global $EVENT_HANDLER; $EVENT_HANDLER->register_hook('RPC_CALL_ADD', 'BEFORE', $this, 'pluginCallCustomPathRegister'); - $remoteApi = new RemoteAPI(); + $remoteApi = new Api(); $result = $remoteApi->call('custom.path'); $this->assertEquals($result, 'success'); } diff --git a/_test/tests/inc/remoteapicore.test.php b/_test/tests/inc/remoteapicore.test.php index c3eda6349..e8277c2c1 100644 --- a/_test/tests/inc/remoteapicore.test.php +++ b/_test/tests/inc/remoteapicore.test.php @@ -1,5 +1,9 @@ <?php +use dokuwiki\Remote\Api; +use dokuwiki\Remote\ApiCore; +use dokuwiki\test\mock\DokuWiki_Auth_Plugin; + /** * Class remoteapicore_test */ @@ -7,7 +11,7 @@ class remoteapicore_test extends DokuWikiTest { protected $userinfo; protected $oldAuthAcl; - /** @var RemoteAPI */ + /** @var Api */ protected $remote; public function setUp() { @@ -27,7 +31,7 @@ class remoteapicore_test extends DokuWikiTest { $conf['remoteuser'] = '@user'; $conf['useacl'] = 0; - $this->remote = new RemoteAPI(); + $this->remote = new Api(); } public function tearDown() { @@ -466,7 +470,7 @@ You can use up to five different levels of', } public function test_getXMLRPCAPIVersion() { - $this->assertEquals(DOKU_API_VERSION, $this->remote->call('dokuwiki.getXMLRPCAPIVersion')); + $this->assertEquals(ApiCore::API_VERSION, $this->remote->call('dokuwiki.getXMLRPCAPIVersion')); } public function test_getRPCVersionSupported() { diff --git a/_test/tests/inc/remoteapicore_aclcheck.test.php b/_test/tests/inc/remoteapicore_aclcheck.test.php index 25aff331f..6ba7f1dcf 100644 --- a/_test/tests/inc/remoteapicore_aclcheck.test.php +++ b/_test/tests/inc/remoteapicore_aclcheck.test.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\Remote\Api; + /** * Class remoteapicore_test */ @@ -7,7 +9,7 @@ class remoteapicore_aclcheck_test extends DokuWikiTest { protected $userinfo; protected $oldAuthAcl; - /** @var RemoteAPI */ + /** @var Api */ protected $remote; protected $pluginsEnabled = array('auth_plugin_authplain'); @@ -38,7 +40,7 @@ class remoteapicore_aclcheck_test extends DokuWikiTest { $conf['remoteuser'] = '@user'; $conf['useacl'] = 0; - $this->remote = new RemoteAPI(); + $this->remote = new Api(); } diff --git a/inc/FeedParser.php b/inc/FeedParser.php index 39434dcaf..9b9db6f1b 100644 --- a/inc/FeedParser.php +++ b/inc/FeedParser.php @@ -5,8 +5,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * We override some methods of the original SimplePie class here */ @@ -15,7 +13,7 @@ class FeedParser extends SimplePie { /** * Constructor. Set some defaults */ - function __construct(){ + public function __construct(){ parent::__construct(); $this->enable_cache(false); $this->set_file_class('FeedParser_File'); @@ -26,7 +24,7 @@ class FeedParser extends SimplePie { * * @param string $url */ - function feed_url($url){ + public function feed_url($url){ $this->set_feed_url($url); } } @@ -37,12 +35,7 @@ class FeedParser extends SimplePie { * Replaces SimplePie's own class */ class FeedParser_File extends SimplePie_File { - var $http; - var $useragent; - var $success = true; - var $headers = array(); - var $body; - var $error; + protected $http; /** @noinspection PhpMissingParentConstructorInspection */ /** @@ -52,7 +45,7 @@ class FeedParser_File extends SimplePie_File { * * @inheritdoc */ - function __construct($url, $timeout=10, $redirects=5, + public function __construct($url, $timeout=10, $redirects=5, $headers=null, $useragent=null, $force_fsockopen=false, $curl_options = array()) { $this->http = new DokuHTTPClient(); $this->success = $this->http->sendRequest($url); @@ -67,17 +60,17 @@ class FeedParser_File extends SimplePie_File { } /** @inheritdoc */ - function headers(){ + public function headers(){ return $this->headers; } /** @inheritdoc */ - function body(){ + public function body(){ return $this->body; } /** @inheritdoc */ - function close(){ + public function close(){ return true; } diff --git a/inc/Form/ButtonElement.php b/inc/Form/ButtonElement.php index e2afe9c97..4f585f0c1 100644 --- a/inc/Form/ButtonElement.php +++ b/inc/Form/ButtonElement.php @@ -17,7 +17,7 @@ class ButtonElement extends Element { * @param string $name * @param string $content HTML content of the button. You have to escape it yourself. */ - function __construct($name, $content = '') { + public function __construct($name, $content = '') { parent::__construct('button', array('name' => $name, 'value' => 1)); $this->content = $content; } diff --git a/inc/Form/DropdownElement.php b/inc/Form/DropdownElement.php index 023b67dd3..51f475196 100644 --- a/inc/Form/DropdownElement.php +++ b/inc/Form/DropdownElement.php @@ -104,7 +104,9 @@ class DropdownElement extends InputElement { */ public function attr($name, $value = null) { if(strtolower($name) == 'multiple') { - throw new \InvalidArgumentException('Sorry, the dropdown element does not support the "multiple" attribute'); + throw new \InvalidArgumentException( + 'Sorry, the dropdown element does not support the "multiple" attribute' + ); } return parent::attr($name, $value); } @@ -181,7 +183,13 @@ class DropdownElement extends InputElement { if($this->useInput) $this->prefillInput(); $html = '<select ' . buildAttributes($this->attrs()) . '>'; - $html = array_reduce($this->optGroups, function($html, OptGroup $optGroup) {return $html . $optGroup->toHTML();}, $html); + $html = array_reduce( + $this->optGroups, + function ($html, OptGroup $optGroup) { + return $html . $optGroup->toHTML(); + }, + $html + ); $html .= '</select>'; return $html; diff --git a/inc/Form/Form.php b/inc/Form/Form.php index 92bbd30f4..c741a698f 100644 --- a/inc/Form/Form.php +++ b/inc/Form/Form.php @@ -84,7 +84,9 @@ class Form extends Element { /** * Get the position of the element in the form or false if it is not in the form * - * Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. + * Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates + * to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the + * return value of this function. * * @param Element $element * @@ -157,7 +159,9 @@ class Form extends Element { * @return Element */ public function addElement(Element $element, $pos = -1) { - if(is_a($element, '\dokuwiki\Form\Form')) throw new \InvalidArgumentException('You can\'t add a form to a form'); + if(is_a($element, '\dokuwiki\Form\Form')) throw new \InvalidArgumentException( + 'You can\'t add a form to a form' + ); if($pos < 0) { $this->elements[] = $element; } else { @@ -173,7 +177,9 @@ class Form extends Element { * @param int $pos 0-based position of the element to replace */ public function replaceElement(Element $element, $pos) { - if(is_a($element, '\dokuwiki\Form\Form')) throw new \InvalidArgumentException('You can\'t add a form to a form'); + if(is_a($element, '\dokuwiki\Form\Form')) throw new \InvalidArgumentException( + 'You can\'t add a form to a form' + ); array_splice($this->elements, $pos, 1, array($element)); } diff --git a/inc/Form/OptGroup.php b/inc/Form/OptGroup.php index 791f0b3f6..40149b171 100644 --- a/inc/Form/OptGroup.php +++ b/inc/Form/OptGroup.php @@ -51,9 +51,13 @@ class OptGroup extends Element { $this->options = array(); foreach($options as $key => $val) { if (is_array($val)) { - if (!key_exists('label', $val)) throw new \InvalidArgumentException('If option is given as array, it has to have a "label"-key!'); + if (!key_exists('label', $val)) throw new \InvalidArgumentException( + 'If option is given as array, it has to have a "label"-key!' + ); if (key_exists('attrs', $val) && is_array($val['attrs']) && key_exists('selected', $val['attrs'])) { - throw new \InvalidArgumentException('Please use function "DropdownElement::val()" to set the selected option'); + throw new \InvalidArgumentException( + 'Please use function "DropdownElement::val()" to set the selected option' + ); } $this->options[$key] = $val; } elseif(is_int($key)) { @@ -93,7 +97,9 @@ class OptGroup extends Element { if (!empty($val['attrs']) && is_array($val['attrs'])) { $attrs = buildAttributes($val['attrs']); } - $html .= '<option' . $selected . ' value="' . hsc($key) . '" '.$attrs.'>' . hsc($val['label']) . '</option>'; + $html .= '<option' . $selected . ' value="' . hsc($key) . '" '.$attrs.'>'; + $html .= hsc($val['label']); + $html .= '</option>'; } return $html; } diff --git a/inc/HTTPClient.php b/inc/HTTPClient.php index e20b7d98f..1659392ce 100644 --- a/inc/HTTPClient.php +++ b/inc/HTTPClient.php @@ -28,53 +28,53 @@ class HTTPClientException extends Exception { } */ class HTTPClient { //set these if you like - var $agent; // User agent - var $http; // HTTP version defaults to 1.0 - var $timeout; // read timeout (seconds) - var $cookies; - var $referer; - var $max_redirect; - var $max_bodysize; - var $max_bodysize_abort = true; // if set, abort if the response body is bigger than max_bodysize - var $header_regexp; // if set this RE must match against the headers, else abort - var $headers; - var $debug; - var $start = 0.0; // for timings - var $keep_alive = true; // keep alive rocks + public $agent; // User agent + public $http; // HTTP version defaults to 1.0 + public $timeout; // read timeout (seconds) + public $cookies; + public $referer; + public $max_redirect; + public $max_bodysize; + public $max_bodysize_abort = true; // if set, abort if the response body is bigger than max_bodysize + public $header_regexp; // if set this RE must match against the headers, else abort + public $headers; + public $debug; + public $start = 0.0; // for timings + public $keep_alive = true; // keep alive rocks // don't set these, read on error - var $error; - var $redirect_count; + public $error; + public $redirect_count; // read these after a successful request - var $status; - var $resp_body; - var $resp_headers; + public $status; + public $resp_body; + public $resp_headers; // set these to do basic authentication - var $user; - var $pass; + public $user; + public $pass; // set these if you need to use a proxy - var $proxy_host; - var $proxy_port; - var $proxy_user; - var $proxy_pass; - var $proxy_ssl; //boolean set to true if your proxy needs SSL - var $proxy_except; // regexp of URLs to exclude from proxy + public $proxy_host; + public $proxy_port; + public $proxy_user; + public $proxy_pass; + public $proxy_ssl; //boolean set to true if your proxy needs SSL + public $proxy_except; // regexp of URLs to exclude from proxy // list of kept alive connections - static $connections = array(); + protected static $connections = array(); // what we use as boundary on multipart/form-data posts - var $boundary = '---DokuWikiHTTPClient--4523452351'; + protected $boundary = '---DokuWikiHTTPClient--4523452351'; /** * Constructor. * * @author Andreas Gohr <andi@splitbrain.org> */ - function __construct(){ + public function __construct(){ $this->agent = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; '.PHP_OS.')'; $this->timeout = 15; $this->cookies = array(); @@ -105,7 +105,7 @@ class HTTPClient { * * @author Andreas Gohr <andi@splitbrain.org> */ - function get($url,$sloppy304=false){ + public function get($url,$sloppy304=false){ if(!$this->sendRequest($url)) return false; if($this->status == 304 && $sloppy304) return $this->resp_body; if($this->status < 200 || $this->status > 206) return false; @@ -127,7 +127,7 @@ class HTTPClient { * * @author Andreas Gohr <andi@splitbrain.org> */ - function dget($url,$data,$sloppy304=false){ + public function dget($url,$data,$sloppy304=false){ if(strpos($url,'?')){ $url .= '&'; }else{ @@ -147,7 +147,7 @@ class HTTPClient { * @return false|string response body, false on error * @author Andreas Gohr <andi@splitbrain.org> */ - function post($url,$data){ + public function post($url,$data){ if(!$this->sendRequest($url,$data,'POST')) return false; if($this->status < 200 || $this->status > 206) return false; return $this->resp_body; @@ -170,7 +170,7 @@ class HTTPClient { * @author Andreas Goetz <cpuidle@gmx.de> * @author Andreas Gohr <andi@splitbrain.org> */ - function sendRequest($url,$data='',$method='GET'){ + public function sendRequest($url,$data='',$method='GET'){ $this->start = $this->_time(); $this->error = ''; $this->status = 0; @@ -398,8 +398,15 @@ class HTTPClient { //read body (with chunked encoding if needed) $r_body = ''; - if((isset($this->resp_headers['transfer-encoding']) && $this->resp_headers['transfer-encoding'] == 'chunked') - || (isset($this->resp_headers['transfer-coding']) && $this->resp_headers['transfer-coding'] == 'chunked')){ + if( + ( + isset($this->resp_headers['transfer-encoding']) && + $this->resp_headers['transfer-encoding'] == 'chunked' + ) || ( + isset($this->resp_headers['transfer-coding']) && + $this->resp_headers['transfer-coding'] == 'chunked' + ) + ) { $abort = false; do { $chunk_size = ''; @@ -433,7 +440,11 @@ class HTTPClient { // read up to the content-length or max_bodysize // for keep alive we need to read the whole message to clean up the socket for the next read - if(!$this->keep_alive && $this->max_bodysize && $this->max_bodysize < $this->resp_headers['content-length']){ + if( + !$this->keep_alive && + $this->max_bodysize && + $this->max_bodysize < $this->resp_headers['content-length'] + ) { $length = $this->max_bodysize; }else{ $length = $this->resp_headers['content-length']; @@ -506,7 +517,7 @@ class HTTPClient { * @throws HTTPClientException when a tunnel is needed but could not be established * @return bool true if a tunnel was established */ - function _ssltunnel(&$socket, &$requesturl){ + protected function _ssltunnel(&$socket, &$requesturl){ if(!$this->proxy_host) return false; $requestinfo = parse_url($requesturl); if($requestinfo['scheme'] != 'https') return false; @@ -550,7 +561,9 @@ class HTTPClient { return true; } - throw new HTTPClientException('Failed to set up crypto for secure connection to '.$requestinfo['host'], -151); + throw new HTTPClientException( + 'Failed to set up crypto for secure connection to '.$requestinfo['host'], -151 + ); } throw new HTTPClientException('Failed to establish secure proxy connection', -150); @@ -566,7 +579,7 @@ class HTTPClient { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function _sendData($socket, $data, $message) { + protected function _sendData($socket, $data, $message) { // send request $towrite = strlen($data); $written = 0; @@ -611,7 +624,7 @@ class HTTPClient { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function _readData($socket, $nbytes, $message, $ignore_eof = false) { + protected function _readData($socket, $nbytes, $message, $ignore_eof = false) { $r_data = ''; // Does not return immediately so timeout and eof can be checked if ($nbytes < 0) $nbytes = 0; @@ -661,7 +674,7 @@ class HTTPClient { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function _readLine($socket, $message) { + protected function _readLine($socket, $message) { $r_data = ''; do { $time_used = $this->_time() - $this->start; @@ -697,7 +710,7 @@ class HTTPClient { * @param string $info * @param mixed $var */ - function _debug($info,$var=null){ + protected function _debug($info,$var=null){ if(!$this->debug) return; if(php_sapi_name() == 'cli'){ $this->_debug_text($info, $var); @@ -712,7 +725,7 @@ class HTTPClient { * @param string $info * @param mixed $var */ - function _debug_html($info, $var=null){ + protected function _debug_html($info, $var=null){ print '<b>'.$info.'</b> '.($this->_time() - $this->start).'s<br />'; if(!is_null($var)){ ob_start(); @@ -729,7 +742,7 @@ class HTTPClient { * @param string $info * @param mixed $var */ - function _debug_text($info, $var=null){ + protected function _debug_text($info, $var=null){ print '*'.$info.'* '.($this->_time() - $this->start)."s\n"; if(!is_null($var)) print_r($var); print "\n-----------------------------------------------\n"; @@ -740,7 +753,7 @@ class HTTPClient { * * @return float */ - static function _time(){ + protected static function _time(){ list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } @@ -755,7 +768,7 @@ class HTTPClient { * @param string $string * @return array */ - function _parseHeaders($string){ + protected function _parseHeaders($string){ $headers = array(); $lines = explode("\n",$string); array_shift($lines); //skip first line (status) @@ -786,7 +799,7 @@ class HTTPClient { * @param array $headers * @return string */ - function _buildHeaders($headers){ + protected function _buildHeaders($headers){ $string = ''; foreach($headers as $key => $value){ if($value === '') continue; @@ -802,7 +815,7 @@ class HTTPClient { * * @return string */ - function _getCookies(){ + protected function _getCookies(){ $headers = ''; foreach ($this->cookies as $key => $val){ $headers .= "$key=$val; "; @@ -820,7 +833,7 @@ class HTTPClient { * @param array $data * @return string */ - function _postEncode($data){ + protected function _postEncode($data){ return http_build_query($data,'','&'); } @@ -833,7 +846,7 @@ class HTTPClient { * @param array $data * @return string */ - function _postMultipartEncode($data){ + protected function _postMultipartEncode($data){ $boundary = '--'.$this->boundary; $out = ''; foreach($data as $key => $val){ @@ -864,7 +877,7 @@ class HTTPClient { * @param string $port * @return string unique identifier */ - function _uniqueConnectionId($server, $port) { + protected function _uniqueConnectionId($server, $port) { return "$server:$port"; } } @@ -882,7 +895,7 @@ class DokuHTTPClient extends HTTPClient { * * @author Andreas Gohr <andi@splitbrain.org> */ - function __construct(){ + public function __construct(){ global $conf; // call parent constructor @@ -923,7 +936,7 @@ class DokuHTTPClient extends HTTPClient { * @param string $method * @return bool */ - function sendRequest($url,$data='',$method='GET'){ + public function sendRequest($url,$data='',$method='GET'){ $httpdata = array('url' => $url, 'data' => $data, 'method' => $method); diff --git a/inc/Input.class.php b/inc/Input.class.php index 199994d8d..2a6f35de4 100644 --- a/inc/Input.class.php +++ b/inc/Input.class.php @@ -28,7 +28,7 @@ class Input { /** * Intilizes the Input class and it subcomponents */ - function __construct() { + public function __construct() { $this->access = &$_REQUEST; $this->post = new PostInput(); $this->get = new GetInput(); @@ -273,12 +273,13 @@ class Input { * Internal class used for $_POST access in Input class */ class PostInput extends Input { + protected $access; - /** + /** @noinspection PhpMissingParentConstructorInspection * Initialize the $access array, remove subclass members */ - function __construct() { + public function __construct() { $this->access = &$_POST; } @@ -300,10 +301,10 @@ class PostInput extends Input { class GetInput extends Input { protected $access; - /** + /** @noinspection PhpMissingParentConstructorInspection * Initialize the $access array, remove subclass members */ - function __construct() { + public function __construct() { $this->access = &$_GET; } @@ -325,10 +326,10 @@ class GetInput extends Input { class ServerInput extends Input { protected $access; - /** + /** @noinspection PhpMissingParentConstructorInspection * Initialize the $access array, remove subclass members */ - function __construct() { + public function __construct() { $this->access = &$_SERVER; } diff --git a/inc/JSON.php b/inc/JSON.php index fe4ca5cef..ec5fc70bf 100644 --- a/inc/JSON.php +++ b/inc/JSON.php @@ -55,9 +55,6 @@ * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 */ -// for DokuWiki -if(!defined('DOKU_INC')) die('meh.'); - /** * Marker constant for JSON::decode(), used to flag stack state */ diff --git a/inc/Mailer.class.php b/inc/Mailer.class.php index 7968ce9fc..c1b1d09a2 100644 --- a/inc/Mailer.class.php +++ b/inc/Mailer.class.php @@ -186,7 +186,7 @@ class Mailer { * * @param string $text plain text body * @param array $textrep replacements to apply on the text part - * @param array $htmlrep replacements to apply on the HTML part, null to use $textrep (with urls wrapped in <a> tags) + * @param array $htmlrep replacements to apply on the HTML part, null to use $textrep (urls wrapped in <a> tags) * @param string $html the HTML body, leave null to create it from $text * @param bool $wrap wrap the HTML in the default header/Footer */ @@ -616,7 +616,11 @@ class Mailer { 'NAME' => $INFO['userinfo']['name'], 'MAIL' => $INFO['userinfo']['mail'] ); - $signature = str_replace('@DOKUWIKIURL@', $this->replacements['text']['DOKUWIKIURL'], $lang['email_signature_text']); + $signature = str_replace( + '@DOKUWIKIURL@', + $this->replacements['text']['DOKUWIKIURL'], + $lang['email_signature_text'] + ); $this->replacements['text']['EMAILSIGNATURE'] = "\n-- \n" . $signature . "\n"; $this->replacements['html'] = array( diff --git a/inc/Manifest.php b/inc/Manifest.php index 0df9c2b81..5c6d828da 100644 --- a/inc/Manifest.php +++ b/inc/Manifest.php @@ -37,7 +37,9 @@ class Manifest } if (empty($manifest['theme_color'])) { - $manifest['theme_color'] = !empty($replacements['__theme_color__']) ? $replacements['__theme_color__'] : $replacements['__background_alt__']; + $manifest['theme_color'] = !empty($replacements['__theme_color__']) + ? $replacements['__theme_color__'] + : $replacements['__background_alt__']; } if (empty($manifest['icons'])) { diff --git a/inc/Parsing/Handler/Block.php b/inc/Parsing/Handler/Block.php new file mode 100644 index 000000000..4cfa686d4 --- /dev/null +++ b/inc/Parsing/Handler/Block.php @@ -0,0 +1,211 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +/** + * Handler for paragraphs + * + * @author Harry Fuecks <hfuecks@gmail.com> + */ +class Block +{ + protected $calls = array(); + protected $skipEol = false; + protected $inParagraph = false; + + // Blocks these should not be inside paragraphs + protected $blockOpen = array( + 'header', + 'listu_open','listo_open','listitem_open','listcontent_open', + 'table_open','tablerow_open','tablecell_open','tableheader_open','tablethead_open', + 'quote_open', + 'code','file','hr','preformatted','rss', + 'htmlblock','phpblock', + 'footnote_open', + ); + + protected $blockClose = array( + 'header', + 'listu_close','listo_close','listitem_close','listcontent_close', + 'table_close','tablerow_close','tablecell_close','tableheader_close','tablethead_close', + 'quote_close', + 'code','file','hr','preformatted','rss', + 'htmlblock','phpblock', + 'footnote_close', + ); + + // Stacks can contain paragraphs + protected $stackOpen = array( + 'section_open', + ); + + protected $stackClose = array( + 'section_close', + ); + + + /** + * Constructor. Adds loaded syntax plugins to the block and stack + * arrays + * + * @author Andreas Gohr <andi@splitbrain.org> + */ + public function __construct() + { + global $DOKU_PLUGINS; + //check if syntax plugins were loaded + if (empty($DOKU_PLUGINS['syntax'])) return; + foreach ($DOKU_PLUGINS['syntax'] as $n => $p) { + $ptype = $p->getPType(); + if ($ptype == 'block') { + $this->blockOpen[] = 'plugin_'.$n; + $this->blockClose[] = 'plugin_'.$n; + } elseif ($ptype == 'stack') { + $this->stackOpen[] = 'plugin_'.$n; + $this->stackClose[] = 'plugin_'.$n; + } + } + } + + protected function openParagraph($pos) + { + if ($this->inParagraph) return; + $this->calls[] = array('p_open',array(), $pos); + $this->inParagraph = true; + $this->skipEol = true; + } + + /** + * Close a paragraph if needed + * + * This function makes sure there are no empty paragraphs on the stack + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string|integer $pos + */ + protected function closeParagraph($pos) + { + if (!$this->inParagraph) return; + // look back if there was any content - we don't want empty paragraphs + $content = ''; + $ccount = count($this->calls); + for ($i=$ccount-1; $i>=0; $i--) { + if ($this->calls[$i][0] == 'p_open') { + break; + } elseif ($this->calls[$i][0] == 'cdata') { + $content .= $this->calls[$i][1][0]; + } else { + $content = 'found markup'; + break; + } + } + + if (trim($content)=='') { + //remove the whole paragraph + //array_splice($this->calls,$i); // <- this is much slower than the loop below + for ($x=$ccount; $x>$i; + $x--) array_pop($this->calls); + } else { + // remove ending linebreaks in the paragraph + $i=count($this->calls)-1; + if ($this->calls[$i][0] == 'cdata') $this->calls[$i][1][0] = rtrim($this->calls[$i][1][0], "\n"); + $this->calls[] = array('p_close',array(), $pos); + } + + $this->inParagraph = false; + $this->skipEol = true; + } + + protected function addCall($call) + { + $key = count($this->calls); + if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) { + $this->calls[$key-1][1][0] .= $call[1][0]; + } else { + $this->calls[] = $call; + } + } + + // simple version of addCall, without checking cdata + protected function storeCall($call) + { + $this->calls[] = $call; + } + + /** + * Processes the whole instruction stack to open and close paragraphs + * + * @author Harry Fuecks <hfuecks@gmail.com> + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param array $calls + * + * @return array + */ + public function process($calls) + { + // open first paragraph + $this->openParagraph(0); + foreach ($calls as $key => $call) { + $cname = $call[0]; + if ($cname == 'plugin') { + $cname='plugin_'.$call[1][0]; + $plugin = true; + $plugin_open = (($call[1][2] == DOKU_LEXER_ENTER) || ($call[1][2] == DOKU_LEXER_SPECIAL)); + $plugin_close = (($call[1][2] == DOKU_LEXER_EXIT) || ($call[1][2] == DOKU_LEXER_SPECIAL)); + } else { + $plugin = false; + } + /* stack */ + if (in_array($cname, $this->stackClose) && (!$plugin || $plugin_close)) { + $this->closeParagraph($call[2]); + $this->storeCall($call); + $this->openParagraph($call[2]); + continue; + } + if (in_array($cname, $this->stackOpen) && (!$plugin || $plugin_open)) { + $this->closeParagraph($call[2]); + $this->storeCall($call); + $this->openParagraph($call[2]); + continue; + } + /* block */ + // If it's a substition it opens and closes at the same call. + // To make sure next paragraph is correctly started, let close go first. + if (in_array($cname, $this->blockClose) && (!$plugin || $plugin_close)) { + $this->closeParagraph($call[2]); + $this->storeCall($call); + $this->openParagraph($call[2]); + continue; + } + if (in_array($cname, $this->blockOpen) && (!$plugin || $plugin_open)) { + $this->closeParagraph($call[2]); + $this->storeCall($call); + continue; + } + /* eol */ + if ($cname == 'eol') { + // Check this isn't an eol instruction to skip... + if (!$this->skipEol) { + // Next is EOL => double eol => mark as paragraph + if (isset($calls[$key+1]) && $calls[$key+1][0] == 'eol') { + $this->closeParagraph($call[2]); + $this->openParagraph($call[2]); + } else { + //if this is just a single eol make a space from it + $this->addCall(array('cdata',array("\n"), $call[2])); + } + } + continue; + } + /* normal */ + $this->addCall($call); + $this->skipEol = false; + } + // close last paragraph + $call = end($this->calls); + $this->closeParagraph($call[2]); + return $this->calls; + } +} diff --git a/inc/Parsing/Handler/CallWriter.php b/inc/Parsing/Handler/CallWriter.php new file mode 100644 index 000000000..2457143ed --- /dev/null +++ b/inc/Parsing/Handler/CallWriter.php @@ -0,0 +1,40 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +class CallWriter implements CallWriterInterface +{ + + /** @var \Doku_Handler $Handler */ + protected $Handler; + + /** + * @param \Doku_Handler $Handler + */ + public function __construct(\Doku_Handler $Handler) + { + $this->Handler = $Handler; + } + + /** @inheritdoc */ + public function writeCall($call) + { + $this->Handler->calls[] = $call; + } + + /** @inheritdoc */ + public function writeCalls($calls) + { + $this->Handler->calls = array_merge($this->Handler->calls, $calls); + } + + /** + * @inheritdoc + * function is required, but since this call writer is first/highest in + * the chain it is not required to do anything + */ + public function finalise() + { + unset($this->Handler); + } +} diff --git a/inc/Parsing/Handler/CallWriterInterface.php b/inc/Parsing/Handler/CallWriterInterface.php new file mode 100644 index 000000000..1ade7c060 --- /dev/null +++ b/inc/Parsing/Handler/CallWriterInterface.php @@ -0,0 +1,30 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +interface CallWriterInterface +{ + /** + * Add a call to our call list + * + * @param $call the call to be added + */ + public function writeCall($call); + + /** + * Append a list of calls to our call list + * + * @param $calls list of calls to be appended + */ + public function writeCalls($calls); + + /** + * Explicit request to finish up and clean up NOW! + * (probably because document end has been reached) + * + * If part of a CallWriter chain, call finalise on + * the original call writer + * + */ + public function finalise(); +} diff --git a/inc/Parsing/Handler/Lists.php b/inc/Parsing/Handler/Lists.php new file mode 100644 index 000000000..c4428fe46 --- /dev/null +++ b/inc/Parsing/Handler/Lists.php @@ -0,0 +1,213 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +class Lists implements ReWriterInterface +{ + + /** @var CallWriterInterface original call writer */ + protected $callWriter; + + protected $calls = array(); + protected $listCalls = array(); + protected $listStack = array(); + + protected $initialDepth = 0; + + const NODE = 1; + + + /** @inheritdoc */ + public function __construct(CallWriterInterface $CallWriter) + { + $this->callWriter = $CallWriter; + } + + /** @inheritdoc */ + public function writeCall($call) + { + $this->calls[] = $call; + } + + /** + * @inheritdoc + * Probably not needed but just in case... + */ + public function writeCalls($calls) + { + $this->calls = array_merge($this->calls, $calls); + } + + /** @inheritdoc */ + public function finalise() + { + $last_call = end($this->calls); + $this->writeCall(array('list_close',array(), $last_call[2])); + + $this->process(); + $this->callWriter->finalise(); + unset($this->callWriter); + } + + /** @inheritdoc */ + public function process() + { + + foreach ($this->calls as $call) { + switch ($call[0]) { + case 'list_item': + $this->listOpen($call); + break; + case 'list_open': + $this->listStart($call); + break; + case 'list_close': + $this->listEnd($call); + break; + default: + $this->listContent($call); + break; + } + } + + $this->callWriter->writeCalls($this->listCalls); + return $this->callWriter; + } + + protected function listStart($call) + { + $depth = $this->interpretSyntax($call[1][0], $listType); + + $this->initialDepth = $depth; + // array(list type, current depth, index of current listitem_open) + $this->listStack[] = array($listType, $depth, 1); + + $this->listCalls[] = array('list'.$listType.'_open',array(),$call[2]); + $this->listCalls[] = array('listitem_open',array(1),$call[2]); + $this->listCalls[] = array('listcontent_open',array(),$call[2]); + } + + + protected function listEnd($call) + { + $closeContent = true; + + while ($list = array_pop($this->listStack)) { + if ($closeContent) { + $this->listCalls[] = array('listcontent_close',array(),$call[2]); + $closeContent = false; + } + $this->listCalls[] = array('listitem_close',array(),$call[2]); + $this->listCalls[] = array('list'.$list[0].'_close', array(), $call[2]); + } + } + + protected function listOpen($call) + { + $depth = $this->interpretSyntax($call[1][0], $listType); + $end = end($this->listStack); + $key = key($this->listStack); + + // Not allowed to be shallower than initialDepth + if ($depth < $this->initialDepth) { + $depth = $this->initialDepth; + } + + if ($depth == $end[1]) { + // Just another item in the list... + if ($listType == $end[0]) { + $this->listCalls[] = array('listcontent_close',array(),$call[2]); + $this->listCalls[] = array('listitem_close',array(),$call[2]); + $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]); + $this->listCalls[] = array('listcontent_open',array(),$call[2]); + + // new list item, update list stack's index into current listitem_open + $this->listStack[$key][2] = count($this->listCalls) - 2; + + // Switched list type... + } else { + $this->listCalls[] = array('listcontent_close',array(),$call[2]); + $this->listCalls[] = array('listitem_close',array(),$call[2]); + $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]); + $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]); + $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]); + $this->listCalls[] = array('listcontent_open',array(),$call[2]); + + array_pop($this->listStack); + $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2); + } + } elseif ($depth > $end[1]) { // Getting deeper... + $this->listCalls[] = array('listcontent_close',array(),$call[2]); + $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]); + $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]); + $this->listCalls[] = array('listcontent_open',array(),$call[2]); + + // set the node/leaf state of this item's parent listitem_open to NODE + $this->listCalls[$this->listStack[$key][2]][1][1] = self::NODE; + + $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2); + } else { // Getting shallower ( $depth < $end[1] ) + $this->listCalls[] = array('listcontent_close',array(),$call[2]); + $this->listCalls[] = array('listitem_close',array(),$call[2]); + $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]); + + // Throw away the end - done + array_pop($this->listStack); + + while (1) { + $end = end($this->listStack); + $key = key($this->listStack); + + if ($end[1] <= $depth) { + // Normalize depths + $depth = $end[1]; + + $this->listCalls[] = array('listitem_close',array(),$call[2]); + + if ($end[0] == $listType) { + $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]); + $this->listCalls[] = array('listcontent_open',array(),$call[2]); + + // new list item, update list stack's index into current listitem_open + $this->listStack[$key][2] = count($this->listCalls) - 2; + } else { + // Switching list type... + $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]); + $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]); + $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]); + $this->listCalls[] = array('listcontent_open',array(),$call[2]); + + array_pop($this->listStack); + $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2); + } + + break; + + // Haven't dropped down far enough yet.... ( $end[1] > $depth ) + } else { + $this->listCalls[] = array('listitem_close',array(),$call[2]); + $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]); + + array_pop($this->listStack); + } + } + } + } + + protected function listContent($call) + { + $this->listCalls[] = $call; + } + + protected function interpretSyntax($match, & $type) + { + if (substr($match, -1) == '*') { + $type = 'u'; + } else { + $type = 'o'; + } + // Is the +1 needed? It used to be count(explode(...)) + // but I don't think the number is seen outside this handler + return substr_count(str_replace("\t", ' ', $match), ' ') + 1; + } +} diff --git a/inc/Parsing/Handler/Nest.php b/inc/Parsing/Handler/Nest.php new file mode 100644 index 000000000..b0044a3cb --- /dev/null +++ b/inc/Parsing/Handler/Nest.php @@ -0,0 +1,83 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +/** + * Generic call writer class to handle nesting of rendering instructions + * within a render instruction. Also see nest() method of renderer base class + * + * @author Chris Smith <chris@jalakai.co.uk> + */ +class Nest implements ReWriterInterface +{ + + /** @var CallWriterInterface original CallWriter */ + protected $callWriter; + + protected $calls = array(); + protected $closingInstruction; + + /** + * @inheritdoc + * + * @param CallWriterInterface $CallWriter the parser's current call writer, i.e. the one above us in the chain + * @param string $close closing instruction name, this is required to properly terminate the + * syntax mode if the document ends without a closing pattern + */ + public function __construct(CallWriterInterface $CallWriter, $close = "nest_close") + { + $this->callWriter = $CallWriter; + + $this->closingInstruction = $close; + } + + /** @inheritdoc */ + public function writeCall($call) + { + $this->calls[] = $call; + } + + /** @inheritdoc */ + public function writeCalls($calls) + { + $this->calls = array_merge($this->calls, $calls); + } + + /** @inheritdoc */ + public function finalise() + { + $last_call = end($this->calls); + $this->writeCall(array($this->closingInstruction,array(), $last_call[2])); + + $this->process(); + $this->callWriter->finalise(); + unset($this->callWriter); + } + + /** @inheritdoc */ + public function process() + { + // merge consecutive cdata + $unmerged_calls = $this->calls; + $this->calls = array(); + + foreach ($unmerged_calls as $call) $this->addCall($call); + + $first_call = reset($this->calls); + $this->callWriter->writeCall(array("nest", array($this->calls), $first_call[2])); + + return $this->callWriter; + } + + protected function addCall($call) + { + $key = count($this->calls); + if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) { + $this->calls[$key-1][1][0] .= $call[1][0]; + } elseif ($call[0] == 'eol') { + // do nothing (eol shouldn't be allowed, to counter preformatted fix in #1652 & #1699) + } else { + $this->calls[] = $call; + } + } +} diff --git a/inc/Parsing/Handler/Preformatted.php b/inc/Parsing/Handler/Preformatted.php new file mode 100644 index 000000000..a668771a7 --- /dev/null +++ b/inc/Parsing/Handler/Preformatted.php @@ -0,0 +1,76 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +class Preformatted implements ReWriterInterface +{ + + /** @var CallWriterInterface original call writer */ + protected $callWriter; + + protected $calls = array(); + protected $pos; + protected $text =''; + + /** + * @inheritdoc + */ + public function __construct(CallWriterInterface $CallWriter) + { + $this->callWriter = $CallWriter; + } + + /** @inheritdoc */ + public function writeCall($call) + { + $this->calls[] = $call; + } + + /** + * @inheritdoc + * Probably not needed but just in case... + */ + public function writeCalls($calls) + { + $this->calls = array_merge($this->calls, $calls); + } + + /** @inheritdoc */ + public function finalise() + { + $last_call = end($this->calls); + $this->writeCall(array('preformatted_end',array(), $last_call[2])); + + $this->process(); + $this->callWriter->finalise(); + unset($this->callWriter); + } + + /** @inheritdoc */ + public function process() + { + foreach ($this->calls as $call) { + switch ($call[0]) { + case 'preformatted_start': + $this->pos = $call[2]; + break; + case 'preformatted_newline': + $this->text .= "\n"; + break; + case 'preformatted_content': + $this->text .= $call[1][0]; + break; + case 'preformatted_end': + if (trim($this->text)) { + $this->callWriter->writeCall(array('preformatted', array($this->text), $this->pos)); + } + // see FS#1699 & FS#1652, add 'eol' instructions to ensure proper triggering of following p_open + $this->callWriter->writeCall(array('eol', array(), $this->pos)); + $this->callWriter->writeCall(array('eol', array(), $this->pos)); + break; + } + } + + return $this->callWriter; + } +} diff --git a/inc/Parsing/Handler/Quote.php b/inc/Parsing/Handler/Quote.php new file mode 100644 index 000000000..a786d10c0 --- /dev/null +++ b/inc/Parsing/Handler/Quote.php @@ -0,0 +1,110 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +class Quote implements ReWriterInterface +{ + + /** @var CallWriterInterface original CallWriter */ + protected $callWriter; + + protected $calls = array(); + + protected $quoteCalls = array(); + + /** @inheritdoc */ + public function __construct(CallWriterInterface $CallWriter) + { + $this->callWriter = $CallWriter; + } + + /** @inheritdoc */ + public function writeCall($call) + { + $this->calls[] = $call; + } + + /** + * @inheritdoc + * + * Probably not needed but just in case... + */ + public function writeCalls($calls) + { + $this->calls = array_merge($this->calls, $calls); + } + + /** @inheritdoc */ + public function finalise() + { + $last_call = end($this->calls); + $this->writeCall(array('quote_end',array(), $last_call[2])); + + $this->process(); + $this->callWriter->finalise(); + unset($this->callWriter); + } + + /** @inheritdoc */ + public function process() + { + + $quoteDepth = 1; + + foreach ($this->calls as $call) { + switch ($call[0]) { + + /** @noinspection PhpMissingBreakStatementInspection */ + case 'quote_start': + $this->quoteCalls[] = array('quote_open',array(),$call[2]); + // fallthrough + case 'quote_newline': + $quoteLength = $this->getDepth($call[1][0]); + + if ($quoteLength > $quoteDepth) { + $quoteDiff = $quoteLength - $quoteDepth; + for ($i = 1; $i <= $quoteDiff; $i++) { + $this->quoteCalls[] = array('quote_open',array(),$call[2]); + } + } elseif ($quoteLength < $quoteDepth) { + $quoteDiff = $quoteDepth - $quoteLength; + for ($i = 1; $i <= $quoteDiff; $i++) { + $this->quoteCalls[] = array('quote_close',array(),$call[2]); + } + } else { + if ($call[0] != 'quote_start') $this->quoteCalls[] = array('linebreak',array(),$call[2]); + } + + $quoteDepth = $quoteLength; + + break; + + case 'quote_end': + if ($quoteDepth > 1) { + $quoteDiff = $quoteDepth - 1; + for ($i = 1; $i <= $quoteDiff; $i++) { + $this->quoteCalls[] = array('quote_close',array(),$call[2]); + } + } + + $this->quoteCalls[] = array('quote_close',array(),$call[2]); + + $this->callWriter->writeCalls($this->quoteCalls); + break; + + default: + $this->quoteCalls[] = $call; + break; + } + } + + return $this->callWriter; + } + + protected function getDepth($marker) + { + preg_match('/>{1,}/', $marker, $matches); + $quoteLength = strlen($matches[0]); + return $quoteLength; + } +} diff --git a/inc/Parsing/Handler/ReWriterInterface.php b/inc/Parsing/Handler/ReWriterInterface.php new file mode 100644 index 000000000..13f7b48e3 --- /dev/null +++ b/inc/Parsing/Handler/ReWriterInterface.php @@ -0,0 +1,29 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +/** + * A ReWriter takes over from the orignal call writer and handles all new calls itself until + * the process method is called and control is given back to the original writer. + */ +interface ReWriterInterface extends CallWriterInterface +{ + + /** + * ReWriterInterface constructor. + * + * This rewriter will be registered as the new call writer in the Handler. + * The original is passed as parameter + * + * @param CallWriterInterface $callWriter the original callwriter + */ + public function __construct(CallWriterInterface $callWriter); + + /** + * Process any calls that have been added and add them to the + * original call writer + * + * @return CallWriterInterface the orignal call writer + */ + public function process(); +} diff --git a/inc/Parsing/Handler/Table.php b/inc/Parsing/Handler/Table.php new file mode 100644 index 000000000..908762dff --- /dev/null +++ b/inc/Parsing/Handler/Table.php @@ -0,0 +1,345 @@ +<?php + +namespace dokuwiki\Parsing\Handler; + +class Table implements ReWriterInterface +{ + + /** @var CallWriterInterface original CallWriter */ + protected $callWriter; + + protected $calls = array(); + protected $tableCalls = array(); + protected $maxCols = 0; + protected $maxRows = 1; + protected $currentCols = 0; + protected $firstCell = false; + protected $lastCellType = 'tablecell'; + protected $inTableHead = true; + protected $currentRow = array('tableheader' => 0, 'tablecell' => 0); + protected $countTableHeadRows = 0; + + /** @inheritdoc */ + public function __construct(CallWriterInterface $CallWriter) + { + $this->callWriter = $CallWriter; + } + + /** @inheritdoc */ + public function writeCall($call) + { + $this->calls[] = $call; + } + + /** + * @inheritdoc + * Probably not needed but just in case... + */ + public function writeCalls($calls) + { + $this->calls = array_merge($this->calls, $calls); + } + + /** @inheritdoc */ + public function finalise() + { + $last_call = end($this->calls); + $this->writeCall(array('table_end',array(), $last_call[2])); + + $this->process(); + $this->callWriter->finalise(); + unset($this->callWriter); + } + + /** @inheritdoc */ + public function process() + { + foreach ($this->calls as $call) { + switch ($call[0]) { + case 'table_start': + $this->tableStart($call); + break; + case 'table_row': + $this->tableRowClose($call); + $this->tableRowOpen(array('tablerow_open',$call[1],$call[2])); + break; + case 'tableheader': + case 'tablecell': + $this->tableCell($call); + break; + case 'table_end': + $this->tableRowClose($call); + $this->tableEnd($call); + break; + default: + $this->tableDefault($call); + break; + } + } + $this->callWriter->writeCalls($this->tableCalls); + + return $this->callWriter; + } + + protected function tableStart($call) + { + $this->tableCalls[] = array('table_open',$call[1],$call[2]); + $this->tableCalls[] = array('tablerow_open',array(),$call[2]); + $this->firstCell = true; + } + + protected function tableEnd($call) + { + $this->tableCalls[] = array('table_close',$call[1],$call[2]); + $this->finalizeTable(); + } + + protected function tableRowOpen($call) + { + $this->tableCalls[] = $call; + $this->currentCols = 0; + $this->firstCell = true; + $this->lastCellType = 'tablecell'; + $this->maxRows++; + if ($this->inTableHead) { + $this->currentRow = array('tablecell' => 0, 'tableheader' => 0); + } + } + + protected function tableRowClose($call) + { + if ($this->inTableHead && ($this->inTableHead = $this->isTableHeadRow())) { + $this->countTableHeadRows++; + } + // Strip off final cell opening and anything after it + while ($discard = array_pop($this->tableCalls)) { + if ($discard[0] == 'tablecell_open' || $discard[0] == 'tableheader_open') { + break; + } + if (!empty($this->currentRow[$discard[0]])) { + $this->currentRow[$discard[0]]--; + } + } + $this->tableCalls[] = array('tablerow_close', array(), $call[2]); + + if ($this->currentCols > $this->maxCols) { + $this->maxCols = $this->currentCols; + } + } + + protected function isTableHeadRow() + { + $td = $this->currentRow['tablecell']; + $th = $this->currentRow['tableheader']; + + if (!$th || $td > 2) return false; + if (2*$td > $th) return false; + + return true; + } + + protected function tableCell($call) + { + if ($this->inTableHead) { + $this->currentRow[$call[0]]++; + } + if (!$this->firstCell) { + // Increase the span + $lastCall = end($this->tableCalls); + + // A cell call which follows an open cell means an empty cell so span + if ($lastCall[0] == 'tablecell_open' || $lastCall[0] == 'tableheader_open') { + $this->tableCalls[] = array('colspan',array(),$call[2]); + } + + $this->tableCalls[] = array($this->lastCellType.'_close',array(),$call[2]); + $this->tableCalls[] = array($call[0].'_open',array(1,null,1),$call[2]); + $this->lastCellType = $call[0]; + } else { + $this->tableCalls[] = array($call[0].'_open',array(1,null,1),$call[2]); + $this->lastCellType = $call[0]; + $this->firstCell = false; + } + + $this->currentCols++; + } + + protected function tableDefault($call) + { + $this->tableCalls[] = $call; + } + + protected function finalizeTable() + { + + // Add the max cols and rows to the table opening + if ($this->tableCalls[0][0] == 'table_open') { + // Adjust to num cols not num col delimeters + $this->tableCalls[0][1][] = $this->maxCols - 1; + $this->tableCalls[0][1][] = $this->maxRows; + $this->tableCalls[0][1][] = array_shift($this->tableCalls[0][1]); + } else { + trigger_error('First element in table call list is not table_open'); + } + + $lastRow = 0; + $lastCell = 0; + $cellKey = array(); + $toDelete = array(); + + // if still in tableheader, then there can be no table header + // as all rows can't be within <THEAD> + if ($this->inTableHead) { + $this->inTableHead = false; + $this->countTableHeadRows = 0; + } + + // Look for the colspan elements and increment the colspan on the + // previous non-empty opening cell. Once done, delete all the cells + // that contain colspans + for ($key = 0; $key < count($this->tableCalls); ++$key) { + $call = $this->tableCalls[$key]; + + switch ($call[0]) { + case 'table_open': + if ($this->countTableHeadRows) { + array_splice($this->tableCalls, $key+1, 0, array( + array('tablethead_open', array(), $call[2]))); + } + break; + + case 'tablerow_open': + $lastRow++; + $lastCell = 0; + break; + + case 'tablecell_open': + case 'tableheader_open': + $lastCell++; + $cellKey[$lastRow][$lastCell] = $key; + break; + + case 'table_align': + $prev = in_array($this->tableCalls[$key-1][0], array('tablecell_open', 'tableheader_open')); + $next = in_array($this->tableCalls[$key+1][0], array('tablecell_close', 'tableheader_close')); + // If the cell is empty, align left + if ($prev && $next) { + $this->tableCalls[$key-1][1][1] = 'left'; + + // If the previous element was a cell open, align right + } elseif ($prev) { + $this->tableCalls[$key-1][1][1] = 'right'; + + // If the next element is the close of an element, align either center or left + } elseif ($next) { + if ($this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] == 'right') { + $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'center'; + } else { + $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'left'; + } + } + + // Now convert the whitespace back to cdata + $this->tableCalls[$key][0] = 'cdata'; + break; + + case 'colspan': + $this->tableCalls[$key-1][1][0] = false; + + for ($i = $key-2; $i >= $cellKey[$lastRow][1]; $i--) { + if ($this->tableCalls[$i][0] == 'tablecell_open' || + $this->tableCalls[$i][0] == 'tableheader_open' + ) { + if (false !== $this->tableCalls[$i][1][0]) { + $this->tableCalls[$i][1][0]++; + break; + } + } + } + + $toDelete[] = $key-1; + $toDelete[] = $key; + $toDelete[] = $key+1; + break; + + case 'rowspan': + if ($this->tableCalls[$key-1][0] == 'cdata') { + // ignore rowspan if previous call was cdata (text mixed with :::) + // we don't have to check next call as that wont match regex + $this->tableCalls[$key][0] = 'cdata'; + } else { + $spanning_cell = null; + + // can't cross thead/tbody boundary + if (!$this->countTableHeadRows || ($lastRow-1 != $this->countTableHeadRows)) { + for ($i = $lastRow-1; $i > 0; $i--) { + if ($this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tablecell_open' || + $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tableheader_open' + ) { + if ($this->tableCalls[$cellKey[$i][$lastCell]][1][2] >= $lastRow - $i) { + $spanning_cell = $i; + break; + } + } + } + } + if (is_null($spanning_cell)) { + // No spanning cell found, so convert this cell to + // an empty one to avoid broken tables + $this->tableCalls[$key][0] = 'cdata'; + $this->tableCalls[$key][1][0] = ''; + continue; + } + $this->tableCalls[$cellKey[$spanning_cell][$lastCell]][1][2]++; + + $this->tableCalls[$key-1][1][2] = false; + + $toDelete[] = $key-1; + $toDelete[] = $key; + $toDelete[] = $key+1; + } + break; + + case 'tablerow_close': + // Fix broken tables by adding missing cells + $moreCalls = array(); + while (++$lastCell < $this->maxCols) { + $moreCalls[] = array('tablecell_open', array(1, null, 1), $call[2]); + $moreCalls[] = array('cdata', array(''), $call[2]); + $moreCalls[] = array('tablecell_close', array(), $call[2]); + } + $moreCallsLength = count($moreCalls); + if ($moreCallsLength) { + array_splice($this->tableCalls, $key, 0, $moreCalls); + $key += $moreCallsLength; + } + + if ($this->countTableHeadRows == $lastRow) { + array_splice($this->tableCalls, $key+1, 0, array( + array('tablethead_close', array(), $call[2]))); + } + break; + } + } + + // condense cdata + $cnt = count($this->tableCalls); + for ($key = 0; $key < $cnt; $key++) { + if ($this->tableCalls[$key][0] == 'cdata') { + $ckey = $key; + $key++; + while ($this->tableCalls[$key][0] == 'cdata') { + $this->tableCalls[$ckey][1][0] .= $this->tableCalls[$key][1][0]; + $toDelete[] = $key; + $key++; + } + continue; + } + } + + foreach ($toDelete as $delete) { + unset($this->tableCalls[$delete]); + } + $this->tableCalls = array_values($this->tableCalls); + } +} diff --git a/inc/Parsing/Lexer/Lexer.php b/inc/Parsing/Lexer/Lexer.php new file mode 100644 index 000000000..c164f4ffe --- /dev/null +++ b/inc/Parsing/Lexer/Lexer.php @@ -0,0 +1,347 @@ +<?php +/** + * Lexer adapted from Simple Test: http://sourceforge.net/projects/simpletest/ + * For an intro to the Lexer see: + * https://web.archive.org/web/20120125041816/http://www.phppatterns.com/docs/develop/simple_test_lexer_notes + * + * @author Marcus Baker http://www.lastcraft.com + */ + +namespace dokuwiki\Parsing\Lexer; + +// FIXME move elsewhere + +define("DOKU_LEXER_ENTER", 1); +define("DOKU_LEXER_MATCHED", 2); +define("DOKU_LEXER_UNMATCHED", 3); +define("DOKU_LEXER_EXIT", 4); +define("DOKU_LEXER_SPECIAL", 5); + +/** + * Accepts text and breaks it into tokens. + * + * Some optimisation to make the sure the content is only scanned by the PHP regex + * parser once. Lexer modes must not start with leading underscores. + */ +class Lexer +{ + /** @var ParallelRegex[] */ + protected $regexes; + /** @var \Doku_Handler */ + protected $handler; + /** @var StateStack */ + protected $modeStack; + /** @var array mode "rewrites" */ + protected $mode_handlers; + /** @var bool case sensitive? */ + protected $case; + + /** + * Sets up the lexer in case insensitive matching by default. + * + * @param \Doku_Handler $handler Handling strategy by reference. + * @param string $start Starting handler. + * @param boolean $case True for case sensitive. + */ + public function __construct($handler, $start = "accept", $case = false) + { + $this->case = $case; + $this->regexes = array(); + $this->handler = $handler; + $this->modeStack = new StateStack($start); + $this->mode_handlers = array(); + } + + /** + * Adds a token search pattern for a particular parsing mode. + * + * The pattern does not change the current mode. + * + * @param string $pattern Perl style regex, but ( and ) + * lose the usual meaning. + * @param string $mode Should only apply this + * pattern when dealing with + * this type of input. + */ + public function addPattern($pattern, $mode = "accept") + { + if (! isset($this->regexes[$mode])) { + $this->regexes[$mode] = new ParallelRegex($this->case); + } + $this->regexes[$mode]->addPattern($pattern); + } + + /** + * Adds a pattern that will enter a new parsing mode. + * + * Useful for entering parenthesis, strings, tags, etc. + * + * @param string $pattern Perl style regex, but ( and ) lose the usual meaning. + * @param string $mode Should only apply this pattern when dealing with this type of input. + * @param string $new_mode Change parsing to this new nested mode. + */ + public function addEntryPattern($pattern, $mode, $new_mode) + { + if (! isset($this->regexes[$mode])) { + $this->regexes[$mode] = new ParallelRegex($this->case); + } + $this->regexes[$mode]->addPattern($pattern, $new_mode); + } + + /** + * Adds a pattern that will exit the current mode and re-enter the previous one. + * + * @param string $pattern Perl style regex, but ( and ) lose the usual meaning. + * @param string $mode Mode to leave. + */ + public function addExitPattern($pattern, $mode) + { + if (! isset($this->regexes[$mode])) { + $this->regexes[$mode] = new ParallelRegex($this->case); + } + $this->regexes[$mode]->addPattern($pattern, "__exit"); + } + + /** + * Adds a pattern that has a special mode. + * + * Acts as an entry and exit pattern in one go, effectively calling a special + * parser handler for this token only. + * + * @param string $pattern Perl style regex, but ( and ) lose the usual meaning. + * @param string $mode Should only apply this pattern when dealing with this type of input. + * @param string $special Use this mode for this one token. + */ + public function addSpecialPattern($pattern, $mode, $special) + { + if (! isset($this->regexes[$mode])) { + $this->regexes[$mode] = new ParallelRegex($this->case); + } + $this->regexes[$mode]->addPattern($pattern, "_$special"); + } + + /** + * Adds a mapping from a mode to another handler. + * + * @param string $mode Mode to be remapped. + * @param string $handler New target handler. + */ + public function mapHandler($mode, $handler) + { + $this->mode_handlers[$mode] = $handler; + } + + /** + * Splits the page text into tokens. + * + * Will fail if the handlers report an error or if no content is consumed. If successful then each + * unparsed and parsed token invokes a call to the held listener. + * + * @param string $raw Raw HTML text. + * @return boolean True on success, else false. + */ + public function parse($raw) + { + if (! isset($this->handler)) { + return false; + } + $initialLength = strlen($raw); + $length = $initialLength; + $pos = 0; + while (is_array($parsed = $this->reduce($raw))) { + list($unmatched, $matched, $mode) = $parsed; + $currentLength = strlen($raw); + $matchPos = $initialLength - $currentLength - strlen($matched); + if (! $this->dispatchTokens($unmatched, $matched, $mode, $pos, $matchPos)) { + return false; + } + if ($currentLength == $length) { + return false; + } + $length = $currentLength; + $pos = $initialLength - $currentLength; + } + if (!$parsed) { + return false; + } + return $this->invokeHandler($raw, DOKU_LEXER_UNMATCHED, $pos); + } + + /** + * Sends the matched token and any leading unmatched + * text to the parser changing the lexer to a new + * mode if one is listed. + * + * @param string $unmatched Unmatched leading portion. + * @param string $matched Actual token match. + * @param bool|string $mode Mode after match. A boolean false mode causes no change. + * @param int $initialPos + * @param int $matchPos Current byte index location in raw doc thats being parsed + * @return boolean False if there was any error from the parser. + */ + protected function dispatchTokens($unmatched, $matched, $mode, $initialPos, $matchPos) + { + if (! $this->invokeHandler($unmatched, DOKU_LEXER_UNMATCHED, $initialPos)) { + return false; + } + if ($this->isModeEnd($mode)) { + if (! $this->invokeHandler($matched, DOKU_LEXER_EXIT, $matchPos)) { + return false; + } + return $this->modeStack->leave(); + } + if ($this->isSpecialMode($mode)) { + $this->modeStack->enter($this->decodeSpecial($mode)); + if (! $this->invokeHandler($matched, DOKU_LEXER_SPECIAL, $matchPos)) { + return false; + } + return $this->modeStack->leave(); + } + if (is_string($mode)) { + $this->modeStack->enter($mode); + return $this->invokeHandler($matched, DOKU_LEXER_ENTER, $matchPos); + } + return $this->invokeHandler($matched, DOKU_LEXER_MATCHED, $matchPos); + } + + /** + * Tests to see if the new mode is actually to leave the current mode and pop an item from the matching + * mode stack. + * + * @param string $mode Mode to test. + * @return boolean True if this is the exit mode. + */ + protected function isModeEnd($mode) + { + return ($mode === "__exit"); + } + + /** + * Test to see if the mode is one where this mode is entered for this token only and automatically + * leaves immediately afterwoods. + * + * @param string $mode Mode to test. + * @return boolean True if this is the exit mode. + */ + protected function isSpecialMode($mode) + { + return (strncmp($mode, "_", 1) == 0); + } + + /** + * Strips the magic underscore marking single token modes. + * + * @param string $mode Mode to decode. + * @return string Underlying mode name. + */ + protected function decodeSpecial($mode) + { + return substr($mode, 1); + } + + /** + * Calls the parser method named after the current mode. + * + * Empty content will be ignored. The lexer has a parser handler for each mode in the lexer. + * + * @param string $content Text parsed. + * @param boolean $is_match Token is recognised rather + * than unparsed data. + * @param int $pos Current byte index location in raw doc + * thats being parsed + * @return bool + */ + protected function invokeHandler($content, $is_match, $pos) + { + if (($content === "") || ($content === false)) { + return true; + } + $handler = $this->modeStack->getCurrent(); + if (isset($this->mode_handlers[$handler])) { + $handler = $this->mode_handlers[$handler]; + } + + // modes starting with plugin_ are all handled by the same + // handler but with an additional parameter + if (substr($handler, 0, 7)=='plugin_') { + list($handler,$plugin) = explode('_', $handler, 2); + return $this->handler->$handler($content, $is_match, $pos, $plugin); + } + + return $this->handler->$handler($content, $is_match, $pos); + } + + /** + * Tries to match a chunk of text and if successful removes the recognised chunk and any leading + * unparsed data. Empty strings will not be matched. + * + * @param string $raw The subject to parse. This is the content that will be eaten. + * @return array|bool Three item list of unparsed content followed by the + * recognised token and finally the action the parser is to take. + * True if no match, false if there is a parsing error. + */ + protected function reduce(&$raw) + { + if (! isset($this->regexes[$this->modeStack->getCurrent()])) { + return false; + } + if ($raw === "") { + return true; + } + if ($action = $this->regexes[$this->modeStack->getCurrent()]->split($raw, $split)) { + list($unparsed, $match, $raw) = $split; + return array($unparsed, $match, $action); + } + return true; + } + + /** + * Escapes regex characters other than (, ) and / + * + * @param string $str + * @return string + */ + public static function escape($str) + { + $chars = array( + '/\\\\/', + '/\./', + '/\+/', + '/\*/', + '/\?/', + '/\[/', + '/\^/', + '/\]/', + '/\$/', + '/\{/', + '/\}/', + '/\=/', + '/\!/', + '/\</', + '/\>/', + '/\|/', + '/\:/' + ); + + $escaped = array( + '\\\\\\\\', + '\.', + '\+', + '\*', + '\?', + '\[', + '\^', + '\]', + '\$', + '\{', + '\}', + '\=', + '\!', + '\<', + '\>', + '\|', + '\:' + ); + return preg_replace($chars, $escaped, $str); + } +} diff --git a/inc/Parsing/Lexer/ParallelRegex.php b/inc/Parsing/Lexer/ParallelRegex.php new file mode 100644 index 000000000..96f61a10f --- /dev/null +++ b/inc/Parsing/Lexer/ParallelRegex.php @@ -0,0 +1,203 @@ +<?php +/** + * Lexer adapted from Simple Test: http://sourceforge.net/projects/simpletest/ + * For an intro to the Lexer see: + * https://web.archive.org/web/20120125041816/http://www.phppatterns.com/docs/develop/simple_test_lexer_notes + * + * @author Marcus Baker http://www.lastcraft.com + */ + +namespace dokuwiki\Parsing\Lexer; + +/** + * Compounded regular expression. + * + * Any of the contained patterns could match and when one does it's label is returned. + */ +class ParallelRegex +{ + /** @var string[] patterns to match */ + protected $patterns; + /** @var string[] labels for above patterns */ + protected $labels; + /** @var string the compound regex matching all patterns */ + protected $regex; + /** @var bool case sensitive matching? */ + protected $case; + + /** + * Constructor. Starts with no patterns. + * + * @param boolean $case True for case sensitive, false + * for insensitive. + */ + public function __construct($case) + { + $this->case = $case; + $this->patterns = array(); + $this->labels = array(); + $this->regex = null; + } + + /** + * Adds a pattern with an optional label. + * + * @param mixed $pattern Perl style regex. Must be UTF-8 + * encoded. If its a string, the (, ) + * lose their meaning unless they + * form part of a lookahead or + * lookbehind assertation. + * @param bool|string $label Label of regex to be returned + * on a match. Label must be ASCII + */ + public function addPattern($pattern, $label = true) + { + $count = count($this->patterns); + $this->patterns[$count] = $pattern; + $this->labels[$count] = $label; + $this->regex = null; + } + + /** + * Attempts to match all patterns at once against a string. + * + * @param string $subject String to match against. + * @param string $match First matched portion of + * subject. + * @return bool|string False if no match found, label if label exists, true if not + */ + public function match($subject, &$match) + { + if (count($this->patterns) == 0) { + return false; + } + if (! preg_match($this->getCompoundedRegex(), $subject, $matches)) { + $match = ""; + return false; + } + + $match = $matches[0]; + $size = count($matches); + // FIXME this could be made faster by storing the labels as keys in a hashmap + for ($i = 1; $i < $size; $i++) { + if ($matches[$i] && isset($this->labels[$i - 1])) { + return $this->labels[$i - 1]; + } + } + return true; + } + + /** + * Attempts to split the string against all patterns at once + * + * @param string $subject String to match against. + * @param array $split The split result: array containing, pre-match, match & post-match strings + * @return boolean True on success. + * + * @author Christopher Smith <chris@jalakai.co.uk> + */ + public function split($subject, &$split) + { + if (count($this->patterns) == 0) { + return false; + } + + if (! preg_match($this->getCompoundedRegex(), $subject, $matches)) { + if (function_exists('preg_last_error')) { + $err = preg_last_error(); + switch ($err) { + case PREG_BACKTRACK_LIMIT_ERROR: + msg('A PCRE backtrack error occured. Try to increase the pcre.backtrack_limit in php.ini', -1); + break; + case PREG_RECURSION_LIMIT_ERROR: + msg('A PCRE recursion error occured. Try to increase the pcre.recursion_limit in php.ini', -1); + break; + case PREG_BAD_UTF8_ERROR: + msg('A PCRE UTF-8 error occured. This might be caused by a faulty plugin', -1); + break; + case PREG_INTERNAL_ERROR: + msg('A PCRE internal error occured. This might be caused by a faulty plugin', -1); + break; + } + } + + $split = array($subject, "", ""); + return false; + } + + $idx = count($matches)-2; + list($pre, $post) = preg_split($this->patterns[$idx].$this->getPerlMatchingFlags(), $subject, 2); + $split = array($pre, $matches[0], $post); + + return isset($this->labels[$idx]) ? $this->labels[$idx] : true; + } + + /** + * Compounds the patterns into a single + * regular expression separated with the + * "or" operator. Caches the regex. + * Will automatically escape (, ) and / tokens. + * + * @return null|string + */ + protected function getCompoundedRegex() + { + if ($this->regex == null) { + $cnt = count($this->patterns); + for ($i = 0; $i < $cnt; $i++) { + /* + * decompose the input pattern into "(", "(?", ")", + * "[...]", "[]..]", "[^]..]", "[...[:...:]..]", "\x"... + * elements. + */ + preg_match_all('/\\\\.|' . + '\(\?|' . + '[()]|' . + '\[\^?\]?(?:\\\\.|\[:[^]]*:\]|[^]\\\\])*\]|' . + '[^[()\\\\]+/', $this->patterns[$i], $elts); + + $pattern = ""; + $level = 0; + + foreach ($elts[0] as $elt) { + /* + * for "(", ")" remember the nesting level, add "\" + * only to the non-"(?" ones. + */ + + switch ($elt) { + case '(': + $pattern .= '\('; + break; + case ')': + if ($level > 0) + $level--; /* closing (? */ + else $pattern .= '\\'; + $pattern .= ')'; + break; + case '(?': + $level++; + $pattern .= '(?'; + break; + default: + if (substr($elt, 0, 1) == '\\') + $pattern .= $elt; + else $pattern .= str_replace('/', '\/', $elt); + } + } + $this->patterns[$i] = "($pattern)"; + } + $this->regex = "/" . implode("|", $this->patterns) . "/" . $this->getPerlMatchingFlags(); + } + return $this->regex; + } + + /** + * Accessor for perl regex mode flags to use. + * @return string Perl regex flags. + */ + protected function getPerlMatchingFlags() + { + return ($this->case ? "msS" : "msSi"); + } +} diff --git a/inc/Parsing/Lexer/StateStack.php b/inc/Parsing/Lexer/StateStack.php new file mode 100644 index 000000000..325412bb4 --- /dev/null +++ b/inc/Parsing/Lexer/StateStack.php @@ -0,0 +1,60 @@ +<?php +/** + * Lexer adapted from Simple Test: http://sourceforge.net/projects/simpletest/ + * For an intro to the Lexer see: + * https://web.archive.org/web/20120125041816/http://www.phppatterns.com/docs/develop/simple_test_lexer_notes + * + * @author Marcus Baker http://www.lastcraft.com + */ + +namespace dokuwiki\Parsing\Lexer; + +/** + * States for a stack machine. + */ +class StateStack +{ + protected $stack; + + /** + * Constructor. Starts in named state. + * @param string $start Starting state name. + */ + public function __construct($start) + { + $this->stack = array($start); + } + + /** + * Accessor for current state. + * @return string State. + */ + public function getCurrent() + { + return $this->stack[count($this->stack) - 1]; + } + + /** + * Adds a state to the stack and sets it to be the current state. + * + * @param string $state New state. + */ + public function enter($state) + { + array_push($this->stack, $state); + } + + /** + * Leaves the current state and reverts + * to the previous one. + * @return boolean false if we attempt to drop off the bottom of the list. + */ + public function leave() + { + if (count($this->stack) == 1) { + return false; + } + array_pop($this->stack); + return true; + } +} diff --git a/inc/Parsing/Parser.php b/inc/Parsing/Parser.php new file mode 100644 index 000000000..b2070569f --- /dev/null +++ b/inc/Parsing/Parser.php @@ -0,0 +1,114 @@ +<?php + +namespace dokuwiki\Parsing; + +use Doku_Handler; +use dokuwiki\Parsing\Lexer\Lexer; +use dokuwiki\Parsing\ParserMode\Base; +use dokuwiki\Parsing\ParserMode\ModeInterface; + +/** + * Sets up the Lexer with modes and points it to the Handler + * For an intro to the Lexer see: wiki:parser + */ +class Parser { + + /** @var Doku_Handler */ + protected $handler; + + /** @var Lexer $lexer */ + protected $lexer; + + /** @var ModeInterface[] $modes */ + protected $modes = array(); + + /** @var bool mode connections may only be set up once */ + protected $connected = false; + + /** + * dokuwiki\Parsing\Doku_Parser constructor. + * + * @param Doku_Handler $handler + */ + public function __construct(Doku_Handler $handler) { + $this->handler = $handler; + } + + /** + * Adds the base mode and initialized the lexer + * + * @param Base $BaseMode + */ + protected function addBaseMode($BaseMode) { + $this->modes['base'] = $BaseMode; + if(!$this->lexer) { + $this->lexer = new Lexer($this->handler, 'base', true); + } + $this->modes['base']->Lexer = $this->lexer; + } + + /** + * Add a new syntax element (mode) to the parser + * + * PHP preserves order of associative elements + * Mode sequence is important + * + * @param string $name + * @param ModeInterface $Mode + */ + public function addMode($name, ModeInterface $Mode) { + if(!isset($this->modes['base'])) { + $this->addBaseMode(new Base()); + } + $Mode->Lexer = $this->lexer; // FIXME should be done by setter + $this->modes[$name] = $Mode; + } + + /** + * Connect all modes with each other + * + * This is the last step before actually parsing. + */ + protected function connectModes() { + + if($this->connected) { + return; + } + + foreach(array_keys($this->modes) as $mode) { + // Base isn't connected to anything + if($mode == 'base') { + continue; + } + $this->modes[$mode]->preConnect(); + + foreach(array_keys($this->modes) as $cm) { + + if($this->modes[$cm]->accepts($mode)) { + $this->modes[$mode]->connectTo($cm); + } + + } + + $this->modes[$mode]->postConnect(); + } + + $this->connected = true; + } + + /** + * Parses wiki syntax to instructions + * + * @param string $doc the wiki syntax text + * @return array instructions + */ + public function parse($doc) { + $this->connectModes(); + // Normalize CRs and pad doc + $doc = "\n" . str_replace("\r\n", "\n", $doc) . "\n"; + $this->lexer->parse($doc); + $this->handler->finalize(); + return $this->handler->calls; + } + +} diff --git a/inc/Parsing/ParserMode/AbstractMode.php b/inc/Parsing/ParserMode/AbstractMode.php new file mode 100644 index 000000000..15fc9fe04 --- /dev/null +++ b/inc/Parsing/ParserMode/AbstractMode.php @@ -0,0 +1,40 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +/** + * This class and all the subclasses below are used to reduce the effort required to register + * modes with the Lexer. + * + * @author Harry Fuecks <hfuecks@gmail.com> + */ +abstract class AbstractMode implements ModeInterface +{ + /** @var \dokuwiki\Parsing\Lexer\Lexer $Lexer will be injected on loading FIXME this should be done by setter */ + public $Lexer; + protected $allowedModes = array(); + + /** @inheritdoc */ + abstract public function getSort(); + + /** @inheritdoc */ + public function preConnect() + { + } + + /** @inheritdoc */ + public function connectTo($mode) + { + } + + /** @inheritdoc */ + public function postConnect() + { + } + + /** @inheritdoc */ + public function accepts($mode) + { + return in_array($mode, (array) $this->allowedModes); + } +} diff --git a/inc/Parsing/ParserMode/Acronym.php b/inc/Parsing/ParserMode/Acronym.php new file mode 100644 index 000000000..b42a7b573 --- /dev/null +++ b/inc/Parsing/ParserMode/Acronym.php @@ -0,0 +1,68 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Acronym extends AbstractMode +{ + // A list + protected $acronyms = array(); + protected $pattern = ''; + + /** + * Acronym constructor. + * + * @param string[] $acronyms + */ + public function __construct($acronyms) + { + usort($acronyms, array($this,'compare')); + $this->acronyms = $acronyms; + } + + /** @inheritdoc */ + public function preConnect() + { + if (!count($this->acronyms)) return; + + $bound = '[\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]'; + $acronyms = array_map(['\\dokuwiki\\Parsing\\Lexer\\Lexer', 'escape'], $this->acronyms); + $this->pattern = '(?<=^|'.$bound.')(?:'.join('|', $acronyms).')(?='.$bound.')'; + } + + /** @inheritdoc */ + public function connectTo($mode) + { + if (!count($this->acronyms)) return; + + if (strlen($this->pattern) > 0) { + $this->Lexer->addSpecialPattern($this->pattern, $mode, 'acronym'); + } + } + + /** @inheritdoc */ + public function getSort() + { + return 240; + } + + /** + * sort callback to order by string length descending + * + * @param string $a + * @param string $b + * + * @return int + */ + protected function compare($a, $b) + { + $a_len = strlen($a); + $b_len = strlen($b); + if ($a_len > $b_len) { + return -1; + } elseif ($a_len < $b_len) { + return 1; + } + + return 0; + } +} diff --git a/inc/Parsing/ParserMode/Base.php b/inc/Parsing/ParserMode/Base.php new file mode 100644 index 000000000..562275600 --- /dev/null +++ b/inc/Parsing/ParserMode/Base.php @@ -0,0 +1,31 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Base extends AbstractMode +{ + + /** + * Base constructor. + */ + public function __construct() + { + global $PARSER_MODES; + + $this->allowedModes = array_merge( + $PARSER_MODES['container'], + $PARSER_MODES['baseonly'], + $PARSER_MODES['paragraphs'], + $PARSER_MODES['formatting'], + $PARSER_MODES['substition'], + $PARSER_MODES['protected'], + $PARSER_MODES['disabled'] + ); + } + + /** @inheritdoc */ + public function getSort() + { + return 0; + } +} diff --git a/inc/Parsing/ParserMode/Camelcaselink.php b/inc/Parsing/ParserMode/Camelcaselink.php new file mode 100644 index 000000000..ef0b32531 --- /dev/null +++ b/inc/Parsing/ParserMode/Camelcaselink.php @@ -0,0 +1,23 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Camelcaselink extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern( + '\b[A-Z]+[a-z]+[A-Z][A-Za-z]*\b', + $mode, + 'camelcaselink' + ); + } + + /** @inheritdoc */ + public function getSort() + { + return 290; + } +} diff --git a/inc/Parsing/ParserMode/Code.php b/inc/Parsing/ParserMode/Code.php new file mode 100644 index 000000000..aa494377d --- /dev/null +++ b/inc/Parsing/ParserMode/Code.php @@ -0,0 +1,25 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Code extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern('<code\b(?=.*</code>)', $mode, 'code'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addExitPattern('</code>', 'code'); + } + + /** @inheritdoc */ + public function getSort() + { + return 200; + } +} diff --git a/inc/Parsing/ParserMode/Emaillink.php b/inc/Parsing/ParserMode/Emaillink.php new file mode 100644 index 000000000..f9af28c66 --- /dev/null +++ b/inc/Parsing/ParserMode/Emaillink.php @@ -0,0 +1,20 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Emaillink extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + // pattern below is defined in inc/mail.php + $this->Lexer->addSpecialPattern('<'.PREG_PATTERN_VALID_EMAIL.'>', $mode, 'emaillink'); + } + + /** @inheritdoc */ + public function getSort() + { + return 340; + } +} diff --git a/inc/Parsing/ParserMode/Entity.php b/inc/Parsing/ParserMode/Entity.php new file mode 100644 index 000000000..b670124b2 --- /dev/null +++ b/inc/Parsing/ParserMode/Entity.php @@ -0,0 +1,50 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +use dokuwiki\Parsing\Lexer\Lexer; + +class Entity extends AbstractMode +{ + + protected $entities = array(); + protected $pattern = ''; + + /** + * Entity constructor. + * @param string[] $entities + */ + public function __construct($entities) + { + $this->entities = $entities; + } + + + /** @inheritdoc */ + public function preConnect() + { + if (!count($this->entities) || $this->pattern != '') return; + + $sep = ''; + foreach ($this->entities as $entity) { + $this->pattern .= $sep. Lexer::escape($entity); + $sep = '|'; + } + } + + /** @inheritdoc */ + public function connectTo($mode) + { + if (!count($this->entities)) return; + + if (strlen($this->pattern) > 0) { + $this->Lexer->addSpecialPattern($this->pattern, $mode, 'entity'); + } + } + + /** @inheritdoc */ + public function getSort() + { + return 260; + } +} diff --git a/inc/Parsing/ParserMode/Eol.php b/inc/Parsing/ParserMode/Eol.php new file mode 100644 index 000000000..a5886b51f --- /dev/null +++ b/inc/Parsing/ParserMode/Eol.php @@ -0,0 +1,25 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Eol extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $badModes = array('listblock','table'); + if (in_array($mode, $badModes)) { + return; + } + // see FS#1652, pattern extended to swallow preceding whitespace to avoid + // issues with lines that only contain whitespace + $this->Lexer->addSpecialPattern('(?:^[ \t]*)?\n', $mode, 'eol'); + } + + /** @inheritdoc */ + public function getSort() + { + return 370; + } +} diff --git a/inc/Parsing/ParserMode/Externallink.php b/inc/Parsing/ParserMode/Externallink.php new file mode 100644 index 000000000..747574595 --- /dev/null +++ b/inc/Parsing/ParserMode/Externallink.php @@ -0,0 +1,44 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Externallink extends AbstractMode +{ + protected $schemes = array(); + protected $patterns = array(); + + /** @inheritdoc */ + public function preConnect() + { + if (count($this->patterns)) return; + + $ltrs = '\w'; + $gunk = '/\#~:.?+=&%@!\-\[\]'; + $punc = '.:?\-;,'; + $host = $ltrs.$punc; + $any = $ltrs.$gunk.$punc; + + $this->schemes = getSchemes(); + foreach ($this->schemes as $scheme) { + $this->patterns[] = '\b(?i)'.$scheme.'(?-i)://['.$any.']+?(?=['.$punc.']*[^'.$any.'])'; + } + + $this->patterns[] = '(?<=\s)(?i)www?(?-i)\.['.$host.']+?\.['.$host.']+?['.$any.']+?(?=['.$punc.']*[^'.$any.'])'; + $this->patterns[] = '(?<=\s)(?i)ftp?(?-i)\.['.$host.']+?\.['.$host.']+?['.$any.']+?(?=['.$punc.']*[^'.$any.'])'; + } + + /** @inheritdoc */ + public function connectTo($mode) + { + + foreach ($this->patterns as $pattern) { + $this->Lexer->addSpecialPattern($pattern, $mode, 'externallink'); + } + } + + /** @inheritdoc */ + public function getSort() + { + return 330; + } +} diff --git a/inc/Parsing/ParserMode/File.php b/inc/Parsing/ParserMode/File.php new file mode 100644 index 000000000..149134135 --- /dev/null +++ b/inc/Parsing/ParserMode/File.php @@ -0,0 +1,25 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class File extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern('<file\b(?=.*</file>)', $mode, 'file'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addExitPattern('</file>', 'file'); + } + + /** @inheritdoc */ + public function getSort() + { + return 210; + } +} diff --git a/inc/Parsing/ParserMode/Filelink.php b/inc/Parsing/ParserMode/Filelink.php new file mode 100644 index 000000000..3cd86cb8b --- /dev/null +++ b/inc/Parsing/ParserMode/Filelink.php @@ -0,0 +1,39 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Filelink extends AbstractMode +{ + + protected $pattern; + + /** @inheritdoc */ + public function preConnect() + { + + $ltrs = '\w'; + $gunk = '/\#~:.?+=&%@!\-'; + $punc = '.:?\-;,'; + $host = $ltrs.$punc; + $any = $ltrs.$gunk.$punc; + + $this->pattern = '\b(?i)file(?-i)://['.$any.']+?['. + $punc.']*[^'.$any.']'; + } + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern( + $this->pattern, + $mode, + 'filelink' + ); + } + + /** @inheritdoc */ + public function getSort() + { + return 360; + } +} diff --git a/inc/Parsing/ParserMode/Footnote.php b/inc/Parsing/ParserMode/Footnote.php new file mode 100644 index 000000000..c399f9849 --- /dev/null +++ b/inc/Parsing/ParserMode/Footnote.php @@ -0,0 +1,50 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Footnote extends AbstractMode +{ + + /** + * Footnote constructor. + */ + public function __construct() + { + global $PARSER_MODES; + + $this->allowedModes = array_merge( + $PARSER_MODES['container'], + $PARSER_MODES['formatting'], + $PARSER_MODES['substition'], + $PARSER_MODES['protected'], + $PARSER_MODES['disabled'] + ); + + unset($this->allowedModes[array_search('footnote', $this->allowedModes)]); + } + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern( + '\x28\x28(?=.*\x29\x29)', + $mode, + 'footnote' + ); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addExitPattern( + '\x29\x29', + 'footnote' + ); + } + + /** @inheritdoc */ + public function getSort() + { + return 150; + } +} diff --git a/inc/Parsing/ParserMode/Formatting.php b/inc/Parsing/ParserMode/Formatting.php new file mode 100644 index 000000000..a3c465cc0 --- /dev/null +++ b/inc/Parsing/ParserMode/Formatting.php @@ -0,0 +1,115 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +/** + * This class sets the markup for bold (=strong), + * italic (=emphasis), underline etc. + */ +class Formatting extends AbstractMode +{ + protected $type; + + protected $formatting = array( + 'strong' => array( + 'entry' => '\*\*(?=.*\*\*)', + 'exit' => '\*\*', + 'sort' => 70 + ), + + 'emphasis' => array( + 'entry' => '//(?=[^\x00]*[^:])', //hack for bugs #384 #763 #1468 + 'exit' => '//', + 'sort' => 80 + ), + + 'underline' => array( + 'entry' => '__(?=.*__)', + 'exit' => '__', + 'sort' => 90 + ), + + 'monospace' => array( + 'entry' => '\x27\x27(?=.*\x27\x27)', + 'exit' => '\x27\x27', + 'sort' => 100 + ), + + 'subscript' => array( + 'entry' => '<sub>(?=.*</sub>)', + 'exit' => '</sub>', + 'sort' => 110 + ), + + 'superscript' => array( + 'entry' => '<sup>(?=.*</sup>)', + 'exit' => '</sup>', + 'sort' => 120 + ), + + 'deleted' => array( + 'entry' => '<del>(?=.*</del>)', + 'exit' => '</del>', + 'sort' => 130 + ), + ); + + /** + * @param string $type + */ + public function __construct($type) + { + global $PARSER_MODES; + + if (!array_key_exists($type, $this->formatting)) { + trigger_error('Invalid formatting type ' . $type, E_USER_WARNING); + } + + $this->type = $type; + + // formatting may contain other formatting but not it self + $modes = $PARSER_MODES['formatting']; + $key = array_search($type, $modes); + if (is_int($key)) { + unset($modes[$key]); + } + + $this->allowedModes = array_merge( + $modes, + $PARSER_MODES['substition'], + $PARSER_MODES['disabled'] + ); + } + + /** @inheritdoc */ + public function connectTo($mode) + { + + // Can't nest formatting in itself + if ($mode == $this->type) { + return; + } + + $this->Lexer->addEntryPattern( + $this->formatting[$this->type]['entry'], + $mode, + $this->type + ); + } + + /** @inheritdoc */ + public function postConnect() + { + + $this->Lexer->addExitPattern( + $this->formatting[$this->type]['exit'], + $this->type + ); + } + + /** @inheritdoc */ + public function getSort() + { + return $this->formatting[$this->type]['sort']; + } +} diff --git a/inc/Parsing/ParserMode/Header.php b/inc/Parsing/ParserMode/Header.php new file mode 100644 index 000000000..854b3178c --- /dev/null +++ b/inc/Parsing/ParserMode/Header.php @@ -0,0 +1,24 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Header extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + //we're not picky about the closing ones, two are enough + $this->Lexer->addSpecialPattern( + '[ \t]*={2,}[^\n]+={2,}[ \t]*(?=\n)', + $mode, + 'header' + ); + } + + /** @inheritdoc */ + public function getSort() + { + return 50; + } +} diff --git a/inc/Parsing/ParserMode/Hr.php b/inc/Parsing/ParserMode/Hr.php new file mode 100644 index 000000000..e4f0b444b --- /dev/null +++ b/inc/Parsing/ParserMode/Hr.php @@ -0,0 +1,19 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Hr extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern('\n[ \t]*-{4,}[ \t]*(?=\n)', $mode, 'hr'); + } + + /** @inheritdoc */ + public function getSort() + { + return 160; + } +} diff --git a/inc/Parsing/ParserMode/Html.php b/inc/Parsing/ParserMode/Html.php new file mode 100644 index 000000000..f5b63ef09 --- /dev/null +++ b/inc/Parsing/ParserMode/Html.php @@ -0,0 +1,27 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Html extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern('<html>(?=.*</html>)', $mode, 'html'); + $this->Lexer->addEntryPattern('<HTML>(?=.*</HTML>)', $mode, 'htmlblock'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addExitPattern('</html>', 'html'); + $this->Lexer->addExitPattern('</HTML>', 'htmlblock'); + } + + /** @inheritdoc */ + public function getSort() + { + return 190; + } +} diff --git a/inc/Parsing/ParserMode/Internallink.php b/inc/Parsing/ParserMode/Internallink.php new file mode 100644 index 000000000..6def0d9a3 --- /dev/null +++ b/inc/Parsing/ParserMode/Internallink.php @@ -0,0 +1,20 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Internallink extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + // Word boundaries? + $this->Lexer->addSpecialPattern("\[\[.*?\]\](?!\])", $mode, 'internallink'); + } + + /** @inheritdoc */ + public function getSort() + { + return 300; + } +} diff --git a/inc/Parsing/ParserMode/Linebreak.php b/inc/Parsing/ParserMode/Linebreak.php new file mode 100644 index 000000000..dd95cc383 --- /dev/null +++ b/inc/Parsing/ParserMode/Linebreak.php @@ -0,0 +1,19 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Linebreak extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern('\x5C{2}(?:[ \t]|(?=\n))', $mode, 'linebreak'); + } + + /** @inheritdoc */ + public function getSort() + { + return 140; + } +} diff --git a/inc/Parsing/ParserMode/Listblock.php b/inc/Parsing/ParserMode/Listblock.php new file mode 100644 index 000000000..eef762777 --- /dev/null +++ b/inc/Parsing/ParserMode/Listblock.php @@ -0,0 +1,44 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Listblock extends AbstractMode +{ + + /** + * Listblock constructor. + */ + public function __construct() + { + global $PARSER_MODES; + + $this->allowedModes = array_merge( + $PARSER_MODES['formatting'], + $PARSER_MODES['substition'], + $PARSER_MODES['disabled'], + $PARSER_MODES['protected'] + ); + } + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern('[ \t]*\n {2,}[\-\*]', $mode, 'listblock'); + $this->Lexer->addEntryPattern('[ \t]*\n\t{1,}[\-\*]', $mode, 'listblock'); + + $this->Lexer->addPattern('\n {2,}[\-\*]', 'listblock'); + $this->Lexer->addPattern('\n\t{1,}[\-\*]', 'listblock'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addExitPattern('\n', 'listblock'); + } + + /** @inheritdoc */ + public function getSort() + { + return 10; + } +} diff --git a/inc/Parsing/ParserMode/Media.php b/inc/Parsing/ParserMode/Media.php new file mode 100644 index 000000000..f93f94773 --- /dev/null +++ b/inc/Parsing/ParserMode/Media.php @@ -0,0 +1,20 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Media extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + // Word boundaries? + $this->Lexer->addSpecialPattern("\{\{(?:[^\}]|(?:\}[^\}]))+\}\}", $mode, 'media'); + } + + /** @inheritdoc */ + public function getSort() + { + return 320; + } +} diff --git a/inc/Parsing/ParserMode/ModeInterface.php b/inc/Parsing/ParserMode/ModeInterface.php new file mode 100644 index 000000000..7cca0385f --- /dev/null +++ b/inc/Parsing/ParserMode/ModeInterface.php @@ -0,0 +1,46 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +/** + * Defines a mode (syntax component) in the Parser + */ +interface ModeInterface +{ + /** + * returns a number used to determine in which order modes are added + * + * @return int; + */ + public function getSort(); + + /** + * Called before any calls to connectTo + * + * @return void + */ + public function preConnect(); + + /** + * Connects the mode + * + * @param string $mode + * @return void + */ + public function connectTo($mode); + + /** + * Called after all calls to connectTo + * + * @return void + */ + public function postConnect(); + + /** + * Check if given mode is accepted inside this mode + * + * @param string $mode + * @return bool + */ + public function accepts($mode); +} diff --git a/inc/Parsing/ParserMode/Multiplyentity.php b/inc/Parsing/ParserMode/Multiplyentity.php new file mode 100644 index 000000000..89df136df --- /dev/null +++ b/inc/Parsing/ParserMode/Multiplyentity.php @@ -0,0 +1,27 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +/** + * Implements the 640x480 replacement + */ +class Multiplyentity extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + + $this->Lexer->addSpecialPattern( + '(?<=\b)(?:[1-9]|\d{2,})[xX]\d+(?=\b)', + $mode, + 'multiplyentity' + ); + } + + /** @inheritdoc */ + public function getSort() + { + return 270; + } +} diff --git a/inc/Parsing/ParserMode/Nocache.php b/inc/Parsing/ParserMode/Nocache.php new file mode 100644 index 000000000..fa6db8305 --- /dev/null +++ b/inc/Parsing/ParserMode/Nocache.php @@ -0,0 +1,19 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Nocache extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern('~~NOCACHE~~', $mode, 'nocache'); + } + + /** @inheritdoc */ + public function getSort() + { + return 40; + } +} diff --git a/inc/Parsing/ParserMode/Notoc.php b/inc/Parsing/ParserMode/Notoc.php new file mode 100644 index 000000000..5956207c1 --- /dev/null +++ b/inc/Parsing/ParserMode/Notoc.php @@ -0,0 +1,19 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Notoc extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern('~~NOTOC~~', $mode, 'notoc'); + } + + /** @inheritdoc */ + public function getSort() + { + return 30; + } +} diff --git a/inc/Parsing/ParserMode/Php.php b/inc/Parsing/ParserMode/Php.php new file mode 100644 index 000000000..914648b51 --- /dev/null +++ b/inc/Parsing/ParserMode/Php.php @@ -0,0 +1,27 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Php extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern('<php>(?=.*</php>)', $mode, 'php'); + $this->Lexer->addEntryPattern('<PHP>(?=.*</PHP>)', $mode, 'phpblock'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addExitPattern('</php>', 'php'); + $this->Lexer->addExitPattern('</PHP>', 'phpblock'); + } + + /** @inheritdoc */ + public function getSort() + { + return 180; + } +} diff --git a/inc/Parsing/ParserMode/Plugin.php b/inc/Parsing/ParserMode/Plugin.php new file mode 100644 index 000000000..c885c6037 --- /dev/null +++ b/inc/Parsing/ParserMode/Plugin.php @@ -0,0 +1,8 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +/** + * @fixme do we need this anymore or could the syntax plugin inherit directly from abstract mode? + */ +abstract class Plugin extends AbstractMode {} diff --git a/inc/Parsing/ParserMode/Preformatted.php b/inc/Parsing/ParserMode/Preformatted.php new file mode 100644 index 000000000..7dfc47489 --- /dev/null +++ b/inc/Parsing/ParserMode/Preformatted.php @@ -0,0 +1,31 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Preformatted extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + // Has hard coded awareness of lists... + $this->Lexer->addEntryPattern('\n (?![\*\-])', $mode, 'preformatted'); + $this->Lexer->addEntryPattern('\n\t(?![\*\-])', $mode, 'preformatted'); + + // How to effect a sub pattern with the Lexer! + $this->Lexer->addPattern('\n ', 'preformatted'); + $this->Lexer->addPattern('\n\t', 'preformatted'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addExitPattern('\n', 'preformatted'); + } + + /** @inheritdoc */ + public function getSort() + { + return 20; + } +} diff --git a/inc/Parsing/ParserMode/Quote.php b/inc/Parsing/ParserMode/Quote.php new file mode 100644 index 000000000..65525b241 --- /dev/null +++ b/inc/Parsing/ParserMode/Quote.php @@ -0,0 +1,41 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Quote extends AbstractMode +{ + + /** + * Quote constructor. + */ + public function __construct() + { + global $PARSER_MODES; + + $this->allowedModes = array_merge( + $PARSER_MODES['formatting'], + $PARSER_MODES['substition'], + $PARSER_MODES['disabled'], + $PARSER_MODES['protected'] + ); + } + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern('\n>{1,}', $mode, 'quote'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addPattern('\n>{1,}', 'quote'); + $this->Lexer->addExitPattern('\n', 'quote'); + } + + /** @inheritdoc */ + public function getSort() + { + return 220; + } +} diff --git a/inc/Parsing/ParserMode/Quotes.php b/inc/Parsing/ParserMode/Quotes.php new file mode 100644 index 000000000..13db2e679 --- /dev/null +++ b/inc/Parsing/ParserMode/Quotes.php @@ -0,0 +1,51 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Quotes extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + global $conf; + + $ws = '\s/\#~:+=&%@\-\x28\x29\]\[{}><"\''; // whitespace + $punc = ';,\.?!'; + + if ($conf['typography'] == 2) { + $this->Lexer->addSpecialPattern( + "(?<=^|[$ws])'(?=[^$ws$punc])", + $mode, + 'singlequoteopening' + ); + $this->Lexer->addSpecialPattern( + "(?<=^|[^$ws]|[$punc])'(?=$|[$ws$punc])", + $mode, + 'singlequoteclosing' + ); + $this->Lexer->addSpecialPattern( + "(?<=^|[^$ws$punc])'(?=$|[^$ws$punc])", + $mode, + 'apostrophe' + ); + } + + $this->Lexer->addSpecialPattern( + "(?<=^|[$ws])\"(?=[^$ws$punc])", + $mode, + 'doublequoteopening' + ); + $this->Lexer->addSpecialPattern( + "\"", + $mode, + 'doublequoteclosing' + ); + } + + /** @inheritdoc */ + public function getSort() + { + return 280; + } +} diff --git a/inc/Parsing/ParserMode/Rss.php b/inc/Parsing/ParserMode/Rss.php new file mode 100644 index 000000000..a62d9b807 --- /dev/null +++ b/inc/Parsing/ParserMode/Rss.php @@ -0,0 +1,19 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Rss extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern("\{\{rss>[^\}]+\}\}", $mode, 'rss'); + } + + /** @inheritdoc */ + public function getSort() + { + return 310; + } +} diff --git a/inc/Parsing/ParserMode/Smiley.php b/inc/Parsing/ParserMode/Smiley.php new file mode 100644 index 000000000..084ccc9ed --- /dev/null +++ b/inc/Parsing/ParserMode/Smiley.php @@ -0,0 +1,48 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +use dokuwiki\Parsing\Lexer\Lexer; + +class Smiley extends AbstractMode +{ + protected $smileys = array(); + protected $pattern = ''; + + /** + * Smiley constructor. + * @param string[] $smileys + */ + public function __construct($smileys) + { + $this->smileys = $smileys; + } + + /** @inheritdoc */ + public function preConnect() + { + if (!count($this->smileys) || $this->pattern != '') return; + + $sep = ''; + foreach ($this->smileys as $smiley) { + $this->pattern .= $sep.'(?<=\W|^)'. Lexer::escape($smiley).'(?=\W|$)'; + $sep = '|'; + } + } + + /** @inheritdoc */ + public function connectTo($mode) + { + if (!count($this->smileys)) return; + + if (strlen($this->pattern) > 0) { + $this->Lexer->addSpecialPattern($this->pattern, $mode, 'smiley'); + } + } + + /** @inheritdoc */ + public function getSort() + { + return 230; + } +} diff --git a/inc/Parsing/ParserMode/Table.php b/inc/Parsing/ParserMode/Table.php new file mode 100644 index 000000000..b4b512380 --- /dev/null +++ b/inc/Parsing/ParserMode/Table.php @@ -0,0 +1,47 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Table extends AbstractMode +{ + + /** + * Table constructor. + */ + public function __construct() + { + global $PARSER_MODES; + + $this->allowedModes = array_merge( + $PARSER_MODES['formatting'], + $PARSER_MODES['substition'], + $PARSER_MODES['disabled'], + $PARSER_MODES['protected'] + ); + } + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern('[\t ]*\n\^', $mode, 'table'); + $this->Lexer->addEntryPattern('[\t ]*\n\|', $mode, 'table'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addPattern('\n\^', 'table'); + $this->Lexer->addPattern('\n\|', 'table'); + $this->Lexer->addPattern('[\t ]*:::[\t ]*(?=[\|\^])', 'table'); + $this->Lexer->addPattern('[\t ]+', 'table'); + $this->Lexer->addPattern('\^', 'table'); + $this->Lexer->addPattern('\|', 'table'); + $this->Lexer->addExitPattern('\n', 'table'); + } + + /** @inheritdoc */ + public function getSort() + { + return 60; + } +} diff --git a/inc/Parsing/ParserMode/Unformatted.php b/inc/Parsing/ParserMode/Unformatted.php new file mode 100644 index 000000000..1bc2826e6 --- /dev/null +++ b/inc/Parsing/ParserMode/Unformatted.php @@ -0,0 +1,28 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Unformatted extends AbstractMode +{ + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addEntryPattern('<nowiki>(?=.*</nowiki>)', $mode, 'unformatted'); + $this->Lexer->addEntryPattern('%%(?=.*%%)', $mode, 'unformattedalt'); + } + + /** @inheritdoc */ + public function postConnect() + { + $this->Lexer->addExitPattern('</nowiki>', 'unformatted'); + $this->Lexer->addExitPattern('%%', 'unformattedalt'); + $this->Lexer->mapHandler('unformattedalt', 'unformatted'); + } + + /** @inheritdoc */ + public function getSort() + { + return 170; + } +} diff --git a/inc/Parsing/ParserMode/Windowssharelink.php b/inc/Parsing/ParserMode/Windowssharelink.php new file mode 100644 index 000000000..747d4d8a9 --- /dev/null +++ b/inc/Parsing/ParserMode/Windowssharelink.php @@ -0,0 +1,31 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +class Windowssharelink extends AbstractMode +{ + + protected $pattern; + + /** @inheritdoc */ + public function preConnect() + { + $this->pattern = "\\\\\\\\\w+?(?:\\\\[\w\-$]+)+"; + } + + /** @inheritdoc */ + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern( + $this->pattern, + $mode, + 'windowssharelink' + ); + } + + /** @inheritdoc */ + public function getSort() + { + return 350; + } +} diff --git a/inc/Parsing/ParserMode/Wordblock.php b/inc/Parsing/ParserMode/Wordblock.php new file mode 100644 index 000000000..50b24b2db --- /dev/null +++ b/inc/Parsing/ParserMode/Wordblock.php @@ -0,0 +1,52 @@ +<?php + +namespace dokuwiki\Parsing\ParserMode; + +use dokuwiki\Parsing\Lexer\Lexer; + +/** + * @fixme is this actually used? + */ +class Wordblock extends AbstractMode +{ + protected $badwords = array(); + protected $pattern = ''; + + /** + * Wordblock constructor. + * @param $badwords + */ + public function __construct($badwords) + { + $this->badwords = $badwords; + } + + /** @inheritdoc */ + public function preConnect() + { + + if (count($this->badwords) == 0 || $this->pattern != '') { + return; + } + + $sep = ''; + foreach ($this->badwords as $badword) { + $this->pattern .= $sep.'(?<=\b)(?i)'. Lexer::escape($badword).'(?-i)(?=\b)'; + $sep = '|'; + } + } + + /** @inheritdoc */ + public function connectTo($mode) + { + if (strlen($this->pattern) > 0) { + $this->Lexer->addSpecialPattern($this->pattern, $mode, 'wordblock'); + } + } + + /** @inheritdoc */ + public function getSort() + { + return 250; + } +} diff --git a/inc/PassHash.class.php b/inc/PassHash.class.php index 3d03c1e05..1e66c2827 100644 --- a/inc/PassHash.class.php +++ b/inc/PassHash.class.php @@ -21,7 +21,7 @@ class PassHash { * @param string $hash Hash to compare against * @return bool */ - function verify_hash($clear, $hash) { + public function verify_hash($clear, $hash) { $method = ''; $salt = ''; $magic = ''; diff --git a/inc/Remote/AccessDeniedException.php b/inc/Remote/AccessDeniedException.php new file mode 100644 index 000000000..65f668930 --- /dev/null +++ b/inc/Remote/AccessDeniedException.php @@ -0,0 +1,10 @@ +<?php + +namespace dokuwiki\Remote; + +/** + * Class AccessDeniedException + */ +class AccessDeniedException extends RemoteException +{ +} diff --git a/inc/remote.php b/inc/Remote/Api.php index 2d2e327c8..36957a873 100644 --- a/inc/remote.php +++ b/inc/Remote/Api.php @@ -1,9 +1,9 @@ <?php -if (!defined('DOKU_INC')) die(); +namespace dokuwiki\Remote; -class RemoteException extends Exception {} -class RemoteAccessDeniedException extends RemoteException {} +use DokuWiki_Remote_Plugin; +use Input; /** * This class provides information about remote access to the wiki. @@ -33,19 +33,18 @@ class RemoteAccessDeniedException extends RemoteException {} * * plugin methods are formed like 'plugin.<plugin name>.<method name>'. * i.e.: plugin.clock.getTime or plugin.clock_gmt.getTime - * - * @throws RemoteException */ -class RemoteAPI { +class Api +{ /** - * @var RemoteAPICore + * @var ApiCore */ private $coreMethods = null; /** * @var array remote methods provided by dokuwiki plugins - will be filled lazy via - * {@see RemoteAPI#getPluginMethods} + * {@see dokuwiki\Remote\RemoteAPI#getPluginMethods} */ private $pluginMethods = null; @@ -63,7 +62,8 @@ class RemoteAPI { /** * constructor */ - public function __construct() { + public function __construct() + { $this->dateTransformation = array($this, 'dummyTransformation'); $this->fileTransformation = array($this, 'dummyTransformation'); } @@ -72,8 +72,10 @@ class RemoteAPI { * Get all available methods with remote access. * * @return array with information to all available methods + * @throws RemoteException */ - public function getMethods() { + public function getMethods() + { return array_merge($this->getCoreMethods(), $this->getPluginMethods()); } @@ -83,8 +85,10 @@ class RemoteAPI { * @param string $method name of the method to call. * @param array $args arguments to pass to the given method * @return mixed result of method call, must be a primitive type. + * @throws RemoteException */ - public function call($method, $args = array()) { + public function call($method, $args = array()) + { if ($args === null) { $args = array(); } @@ -104,7 +108,8 @@ class RemoteAPI { * @param string $name name of the method * @return bool if method exists */ - private function coreMethodExist($name) { + private function coreMethodExist($name) + { $coreMethods = $this->getCoreMethods(); return array_key_exists($name, $coreMethods); } @@ -113,11 +118,12 @@ class RemoteAPI { * Try to call custom methods provided by plugins * * @param string $method name of method - * @param array $args + * @param array $args * @return mixed * @throws RemoteException if method not exists */ - private function callCustomCallPlugin($method, $args) { + private function callCustomCallPlugin($method, $args) + { $customCalls = $this->getCustomCallPlugins(); if (!array_key_exists($method, $customCalls)) { throw new RemoteException('Method does not exist', -32603); @@ -132,7 +138,8 @@ class RemoteAPI { * @return array with pairs of custom plugin calls * @triggers RPC_CALL_ADD */ - private function getCustomCallPlugins() { + private function getCustomCallPlugins() + { if ($this->pluginCustomCalls === null) { $data = array(); trigger_event('RPC_CALL_ADD', $data); @@ -146,11 +153,12 @@ class RemoteAPI { * * @param string $pluginName * @param string $method method name - * @param array $args + * @param array $args * @return mixed return of custom method * @throws RemoteException */ - private function callPlugin($pluginName, $method, $args) { + private function callPlugin($pluginName, $method, $args) + { $plugin = plugin_load('remote', $pluginName); $methods = $this->getPluginMethods(); if (!$plugin) { @@ -165,11 +173,12 @@ class RemoteAPI { * Call a core method * * @param string $method name of method - * @param array $args + * @param array $args * @return mixed * @throws RemoteException if method not exist */ - private function callCoreMethod($method, $args) { + private function callCoreMethod($method, $args) + { $coreMethods = $this->getCoreMethods(); $this->checkAccess($coreMethods[$method]); if (!isset($coreMethods[$method])) { @@ -183,11 +192,13 @@ class RemoteAPI { * Check if access should be checked * * @param array $methodMeta data about the method + * @throws AccessDeniedException */ - private function checkAccess($methodMeta) { + private function checkAccess($methodMeta) + { if (!isset($methodMeta['public'])) { $this->forceAccess(); - } else{ + } else { if ($methodMeta['public'] == '0') { $this->forceAccess(); } @@ -201,7 +212,8 @@ class RemoteAPI { * @param array $args * @throws RemoteException if wrong parameter count */ - private function checkArgumentLength($methodMeta, $args) { + private function checkArgumentLength($methodMeta, $args) + { if (count($methodMeta['args']) < count($args)) { throw new RemoteException('Method does not exist - wrong parameter count.', -32603); } @@ -214,36 +226,38 @@ class RemoteAPI { * @param string $method name of method * @return string */ - private function getMethodName($methodMeta, $method) { + private function getMethodName($methodMeta, $method) + { if (isset($methodMeta[$method]['name'])) { return $methodMeta[$method]['name']; } $method = explode('.', $method); - return $method[count($method)-1]; + return $method[count($method) - 1]; } /** * Perform access check for current user * * @return bool true if the current user has access to remote api. - * @throws RemoteAccessDeniedException If remote access disabled + * @throws AccessDeniedException If remote access disabled */ - public function hasAccess() { + public function hasAccess() + { global $conf; global $USERINFO; /** @var Input $INPUT */ global $INPUT; if (!$conf['remote']) { - throw new RemoteAccessDeniedException('server error. RPC server not enabled.',-32604); //should not be here,just throw + throw new AccessDeniedException('server error. RPC server not enabled.', -32604); } - if(trim($conf['remoteuser']) == '!!not set!!') { + if (trim($conf['remoteuser']) == '!!not set!!') { return false; } - if(!$conf['useacl']) { + if (!$conf['useacl']) { return true; } - if(trim($conf['remoteuser']) == '') { + if (trim($conf['remoteuser']) == '') { return true; } @@ -254,11 +268,12 @@ class RemoteAPI { * Requests access * * @return void - * @throws RemoteException On denied access. + * @throws AccessDeniedException On denied access. */ - public function forceAccess() { + public function forceAccess() + { if (!$this->hasAccess()) { - throw new RemoteAccessDeniedException('server error. not authorized to call method', -32604); + throw new AccessDeniedException('server error. not authorized to call method', -32604); } } @@ -268,7 +283,8 @@ class RemoteAPI { * @return array all plugin methods. * @throws RemoteException if not implemented */ - public function getPluginMethods() { + public function getPluginMethods() + { if ($this->pluginMethods === null) { $this->pluginMethods = array(); $plugins = plugin_list('remote'); @@ -280,7 +296,12 @@ class RemoteAPI { throw new RemoteException("Plugin $pluginName does not implement DokuWiki_Remote_Plugin"); } - $methods = $plugin->_getMethods(); + try { + $methods = $plugin->_getMethods(); + } catch (\ReflectionException $e) { + throw new RemoteException('Automatic aggregation of available remote methods failed', 0, $e); + } + foreach ($methods as $method => $meta) { $this->pluginMethods["plugin.$pluginName.$method"] = $meta; } @@ -292,14 +313,15 @@ class RemoteAPI { /** * Collects all the core methods * - * @param RemoteAPICore $apiCore this parameter is used for testing. Here you can pass a non-default RemoteAPICore - * instance. (for mocking) + * @param ApiCore $apiCore this parameter is used for testing. Here you can pass a non-default RemoteAPICore + * instance. (for mocking) * @return array all core methods. */ - public function getCoreMethods($apiCore = null) { + public function getCoreMethods($apiCore = null) + { if ($this->coreMethods === null) { if ($apiCore === null) { - $this->coreMethods = new RemoteAPICore($this); + $this->coreMethods = new ApiCore($this); } else { $this->coreMethods = $apiCore; } @@ -313,7 +335,8 @@ class RemoteAPI { * @param mixed $data * @return mixed */ - public function toFile($data) { + public function toFile($data) + { return call_user_func($this->fileTransformation, $data); } @@ -323,7 +346,8 @@ class RemoteAPI { * @param mixed $data * @return mixed */ - public function toDate($data) { + public function toDate($data) + { return call_user_func($this->dateTransformation, $data); } @@ -333,7 +357,8 @@ class RemoteAPI { * @param mixed $data * @return mixed */ - public function dummyTransformation($data) { + public function dummyTransformation($data) + { return $data; } @@ -342,7 +367,8 @@ class RemoteAPI { * * @param callback $dateTransformation */ - public function setDateTransformation($dateTransformation) { + public function setDateTransformation($dateTransformation) + { $this->dateTransformation = $dateTransformation; } @@ -351,7 +377,8 @@ class RemoteAPI { * * @param callback $fileTransformation */ - public function setFileTransformation($fileTransformation) { + public function setFileTransformation($fileTransformation) + { $this->fileTransformation = $fileTransformation; } } diff --git a/inc/RemoteAPICore.php b/inc/Remote/ApiCore.php index c78073db6..897bcf9af 100644 --- a/inc/RemoteAPICore.php +++ b/inc/Remote/ApiCore.php @@ -1,22 +1,32 @@ <?php -/** - * Increased whenever the API is changed - */ +namespace dokuwiki\Remote; + +use Doku_Renderer_xhtml; +use DokuWiki_Auth_Plugin; +use MediaChangeLog; +use PageChangeLog; + define('DOKU_API_VERSION', 10); /** * Provides the core methods for the remote API. * The methods are ordered in 'wiki.<method>' and 'dokuwiki.<method>' namespaces */ -class RemoteAPICore { +class ApiCore +{ + /** @var int Increased whenever the API is changed */ + const API_VERSION = 10; + + /** @var Api */ private $api; /** - * @param RemoteAPI $api + * @param Api $api */ - public function __construct(RemoteAPI $api) { + public function __construct(Api $api) + { $this->api = $api; } @@ -25,7 +35,8 @@ class RemoteAPICore { * * @return array */ - public function __getRemoteInfo() { + public function __getRemoteInfo() + { return array( 'dokuwiki.getVersion' => array( 'args' => array(), @@ -52,7 +63,7 @@ class RemoteAPICore { ), 'dokuwiki.getTime' => array( 'args' => array(), 'return' => 'int', - 'doc' => 'Returns the current time at the remote wiki server as Unix timestamp.', + 'doc' => 'Returns the current time at the remote wiki server as Unix timestamp.', ), 'dokuwiki.setLocks' => array( 'args' => array('array'), 'return' => 'array', @@ -165,7 +176,7 @@ class RemoteAPICore { 'public' => '1', ), 'wiki.getRPCVersionSupported' => array( 'args' => array(), - 'name' => 'wiki_RPCVersion', + 'name' => 'wikiRpcVersion', 'return' => 'int', 'doc' => 'Returns 2 with the supported RPC API version.', 'public' => '1' @@ -177,14 +188,16 @@ class RemoteAPICore { /** * @return string */ - public function getVersion() { + public function getVersion() + { return getVersion(); } /** * @return int unix timestamp */ - public function getTime() { + public function getTime() + { return time(); } @@ -194,15 +207,16 @@ class RemoteAPICore { * @param string $id wiki page id * @param int|string $rev revision timestamp of the page or empty string * @return string page text. - * @throws RemoteAccessDeniedException if no permission for page + * @throws AccessDeniedException if no permission for page */ - public function rawPage($id,$rev=''){ + public function rawPage($id, $rev = '') + { $id = $this->resolvePageId($id); - if(auth_quickaclcheck($id) < AUTH_READ){ - throw new RemoteAccessDeniedException('You are not allowed to read this file', 111); + if (auth_quickaclcheck($id) < AUTH_READ) { + throw new AccessDeniedException('You are not allowed to read this file', 111); } - $text = rawWiki($id,$rev); - if(!$text) { + $text = rawWiki($id, $rev); + if (!$text) { return pageTemplate($id); } else { return $text; @@ -216,13 +230,14 @@ class RemoteAPICore { * * @param string $id file id * @return mixed media file - * @throws RemoteAccessDeniedException no permission for media + * @throws AccessDeniedException no permission for media * @throws RemoteException not exist */ - public function getAttachment($id){ + public function getAttachment($id) + { $id = cleanID($id); - if (auth_quickaclcheck(getNS($id).':*') < AUTH_READ) { - throw new RemoteAccessDeniedException('You are not allowed to read this file', 211); + if (auth_quickaclcheck(getNS($id) . ':*') < AUTH_READ) { + throw new AccessDeniedException('You are not allowed to read this file', 211); } $file = mediaFN($id); @@ -242,7 +257,8 @@ class RemoteAPICore { * @param string $id page id * @return array */ - public function getAttachmentInfo($id){ + public function getAttachmentInfo($id) + { $id = cleanID($id); $info = array( 'lastModified' => $this->api->toDate(0), @@ -250,15 +266,15 @@ class RemoteAPICore { ); $file = mediaFN($id); - if(auth_quickaclcheck(getNS($id) . ':*') >= AUTH_READ) { - if(file_exists($file)) { + if (auth_quickaclcheck(getNS($id) . ':*') >= AUTH_READ) { + if (file_exists($file)) { $info['lastModified'] = $this->api->toDate(filemtime($file)); $info['size'] = filesize($file); } else { //Is it deleted media with changelog? $medialog = new MediaChangeLog($id); $revisions = $medialog->getRevisions(0, 1); - if(!empty($revisions)) { + if (!empty($revisions)) { $info['lastModified'] = $this->api->toDate($revisions[0]); } } @@ -270,17 +286,18 @@ class RemoteAPICore { /** * Return a wiki page rendered to html * - * @param string $id page id + * @param string $id page id * @param string|int $rev revision timestamp or empty string * @return null|string html - * @throws RemoteAccessDeniedException no access to page + * @throws AccessDeniedException no access to page */ - public function htmlPage($id,$rev=''){ + public function htmlPage($id, $rev = '') + { $id = $this->resolvePageId($id); - if(auth_quickaclcheck($id) < AUTH_READ){ - throw new RemoteAccessDeniedException('You are not allowed to read this page', 111); + if (auth_quickaclcheck($id) < AUTH_READ) { + throw new AccessDeniedException('You are not allowed to read this page', 111); } - return p_wiki_xhtml($id,$rev,false); + return p_wiki_xhtml($id, $rev, false); } /** @@ -288,14 +305,15 @@ class RemoteAPICore { * * @return array */ - public function listPages(){ - $list = array(); + public function listPages() + { + $list = array(); $pages = idx_get_indexer()->getPages(); - $pages = array_filter(array_filter($pages,'isVisiblePage'),'page_exists'); + $pages = array_filter(array_filter($pages, 'isVisiblePage'), 'page_exists'); - foreach(array_keys($pages) as $idx) { + foreach (array_keys($pages) as $idx) { $perm = auth_quickaclcheck($pages[$idx]); - if($perm < AUTH_READ) { + if ($perm < AUTH_READ) { continue; } $page = array(); @@ -313,15 +331,16 @@ class RemoteAPICore { * List all pages in the given namespace (and below) * * @param string $ns - * @param array $opts + * @param array $opts * $opts['depth'] recursion level, 0 for all * $opts['hash'] do md5 sum of content? * @return array */ - public function readNamespace($ns,$opts){ + public function readNamespace($ns, $opts) + { global $conf; - if(!is_array($opts)) $opts=array(); + if (!is_array($opts)) $opts = array(); $ns = cleanID($ns); $dir = utf8_encodeFN(str_replace(':', '/', $ns)); @@ -337,29 +356,30 @@ class RemoteAPICore { * @param string $query * @return array */ - public function search($query){ + public function search($query) + { $regex = array(); - $data = ft_pageSearch($query,$regex); + $data = ft_pageSearch($query, $regex); $pages = array(); // prepare additional data $idx = 0; - foreach($data as $id => $score){ + foreach ($data as $id => $score) { $file = wikiFN($id); - if($idx < FT_SNIPPET_NUMBER){ - $snippet = ft_snippet($id,$regex); + if ($idx < FT_SNIPPET_NUMBER) { + $snippet = ft_snippet($id, $regex); $idx++; - }else{ + } else { $snippet = ''; } $pages[] = array( - 'id' => $id, - 'score' => intval($score), - 'rev' => filemtime($file), - 'mtime' => filemtime($file), - 'size' => filesize($file), + 'id' => $id, + 'score' => intval($score), + 'rev' => filemtime($file), + 'mtime' => filemtime($file), + 'size' => filesize($file), 'snippet' => $snippet, 'title' => useHeading('navigation') ? p_get_first_heading($id) : $id ); @@ -372,7 +392,8 @@ class RemoteAPICore { * * @return string */ - public function getTitle(){ + public function getTitle() + { global $conf; return $conf['title']; } @@ -387,15 +408,16 @@ class RemoteAPICore { * @author Gina Haeussge <osd@foosel.net> * * @param string $ns - * @param array $options + * @param array $options * $options['depth'] recursion level, 0 for all * $options['showmsg'] shows message if invalid media id is used * $options['pattern'] check given pattern * $options['hash'] add hashes to result list * @return array - * @throws RemoteAccessDeniedException no access to the media files + * @throws AccessDeniedException no access to the media files */ - public function listAttachments($ns, $options = array()) { + public function listAttachments($ns, $options = array()) + { global $conf; $ns = cleanID($ns); @@ -403,15 +425,15 @@ class RemoteAPICore { if (!is_array($options)) $options = array(); $options['skipacl'] = 0; // no ACL skipping for XMLRPC - if(auth_quickaclcheck($ns.':*') >= AUTH_READ) { + if (auth_quickaclcheck($ns . ':*') >= AUTH_READ) { $dir = utf8_encodeFN(str_replace(':', '/', $ns)); $data = array(); search($data, $conf['mediadir'], 'search_media', $options, $dir); $len = count($data); - if(!$len) return array(); + if (!$len) return array(); - for($i=0; $i<$len; $i++) { + for ($i = 0; $i < $len; $i++) { unset($data[$i]['meta']); $data[$i]['perms'] = $data[$i]['perm']; unset($data[$i]['perm']); @@ -419,7 +441,7 @@ class RemoteAPICore { } return $data; } else { - throw new RemoteAccessDeniedException('You are not allowed to list media files.', 215); + throw new AccessDeniedException('You are not allowed to list media files.', 215); } } @@ -429,33 +451,35 @@ class RemoteAPICore { * @param string $id page id * @return array */ - function listBackLinks($id){ + public function listBackLinks($id) + { return ft_backlinks($this->resolvePageId($id)); } /** * Return some basic data about a page * - * @param string $id page id + * @param string $id page id * @param string|int $rev revision timestamp or empty string * @return array - * @throws RemoteAccessDeniedException no access for page + * @throws AccessDeniedException no access for page * @throws RemoteException page not exist */ - public function pageInfo($id,$rev=''){ + public function pageInfo($id, $rev = '') + { $id = $this->resolvePageId($id); - if(auth_quickaclcheck($id) < AUTH_READ){ - throw new RemoteAccessDeniedException('You are not allowed to read this page', 111); + if (auth_quickaclcheck($id) < AUTH_READ) { + throw new AccessDeniedException('You are not allowed to read this page', 111); } - $file = wikiFN($id,$rev); + $file = wikiFN($id, $rev); $time = @filemtime($file); - if(!$time){ + if (!$time) { throw new RemoteException('The requested page does not exist', 121); } // set revision to current version if empty, use revision otherwise // as the timestamps of old files are not necessarily correct - if($rev === '') { + if ($rev === '') { $rev = $time; } @@ -463,10 +487,10 @@ class RemoteAPICore { $info = $pagelog->getRevisionInfo($rev); $data = array( - 'name' => $id, + 'name' => $id, 'lastModified' => $this->api->toDate($rev), - 'author' => (($info['user']) ? $info['user'] : $info['ip']), - 'version' => $rev + 'author' => (($info['user']) ? $info['user'] : $info['ip']), + 'version' => $rev ); return ($data); @@ -481,53 +505,54 @@ class RemoteAPICore { * @param string $text wiki text * @param array $params parameters: summary, minor edit * @return bool - * @throws RemoteAccessDeniedException no write access for page + * @throws AccessDeniedException no write access for page * @throws RemoteException no id, empty new page or locked */ - public function putPage($id, $text, $params) { + public function putPage($id, $text, $params) + { global $TEXT; global $lang; - $id = $this->resolvePageId($id); - $TEXT = cleanText($text); - $sum = $params['sum']; + $id = $this->resolvePageId($id); + $TEXT = cleanText($text); + $sum = $params['sum']; $minor = $params['minor']; - if(empty($id)) { + if (empty($id)) { throw new RemoteException('Empty page ID', 131); } - if(!page_exists($id) && trim($TEXT) == '' ) { + if (!page_exists($id) && trim($TEXT) == '') { throw new RemoteException('Refusing to write an empty new wiki page', 132); } - if(auth_quickaclcheck($id) < AUTH_EDIT) { - throw new RemoteAccessDeniedException('You are not allowed to edit this page', 112); + if (auth_quickaclcheck($id) < AUTH_EDIT) { + throw new AccessDeniedException('You are not allowed to edit this page', 112); } // Check, if page is locked - if(checklock($id)) { + if (checklock($id)) { throw new RemoteException('The page is currently locked', 133); } // SPAM check - if(checkwordblock()) { + if (checkwordblock()) { throw new RemoteException('Positive wordblock check', 134); } // autoset summary on new pages - if(!page_exists($id) && empty($sum)) { + if (!page_exists($id) && empty($sum)) { $sum = $lang['created']; } // autoset summary on deleted pages - if(page_exists($id) && empty($TEXT) && empty($sum)) { + if (page_exists($id) && empty($TEXT) && empty($sum)) { $sum = $lang['deleted']; } lock($id); - saveWikiText($id,$TEXT,$sum,$minor); + saveWikiText($id, $TEXT, $sum, $minor); unlock($id); @@ -544,13 +569,15 @@ class RemoteAPICore { * @param string $text wiki text * @param array $params such as summary,minor * @return bool|string + * @throws RemoteException */ - public function appendPage($id, $text, $params) { + public function appendPage($id, $text, $params) + { $currentpage = $this->rawPage($id); if (!is_string($currentpage)) { return $currentpage; } - return $this->putPage($id, $currentpage.$text, $params); + return $this->putPage($id, $currentpage . $text, $params); } /** @@ -560,12 +587,12 @@ class RemoteAPICore { * * @return bool * - * @throws RemoteAccessDeniedException + * @throws AccessDeniedException */ public function deleteUsers($usernames) { if (!auth_isadmin()) { - throw new RemoteAccessDeniedException('Only admins are allowed to delete users', 114); + throw new AccessDeniedException('Only admins are allowed to delete users', 114); } /** @var DokuWiki_Auth_Plugin $auth */ global $auth; @@ -583,17 +610,18 @@ class RemoteAPICore { * @return false|string * @throws RemoteException */ - public function putAttachment($id, $file, $params) { + public function putAttachment($id, $file, $params) + { $id = cleanID($id); - $auth = auth_quickaclcheck(getNS($id).':*'); + $auth = auth_quickaclcheck(getNS($id) . ':*'); - if(!isset($id)) { + if (!isset($id)) { throw new RemoteException('Filename not given.', 231); } global $conf; - $ftmp = $conf['tmpdir'] . '/' . md5($id.clientIP()); + $ftmp = $conf['tmpdir'] . '/' . md5($id . clientIP()); // save temporary file @unlink($ftmp); @@ -614,17 +642,18 @@ class RemoteAPICore { * * @param string $id page id * @return int - * @throws RemoteAccessDeniedException no permissions + * @throws AccessDeniedException no permissions * @throws RemoteException file in use or not deleted */ - public function deleteAttachment($id){ + public function deleteAttachment($id) + { $id = cleanID($id); - $auth = auth_quickaclcheck(getNS($id).':*'); + $auth = auth_quickaclcheck(getNS($id) . ':*'); $res = media_delete($id, $auth); if ($res & DOKU_MEDIA_DELETED) { return 0; } elseif ($res & DOKU_MEDIA_NOT_AUTH) { - throw new RemoteAccessDeniedException('You don\'t have permissions to delete files.', 212); + throw new AccessDeniedException('You don\'t have permissions to delete files.', 212); } elseif ($res & DOKU_MEDIA_INUSE) { throw new RemoteException('File is still referenced', 232); } else { @@ -640,17 +669,18 @@ class RemoteAPICore { * @param array|null $groups array of groups * @return int permission level */ - public function aclCheck($id, $user = null, $groups = null) { + public function aclCheck($id, $user = null, $groups = null) + { /** @var DokuWiki_Auth_Plugin $auth */ global $auth; $id = $this->resolvePageId($id); - if($user === null) { + if ($user === null) { return auth_quickaclcheck($id); } else { - if($groups === null) { + if ($groups === null) { $userinfo = $auth->getUserData($user); - if($userinfo === false) { + if ($userinfo === false) { $groups = array(); } else { $groups = $userinfo['grps']; @@ -667,44 +697,45 @@ class RemoteAPICore { * * @param string $id page id * @return array - * @throws RemoteAccessDeniedException no read access for page + * @throws AccessDeniedException no read access for page */ - public function listLinks($id) { + public function listLinks($id) + { $id = $this->resolvePageId($id); - if(auth_quickaclcheck($id) < AUTH_READ){ - throw new RemoteAccessDeniedException('You are not allowed to read this page', 111); + if (auth_quickaclcheck($id) < AUTH_READ) { + throw new AccessDeniedException('You are not allowed to read this page', 111); } $links = array(); // resolve page instructions - $ins = p_cached_instructions(wikiFN($id)); + $ins = p_cached_instructions(wikiFN($id)); // instantiate new Renderer - needed for interwiki links $Renderer = new Doku_Renderer_xhtml(); $Renderer->interwiki = getInterwiki(); // parse parse instructions - foreach($ins as $in) { + foreach ($ins as $in) { $link = array(); - switch($in[0]) { + switch ($in[0]) { case 'internallink': $link['type'] = 'local'; $link['page'] = $in[1][0]; $link['href'] = wl($in[1][0]); - array_push($links,$link); + array_push($links, $link); break; case 'externallink': $link['type'] = 'extern'; $link['page'] = $in[1][0]; $link['href'] = $in[1][0]; - array_push($links,$link); + array_push($links, $link); break; case 'interwikilink': - $url = $Renderer->_resolveInterWiki($in[1][2],$in[1][3]); + $url = $Renderer->_resolveInterWiki($in[1][2], $in[1][3]); $link['type'] = 'extern'; $link['page'] = $url; $link['href'] = $url; - array_push($links,$link); + array_push($links, $link); break; } } @@ -722,8 +753,9 @@ class RemoteAPICore { * @return array * @throws RemoteException no valid timestamp */ - public function getRecentChanges($timestamp) { - if(strlen($timestamp) != 10) { + public function getRecentChanges($timestamp) + { + if (strlen($timestamp) != 10) { throw new RemoteException('The provided value is not a valid timestamp', 311); } @@ -733,12 +765,12 @@ class RemoteAPICore { foreach ($recents as $recent) { $change = array(); - $change['name'] = $recent['id']; + $change['name'] = $recent['id']; $change['lastModified'] = $this->api->toDate($recent['date']); - $change['author'] = $recent['user']; - $change['version'] = $recent['date']; - $change['perms'] = $recent['perms']; - $change['size'] = @filesize(wikiFN($recent['id'])); + $change['author'] = $recent['user']; + $change['version'] = $recent['date']; + $change['perms'] = $recent['perms']; + $change['size'] = @filesize(wikiFN($recent['id'])); array_push($changes, $change); } @@ -760,8 +792,9 @@ class RemoteAPICore { * @return array * @throws RemoteException no valid timestamp */ - public function getRecentMediaChanges($timestamp) { - if(strlen($timestamp) != 10) + public function getRecentMediaChanges($timestamp) + { + if (strlen($timestamp) != 10) throw new RemoteException('The provided value is not a valid timestamp', 311); $recents = getRecentsSince($timestamp, null, '', RECENTS_MEDIA_CHANGES); @@ -770,12 +803,12 @@ class RemoteAPICore { foreach ($recents as $recent) { $change = array(); - $change['name'] = $recent['id']; + $change['name'] = $recent['id']; $change['lastModified'] = $this->api->toDate($recent['date']); - $change['author'] = $recent['user']; - $change['version'] = $recent['date']; - $change['perms'] = $recent['perms']; - $change['size'] = @filesize(mediaFN($recent['id'])); + $change['author'] = $recent['user']; + $change['version'] = $recent['date']; + $change['perms'] = $recent['perms']; + $change['size'] = @filesize(mediaFN($recent['id'])); array_push($changes, $change); } @@ -794,22 +827,26 @@ class RemoteAPICore { * * @author Michael Klier <chi@chimeric.de> * - * @param string $id page id - * @param int $first skip the first n changelog lines (0 = from current(if exists), 1 = from 1st old rev, 2 = from 2nd old rev, etc) + * @param string $id page id + * @param int $first skip the first n changelog lines + * 0 = from current(if exists) + * 1 = from 1st old rev + * 2 = from 2nd old rev, etc * @return array - * @throws RemoteAccessDeniedException no read access for page + * @throws AccessDeniedException no read access for page * @throws RemoteException empty id */ - public function pageVersions($id, $first) { + public function pageVersions($id, $first) + { $id = $this->resolvePageId($id); - if(auth_quickaclcheck($id) < AUTH_READ) { - throw new RemoteAccessDeniedException('You are not allowed to read this page', 111); + if (auth_quickaclcheck($id) < AUTH_READ) { + throw new AccessDeniedException('You are not allowed to read this page', 111); } global $conf; $versions = array(); - if(empty($id)) { + if (empty($id)) { throw new RemoteException('Empty page ID', 131); } @@ -819,29 +856,29 @@ class RemoteAPICore { $pagelog = new PageChangeLog($id); $revisions = $pagelog->getRevisions($first_rev, $conf['recent']); - if($first == 0) { + if ($first == 0) { array_unshift($revisions, ''); // include current revision - if ( count($revisions) > $conf['recent'] ){ + if (count($revisions) > $conf['recent']) { array_pop($revisions); // remove extra log entry } } - if(!empty($revisions)) { - foreach($revisions as $rev) { - $file = wikiFN($id,$rev); + if (!empty($revisions)) { + foreach ($revisions as $rev) { + $file = wikiFN($id, $rev); $time = @filemtime($file); // we check if the page actually exists, if this is not the // case this can lead to less pages being returned than // specified via $conf['recent'] - if($time){ + if ($time) { $pagelog->setChunkSize(1024); $info = $pagelog->getRevisionInfo($rev ? $rev : $time); - if(!empty($info)) { + if (!empty($info)) { $data = array(); $data['user'] = $info['user']; - $data['ip'] = $info['ip']; + $data['ip'] = $info['ip']; $data['type'] = $info['type']; - $data['sum'] = $info['sum']; + $data['sum'] = $info['sum']; $data['modified'] = $this->api->toDate($info['date']); $data['version'] = $info['date']; array_push($versions, $data); @@ -857,11 +894,11 @@ class RemoteAPICore { /** * The version of Wiki RPC API supported */ - public function wiki_RPCVersion(){ + public function wikiRpcVersion() + { return 2; } - /** * Locks or unlocks a given batch of pages * @@ -874,35 +911,36 @@ class RemoteAPICore { * @param array[] $set list pages with array('lock' => array, 'unlock' => array) * @return array */ - public function setLocks($set){ - $locked = array(); - $lockfail = array(); - $unlocked = array(); + public function setLocks($set) + { + $locked = array(); + $lockfail = array(); + $unlocked = array(); $unlockfail = array(); - foreach((array) $set['lock'] as $id){ + foreach ((array) $set['lock'] as $id) { $id = $this->resolvePageId($id); - if(auth_quickaclcheck($id) < AUTH_EDIT || checklock($id)){ + if (auth_quickaclcheck($id) < AUTH_EDIT || checklock($id)) { $lockfail[] = $id; - }else{ + } else { lock($id); $locked[] = $id; } } - foreach((array) $set['unlock'] as $id){ + foreach ((array) $set['unlock'] as $id) { $id = $this->resolvePageId($id); - if(auth_quickaclcheck($id) < AUTH_EDIT || !unlock($id)){ + if (auth_quickaclcheck($id) < AUTH_EDIT || !unlock($id)) { $unlockfail[] = $id; - }else{ + } else { $unlocked[] = $id; } } return array( - 'locked' => $locked, - 'lockfail' => $lockfail, - 'unlocked' => $unlocked, + 'locked' => $locked, + 'lockfail' => $lockfail, + 'unlocked' => $unlocked, 'unlockfail' => $unlockfail, ); } @@ -912,8 +950,9 @@ class RemoteAPICore { * * @return int */ - public function getAPIVersion(){ - return DOKU_API_VERSION; + public function getAPIVersion() + { + return self::API_VERSION; } /** @@ -923,23 +962,24 @@ class RemoteAPICore { * @param string $pass * @return int */ - public function login($user,$pass){ + public function login($user, $pass) + { global $conf; /** @var DokuWiki_Auth_Plugin $auth */ global $auth; - if(!$conf['useacl']) return 0; - if(!$auth) return 0; + if (!$conf['useacl']) return 0; + if (!$auth) return 0; @session_start(); // reopen session for login - if($auth->canDo('external')){ - $ok = $auth->trustExternal($user,$pass,false); - }else{ + if ($auth->canDo('external')) { + $ok = $auth->trustExternal($user, $pass, false); + } else { $evdata = array( - 'user' => $user, + 'user' => $user, 'password' => $pass, - 'sticky' => false, - 'silent' => true, + 'sticky' => false, + 'silent' => true, ); $ok = trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper'); } @@ -953,11 +993,12 @@ class RemoteAPICore { * * @return int */ - public function logoff(){ + public function logoff() + { global $conf; global $auth; - if(!$conf['useacl']) return 0; - if(!$auth) return 0; + if (!$conf['useacl']) return 0; + if (!$auth) return 0; auth_logoff(); @@ -970,14 +1011,13 @@ class RemoteAPICore { * @param string $id page id * @return string */ - private function resolvePageId($id) { + private function resolvePageId($id) + { $id = cleanID($id); - if(empty($id)) { + if (empty($id)) { global $conf; $id = cleanID($conf['start']); } return $id; } - } - diff --git a/inc/Remote/RemoteException.php b/inc/Remote/RemoteException.php new file mode 100644 index 000000000..129a6c240 --- /dev/null +++ b/inc/Remote/RemoteException.php @@ -0,0 +1,10 @@ +<?php + +namespace dokuwiki\Remote; + +/** + * Class RemoteException + */ +class RemoteException extends \Exception +{ +} diff --git a/inc/Remote/XmlRpcServer.php b/inc/Remote/XmlRpcServer.php new file mode 100644 index 000000000..1b0097856 --- /dev/null +++ b/inc/Remote/XmlRpcServer.php @@ -0,0 +1,61 @@ +<?php + +namespace dokuwiki\Remote; + +/** + * Contains needed wrapper functions and registers all available XMLRPC functions. + */ +class XmlRpcServer extends \IXR_Server +{ + protected $remote; + + /** + * Constructor. Register methods and run Server + */ + public function __construct() + { + $this->remote = new Api(); + $this->remote->setDateTransformation(array($this, 'toDate')); + $this->remote->setFileTransformation(array($this, 'toFile')); + parent::__construct(); + } + + /** + * @inheritdoc + */ + public function call($methodname, $args) + { + try { + $result = $this->remote->call($methodname, $args); + return $result; + } /** @noinspection PhpRedundantCatchClauseInspection */ catch (AccessDeniedException $e) { + if (!isset($_SERVER['REMOTE_USER'])) { + http_status(401); + return new \IXR_Error(-32603, "server error. not authorized to call method $methodname"); + } else { + http_status(403); + return new \IXR_Error(-32604, "server error. forbidden to call the method $methodname"); + } + } catch (RemoteException $e) { + return new \IXR_Error($e->getCode(), $e->getMessage()); + } + } + + /** + * @param string|int $data iso date(yyyy[-]mm[-]dd[ hh:mm[:ss]]) or timestamp + * @return \IXR_Date + */ + public function toDate($data) + { + return new \IXR_Date($data); + } + + /** + * @param string $data + * @return \IXR_Base64 + */ + public function toFile($data) + { + return new \IXR_Base64($data); + } +} diff --git a/inc/Sitemapper.php b/inc/Sitemapper.php index 037990e96..44c69ec59 100644 --- a/inc/Sitemapper.php +++ b/inc/Sitemapper.php @@ -6,8 +6,6 @@ * @author Michael Hamann <michael@content-space.de> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * A class for building sitemaps and pinging search engines with the sitemap URL. * @@ -176,8 +174,10 @@ class SitemapItem { * * @param string $url The url of the item * @param int $lastmod Timestamp of the last modification - * @param string $changefreq How frequently the item is likely to change. Valid values: always, hourly, daily, weekly, monthly, yearly, never. - * @param $priority float|string The priority of the item relative to other URLs on your site. Valid values range from 0.0 to 1.0. + * @param string $changefreq How frequently the item is likely to change. + * Valid values: always, hourly, daily, weekly, monthly, yearly, never. + * @param $priority float|string The priority of the item relative to other URLs on your site. + * Valid values range from 0.0 to 1.0. */ public function __construct($url, $lastmod, $changefreq = null, $priority = null) { $this->url = $url; @@ -190,8 +190,10 @@ class SitemapItem { * Helper function for creating an item for a wikipage id. * * @param string $id A wikipage id. - * @param string $changefreq How frequently the item is likely to change. Valid values: always, hourly, daily, weekly, monthly, yearly, never. - * @param float|string $priority The priority of the item relative to other URLs on your site. Valid values range from 0.0 to 1.0. + * @param string $changefreq How frequently the item is likely to change. + * Valid values: always, hourly, daily, weekly, monthly, yearly, never. + * @param float|string $priority The priority of the item relative to other URLs on your site. + * Valid values range from 0.0 to 1.0. * @return SitemapItem The sitemap item. */ public static function createFromID($id, $changefreq = null, $priority = null) { diff --git a/inc/StyleUtils.php b/inc/StyleUtils.php index e584942c0..98a38b83d 100644 --- a/inc/StyleUtils.php +++ b/inc/StyleUtils.php @@ -48,7 +48,11 @@ class StyleUtils if (file_exists($incbase . $basename . '.' . $newExtension)) { $stylesheets[$mode][$incbase . $basename . '.' . $newExtension] = $webbase; if ($conf['allowdebug']) { - msg("Stylesheet $file not found, using $basename.$newExtension instead. Please contact developer of \"{$conf['template']}\" template.", 2); + msg( + "Stylesheet $file not found, using $basename.$newExtension instead. + Please contact developer of \"{$conf['template']}\" template.", + 2 + ); } continue; } @@ -58,7 +62,10 @@ class StyleUtils // replacements if(is_array($data['replacements'])){ - $replacements = array_merge($replacements, $this->cssFixreplacementurls($data['replacements'],$webbase)); + $replacements = array_merge( + $replacements, + $this->cssFixreplacementurls($data['replacements'], $webbase) + ); } } @@ -70,13 +77,18 @@ class StyleUtils $data = parse_ini_file($ini, true); // stylesheets - if(isset($data['stylesheets']) && is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ - $stylesheets[$mode][$incbase.$file] = $webbase; + if(isset($data['stylesheets']) && is_array($data['stylesheets'])) { + foreach($data['stylesheets'] as $file => $mode) { + $stylesheets[$mode][$incbase . $file] = $webbase; + } } // replacements if(isset($data['replacements']) && is_array($data['replacements'])){ - $replacements = array_merge($replacements, $this->cssFixreplacementurls($data['replacements'],$webbase)); + $replacements = array_merge( + $replacements, + $this->cssFixreplacementurls($data['replacements'], $webbase) + ); } } @@ -88,7 +100,10 @@ class StyleUtils $data = parse_ini_file($ini, true); // replacements if(is_array($data['replacements'])) { - $replacements = array_merge($replacements, $this->cssFixreplacementurls($data['replacements'], $webbase)); + $replacements = array_merge( + $replacements, + $this->cssFixreplacementurls($data['replacements'], $webbase) + ); } } } @@ -111,7 +126,11 @@ class StyleUtils */ protected function cssFixreplacementurls($replacements, $location) { foreach($replacements as $key => $value) { - $replacements[$key] = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$value); + $replacements[$key] = preg_replace( + '#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#', + '\\1' . $location, + $value + ); } return $replacements; } diff --git a/inc/Ui/Admin.php b/inc/Ui/Admin.php index aa3b8b99e..75eb013ad 100644 --- a/inc/Ui/Admin.php +++ b/inc/Ui/Admin.php @@ -102,9 +102,11 @@ class Admin extends Ui { protected function showSecurityCheck() { global $conf; if(substr($conf['savedir'], 0, 2) !== './') return; + $img = DOKU_URL . $conf['savedir'] . + '/dont-panic-if-you-see-this-in-your-logs-it-means-your-directory-permissions-are-correct.png'; echo '<a style="border:none; float:right;" href="http://www.dokuwiki.org/security#web_access_security"> - <img src="' . DOKU_URL . $conf['savedir'] . '/dont-panic-if-you-see-this-in-your-logs-it-means-your-directory-permissions-are-correct.png" alt="Your data directory seems to be protected properly." + <img src="' . $img . '" alt="Your data directory seems to be protected properly." onerror="this.parentNode.style.display=\'none\'" /></a>'; } diff --git a/inc/Ui/Search.php b/inc/Ui/Search.php index 419b967d7..da1a4e569 100644 --- a/inc/Ui/Search.php +++ b/inc/Ui/Search.php @@ -2,7 +2,7 @@ namespace dokuwiki\Ui; -use \dokuwiki\Form\Form; +use dokuwiki\Form\Form; class Search extends Ui { @@ -587,7 +587,9 @@ class Search extends Ui $resultBody = []; $mtime = filemtime(wikiFN($id)); $lastMod = '<span class="lastmod">' . $lang['lastmod'] . '</span> '; - $lastMod .= '<time datetime="' . date_iso8601($mtime) . '" title="'.dformat($mtime).'">' . dformat($mtime, '%f') . '</time>'; + $lastMod .= '<time datetime="' . date_iso8601($mtime) . '" title="' . dformat($mtime) . '">' . + dformat($mtime, '%f') . + '</time>'; $resultBody['meta'] = $lastMod; if ($cnt !== 0) { $num++; diff --git a/inc/actions.php b/inc/actions.php index 9ba887860..88596bbe8 100644 --- a/inc/actions.php +++ b/inc/actions.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * All action processing starts here */ diff --git a/inc/auth.php b/inc/auth.php index e1d7a645a..336414015 100644 --- a/inc/auth.php +++ b/inc/auth.php @@ -9,8 +9,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - // some ACL level defines define('AUTH_NONE', 0); define('AUTH_READ', 1); diff --git a/inc/cache.php b/inc/cache.php index 8589d91ba..470eff94a 100644 --- a/inc/cache.php +++ b/inc/cache.php @@ -6,8 +6,6 @@ * @author Chris Smith <chris@jalakai.co.uk> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * Generic handling of caching */ @@ -211,12 +209,14 @@ class cache_parser extends cache { // parser cache file dependencies ... $files = array($this->file, // ... source - DOKU_INC.'inc/parser/parser.php', // ... parser + DOKU_INC.'inc/parser/Parser.php', // ... parser DOKU_INC.'inc/parser/handler.php', // ... handler ); $files = array_merge($files, getConfigFiles('main')); // ... wiki settings - $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files; + $this->depends['files'] = !empty($this->depends['files']) ? + array_merge($files, $this->depends['files']) : + $files; parent::_addDependencies(); } @@ -241,7 +241,8 @@ class cache_renderer extends cache_parser { return true; } - if ($this->_time < @filemtime(metaFN($this->page,'.meta'))) return false; // meta cache older than file it depends on? + // meta cache older than file it depends on? + if ($this->_time < @filemtime(metaFN($this->page,'.meta'))) return false; // check current link existence is consistent with cache version // first check the purgefile @@ -287,14 +288,18 @@ class cache_renderer extends cache_parser { // page implies metadata and possibly some other dependencies if (isset($this->page)) { - $valid = p_get_metadata($this->page, 'date valid'); // for xhtml this will render the metadata if needed + // for xhtml this will render the metadata if needed + $valid = p_get_metadata($this->page, 'date valid'); if (!empty($valid['age'])) { $this->depends['age'] = isset($this->depends['age']) ? min($this->depends['age'],$valid['age']) : $valid['age']; } } - $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files; + $this->depends['files'] = !empty($this->depends['files']) ? + array_merge($files, $this->depends['files']) : + $files; + parent::_addDependencies(); } } diff --git a/inc/changelog.php b/inc/changelog.php index d77b0180a..1981a7d8f 100644 --- a/inc/changelog.php +++ b/inc/changelog.php @@ -104,13 +104,15 @@ function addLogEntry($date, $id, $type=DOKU_CHANGE_TYPE_EDIT, $summary='', $extr if (!$wasRemoved) { $oldmeta = p_read_metadata($id); $meta = array(); - if ($wasCreated && empty($oldmeta['persistent']['date']['created'])){ // newly created + if ($wasCreated && empty($oldmeta['persistent']['date']['created'])){ + // newly created $meta['date']['created'] = $created; if ($user){ $meta['creator'] = $INFO['userinfo']['name']; $meta['user'] = $user; } - } elseif (($wasCreated || $wasReverted) && !empty($oldmeta['persistent']['date']['created'])) { // re-created / restored + } elseif (($wasCreated || $wasReverted) && !empty($oldmeta['persistent']['date']['created'])) { + // re-created / restored $meta['date']['created'] = $oldmeta['persistent']['date']['created']; $meta['date']['modified'] = $created; // use the files ctime here $meta['creator'] = $oldmeta['persistent']['creator']; @@ -147,7 +149,15 @@ function addLogEntry($date, $id, $type=DOKU_CHANGE_TYPE_EDIT, $summary='', $extr * - (none, so far) * @param null|int $sizechange Change of filesize */ -function addMediaLogEntry($date, $id, $type=DOKU_CHANGE_TYPE_EDIT, $summary='', $extra='', $flags=null, $sizechange = null){ +function addMediaLogEntry( + $date, + $id, + $type=DOKU_CHANGE_TYPE_EDIT, + $summary='', + $extra='', + $flags=null, + $sizechange = null) +{ global $conf; /** @var Input $INPUT */ global $INPUT; @@ -238,7 +248,12 @@ function getRecents($first,$num,$ns='',$flags=0){ } } if (($flags & RECENTS_MEDIA_PAGES_MIXED) && empty($media_rec) && $media_lines_position >= 0) { - $media_rec = _handleRecent(@$media_lines[$media_lines_position], $ns, $flags | RECENTS_MEDIA_CHANGES, $seen); + $media_rec = _handleRecent( + @$media_lines[$media_lines_position], + $ns, + $flags | RECENTS_MEDIA_CHANGES, + $seen + ); if (!$media_rec) { $media_lines_position --; continue; @@ -879,7 +894,7 @@ abstract class ChangeLog { * @param number $date_at timestamp * @return string revision ('' for current) */ - function getLastRevisionAt($date_at){ + public function getLastRevisionAt($date_at){ //requested date_at(timestamp) younger or equal then modified_time($this->id) => load current if(file_exists($this->getFilename()) && $date_at >= @filemtime($this->getFilename())) { return ''; diff --git a/inc/common.php b/inc/common.php index 1fd0154c2..6a710f194 100644 --- a/inc/common.php +++ b/inc/common.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * These constants are used with the recents function */ @@ -490,7 +488,9 @@ function wl($id = '', $urlParameters = '', $absolute = false, $separator = '& global $conf; if(is_array($urlParameters)) { if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']); - if(isset($urlParameters['at']) && $conf['date_at_format']) $urlParameters['at'] = date($conf['date_at_format'],$urlParameters['at']); + if(isset($urlParameters['at']) && $conf['date_at_format']) { + $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']); + } $urlParameters = buildURLparams($urlParameters, $separator); } else { $urlParameters = str_replace(',', $separator, $urlParameters); @@ -714,7 +714,13 @@ function checkwordblock($text = '') { if(!$text) $text = "$PRE $TEXT $SUF $SUM"; // we prepare the text a tiny bit to prevent spammers circumventing URL checks - $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text); + // phpcs:disable Generic.Files.LineLength.TooLong + $text = preg_replace( + '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', + '\1http://\2 \2\3', + $text + ); + // phpcs:enable $wordblocks = getWordblocks(); // how many lines to read at once (to work around some PCRE limits) @@ -840,6 +846,7 @@ function clientIP($single = false) { * * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code * + * @deprecated 2018-04-27 you probably want media queries instead anyway * @return bool if true, client is mobile browser; otherwise false */ function clientismobile() { @@ -852,7 +859,18 @@ function clientismobile() { if(!$INPUT->server->has('HTTP_USER_AGENT')) return false; - $uamatches = 'midp|j2me|avantg|docomo|novarra|palmos|palmsource|240x320|opwv|chtml|pda|windows ce|mmp\/|blackberry|mib\/|symbian|wireless|nokia|hand|mobi|phone|cdm|up\.b|audio|SIE\-|SEC\-|samsung|HTC|mot\-|mitsu|sagem|sony|alcatel|lg|erics|vx|NEC|philips|mmm|xx|panasonic|sharp|wap|sch|rover|pocket|benq|java|pt|pg|vox|amoi|bird|compal|kg|voda|sany|kdd|dbt|sendo|sgh|gradi|jb|\d\d\di|moto'; + $uamatches = join( + '|', + [ + 'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv', + 'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia', + 'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-', + 'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx', + 'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox', + 'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb', + '\d\d\di', 'moto' + ] + ); if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true; @@ -1268,7 +1286,15 @@ function detectExternalEdit($id) { $filesize_new = filesize($fileLastMod); $sizechange = $filesize_new - $filesize_old; - addLogEntry($lastMod, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true), $sizechange); + addLogEntry( + $lastMod, + $id, + DOKU_CHANGE_TYPE_EDIT, + $lang['external_edit'], + '', + array('ExternalEdit' => true), + $sizechange + ); // remove soon to be stale instructions $cache = new cache_instructions($id, $fileLastMod); $cache->removeCache(); @@ -1361,7 +1387,8 @@ function saveWikiText($id, $text, $summary, $minor = false) { // remove empty file @unlink($svdta['file']); $filesize_new = 0; - // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata... + // don't remove old meta info as it should be saved, plugins can use + // IO_WIKIPAGE_WRITE for removing their metadata... // purge non-persistant meta data p_purge_metadata($id); // remove empty namespaces @@ -1378,7 +1405,15 @@ function saveWikiText($id, $text, $summary, $minor = false) { $event->advise_after(); - addLogEntry($svdta['newRevision'], $svdta['id'], $svdta['changeType'], $svdta['summary'], $svdta['changeInfo'], null, $svdta['sizechange']); + addLogEntry( + $svdta['newRevision'], + $svdta['id'], + $svdta['changeType'], + $svdta['summary'], + $svdta['changeInfo'], + null, + $svdta['sizechange'] + ); // send notify mails notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor); @@ -1764,7 +1799,8 @@ function userlink($username = null, $textonly = false) { if($textonly){ $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')'; }else { - $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)'; + $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '. + '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)'; } } @@ -2037,7 +2073,8 @@ function set_doku_pref($pref, $val) { } $cookieVal = implode('#', $parts); } else if (!$orig && $val !== false) { - $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val); + $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : ''). + rawurlencode($pref).'#'.rawurlencode($val); } if (!empty($cookieVal)) { diff --git a/inc/confutils.php b/inc/confutils.php index 59147010f..60c78c928 100644 --- a/inc/confutils.php +++ b/inc/confutils.php @@ -155,9 +155,18 @@ function getCdnUrls() { $src[] = sprintf('https://code.jquery.com/jquery-migrate-%s.min.js', $versions['JQM_VERSION']); $src[] = sprintf('https://code.jquery.com/ui/%s/jquery-ui.min.js', $versions['JQUI_VERSION']); } elseif($conf['jquerycdn'] == 'cdnjs') { - $src[] = sprintf('https://cdnjs.cloudflare.com/ajax/libs/jquery/%s/jquery.min.js', $versions['JQ_VERSION']); - $src[] = sprintf('https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/%s/jquery-migrate.min.js', $versions['JQM_VERSION']); - $src[] = sprintf('https://cdnjs.cloudflare.com/ajax/libs/jqueryui/%s/jquery-ui.min.js', $versions['JQUI_VERSION']); + $src[] = sprintf( + 'https://cdnjs.cloudflare.com/ajax/libs/jquery/%s/jquery.min.js', + $versions['JQ_VERSION'] + ); + $src[] = sprintf( + 'https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/%s/jquery-migrate.min.js', + $versions['JQM_VERSION'] + ); + $src[] = sprintf( + 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/%s/jquery-ui.min.js', + $versions['JQUI_VERSION'] + ); } } $event->advise_after(); diff --git a/inc/deprecated.php b/inc/deprecated.php new file mode 100644 index 000000000..2f7274cda --- /dev/null +++ b/inc/deprecated.php @@ -0,0 +1,44 @@ +<?php + +/** + * These classes and functions are deprecated and will be removed in future releases + */ + +/** + * @inheritdoc + * @deprecated 2018-05-07 + */ +class RemoteAccessDeniedException extends \dokuwiki\Remote\AccessDeniedException { + /** @inheritdoc */ + public function __construct($message = "", $code = 0, Throwable $previous = null) { + dbg_deprecated('dokuwiki\Remote\AccessDeniedException'); + parent::__construct($message, $code, $previous); + } + +} + +/** + * @inheritdoc + * @deprecated 2018-05-07 + */ +class RemoteException extends \dokuwiki\Remote\RemoteException { + /** @inheritdoc */ + public function __construct($message = "", $code = 0, Throwable $previous = null) { + dbg_deprecated('dokuwiki\\Remote\\RemoteException'); + parent::__construct($message, $code, $previous); + } + +} + + +/** + * Escapes regex characters other than (, ) and / + * + * @param string $str + * @return string + * @deprecated 2018-05-04 + */ +function Doku_Lexer_Escape($str) { + dbg_deprecated('dokuwiki\\Parsing\\Lexer\\Lexer::escape'); + return \dokuwiki\Parsing\Lexer\Lexer::escape($str); +} diff --git a/inc/events.php b/inc/events.php index 034414f88..83e6794eb 100644 --- a/inc/events.php +++ b/inc/events.php @@ -6,8 +6,6 @@ * @author Christopher Smith <chris@jalakai.co.uk> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * The event */ @@ -31,7 +29,7 @@ class Doku_Event { * @param string $name * @param mixed $data */ - function __construct($name, &$data) { + public function __construct($name, &$data) { $this->name = $name; $this->data =& $data; @@ -41,7 +39,7 @@ class Doku_Event { /** * @return string */ - function __toString() { + public function __toString() { return $this->name; } @@ -63,7 +61,7 @@ class Doku_Event { * @param bool $enablePreventDefault * @return bool results of processing the event, usually $this->_default */ - function advise_before($enablePreventDefault=true) { + public function advise_before($enablePreventDefault=true) { global $EVENT_HANDLER; $this->canPreventDefault = $enablePreventDefault; @@ -72,7 +70,7 @@ class Doku_Event { return (!$enablePreventDefault || $this->_default); } - function advise_after() { + public function advise_after() { global $EVENT_HANDLER; $this->_continue = true; @@ -94,12 +92,16 @@ class Doku_Event { * or the results of the default action (as modified by <event>_after handlers) * or NULL no action took place and no handler modified the value */ - function trigger($action=null, $enablePrevent=true) { + public function trigger($action=null, $enablePrevent=true) { if (!is_callable($action)) { $enablePrevent = false; if (!is_null($action)) { - trigger_error('The default action of '.$this.' is not null but also not callable. Maybe the method is not public?', E_USER_WARNING); + trigger_error( + 'The default action of ' . $this . + ' is not null but also not callable. Maybe the method is not public?', + E_USER_WARNING + ); } } @@ -171,7 +173,7 @@ class Doku_Event_Handler { * constructor, loads all action plugins and calls their register() method giving them * an opportunity to register any hooks they require */ - function __construct() { + public function __construct() { // load action plugins /** @var DokuWiki_Action_Plugin $plugin */ @@ -198,7 +200,7 @@ class Doku_Event_Handler { * @param mixed $param data passed to the event handler * @param int $seq sequence number for ordering hook execution (ascending) */ - function register_hook($event, $advise, $obj, $method, $param=null, $seq=0) { + public function register_hook($event, $advise, $obj, $method, $param=null, $seq=0) { $seq = (int)$seq; $doSort = !isset($this->_hooks[$event.'_'.$advise][$seq]); $this->_hooks[$event.'_'.$advise][$seq][] = array($obj, $method, $param); @@ -214,7 +216,7 @@ class Doku_Event_Handler { * @param Doku_Event $event * @param string $advise BEFORE or AFTER */ - function process_event($event,$advise='') { + public function process_event($event,$advise='') { $evt_name = $event->name . ($advise ? '_'.$advise : '_BEFORE'); diff --git a/inc/farm.php b/inc/farm.php index 0cd9d4f9c..03aa0eb30 100644 --- a/inc/farm.php +++ b/inc/farm.php @@ -22,7 +22,7 @@ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) */ -// DOKU_FARMDIR needs to be set in preload.php, here the fallback is the same as DOKU_INC would be (if it was set already) +// DOKU_FARMDIR needs to be set in preload.php, the fallback is the same as DOKU_INC would be (if it was set already) if(!defined('DOKU_FARMDIR')) define('DOKU_FARMDIR', fullpath(dirname(__FILE__).'/../').'/'); if(!defined('DOKU_CONF')) define('DOKU_CONF', farm_confpath(DOKU_FARMDIR)); if(!defined('DOKU_FARM')) define('DOKU_FARM', false); diff --git a/inc/fetch.functions.php b/inc/fetch.functions.php index b8e75eaec..04866d384 100644 --- a/inc/fetch.functions.php +++ b/inc/fetch.functions.php @@ -104,7 +104,13 @@ function sendFile($file, $mime, $dl, $cache, $public = false, $orig = null) { * @return string in the format " name*=charset'lang'value" for values WITH special characters */ function rfc2231_encode($name, $value, $charset='utf-8', $lang='en') { - $internal = preg_replace_callback('/[\x00-\x20*\'%()<>@,;:\\\\"\/[\]?=\x80-\xFF]/', function($match) { return rawurlencode($match[0]); }, $value); + $internal = preg_replace_callback( + '/[\x00-\x20*\'%()<>@,;:\\\\"\/[\]?=\x80-\xFF]/', + function ($match) { + return rawurlencode($match[0]); + }, + $value + ); if ( $value != $internal ) { return ' '.$name.'*='.$charset."'".$lang."'".$internal; } else { diff --git a/inc/form.php b/inc/form.php index 7afb0ba30..ddf0732d0 100644 --- a/inc/form.php +++ b/inc/form.php @@ -6,8 +6,6 @@ * @author Tom N Harris <tnharris@whoopdedo.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * Class for creating simple HTML forms. * @@ -55,7 +53,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function __construct($params, $action=false, $method=false, $enctype=false) { + public function __construct($params, $action=false, $method=false, $enctype=false) { if(!is_array($params)) { $this->params = array('id' => $params); if ($action !== false) $this->params['action'] = $action; @@ -88,7 +86,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function startFieldset($legend) { + public function startFieldset($legend) { if ($this->_infieldset) { $this->addElement(array('_elem'=>'closefieldset')); } @@ -101,7 +99,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function endFieldset() { + public function endFieldset() { if ($this->_infieldset) { $this->addElement(array('_elem'=>'closefieldset')); } @@ -120,7 +118,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function addHidden($name, $value) { + public function addHidden($name, $value) { if (is_null($value)) unset($this->_hidden[$name]); else @@ -138,7 +136,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function addElement($elem) { + public function addElement($elem) { $this->_content[] = $elem; } @@ -152,7 +150,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function insertElement($pos, $elem) { + public function insertElement($pos, $elem) { array_splice($this->_content, $pos, 0, array($elem)); } @@ -166,7 +164,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function replaceElement($pos, $elem) { + public function replaceElement($pos, $elem) { $rep = array(); if (!is_null($elem)) $rep[] = $elem; array_splice($this->_content, $pos, 1, $rep); @@ -182,7 +180,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function findElementByType($type) { + public function findElementByType($type) { foreach ($this->_content as $pos=>$elem) { if (is_array($elem) && $elem['_elem'] == $type) return $pos; @@ -200,7 +198,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function findElementById($id) { + public function findElementById($id) { foreach ($this->_content as $pos=>$elem) { if (is_array($elem) && isset($elem['id']) && $elem['id'] == $id) return $pos; @@ -219,7 +217,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function findElementByAttribute($name, $value) { + public function findElementByAttribute($name, $value) { foreach ($this->_content as $pos=>$elem) { if (is_array($elem) && isset($elem[$name]) && $elem[$name] == $value) return $pos; @@ -239,7 +237,7 @@ class Doku_Form { * * @author Tom N Harris <tnharris@whoopdedo.org> */ - function &getElementAt($pos) { + public function &getElementAt($pos) { if ($pos < 0) $pos = count($this->_content) + $pos; if ($pos < 0) $pos = 0; if ($pos >= count($this->_content)) $pos = count($this->_content) - 1; @@ -256,7 +254,7 @@ class Doku_Form { * * @return string html of the form */ - function getForm() { + public function getForm() { global $lang; $form = ''; $this->params['accept-charset'] = $lang['encoding']; @@ -286,7 +284,7 @@ class Doku_Form { * * wraps around getForm() */ - function printForm(){ + public function printForm(){ echo $this->getForm(); } @@ -302,7 +300,7 @@ class Doku_Form { * @author Adrian Lang <lang@cosmocode.de> */ - function addRadioSet($name, $entries) { + public function addRadioSet($name, $entries) { global $INPUT; $value = (array_key_exists($INPUT->post->str($name), $entries)) ? $INPUT->str($name) : key($entries); diff --git a/inc/fulltext.php b/inc/fulltext.php index dba11d0e4..54e7b8cd9 100644 --- a/inc/fulltext.php +++ b/inc/fulltext.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * create snippets for the first few results only */ @@ -23,8 +21,8 @@ if(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15); * @param string $query * @param array $highlight * @param string $sort - * @param int|string $after only show results with an modified time after this date, accepts timestap or strtotime arguments - * @param int|string $before only show results with an modified time before this date, accepts timestap or strtotime arguments + * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments + * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments * * @return array */ @@ -232,8 +230,8 @@ function ft_mediause($id, $ignore_perms = false){ * @param string $id page id * @param bool $in_ns match against namespace as well? * @param bool $in_title search in title? - * @param int|string $after only show results with an modified time after this date, accepts timestap or strtotime arguments - * @param int|string $before only show results with an modified time before this date, accepts timestap or strtotime arguments + * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments + * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments * * @return string[] */ @@ -315,8 +313,8 @@ function _ft_pageLookup(&$data){ /** * @param array $results search results in the form pageid => value - * @param int|string $after only returns results with an modified time after this date, accepts timestap or strtotime arguments - * @param int|string $before only returns results with an modified time after this date, accepts timestap or strtotime arguments + * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments + * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments * * @return array */ @@ -415,7 +413,18 @@ function ft_snippet($id,$highlight){ $len = utf8_strlen($text); // build a regexp from the phrases to highlight - $re1 = '('.join('|',array_map('ft_snippet_re_preprocess', array_map('preg_quote_cb',array_filter((array) $highlight)))).')'; + $re1 = '(' . + join( + '|', + array_map( + 'ft_snippet_re_preprocess', + array_map( + 'preg_quote_cb', + array_filter((array) $highlight) + ) + ) + ) . + ')'; $re2 = "$re1.{0,75}(?!\\1)$re1"; $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; @@ -478,7 +487,11 @@ function ft_snippet($id,$highlight){ $m = "\1"; $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets); - $snippet = preg_replace('/'.$m.'([^'.$m.']*?)'.$m.'/iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets))); + $snippet = preg_replace( + '/' . $m . '([^' . $m . ']*?)' . $m . '/iu', + '<strong class="search_hit">$1</strong>', + hsc(join('... ', $snippets)) + ); $evdata['snippet'] = $snippet; } diff --git a/inc/html.php b/inc/html.php index 7bd38ebda..32a9debf8 100644 --- a/inc/html.php +++ b/inc/html.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); -if(!defined('NL')) define('NL',"\n"); if (!defined('SEC_EDIT_PATTERN')) { define('SEC_EDIT_PATTERN', '#<!-- EDIT({.*?}) -->#'); } @@ -51,7 +49,13 @@ function html_login($svg = false){ $form->startFieldset($lang['btn_login']); $form->addHidden('id', $ID); $form->addHidden('do', 'login'); - $form->addElement(form_makeTextField('u', ((!$INPUT->bool('http_credentials')) ? $INPUT->str('u') : ''), $lang['user'], 'focus__this', 'block')); + $form->addElement(form_makeTextField( + 'u', + ((!$INPUT->bool('http_credentials')) ? $INPUT->str('u') : ''), + $lang['user'], + 'focus__this', + 'block') + ); $form->addElement(form_makePasswordField('p', $lang['pass'], '', 'block')); if($conf['rememberme']) { $form->addElement(form_makeCheckboxField('r', '1', $lang['remember'], 'remember__me', 'simple')); @@ -170,7 +174,10 @@ function html_secedit_get_button($data) { function html_topbtn(){ global $lang; - $ret = '<a class="nolink" href="#dokuwiki__top"><button class="button" onclick="window.scrollTo(0, 0)" title="'.$lang['btn_top'].'">'.$lang['btn_top'].'</button></a>'; + $ret = '<a class="nolink" href="#dokuwiki__top">' . + '<button class="button" onclick="window.scrollTo(0, 0)" title="' . $lang['btn_top'] . '">' . + $lang['btn_top'] . + '</button></a>'; return $ret; } @@ -690,7 +697,9 @@ function html_recent($first = 0, $show_changes = 'both') { print p_locale_xhtml('recent'); if(getNS($ID) != '') { - print '<div class="level1"><p>' . sprintf($lang['recent_global'], getNS($ID), wl('', 'do=recent')) . '</p></div>'; + print '<div class="level1"><p>' . + sprintf($lang['recent_global'], getNS($ID), wl('', 'do=recent')) . + '</p></div>'; } $form = new Doku_Form(array('id' => 'dw__recent', 'method' => 'GET', 'class' => 'changes')); @@ -773,7 +782,14 @@ function html_recent($first = 0, $show_changes = 'both') { } if(!empty($recent['media'])) { - $href = media_managerURL(array('tab_details' => 'history', 'image' => $recent['id'], 'ns' => getNS($recent['id'])), '&'); + $href = media_managerURL( + array( + 'tab_details' => 'history', + 'image' => $recent['id'], + 'ns' => getNS($recent['id']) + ), + '&' + ); } else { $href = wl($recent['id'], "do=revisions", false, '&'); } @@ -790,7 +806,14 @@ function html_recent($first = 0, $show_changes = 'both') { $form->addElement(form_makeCloseTag('a')); if(!empty($recent['media'])) { - $href = media_managerURL(array('tab_details' => 'view', 'image' => $recent['id'], 'ns' => getNS($recent['id'])), '&'); + $href = media_managerURL( + array( + 'tab_details' => 'view', + 'image' => $recent['id'], + 'ns' => getNS($recent['id']) + ), + '&' + ); $class = file_exists(mediaFN($recent['id'])) ? 'wikilink1' : 'wikilink2'; $form->addElement(form_makeOpenTag('a', array( 'class' => $class, @@ -897,14 +920,15 @@ function html_list_index($item){ global $ID, $conf; // prevent searchbots needlessly following links - $nofollow = ($ID != $conf['start'] || $conf['sitemap']) ? ' rel="nofollow"' : ''; + $nofollow = ($ID != $conf['start'] || $conf['sitemap']) ? 'rel="nofollow"' : ''; $ret = ''; $base = ':'.$item['id']; $base = substr($base,strrpos($base,':')+1); if($item['type']=='d'){ // FS#2766, no need for search bots to follow namespace links in the index - $ret .= '<a href="'.wl($ID,'idx='.rawurlencode($item['id'])).'" title="' . $item['id'] . '" class="idx_dir"' . $nofollow . '><strong>'; + $link = wl($ID, 'idx=' . rawurlencode($item['id'])); + $ret .= '<a href="' . $link . '" title="' . $item['id'] . '" class="idx_dir" ' . $nofollow . '><strong>'; $ret .= $base; $ret .= '</strong></a>'; }else{ @@ -1562,12 +1586,12 @@ function html_softbreak_callback($match){ // make certain characters into breaking characters by inserting a // breaking character (zero length space, U+200B / #8203) in front them. $regex = <<< REGEX -(?(?= # start a conditional expression with a positive look ahead ... -&\#?\\w{1,6};) # ... for html entities - we don't want to split them (ok to catch some invalid combinations) -&\#?\\w{1,6}; # yes pattern - a quicker match for the html entity, since we know we have one +(?(?= # start a conditional expression with a positive look ahead ... +&\#?\\w{1,6};) # ... for html entities - we don't want to split them (ok to catch some invalid combinations) +&\#?\\w{1,6}; # yes pattern - a quicker match for the html entity, since we know we have one | -[?/,&\#;:] # no pattern - any other group of 'special' characters to insert a breaking character after -)+ # end conditional expression +[?/,&\#;:] # no pattern - any other group of 'special' characters to insert a breaking character after +)+ # end conditional expression REGEX; return preg_replace('<'.$regex.'>xu','\0​',$match[0]); @@ -1643,13 +1667,41 @@ function html_register(){ $form->startFieldset($lang['btn_register']); $form->addHidden('do', 'register'); $form->addHidden('save', '1'); - $form->addElement(form_makeTextField('login', $INPUT->post->str('login'), $lang['user'], '', 'block', $base_attrs)); + $form->addElement( + form_makeTextField( + 'login', + $INPUT->post->str('login'), + $lang['user'], + '', + 'block', + $base_attrs + ) + ); if (!$conf['autopasswd']) { $form->addElement(form_makePasswordField('pass', $lang['pass'], '', 'block', $base_attrs)); $form->addElement(form_makePasswordField('passchk', $lang['passchk'], '', 'block', $base_attrs)); } - $form->addElement(form_makeTextField('fullname', $INPUT->post->str('fullname'), $lang['fullname'], '', 'block', $base_attrs)); - $form->addElement(form_makeField('email','email', $INPUT->post->str('email'), $lang['email'], '', 'block', $email_attrs)); + $form->addElement( + form_makeTextField( + 'fullname', + $INPUT->post->str('fullname'), + $lang['fullname'], + '', + 'block', + $base_attrs + ) + ); + $form->addElement( + form_makeField( + 'email', + 'email', + $INPUT->post->str('email'), + $lang['email'], + '', + 'block', + $email_attrs + ) + ); $form->addElement(form_makeButton('submit', '', $lang['btn_register'])); $form->endFieldset(); html_form('register', $form); @@ -1680,7 +1732,16 @@ function html_updateprofile(){ $form->startFieldset($lang['profile']); $form->addHidden('do', 'profile'); $form->addHidden('save', '1'); - $form->addElement(form_makeTextField('login', $_SERVER['REMOTE_USER'], $lang['user'], '', 'block', array('size'=>'50', 'disabled'=>'disabled'))); + $form->addElement( + form_makeTextField( + 'login', + $_SERVER['REMOTE_USER'], + $lang['user'], + '', + 'block', + array('size' => '50', 'disabled' => 'disabled') + ) + ); $attr = array('size'=>'50'); if (!$auth->canDo('modName')) $attr['disabled'] = 'disabled'; $form->addElement(form_makeTextField('fullname', $fullname, $lang['fullname'], '', 'block', $attr)); @@ -1694,7 +1755,15 @@ function html_updateprofile(){ } if ($conf['profileconfirm']) { $form->addElement(form_makeTag('br')); - $form->addElement(form_makePasswordField('oldpass', $lang['oldpass'], '', 'block', array('size'=>'50', 'required' => 'required'))); + $form->addElement( + form_makePasswordField( + 'oldpass', + $lang['oldpass'], + '', + 'block', + array('size' => '50', 'required' => 'required') + ) + ); } $form->addElement(form_makeButton('submit', '', $lang['btn_save'])); $form->addElement(form_makeButton('reset', '', $lang['btn_reset'])); @@ -1707,10 +1776,27 @@ function html_updateprofile(){ $form_profiledelete->startFieldset($lang['profdeleteuser']); $form_profiledelete->addHidden('do', 'profile_delete'); $form_profiledelete->addHidden('delete', '1'); - $form_profiledelete->addElement(form_makeCheckboxField('confirm_delete', '1', $lang['profconfdelete'],'dw__confirmdelete','', array('required' => 'required'))); + $form_profiledelete->addElement( + form_makeCheckboxField( + 'confirm_delete', + '1', + $lang['profconfdelete'], + 'dw__confirmdelete', + '', + array('required' => 'required') + ) + ); if ($conf['profileconfirm']) { $form_profiledelete->addElement(form_makeTag('br')); - $form_profiledelete->addElement(form_makePasswordField('oldpass', $lang['oldpass'], '', 'block', array('size'=>'50', 'required' => 'required'))); + $form_profiledelete->addElement( + form_makePasswordField( + 'oldpass', + $lang['oldpass'], + '', + 'block', + array('size' => '50', 'required' => 'required') + ) + ); } $form_profiledelete->addElement(form_makeButton('submit', '', $lang['btn_deleteuser'])); $form_profiledelete->endFieldset(); @@ -1803,12 +1889,35 @@ function html_edit(){ $form->addElement(form_makeCloseTag('div')); if ($wr) { $form->addElement(form_makeOpenTag('div', array('class'=>'editButtons'))); - $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id'=>'edbtn__save', 'accesskey'=>'s', 'tabindex'=>'4'))); - $form->addElement(form_makeButton('submit', 'preview', $lang['btn_preview'], array('id'=>'edbtn__preview', 'accesskey'=>'p', 'tabindex'=>'5'))); + $form->addElement( + form_makeButton( + 'submit', + 'save', + $lang['btn_save'], + array('id' => 'edbtn__save', 'accesskey' => 's', 'tabindex' => '4') + ) + ); + $form->addElement( + form_makeButton( + 'submit', + 'preview', + $lang['btn_preview'], + array('id' => 'edbtn__preview', 'accesskey' => 'p', 'tabindex' => '5') + ) + ); $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('tabindex'=>'6'))); $form->addElement(form_makeCloseTag('div')); $form->addElement(form_makeOpenTag('div', array('class'=>'summary'))); - $form->addElement(form_makeTextField('summary', $SUM, $lang['summary'], 'edit__summary', 'nowrap', array('size'=>'50', 'tabindex'=>'2'))); + $form->addElement( + form_makeTextField( + 'summary', + $SUM, + $lang['summary'], + 'edit__summary', + 'nowrap', + array('size' => '50', 'tabindex' => '2') + ) + ); $elem = html_minoredit(); if ($elem) $form->addElement($elem); $form->addElement(form_makeCloseTag('div')); @@ -1833,9 +1942,14 @@ function html_edit(){ <div class="editBox" role="application"> <div class="toolbar group"> - <div id="draft__status" class="draft__status"><?php if(!empty($INFO['draft'])) echo $lang['draftdate'].' '.dformat();?></div> - <div id="tool__bar" class="tool__bar"><?php if ($wr && $data['media_manager']){?><a href="<?php echo DOKU_BASE?>lib/exe/mediamanager.php?ns=<?php echo $INFO['namespace']?>" - target="_blank"><?php echo $lang['mediaselect'] ?></a><?php }?></div> + <div id="draft__status" class="draft__status"><?php + if(!empty($INFO['draft'])) echo $lang['draftdate'].' '.dformat(); + ?></div> + <div id="tool__bar" class="tool__bar"><?php + if ($wr && $data['media_manager']){ + ?><a href="<?php echo DOKU_BASE?>lib/exe/mediamanager.php?ns=<?php echo $INFO['namespace']?>" + target="_blank"><?php echo $lang['mediaselect'] ?></a><?php + }?></div> </div> <?php diff --git a/inc/indexer.php b/inc/indexer.php index fac7a3f68..8ec3911d7 100644 --- a/inc/indexer.php +++ b/inc/indexer.php @@ -7,8 +7,6 @@ * @author Tom N Harris <tnharris@whoopdedo.org> */ -if(!defined('DOKU_INC')) die('meh.'); - // Version tag used to force rebuild on upgrade define('INDEXER_VERSION', 8); @@ -403,7 +401,7 @@ class Doku_Indexer { * * @param string $key The metadata key of which a value shall be changed * @param string $oldvalue The old value that shall be renamed - * @param string $newvalue The new value to which the old value shall be renamed, can exist (then values will be merged) + * @param string $newvalue The new value to which the old value shall be renamed, if exists values will be merged * @return bool|string If renaming the value has been successful, false or error message on error. */ public function renameMetaValue($key, $oldvalue, $newvalue) { @@ -1521,7 +1519,10 @@ function idx_listIndexLengths() { clearstatcache(); if (file_exists($conf['indexdir'].'/lengths.idx') && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) { - if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) { + if ( + ($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) + !== false + ) { $idx = array(); foreach ($lengths as $length) { $idx[] = (int)$length; diff --git a/inc/infoutils.php b/inc/infoutils.php index 57f89e508..e16b0d673 100644 --- a/inc/infoutils.php +++ b/inc/infoutils.php @@ -5,8 +5,6 @@ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - if(!defined('DOKU_MESSAGEURL')){ if(in_array('ssl', stream_get_transports())) { define('DOKU_MESSAGEURL','https://update.dokuwiki.org/check/'); @@ -138,9 +136,11 @@ function check(){ if($mem < 16777216){ msg('PHP is limited to less than 16MB RAM ('.$mem.' bytes). Increase memory_limit in php.ini',-1); }elseif($mem < 20971520){ - msg('PHP is limited to less than 20MB RAM ('.$mem.' bytes), you might encounter problems with bigger pages. Increase memory_limit in php.ini',-1); + msg('PHP is limited to less than 20MB RAM ('.$mem.' bytes), + you might encounter problems with bigger pages. Increase memory_limit in php.ini',-1); }elseif($mem < 33554432){ - msg('PHP is limited to less than 32MB RAM ('.$mem.' bytes), but that should be enough in most cases. If not, increase memory_limit in php.ini',0); + msg('PHP is limited to less than 32MB RAM ('.$mem.' bytes), + but that should be enough in most cases. If not, increase memory_limit in php.ini',0); }else{ msg('More than 32MB RAM ('.$mem.' bytes) available.',1); } @@ -208,7 +208,8 @@ function check(){ if(!$loc){ msg('No valid locale is set for your PHP setup. You should fix this',-1); }elseif(stripos($loc,'utf') === false){ - msg('Your locale <code>'.hsc($loc).'</code> seems not to be a UTF-8 locale, you should fix this if you encounter problems.',0); + msg('Your locale <code>'.hsc($loc).'</code> seems not to be a UTF-8 locale, + you should fix this if you encounter problems.',0); }else{ msg('Valid locale '.hsc($loc).' found.', 1); } @@ -288,7 +289,8 @@ function check(){ if(abs($diff) < 4) { msg("Server time seems to be okay. Diff: {$diff}s", 1); } else { - msg("Your server's clock seems to be out of sync! Consider configuring a sync with a NTP server. Diff: {$diff}s"); + msg("Your server's clock seems to be out of sync! + Consider configuring a sync with a NTP server. Diff: {$diff}s"); } } @@ -378,7 +380,8 @@ function info_msg_allowed($msg){ return $INFO['isadmin']; default: - trigger_error('invalid msg allow restriction. msg="'.$msg['msg'].'" allow='.$msg['allow'].'"', E_USER_WARNING); + trigger_error('invalid msg allow restriction. msg="'.$msg['msg'].'" allow='.$msg['allow'].'"', + E_USER_WARNING); return $INFO['isadmin']; } diff --git a/inc/init.php b/inc/init.php index ba6743f95..89c0d4bc8 100644 --- a/inc/init.php +++ b/inc/init.php @@ -104,11 +104,15 @@ if(!defined('DOKU_BASE')){ } // define whitespace +if(!defined('NL')) define ('NL',"\n"); if(!defined('DOKU_LF')) define ('DOKU_LF',"\n"); if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t"); // define cookie and session id, append server port when securecookie is configured FS#1664 -if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:''))); +if(!defined('DOKU_COOKIE')) define( + 'DOKU_COOKIE', + 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $_SERVER['SERVER_PORT'] : '')) +); // define main script @@ -229,7 +233,13 @@ mail_setup(); function init_session() { global $conf; session_name(DOKU_SESSION_NAME); - session_set_cookie_params(DOKU_SESSION_LIFETIME, DOKU_SESSION_PATH, DOKU_SESSION_DOMAIN, ($conf['securecookie'] && is_ssl()), true); + session_set_cookie_params( + DOKU_SESSION_LIFETIME, + DOKU_SESSION_PATH, + DOKU_SESSION_DOMAIN, + ($conf['securecookie'] && is_ssl()), + true + ); // make sure the session cookie contains a valid session ID if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) { @@ -268,7 +278,9 @@ function init_paths(){ } // path to old changelog only needed for upgrading - $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log')); + $conf['changelog_old'] = init_path( + (isset($conf['changelog'])) ? ($conf['changelog']) : ($conf['savedir'] . '/changes.log') + ); if ($conf['changelog_old']=='') { unset($conf['changelog_old']); } // hardcoded changelog because it is now a cache that lives in meta $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes'; @@ -437,7 +449,7 @@ function getBaseURL($abs=null){ //finish here for relative URLs if(!$abs) return $dir; - //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path + //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir; //split hostheader into host and port diff --git a/inc/io.php b/inc/io.php index 7b646f127..c39325e73 100644 --- a/inc/io.php +++ b/inc/io.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * Removes empty directories * @@ -646,7 +644,8 @@ function io_mktmpdir() { * * @param string $url url to download * @param string $file path to file or directory where to save - * @param bool $useAttachment if true: try to use name of download, uses otherwise $defaultName, false: uses $file as path to file + * @param bool $useAttachment true: try to use name of download, uses otherwise $defaultName + * false: uses $file as path to file * @param string $defaultName fallback for if using $useAttachment * @param int $maxSize maximum file size * @return bool|string if failed false, otherwise true or the name of the file in the given dir diff --git a/inc/load.php b/inc/load.php index 2131b9d62..2ec96ac8f 100644 --- a/inc/load.php +++ b/inc/load.php @@ -34,6 +34,7 @@ require_once(DOKU_INC.'inc/toolbar.php'); require_once(DOKU_INC.'inc/utf8.php'); require_once(DOKU_INC.'inc/auth.php'); require_once(DOKU_INC.'inc/compatibility.php'); +require_once(DOKU_INC.'inc/deprecated.php'); /** * spl_autoload_register callback @@ -72,14 +73,10 @@ function load_autoload($name){ 'IXR_Error' => DOKU_INC.'inc/IXR_Library.php', 'IXR_IntrospectionServer' => DOKU_INC.'inc/IXR_Library.php', 'Doku_Plugin_Controller'=> DOKU_INC.'inc/plugincontroller.class.php', - 'Doku_Parser_Mode' => DOKU_INC.'inc/parser/parser.php', - 'Doku_Parser_Mode_Plugin' => DOKU_INC.'inc/parser/parser.php', 'SafeFN' => DOKU_INC.'inc/SafeFN.class.php', 'Sitemapper' => DOKU_INC.'inc/Sitemapper.php', 'PassHash' => DOKU_INC.'inc/PassHash.class.php', 'Mailer' => DOKU_INC.'inc/Mailer.class.php', - 'RemoteAPI' => DOKU_INC.'inc/remote.php', - 'RemoteAPICore' => DOKU_INC.'inc/RemoteAPICore.php', 'Subscription' => DOKU_INC.'inc/subscription.php', 'DokuWiki_PluginInterface' => DOKU_INC.'inc/PluginInterface.php', @@ -94,6 +91,7 @@ function load_autoload($name){ 'DokuWiki_Auth_Plugin' => DOKU_PLUGIN.'auth.php', 'DokuWiki_CLI_Plugin' => DOKU_PLUGIN.'cli.php', + 'Doku_Handler' => DOKU_INC.'inc/parser/handler.php', 'Doku_Renderer' => DOKU_INC.'inc/parser/renderer.php', 'Doku_Renderer_xhtml' => DOKU_INC.'inc/parser/xhtml.php', 'Doku_Renderer_code' => DOKU_INC.'inc/parser/code.php', @@ -114,6 +112,15 @@ function load_autoload($name){ // namespace to directory conversion $name = str_replace('\\', '/', $name); + // test namespace + if(substr($name, 0, 14) == 'dokuwiki/test/') { + $file = DOKU_INC . '_test/' . substr($name, 14) . '.php'; + if(file_exists($file)) { + require $file; + return true; + } + } + // plugin namespace if(substr($name, 0, 16) == 'dokuwiki/plugin/') { $name = str_replace('/test/', '/_test/', $name); // no underscore in test namespace @@ -144,8 +151,13 @@ function load_autoload($name){ } // Plugin loading - if(preg_match('/^(auth|helper|syntax|action|admin|renderer|remote|cli)_plugin_('.DOKU_PLUGIN_NAME_REGEX.')(?:_([^_]+))?$/', - $name, $m)) { + if(preg_match( + '/^(auth|helper|syntax|action|admin|renderer|remote|cli)_plugin_(' . + DOKU_PLUGIN_NAME_REGEX . + ')(?:_([^_]+))?$/', + $name, + $m + )) { // try to load the wanted plugin file $c = ((count($m) === 4) ? "/{$m[3]}" : ''); $plg = DOKU_PLUGIN . "{$m[2]}/{$m[1]}$c.php"; diff --git a/inc/mail.php b/inc/mail.php index f72dbdeec..230fe4f1f 100644 --- a/inc/mail.php +++ b/inc/mail.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - // end of line for mail lines - RFC822 says CRLF but postfix (and other MTAs?) // think different if(!defined('MAILHEADER_EOL')) define('MAILHEADER_EOL',"\n"); @@ -27,7 +25,10 @@ if(!defined('MAILHEADER_EOL')) define('MAILHEADER_EOL',"\n"); * Check if a given mail address is valid */ if (!defined('RFC2822_ATEXT')) define('RFC2822_ATEXT',"0-9a-zA-Z!#$%&'*+/=?^_`{|}~-"); -if (!defined('PREG_PATTERN_VALID_EMAIL')) define('PREG_PATTERN_VALID_EMAIL', '['.RFC2822_ATEXT.']+(?:\.['.RFC2822_ATEXT.']+)*@(?i:[0-9a-z][0-9a-z-]*\.)+(?i:[a-z]{2,63})'); +if (!defined('PREG_PATTERN_VALID_EMAIL')) define( + 'PREG_PATTERN_VALID_EMAIL', + '['.RFC2822_ATEXT.']+(?:\.['.RFC2822_ATEXT.']+)*@(?i:[0-9a-z][0-9a-z-]*\.)+(?i:[a-z]{2,63})' +); /** * Prepare mailfrom replacement patterns diff --git a/inc/media.php b/inc/media.php index 128466061..5feefcd53 100644 --- a/inc/media.php +++ b/inc/media.php @@ -6,9 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); -if(!defined('NL')) define('NL',"\n"); - /** * Lists pages which currently use a media file selected for deletion * @@ -172,7 +169,17 @@ function media_metaform($id,$auth){ $form->addElement('<div class="row">'); if($field[2] == 'text'){ - $form->addElement(form_makeField('text', $p['name'], $value, ($lang[$field[1]]) ? $lang[$field[1]] : $field[1] . ':', $p['id'], $p['class'], $p_attrs)); + $form->addElement( + form_makeField( + 'text', + $p['name'], + $value, + ($lang[$field[1]]) ? $lang[$field[1]] : $field[1] . ':', + $p['id'], + $p['class'], + $p_attrs + ) + ); }else{ $att = buildAttributes($p); $form->addElement('<label for="meta__'.$key.'">'.$lang[$field[1]].'</label>'); @@ -181,7 +188,14 @@ function media_metaform($id,$auth){ $form->addElement('</div>'.NL); } $form->addElement('<div class="buttons">'); - $form->addElement(form_makeButton('submit', '', $lang['btn_save'], array('accesskey' => 's', 'name' => 'mediado[save]'))); + $form->addElement( + form_makeButton( + 'submit', + '', + $lang['btn_save'], + array('accesskey' => 's', 'name' => 'mediado[save]') + ) + ); $form->addElement('</div>'.NL); $form->printForm(); @@ -530,7 +544,15 @@ function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'mov $filesize_new = filesize($fn); $sizechange = $filesize_new - $filesize_old; if($REV) { - addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_REVERT, sprintf($lang['restored'], dformat($REV)), $REV, null, $sizechange); + addMediaLogEntry( + $new, + $id, + DOKU_CHANGE_TYPE_REVERT, + sprintf($lang['restored'], dformat($REV)), + $REV, + null, + $sizechange + ); } elseif($overwrite) { addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange); } else { @@ -1716,7 +1738,7 @@ function media_printimgdetail($item, $fullscreen=false){ // output if ($fullscreen) { echo '<a id="l_:'.$item['id'].'" class="image thumb" href="'. - media_managerURL(array('image' => hsc($item['id']), 'ns' => getNS($item['id']), 'tab_details' => 'view')).'">'; + media_managerURL(['image' => hsc($item['id']), 'ns' => getNS($item['id']), 'tab_details' => 'view']).'">'; echo '<img src="'.$src.'" '.$att.' />'; echo '</a>'; } @@ -1900,7 +1922,16 @@ function media_searchform($ns,$query='',$fullscreen=false){ $form->addHidden($fullscreen ? 'mediado' : 'do', 'searchlist'); $form->addElement(form_makeOpenTag('p')); - $form->addElement(form_makeTextField('q', $query,$lang['searchmedia'],'','',array('title'=>sprintf($lang['searchmedia_in'],hsc($ns).':*')))); + $form->addElement( + form_makeTextField( + 'q', + $query, + $lang['searchmedia'], + '', + '', + array('title' => sprintf($lang['searchmedia_in'], hsc($ns) . ':*')) + ) + ); $form->addElement(form_makeButton('submit', '', $lang['btn_search'])); $form->addElement(form_makeCloseTag('p')); html_form('searchmedia', $form); @@ -1943,7 +1974,13 @@ function media_nstree($ns){ // find the namespace parts or insert them while ($data[$pos]['id'] != $tmp_ns) { - if ($pos >= count($data) || ($data[$pos]['level'] <= $level+1 && strnatcmp(utf8_encodeFN($data[$pos]['id']), utf8_encodeFN($tmp_ns)) > 0)) { + if ( + $pos >= count($data) || + ( + $data[$pos]['level'] <= $level+1 && + strnatcmp(utf8_encodeFN($data[$pos]['id']), utf8_encodeFN($tmp_ns)) > 0 + ) + ) { array_splice($data, $pos, 0, array(array('level' => $level+1, 'id' => $tmp_ns, 'open' => 'true'))); break; } @@ -2353,7 +2390,12 @@ function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x= $transcolorindex = @imagecolortransparent($image); if($transcolorindex >= 0 ) { //transparent color exists $transcolor = @imagecolorsforindex($image, $transcolorindex); - $transcolorindex = @imagecolorallocate($newimg, $transcolor['red'], $transcolor['green'], $transcolor['blue']); + $transcolorindex = @imagecolorallocate( + $newimg, + $transcolor['red'], + $transcolor['green'], + $transcolor['blue'] + ); @imagefill($newimg, 0, 0, $transcolorindex); @imagecolortransparent($newimg, $transcolorindex); }else{ //filling with white diff --git a/inc/parser/code.php b/inc/parser/code.php index f91f1d228..043ce5be9 100644 --- a/inc/parser/code.php +++ b/inc/parser/code.php @@ -4,10 +4,8 @@ * * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - class Doku_Renderer_code extends Doku_Renderer { - var $_codeblock = 0; + protected $_codeblock = 0; /** * Send the wanted code block to the browser @@ -18,7 +16,7 @@ class Doku_Renderer_code extends Doku_Renderer { * @param string $language * @param string $filename */ - function code($text, $language = null, $filename = '') { + public function code($text, $language = null, $filename = '') { global $INPUT; if(!$language) $language = 'txt'; $language = preg_replace(PREG_PATTERN_VALID_LANGUAGE, '', $language); @@ -49,14 +47,14 @@ class Doku_Renderer_code extends Doku_Renderer { * @param string $language * @param string $filename */ - function file($text, $language = null, $filename = '') { + public function file($text, $language = null, $filename = '') { $this->code($text, $language, $filename); } /** * This should never be reached, if it is send a 404 */ - function document_end() { + public function document_end() { http_status(404); echo '404 - Not found'; exit; @@ -67,7 +65,7 @@ class Doku_Renderer_code extends Doku_Renderer { * * @returns string 'code' */ - function getFormat() { + public function getFormat() { return 'code'; } } diff --git a/inc/parser/handler.php b/inc/parser/handler.php index 780c6cf48..6d4c6b97e 100644 --- a/inc/parser/handler.php +++ b/inc/parser/handler.php @@ -1,44 +1,76 @@ <?php -if(!defined('DOKU_INC')) die('meh.'); -if (!defined('DOKU_PARSER_EOL')) define('DOKU_PARSER_EOL',"\n"); // add this to make handling test cases simpler -class Doku_Handler { - - var $Renderer = null; +use dokuwiki\Parsing\Handler\Block; +use dokuwiki\Parsing\Handler\CallWriter; +use dokuwiki\Parsing\Handler\CallWriterInterface; +use dokuwiki\Parsing\Handler\Lists; +use dokuwiki\Parsing\Handler\Nest; +use dokuwiki\Parsing\Handler\Preformatted; +use dokuwiki\Parsing\Handler\Quote; +use dokuwiki\Parsing\Handler\Table; - var $CallWriter = null; +/** + * Class Doku_Handler + */ +class Doku_Handler { + /** @var CallWriterInterface */ + protected $callWriter = null; - var $calls = array(); + /** @var array The current CallWriter will write directly to this list of calls, Parser reads it */ + public $calls = array(); - var $status = array( + /** @var array internal status holders for some modes */ + protected $status = array( 'section' => false, 'doublequote' => 0, ); - var $rewriteBlocks = true; + /** @var bool should blocks be rewritten? FIXME seems to always be true */ + protected $rewriteBlocks = true; - function __construct() { - $this->CallWriter = new Doku_Handler_CallWriter($this); + /** + * Doku_Handler constructor. + */ + public function __construct() { + $this->callWriter = new CallWriter($this); } /** - * @param string $handler - * @param mixed $args - * @param integer|string $pos + * Add a new call by passing it to the current CallWriter + * + * @param string $handler handler method name (see mode handlers below) + * @param mixed $args arguments for this call + * @param int $pos byte position in the original source file */ - function _addCall($handler, $args, $pos) { + protected function addCall($handler, $args, $pos) { $call = array($handler,$args, $pos); - $this->CallWriter->writeCall($call); + $this->callWriter->writeCall($call); } - function addPluginCall($plugin, $args, $state, $pos, $match) { + /** + * Similar to addCall, but adds a plugin call + * + * @param string $plugin name of the plugin + * @param mixed $args arguments for this call + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @param string $match matched syntax + */ + protected function addPluginCall($plugin, $args, $state, $pos, $match) { $call = array('plugin',array($plugin, $args, $state, $match), $pos); - $this->CallWriter->writeCall($call); + $this->callWriter->writeCall($call); } - function _finalize(){ - - $this->CallWriter->finalise(); + /** + * Finishes handling + * + * Called from the parser. Calls finalise() on the call writer, closes open + * sections, rewrites blocks and adds document_start and document_end calls. + * + * @triggers PARSER_HANDLER_DONE + */ + public function finalize(){ + $this->callWriter->finalise(); if ( $this->status['section'] ) { $last_call = end($this->calls); @@ -46,7 +78,7 @@ class Doku_Handler { } if ( $this->rewriteBlocks ) { - $B = new Doku_Handler_Block(); + $B = new Block(); $this->calls = $B->process($this->calls); } @@ -60,9 +92,10 @@ class Doku_Handler { /** * fetch the current call and advance the pointer to the next one * + * @fixme seems to be unused? * @return bool|mixed */ - function fetch() { + public function fetch() { $call = current($this->calls); if($call !== false) { next($this->calls); //advance the pointer @@ -73,21 +106,125 @@ class Doku_Handler { /** + * Internal function for parsing highlight options. + * $options is parsed for key value pairs separated by commas. + * A value might also be missing in which case the value will simple + * be set to true. Commas in strings are ignored, e.g. option="4,56" + * will work as expected and will only create one entry. + * + * @param string $options space separated list of key-value pairs, + * e.g. option1=123, option2="456" + * @return array|null Array of key-value pairs $array['key'] = 'value'; + * or null if no entries found + */ + protected function parse_highlight_options($options) { + $result = array(); + preg_match_all('/(\w+(?:="[^"]*"))|(\w+(?:=[^\s]*))|(\w+[^=\s\]])(?:\s*)/', $options, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { + $equal_sign = strpos($match [0], '='); + if ($equal_sign === false) { + $key = trim($match[0]); + $result [$key] = 1; + } else { + $key = substr($match[0], 0, $equal_sign); + $value = substr($match[0], $equal_sign+1); + $value = trim($value, '"'); + if (strlen($value) > 0) { + $result [$key] = $value; + } else { + $result [$key] = 1; + } + } + } + + // Check for supported options + $result = array_intersect_key( + $result, + array_flip(array( + 'enable_line_numbers', + 'start_line_numbers_at', + 'highlight_lines_extra', + 'enable_keyword_links') + ) + ); + + // Sanitize values + if(isset($result['enable_line_numbers'])) { + if($result['enable_line_numbers'] === 'false') { + $result['enable_line_numbers'] = false; + } + $result['enable_line_numbers'] = (bool) $result['enable_line_numbers']; + } + if(isset($result['highlight_lines_extra'])) { + $result['highlight_lines_extra'] = array_map('intval', explode(',', $result['highlight_lines_extra'])); + $result['highlight_lines_extra'] = array_filter($result['highlight_lines_extra']); + $result['highlight_lines_extra'] = array_unique($result['highlight_lines_extra']); + } + if(isset($result['start_line_numbers_at'])) { + $result['start_line_numbers_at'] = (int) $result['start_line_numbers_at']; + } + if(isset($result['enable_keyword_links'])) { + if($result['enable_keyword_links'] === 'false') { + $result['enable_keyword_links'] = false; + } + $result['enable_keyword_links'] = (bool) $result['enable_keyword_links']; + } + if (count($result) == 0) { + return null; + } + + return $result; + } + + /** + * Simplifies handling for the formatting tags which all behave the same + * + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @param string $name actual mode name + */ + protected function nestingTag($match, $state, $pos, $name) { + switch ( $state ) { + case DOKU_LEXER_ENTER: + $this->addCall($name.'_open', array(), $pos); + break; + case DOKU_LEXER_EXIT: + $this->addCall($name.'_close', array(), $pos); + break; + case DOKU_LEXER_UNMATCHED: + $this->addCall('cdata', array($match), $pos); + break; + } + } + + + /** + * The following methods define the handlers for the different Syntax modes + * + * The handlers are called from dokuwiki\Parsing\Lexer\Lexer\invokeParser() + * + * @todo it might make sense to move these into their own class or merge them with the + * ParserMode classes some time. + */ + // region mode handlers + + /** * Special plugin handler * * This handler is called for all modes starting with 'plugin_'. - * An additional parameter with the plugin name is passed + * An additional parameter with the plugin name is passed. The plugin's handle() + * method is called here * * @author Andreas Gohr <andi@splitbrain.org> * - * @param string|integer $match - * @param string|integer $state - * @param integer $pos - * @param $pluginname - * - * @return bool + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @param string $pluginname name of the plugin + * @return bool mode handled? */ - function plugin($match, $state, $pos, $pluginname){ + public function plugin($match, $state, $pos, $pluginname){ $data = array($match); /** @var DokuWiki_Syntax_Plugin $plugin */ $plugin = plugin_load('syntax',$pluginname); @@ -100,16 +237,29 @@ class Doku_Handler { return true; } - function base($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function base($match, $state, $pos) { switch ( $state ) { case DOKU_LEXER_UNMATCHED: - $this->_addCall('cdata',array($match), $pos); + $this->addCall('cdata', array($match), $pos); return true; break; } + return false; } - function header($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function header($match, $state, $pos) { // get level and title $title = trim($match); $level = 7 - strspn($title,'='); @@ -117,98 +267,154 @@ class Doku_Handler { $title = trim($title,'='); $title = trim($title); - if ($this->status['section']) $this->_addCall('section_close',array(),$pos); + if ($this->status['section']) $this->addCall('section_close', array(), $pos); - $this->_addCall('header',array($title,$level,$pos), $pos); + $this->addCall('header', array($title, $level, $pos), $pos); - $this->_addCall('section_open',array($level),$pos); + $this->addCall('section_open', array($level), $pos); $this->status['section'] = true; return true; } - function notoc($match, $state, $pos) { - $this->_addCall('notoc',array(),$pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function notoc($match, $state, $pos) { + $this->addCall('notoc', array(), $pos); return true; } - function nocache($match, $state, $pos) { - $this->_addCall('nocache',array(),$pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function nocache($match, $state, $pos) { + $this->addCall('nocache', array(), $pos); return true; } - function linebreak($match, $state, $pos) { - $this->_addCall('linebreak',array(),$pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function linebreak($match, $state, $pos) { + $this->addCall('linebreak', array(), $pos); return true; } - function eol($match, $state, $pos) { - $this->_addCall('eol',array(),$pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function eol($match, $state, $pos) { + $this->addCall('eol', array(), $pos); return true; } - function hr($match, $state, $pos) { - $this->_addCall('hr',array(),$pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function hr($match, $state, $pos) { + $this->addCall('hr', array(), $pos); return true; } /** - * @param string|integer $match - * @param string|integer $state - * @param integer $pos - * @param string $name + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? */ - function _nestingTag($match, $state, $pos, $name) { - switch ( $state ) { - case DOKU_LEXER_ENTER: - $this->_addCall($name.'_open', array(), $pos); - break; - case DOKU_LEXER_EXIT: - $this->_addCall($name.'_close', array(), $pos); - break; - case DOKU_LEXER_UNMATCHED: - $this->_addCall('cdata',array($match), $pos); - break; - } - } - - function strong($match, $state, $pos) { - $this->_nestingTag($match, $state, $pos, 'strong'); + public function strong($match, $state, $pos) { + $this->nestingTag($match, $state, $pos, 'strong'); return true; } - function emphasis($match, $state, $pos) { - $this->_nestingTag($match, $state, $pos, 'emphasis'); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function emphasis($match, $state, $pos) { + $this->nestingTag($match, $state, $pos, 'emphasis'); return true; } - function underline($match, $state, $pos) { - $this->_nestingTag($match, $state, $pos, 'underline'); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function underline($match, $state, $pos) { + $this->nestingTag($match, $state, $pos, 'underline'); return true; } - function monospace($match, $state, $pos) { - $this->_nestingTag($match, $state, $pos, 'monospace'); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function monospace($match, $state, $pos) { + $this->nestingTag($match, $state, $pos, 'monospace'); return true; } - function subscript($match, $state, $pos) { - $this->_nestingTag($match, $state, $pos, 'subscript'); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function subscript($match, $state, $pos) { + $this->nestingTag($match, $state, $pos, 'subscript'); return true; } - function superscript($match, $state, $pos) { - $this->_nestingTag($match, $state, $pos, 'superscript'); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function superscript($match, $state, $pos) { + $this->nestingTag($match, $state, $pos, 'superscript'); return true; } - function deleted($match, $state, $pos) { - $this->_nestingTag($match, $state, $pos, 'deleted'); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function deleted($match, $state, $pos) { + $this->nestingTag($match, $state, $pos, 'deleted'); return true; } - - function footnote($match, $state, $pos) { -// $this->_nestingTag($match, $state, $pos, 'footnote'); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function footnote($match, $state, $pos) { if (!isset($this->_footnote)) $this->_footnote = false; switch ( $state ) { @@ -216,146 +422,185 @@ class Doku_Handler { // footnotes can not be nested - however due to limitations in lexer it can't be prevented // we will still enter a new footnote mode, we just do nothing if ($this->_footnote) { - $this->_addCall('cdata',array($match), $pos); + $this->addCall('cdata', array($match), $pos); break; } - $this->_footnote = true; - $ReWriter = new Doku_Handler_Nest($this->CallWriter,'footnote_close'); - $this->CallWriter = & $ReWriter; - $this->_addCall('footnote_open', array(), $pos); + $this->callWriter = new Nest($this->callWriter, 'footnote_close'); + $this->addCall('footnote_open', array(), $pos); break; case DOKU_LEXER_EXIT: // check whether we have already exitted the footnote mode, can happen if the modes were nested if (!$this->_footnote) { - $this->_addCall('cdata',array($match), $pos); + $this->addCall('cdata', array($match), $pos); break; } $this->_footnote = false; + $this->addCall('footnote_close', array(), $pos); - $this->_addCall('footnote_close', array(), $pos); - $this->CallWriter->process(); - $ReWriter = & $this->CallWriter; - $this->CallWriter = & $ReWriter->CallWriter; + /** @var Nest $reWriter */ + $reWriter = $this->callWriter; + $this->callWriter = $reWriter->process(); break; case DOKU_LEXER_UNMATCHED: - $this->_addCall('cdata', array($match), $pos); + $this->addCall('cdata', array($match), $pos); break; } return true; } - function listblock($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function listblock($match, $state, $pos) { switch ( $state ) { case DOKU_LEXER_ENTER: - $ReWriter = new Doku_Handler_List($this->CallWriter); - $this->CallWriter = & $ReWriter; - $this->_addCall('list_open', array($match), $pos); + $this->callWriter = new Lists($this->callWriter); + $this->addCall('list_open', array($match), $pos); break; case DOKU_LEXER_EXIT: - $this->_addCall('list_close', array(), $pos); - $this->CallWriter->process(); - $ReWriter = & $this->CallWriter; - $this->CallWriter = & $ReWriter->CallWriter; + $this->addCall('list_close', array(), $pos); + /** @var Lists $reWriter */ + $reWriter = $this->callWriter; + $this->callWriter = $reWriter->process(); break; case DOKU_LEXER_MATCHED: - $this->_addCall('list_item', array($match), $pos); + $this->addCall('list_item', array($match), $pos); break; case DOKU_LEXER_UNMATCHED: - $this->_addCall('cdata', array($match), $pos); + $this->addCall('cdata', array($match), $pos); break; } return true; } - function unformatted($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function unformatted($match, $state, $pos) { if ( $state == DOKU_LEXER_UNMATCHED ) { - $this->_addCall('unformatted',array($match), $pos); + $this->addCall('unformatted', array($match), $pos); } return true; } - function php($match, $state, $pos) { - global $conf; + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function php($match, $state, $pos) { if ( $state == DOKU_LEXER_UNMATCHED ) { - $this->_addCall('php',array($match), $pos); + $this->addCall('php', array($match), $pos); } return true; } - function phpblock($match, $state, $pos) { - global $conf; + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function phpblock($match, $state, $pos) { if ( $state == DOKU_LEXER_UNMATCHED ) { - $this->_addCall('phpblock',array($match), $pos); + $this->addCall('phpblock', array($match), $pos); } return true; } - function html($match, $state, $pos) { - global $conf; + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function html($match, $state, $pos) { if ( $state == DOKU_LEXER_UNMATCHED ) { - $this->_addCall('html',array($match), $pos); + $this->addCall('html', array($match), $pos); } return true; } - function htmlblock($match, $state, $pos) { - global $conf; + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function htmlblock($match, $state, $pos) { if ( $state == DOKU_LEXER_UNMATCHED ) { - $this->_addCall('htmlblock',array($match), $pos); + $this->addCall('htmlblock', array($match), $pos); } return true; } - function preformatted($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function preformatted($match, $state, $pos) { switch ( $state ) { case DOKU_LEXER_ENTER: - $ReWriter = new Doku_Handler_Preformatted($this->CallWriter); - $this->CallWriter = $ReWriter; - $this->_addCall('preformatted_start',array(), $pos); + $this->callWriter = new Preformatted($this->callWriter); + $this->addCall('preformatted_start', array(), $pos); break; case DOKU_LEXER_EXIT: - $this->_addCall('preformatted_end',array(), $pos); - $this->CallWriter->process(); - $ReWriter = & $this->CallWriter; - $this->CallWriter = & $ReWriter->CallWriter; + $this->addCall('preformatted_end', array(), $pos); + /** @var Preformatted $reWriter */ + $reWriter = $this->callWriter; + $this->callWriter = $reWriter->process(); break; case DOKU_LEXER_MATCHED: - $this->_addCall('preformatted_newline',array(), $pos); + $this->addCall('preformatted_newline', array(), $pos); break; case DOKU_LEXER_UNMATCHED: - $this->_addCall('preformatted_content',array($match), $pos); + $this->addCall('preformatted_content', array($match), $pos); break; } return true; } - function quote($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function quote($match, $state, $pos) { switch ( $state ) { case DOKU_LEXER_ENTER: - $ReWriter = new Doku_Handler_Quote($this->CallWriter); - $this->CallWriter = & $ReWriter; - $this->_addCall('quote_start',array($match), $pos); + $this->callWriter = new Quote($this->callWriter); + $this->addCall('quote_start', array($match), $pos); break; case DOKU_LEXER_EXIT: - $this->_addCall('quote_end',array(), $pos); - $this->CallWriter->process(); - $ReWriter = & $this->CallWriter; - $this->CallWriter = & $ReWriter->CallWriter; + $this->addCall('quote_end', array(), $pos); + /** @var Lists $reWriter */ + $reWriter = $this->callWriter; + $this->callWriter = $reWriter->process(); break; case DOKU_LEXER_MATCHED: - $this->_addCall('quote_newline',array($match), $pos); + $this->addCall('quote_newline', array($match), $pos); break; case DOKU_LEXER_UNMATCHED: - $this->_addCall('cdata',array($match), $pos); + $this->addCall('cdata', array($match), $pos); break; } @@ -364,81 +609,23 @@ class Doku_Handler { } /** - * Internal function for parsing highlight options. - * $options is parsed for key value pairs separated by commas. - * A value might also be missing in which case the value will simple - * be set to true. Commas in strings are ignored, e.g. option="4,56" - * will work as expected and will only create one entry. - * - * @param string $options space separated list of key-value pairs, - * e.g. option1=123, option2="456" - * @return array|null Array of key-value pairs $array['key'] = 'value'; - * or null if no entries found + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? */ - protected function parse_highlight_options ($options) { - $result = array(); - preg_match_all('/(\w+(?:="[^"]*"))|(\w+(?:=[^\s]*))|(\w+[^=\s\]])(?:\s*)/', $options, $matches, PREG_SET_ORDER); - foreach ($matches as $match) { - $equal_sign = strpos($match [0], '='); - if ($equal_sign === false) { - $key = trim($match[0]); - $result [$key] = 1; - } else { - $key = substr($match[0], 0, $equal_sign); - $value = substr($match[0], $equal_sign+1); - $value = trim($value, '"'); - if (strlen($value) > 0) { - $result [$key] = $value; - } else { - $result [$key] = 1; - } - } - } - - // Check for supported options - $result = array_intersect_key( - $result, - array_flip(array( - 'enable_line_numbers', - 'start_line_numbers_at', - 'highlight_lines_extra', - 'enable_keyword_links') - ) - ); - - // Sanitize values - if(isset($result['enable_line_numbers'])) { - if($result['enable_line_numbers'] === 'false') { - $result['enable_line_numbers'] = false; - } - $result['enable_line_numbers'] = (bool) $result['enable_line_numbers']; - } - if(isset($result['highlight_lines_extra'])) { - $result['highlight_lines_extra'] = array_map('intval', explode(',', $result['highlight_lines_extra'])); - $result['highlight_lines_extra'] = array_filter($result['highlight_lines_extra']); - $result['highlight_lines_extra'] = array_unique($result['highlight_lines_extra']); - } - if(isset($result['start_line_numbers_at'])) { - $result['start_line_numbers_at'] = (int) $result['start_line_numbers_at']; - } - if(isset($result['enable_keyword_links'])) { - if($result['enable_keyword_links'] === 'false') { - $result['enable_keyword_links'] = false; - } - $result['enable_keyword_links'] = (bool) $result['enable_keyword_links']; - } - if (count($result) == 0) { - return null; - } - - return $result; - } - - function file($match, $state, $pos) { + public function file($match, $state, $pos) { return $this->code($match, $state, $pos, 'file'); } - function code($match, $state, $pos, $type='code') { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @param string $type either 'code' or 'file' + * @return bool mode handled? + */ + public function code($match, $state, $pos, $type='code') { if ( $state == DOKU_LEXER_UNMATCHED ) { $matches = explode('>',$match,2); // Cut out variable options enclosed in [] @@ -455,76 +642,146 @@ class Doku_Handler { if (!empty($options[0])) { $param [] = $this->parse_highlight_options ($options[0]); } - $this->_addCall($type, $param, $pos); + $this->addCall($type, $param, $pos); } return true; } - function acronym($match, $state, $pos) { - $this->_addCall('acronym',array($match), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function acronym($match, $state, $pos) { + $this->addCall('acronym', array($match), $pos); return true; } - function smiley($match, $state, $pos) { - $this->_addCall('smiley',array($match), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function smiley($match, $state, $pos) { + $this->addCall('smiley', array($match), $pos); return true; } - function wordblock($match, $state, $pos) { - $this->_addCall('wordblock',array($match), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function wordblock($match, $state, $pos) { + $this->addCall('wordblock', array($match), $pos); return true; } - function entity($match, $state, $pos) { - $this->_addCall('entity',array($match), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function entity($match, $state, $pos) { + $this->addCall('entity', array($match), $pos); return true; } - function multiplyentity($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function multiplyentity($match, $state, $pos) { preg_match_all('/\d+/',$match,$matches); - $this->_addCall('multiplyentity',array($matches[0][0],$matches[0][1]), $pos); + $this->addCall('multiplyentity', array($matches[0][0], $matches[0][1]), $pos); return true; } - function singlequoteopening($match, $state, $pos) { - $this->_addCall('singlequoteopening',array(), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function singlequoteopening($match, $state, $pos) { + $this->addCall('singlequoteopening', array(), $pos); return true; } - function singlequoteclosing($match, $state, $pos) { - $this->_addCall('singlequoteclosing',array(), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function singlequoteclosing($match, $state, $pos) { + $this->addCall('singlequoteclosing', array(), $pos); return true; } - function apostrophe($match, $state, $pos) { - $this->_addCall('apostrophe',array(), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function apostrophe($match, $state, $pos) { + $this->addCall('apostrophe', array(), $pos); return true; } - function doublequoteopening($match, $state, $pos) { - $this->_addCall('doublequoteopening',array(), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function doublequoteopening($match, $state, $pos) { + $this->addCall('doublequoteopening', array(), $pos); $this->status['doublequote']++; return true; } - function doublequoteclosing($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function doublequoteclosing($match, $state, $pos) { if ($this->status['doublequote'] <= 0) { $this->doublequoteopening($match, $state, $pos); } else { - $this->_addCall('doublequoteclosing',array(), $pos); + $this->addCall('doublequoteclosing', array(), $pos); $this->status['doublequote'] = max(0, --$this->status['doublequote']); } return true; } - function camelcaselink($match, $state, $pos) { - $this->_addCall('camelcaselink',array($match), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function camelcaselink($match, $state, $pos) { + $this->addCall('camelcaselink', array($match), $pos); return true; } - /* - */ - function internallink($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function internallink($match, $state, $pos) { // Strip the opening and closing markup $link = preg_replace(array('/^\[\[/','/\]\]$/u'),'',$match); @@ -543,42 +800,42 @@ class Doku_Handler { if ( link_isinterwiki($link[0]) ) { // Interwiki $interwiki = explode('>',$link[0],2); - $this->_addCall( + $this->addCall( 'interwikilink', array($link[0],$link[1],strtolower($interwiki[0]),$interwiki[1]), $pos ); }elseif ( preg_match('/^\\\\\\\\[^\\\\]+?\\\\/u',$link[0]) ) { // Windows Share - $this->_addCall( + $this->addCall( 'windowssharelink', array($link[0],$link[1]), $pos ); }elseif ( preg_match('#^([a-z0-9\-\.+]+?)://#i',$link[0]) ) { // external link (accepts all protocols) - $this->_addCall( + $this->addCall( 'externallink', array($link[0],$link[1]), $pos ); }elseif ( preg_match('<'.PREG_PATTERN_VALID_EMAIL.'>',$link[0]) ) { // E-Mail (pattern above is defined in inc/mail.php) - $this->_addCall( + $this->addCall( 'emaillink', array($link[0],$link[1]), $pos ); }elseif ( preg_match('!^#.+!',$link[0]) ){ // local link - $this->_addCall( + $this->addCall( 'locallink', array(substr($link[0],1),$link[1]), $pos ); }else{ // internal link - $this->_addCall( + $this->addCall( 'internallink', array($link[0],$link[1]), $pos @@ -588,20 +845,38 @@ class Doku_Handler { return true; } - function filelink($match, $state, $pos) { - $this->_addCall('filelink',array($match, null), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function filelink($match, $state, $pos) { + $this->addCall('filelink', array($match, null), $pos); return true; } - function windowssharelink($match, $state, $pos) { - $this->_addCall('windowssharelink',array($match, null), $pos); + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function windowssharelink($match, $state, $pos) { + $this->addCall('windowssharelink', array($match, null), $pos); return true; } - function media($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function media($match, $state, $pos) { $p = Doku_Handler_Parse_Media($match); - $this->_addCall( + $this->addCall( $p['type'], array($p['src'], $p['title'], $p['align'], $p['width'], $p['height'], $p['cache'], $p['linking']), @@ -610,7 +885,13 @@ class Doku_Handler { return true; } - function rss($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function rss($match, $state, $pos) { $link = preg_replace(array('/^\{\{rss>/','/\}\}$/'),'',$match); // get params @@ -635,11 +916,17 @@ class Doku_Handler { $p['refresh'] = 14400; // default to 4 hours } - $this->_addCall('rss',array($link,$p),$pos); + $this->addCall('rss', array($link, $p), $pos); return true; } - function externallink($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function externallink($match, $state, $pos) { $url = $match; $title = null; @@ -653,69 +940,82 @@ class Doku_Handler { $url = 'http://'.$url; } - $this->_addCall('externallink',array($url, $title), $pos); + $this->addCall('externallink', array($url, $title), $pos); return true; } - function emaillink($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function emaillink($match, $state, $pos) { $email = preg_replace(array('/^</','/>$/'),'',$match); - $this->_addCall('emaillink',array($email, null), $pos); + $this->addCall('emaillink', array($email, null), $pos); return true; } - function table($match, $state, $pos) { + /** + * @param string $match matched syntax + * @param int $state a LEXER_STATE_* constant + * @param int $pos byte position in the original source file + * @return bool mode handled? + */ + public function table($match, $state, $pos) { switch ( $state ) { case DOKU_LEXER_ENTER: - $ReWriter = new Doku_Handler_Table($this->CallWriter); - $this->CallWriter = & $ReWriter; + $this->callWriter = new Table($this->callWriter); - $this->_addCall('table_start', array($pos + 1), $pos); + $this->addCall('table_start', array($pos + 1), $pos); if ( trim($match) == '^' ) { - $this->_addCall('tableheader', array(), $pos); + $this->addCall('tableheader', array(), $pos); } else { - $this->_addCall('tablecell', array(), $pos); + $this->addCall('tablecell', array(), $pos); } break; case DOKU_LEXER_EXIT: - $this->_addCall('table_end', array($pos), $pos); - $this->CallWriter->process(); - $ReWriter = & $this->CallWriter; - $this->CallWriter = & $ReWriter->CallWriter; + $this->addCall('table_end', array($pos), $pos); + /** @var Table $reWriter */ + $reWriter = $this->callWriter; + $this->callWriter = $reWriter->process(); break; case DOKU_LEXER_UNMATCHED: if ( trim($match) != '' ) { - $this->_addCall('cdata',array($match), $pos); + $this->addCall('cdata', array($match), $pos); } break; case DOKU_LEXER_MATCHED: if ( $match == ' ' ){ - $this->_addCall('cdata', array($match), $pos); + $this->addCall('cdata', array($match), $pos); } else if ( preg_match('/:::/',$match) ) { - $this->_addCall('rowspan', array($match), $pos); + $this->addCall('rowspan', array($match), $pos); } else if ( preg_match('/\t+/',$match) ) { - $this->_addCall('table_align', array($match), $pos); + $this->addCall('table_align', array($match), $pos); } else if ( preg_match('/ {2,}/',$match) ) { - $this->_addCall('table_align', array($match), $pos); + $this->addCall('table_align', array($match), $pos); } else if ( $match == "\n|" ) { - $this->_addCall('table_row', array(), $pos); - $this->_addCall('tablecell', array(), $pos); + $this->addCall('table_row', array(), $pos); + $this->addCall('tablecell', array(), $pos); } else if ( $match == "\n^" ) { - $this->_addCall('table_row', array(), $pos); - $this->_addCall('tableheader', array(), $pos); + $this->addCall('table_row', array(), $pos); + $this->addCall('tableheader', array(), $pos); } else if ( $match == '|' ) { - $this->_addCall('tablecell', array(), $pos); + $this->addCall('tablecell', array(), $pos); } else if ( $match == '^' ) { - $this->_addCall('tableheader', array(), $pos); + $this->addCall('tableheader', array(), $pos); } break; } return true; } + + // endregion modes } //------------------------------------------------------------------------ @@ -808,1004 +1108,3 @@ function Doku_Handler_Parse_Media($match) { return $params; } -//------------------------------------------------------------------------ -interface Doku_Handler_CallWriter_Interface { - public function writeCall($call); - public function writeCalls($calls); - public function finalise(); -} - -class Doku_Handler_CallWriter implements Doku_Handler_CallWriter_Interface { - - var $Handler; - - /** - * @param Doku_Handler $Handler - */ - function __construct(Doku_Handler $Handler) { - $this->Handler = $Handler; - } - - function writeCall($call) { - $this->Handler->calls[] = $call; - } - - function writeCalls($calls) { - $this->Handler->calls = array_merge($this->Handler->calls, $calls); - } - - // function is required, but since this call writer is first/highest in - // the chain it is not required to do anything - function finalise() { - unset($this->Handler); - } -} - -//------------------------------------------------------------------------ -/** - * Generic call writer class to handle nesting of rendering instructions - * within a render instruction. Also see nest() method of renderer base class - * - * @author Chris Smith <chris@jalakai.co.uk> - */ -class Doku_Handler_Nest implements Doku_Handler_CallWriter_Interface { - - var $CallWriter; - var $calls = array(); - - var $closingInstruction; - - /** - * constructor - * - * @param Doku_Handler_CallWriter $CallWriter the renderers current call writer - * @param string $close closing instruction name, this is required to properly terminate the - * syntax mode if the document ends without a closing pattern - */ - function __construct(Doku_Handler_CallWriter_Interface $CallWriter, $close="nest_close") { - $this->CallWriter = $CallWriter; - - $this->closingInstruction = $close; - } - - function writeCall($call) { - $this->calls[] = $call; - } - - function writeCalls($calls) { - $this->calls = array_merge($this->calls, $calls); - } - - function finalise() { - $last_call = end($this->calls); - $this->writeCall(array($this->closingInstruction,array(), $last_call[2])); - - $this->process(); - $this->CallWriter->finalise(); - unset($this->CallWriter); - } - - function process() { - // merge consecutive cdata - $unmerged_calls = $this->calls; - $this->calls = array(); - - foreach ($unmerged_calls as $call) $this->addCall($call); - - $first_call = reset($this->calls); - $this->CallWriter->writeCall(array("nest", array($this->calls), $first_call[2])); - } - - function addCall($call) { - $key = count($this->calls); - if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) { - $this->calls[$key-1][1][0] .= $call[1][0]; - } else if ($call[0] == 'eol') { - // do nothing (eol shouldn't be allowed, to counter preformatted fix in #1652 & #1699) - } else { - $this->calls[] = $call; - } - } -} - -class Doku_Handler_List implements Doku_Handler_CallWriter_Interface { - - var $CallWriter; - - var $calls = array(); - var $listCalls = array(); - var $listStack = array(); - - const NODE = 1; - - function __construct(Doku_Handler_CallWriter_Interface $CallWriter) { - $this->CallWriter = $CallWriter; - } - - function writeCall($call) { - $this->calls[] = $call; - } - - // Probably not needed but just in case... - function writeCalls($calls) { - $this->calls = array_merge($this->calls, $calls); -# $this->CallWriter->writeCalls($this->calls); - } - - function finalise() { - $last_call = end($this->calls); - $this->writeCall(array('list_close',array(), $last_call[2])); - - $this->process(); - $this->CallWriter->finalise(); - unset($this->CallWriter); - } - - //------------------------------------------------------------------------ - function process() { - - foreach ( $this->calls as $call ) { - switch ($call[0]) { - case 'list_item': - $this->listOpen($call); - break; - case 'list_open': - $this->listStart($call); - break; - case 'list_close': - $this->listEnd($call); - break; - default: - $this->listContent($call); - break; - } - } - - $this->CallWriter->writeCalls($this->listCalls); - } - - //------------------------------------------------------------------------ - function listStart($call) { - $depth = $this->interpretSyntax($call[1][0], $listType); - - $this->initialDepth = $depth; - // array(list type, current depth, index of current listitem_open) - $this->listStack[] = array($listType, $depth, 1); - - $this->listCalls[] = array('list'.$listType.'_open',array(),$call[2]); - $this->listCalls[] = array('listitem_open',array(1),$call[2]); - $this->listCalls[] = array('listcontent_open',array(),$call[2]); - } - - //------------------------------------------------------------------------ - function listEnd($call) { - $closeContent = true; - - while ( $list = array_pop($this->listStack) ) { - if ( $closeContent ) { - $this->listCalls[] = array('listcontent_close',array(),$call[2]); - $closeContent = false; - } - $this->listCalls[] = array('listitem_close',array(),$call[2]); - $this->listCalls[] = array('list'.$list[0].'_close', array(), $call[2]); - } - } - - //------------------------------------------------------------------------ - function listOpen($call) { - $depth = $this->interpretSyntax($call[1][0], $listType); - $end = end($this->listStack); - $key = key($this->listStack); - - // Not allowed to be shallower than initialDepth - if ( $depth < $this->initialDepth ) { - $depth = $this->initialDepth; - } - - //------------------------------------------------------------------------ - if ( $depth == $end[1] ) { - - // Just another item in the list... - if ( $listType == $end[0] ) { - $this->listCalls[] = array('listcontent_close',array(),$call[2]); - $this->listCalls[] = array('listitem_close',array(),$call[2]); - $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]); - $this->listCalls[] = array('listcontent_open',array(),$call[2]); - - // new list item, update list stack's index into current listitem_open - $this->listStack[$key][2] = count($this->listCalls) - 2; - - // Switched list type... - } else { - - $this->listCalls[] = array('listcontent_close',array(),$call[2]); - $this->listCalls[] = array('listitem_close',array(),$call[2]); - $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]); - $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]); - $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]); - $this->listCalls[] = array('listcontent_open',array(),$call[2]); - - array_pop($this->listStack); - $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2); - } - - //------------------------------------------------------------------------ - // Getting deeper... - } else if ( $depth > $end[1] ) { - - $this->listCalls[] = array('listcontent_close',array(),$call[2]); - $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]); - $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]); - $this->listCalls[] = array('listcontent_open',array(),$call[2]); - - // set the node/leaf state of this item's parent listitem_open to NODE - $this->listCalls[$this->listStack[$key][2]][1][1] = self::NODE; - - $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2); - - //------------------------------------------------------------------------ - // Getting shallower ( $depth < $end[1] ) - } else { - $this->listCalls[] = array('listcontent_close',array(),$call[2]); - $this->listCalls[] = array('listitem_close',array(),$call[2]); - $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]); - - // Throw away the end - done - array_pop($this->listStack); - - while (1) { - $end = end($this->listStack); - $key = key($this->listStack); - - if ( $end[1] <= $depth ) { - - // Normalize depths - $depth = $end[1]; - - $this->listCalls[] = array('listitem_close',array(),$call[2]); - - if ( $end[0] == $listType ) { - $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]); - $this->listCalls[] = array('listcontent_open',array(),$call[2]); - - // new list item, update list stack's index into current listitem_open - $this->listStack[$key][2] = count($this->listCalls) - 2; - - } else { - // Switching list type... - $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]); - $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]); - $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]); - $this->listCalls[] = array('listcontent_open',array(),$call[2]); - - array_pop($this->listStack); - $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2); - } - - break; - - // Haven't dropped down far enough yet.... ( $end[1] > $depth ) - } else { - - $this->listCalls[] = array('listitem_close',array(),$call[2]); - $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]); - - array_pop($this->listStack); - - } - - } - - } - } - - //------------------------------------------------------------------------ - function listContent($call) { - $this->listCalls[] = $call; - } - - //------------------------------------------------------------------------ - function interpretSyntax($match, & $type) { - if ( substr($match,-1) == '*' ) { - $type = 'u'; - } else { - $type = 'o'; - } - // Is the +1 needed? It used to be count(explode(...)) - // but I don't think the number is seen outside this handler - return substr_count(str_replace("\t",' ',$match), ' ') + 1; - } -} - -//------------------------------------------------------------------------ -class Doku_Handler_Preformatted implements Doku_Handler_CallWriter_Interface { - - var $CallWriter; - - var $calls = array(); - var $pos; - var $text =''; - - - - function __construct(Doku_Handler_CallWriter_Interface $CallWriter) { - $this->CallWriter = $CallWriter; - } - - function writeCall($call) { - $this->calls[] = $call; - } - - // Probably not needed but just in case... - function writeCalls($calls) { - $this->calls = array_merge($this->calls, $calls); -# $this->CallWriter->writeCalls($this->calls); - } - - function finalise() { - $last_call = end($this->calls); - $this->writeCall(array('preformatted_end',array(), $last_call[2])); - - $this->process(); - $this->CallWriter->finalise(); - unset($this->CallWriter); - } - - function process() { - foreach ( $this->calls as $call ) { - switch ($call[0]) { - case 'preformatted_start': - $this->pos = $call[2]; - break; - case 'preformatted_newline': - $this->text .= "\n"; - break; - case 'preformatted_content': - $this->text .= $call[1][0]; - break; - case 'preformatted_end': - if (trim($this->text)) { - $this->CallWriter->writeCall(array('preformatted',array($this->text),$this->pos)); - } - // see FS#1699 & FS#1652, add 'eol' instructions to ensure proper triggering of following p_open - $this->CallWriter->writeCall(array('eol',array(),$this->pos)); - $this->CallWriter->writeCall(array('eol',array(),$this->pos)); - break; - } - } - } - -} - -//------------------------------------------------------------------------ -class Doku_Handler_Quote implements Doku_Handler_CallWriter_Interface { - - var $CallWriter; - - var $calls = array(); - - var $quoteCalls = array(); - - function __construct(Doku_Handler_CallWriter_Interface $CallWriter) { - $this->CallWriter = $CallWriter; - } - - function writeCall($call) { - $this->calls[] = $call; - } - - // Probably not needed but just in case... - function writeCalls($calls) { - $this->calls = array_merge($this->calls, $calls); - } - - function finalise() { - $last_call = end($this->calls); - $this->writeCall(array('quote_end',array(), $last_call[2])); - - $this->process(); - $this->CallWriter->finalise(); - unset($this->CallWriter); - } - - function process() { - - $quoteDepth = 1; - - foreach ( $this->calls as $call ) { - switch ($call[0]) { - - case 'quote_start': - - $this->quoteCalls[] = array('quote_open',array(),$call[2]); - - case 'quote_newline': - - $quoteLength = $this->getDepth($call[1][0]); - - if ( $quoteLength > $quoteDepth ) { - $quoteDiff = $quoteLength - $quoteDepth; - for ( $i = 1; $i <= $quoteDiff; $i++ ) { - $this->quoteCalls[] = array('quote_open',array(),$call[2]); - } - } else if ( $quoteLength < $quoteDepth ) { - $quoteDiff = $quoteDepth - $quoteLength; - for ( $i = 1; $i <= $quoteDiff; $i++ ) { - $this->quoteCalls[] = array('quote_close',array(),$call[2]); - } - } else { - if ($call[0] != 'quote_start') $this->quoteCalls[] = array('linebreak',array(),$call[2]); - } - - $quoteDepth = $quoteLength; - - break; - - case 'quote_end': - - if ( $quoteDepth > 1 ) { - $quoteDiff = $quoteDepth - 1; - for ( $i = 1; $i <= $quoteDiff; $i++ ) { - $this->quoteCalls[] = array('quote_close',array(),$call[2]); - } - } - - $this->quoteCalls[] = array('quote_close',array(),$call[2]); - - $this->CallWriter->writeCalls($this->quoteCalls); - break; - - default: - $this->quoteCalls[] = $call; - break; - } - } - } - - function getDepth($marker) { - preg_match('/>{1,}/', $marker, $matches); - $quoteLength = strlen($matches[0]); - return $quoteLength; - } -} - -//------------------------------------------------------------------------ -class Doku_Handler_Table implements Doku_Handler_CallWriter_Interface { - - var $CallWriter; - - var $calls = array(); - var $tableCalls = array(); - var $maxCols = 0; - var $maxRows = 1; - var $currentCols = 0; - var $firstCell = false; - var $lastCellType = 'tablecell'; - var $inTableHead = true; - var $currentRow = array('tableheader' => 0, 'tablecell' => 0); - var $countTableHeadRows = 0; - - function __construct(Doku_Handler_CallWriter_Interface $CallWriter) { - $this->CallWriter = $CallWriter; - } - - function writeCall($call) { - $this->calls[] = $call; - } - - // Probably not needed but just in case... - function writeCalls($calls) { - $this->calls = array_merge($this->calls, $calls); - } - - function finalise() { - $last_call = end($this->calls); - $this->writeCall(array('table_end',array(), $last_call[2])); - - $this->process(); - $this->CallWriter->finalise(); - unset($this->CallWriter); - } - - //------------------------------------------------------------------------ - function process() { - foreach ( $this->calls as $call ) { - switch ( $call[0] ) { - case 'table_start': - $this->tableStart($call); - break; - case 'table_row': - $this->tableRowClose($call); - $this->tableRowOpen(array('tablerow_open',$call[1],$call[2])); - break; - case 'tableheader': - case 'tablecell': - $this->tableCell($call); - break; - case 'table_end': - $this->tableRowClose($call); - $this->tableEnd($call); - break; - default: - $this->tableDefault($call); - break; - } - } - $this->CallWriter->writeCalls($this->tableCalls); - } - - function tableStart($call) { - $this->tableCalls[] = array('table_open',$call[1],$call[2]); - $this->tableCalls[] = array('tablerow_open',array(),$call[2]); - $this->firstCell = true; - } - - function tableEnd($call) { - $this->tableCalls[] = array('table_close',$call[1],$call[2]); - $this->finalizeTable(); - } - - function tableRowOpen($call) { - $this->tableCalls[] = $call; - $this->currentCols = 0; - $this->firstCell = true; - $this->lastCellType = 'tablecell'; - $this->maxRows++; - if ($this->inTableHead) { - $this->currentRow = array('tablecell' => 0, 'tableheader' => 0); - } - } - - function tableRowClose($call) { - if ($this->inTableHead && ($this->inTableHead = $this->isTableHeadRow())) { - $this->countTableHeadRows++; - } - // Strip off final cell opening and anything after it - while ( $discard = array_pop($this->tableCalls ) ) { - - if ( $discard[0] == 'tablecell_open' || $discard[0] == 'tableheader_open') { - break; - } - if (!empty($this->currentRow[$discard[0]])) { - $this->currentRow[$discard[0]]--; - } - } - $this->tableCalls[] = array('tablerow_close', array(), $call[2]); - - if ( $this->currentCols > $this->maxCols ) { - $this->maxCols = $this->currentCols; - } - } - - function isTableHeadRow() { - $td = $this->currentRow['tablecell']; - $th = $this->currentRow['tableheader']; - - if (!$th || $td > 2) return false; - if (2*$td > $th) return false; - - return true; - } - - function tableCell($call) { - if ($this->inTableHead) { - $this->currentRow[$call[0]]++; - } - if ( !$this->firstCell ) { - - // Increase the span - $lastCall = end($this->tableCalls); - - // A cell call which follows an open cell means an empty cell so span - if ( $lastCall[0] == 'tablecell_open' || $lastCall[0] == 'tableheader_open' ) { - $this->tableCalls[] = array('colspan',array(),$call[2]); - - } - - $this->tableCalls[] = array($this->lastCellType.'_close',array(),$call[2]); - $this->tableCalls[] = array($call[0].'_open',array(1,null,1),$call[2]); - $this->lastCellType = $call[0]; - - } else { - - $this->tableCalls[] = array($call[0].'_open',array(1,null,1),$call[2]); - $this->lastCellType = $call[0]; - $this->firstCell = false; - - } - - $this->currentCols++; - } - - function tableDefault($call) { - $this->tableCalls[] = $call; - } - - function finalizeTable() { - - // Add the max cols and rows to the table opening - if ( $this->tableCalls[0][0] == 'table_open' ) { - // Adjust to num cols not num col delimeters - $this->tableCalls[0][1][] = $this->maxCols - 1; - $this->tableCalls[0][1][] = $this->maxRows; - $this->tableCalls[0][1][] = array_shift($this->tableCalls[0][1]); - } else { - trigger_error('First element in table call list is not table_open'); - } - - $lastRow = 0; - $lastCell = 0; - $cellKey = array(); - $toDelete = array(); - - // if still in tableheader, then there can be no table header - // as all rows can't be within <THEAD> - if ($this->inTableHead) { - $this->inTableHead = false; - $this->countTableHeadRows = 0; - } - - // Look for the colspan elements and increment the colspan on the - // previous non-empty opening cell. Once done, delete all the cells - // that contain colspans - for ($key = 0 ; $key < count($this->tableCalls) ; ++$key) { - $call = $this->tableCalls[$key]; - - switch ($call[0]) { - case 'table_open' : - if($this->countTableHeadRows) { - array_splice($this->tableCalls, $key+1, 0, array( - array('tablethead_open', array(), $call[2])) - ); - } - break; - - case 'tablerow_open': - - $lastRow++; - $lastCell = 0; - break; - - case 'tablecell_open': - case 'tableheader_open': - - $lastCell++; - $cellKey[$lastRow][$lastCell] = $key; - break; - - case 'table_align': - - $prev = in_array($this->tableCalls[$key-1][0], array('tablecell_open', 'tableheader_open')); - $next = in_array($this->tableCalls[$key+1][0], array('tablecell_close', 'tableheader_close')); - // If the cell is empty, align left - if ($prev && $next) { - $this->tableCalls[$key-1][1][1] = 'left'; - - // If the previous element was a cell open, align right - } elseif ($prev) { - $this->tableCalls[$key-1][1][1] = 'right'; - - // If the next element is the close of an element, align either center or left - } elseif ( $next) { - if ( $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] == 'right' ) { - $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'center'; - } else { - $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'left'; - } - - } - - // Now convert the whitespace back to cdata - $this->tableCalls[$key][0] = 'cdata'; - break; - - case 'colspan': - - $this->tableCalls[$key-1][1][0] = false; - - for($i = $key-2; $i >= $cellKey[$lastRow][1]; $i--) { - - if ( $this->tableCalls[$i][0] == 'tablecell_open' || $this->tableCalls[$i][0] == 'tableheader_open' ) { - - if ( false !== $this->tableCalls[$i][1][0] ) { - $this->tableCalls[$i][1][0]++; - break; - } - - } - } - - $toDelete[] = $key-1; - $toDelete[] = $key; - $toDelete[] = $key+1; - break; - - case 'rowspan': - - if ( $this->tableCalls[$key-1][0] == 'cdata' ) { - // ignore rowspan if previous call was cdata (text mixed with :::) we don't have to check next call as that wont match regex - $this->tableCalls[$key][0] = 'cdata'; - - } else { - - $spanning_cell = null; - - // can't cross thead/tbody boundary - if (!$this->countTableHeadRows || ($lastRow-1 != $this->countTableHeadRows)) { - for($i = $lastRow-1; $i > 0; $i--) { - - if ( $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tablecell_open' || $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tableheader_open' ) { - - if ($this->tableCalls[$cellKey[$i][$lastCell]][1][2] >= $lastRow - $i) { - $spanning_cell = $i; - break; - } - - } - } - } - if (is_null($spanning_cell)) { - // No spanning cell found, so convert this cell to - // an empty one to avoid broken tables - $this->tableCalls[$key][0] = 'cdata'; - $this->tableCalls[$key][1][0] = ''; - continue; - } - $this->tableCalls[$cellKey[$spanning_cell][$lastCell]][1][2]++; - - $this->tableCalls[$key-1][1][2] = false; - - $toDelete[] = $key-1; - $toDelete[] = $key; - $toDelete[] = $key+1; - } - break; - - case 'tablerow_close': - - // Fix broken tables by adding missing cells - $moreCalls = array(); - while (++$lastCell < $this->maxCols) { - $moreCalls[] = array('tablecell_open', array(1, null, 1), $call[2]); - $moreCalls[] = array('cdata', array(''), $call[2]); - $moreCalls[] = array('tablecell_close', array(), $call[2]); - } - $moreCallsLength = count($moreCalls); - if($moreCallsLength) { - array_splice($this->tableCalls, $key, 0, $moreCalls); - $key += $moreCallsLength; - } - - if($this->countTableHeadRows == $lastRow) { - array_splice($this->tableCalls, $key+1, 0, array( - array('tablethead_close', array(), $call[2]))); - } - break; - - } - } - - // condense cdata - $cnt = count($this->tableCalls); - for( $key = 0; $key < $cnt; $key++){ - if($this->tableCalls[$key][0] == 'cdata'){ - $ckey = $key; - $key++; - while($this->tableCalls[$key][0] == 'cdata'){ - $this->tableCalls[$ckey][1][0] .= $this->tableCalls[$key][1][0]; - $toDelete[] = $key; - $key++; - } - continue; - } - } - - foreach ( $toDelete as $delete ) { - unset($this->tableCalls[$delete]); - } - $this->tableCalls = array_values($this->tableCalls); - } -} - - -/** - * Handler for paragraphs - * - * @author Harry Fuecks <hfuecks@gmail.com> - */ -class Doku_Handler_Block { - var $calls = array(); - var $skipEol = false; - var $inParagraph = false; - - // Blocks these should not be inside paragraphs - var $blockOpen = array( - 'header', - 'listu_open','listo_open','listitem_open','listcontent_open', - 'table_open','tablerow_open','tablecell_open','tableheader_open','tablethead_open', - 'quote_open', - 'code','file','hr','preformatted','rss', - 'htmlblock','phpblock', - 'footnote_open', - ); - - var $blockClose = array( - 'header', - 'listu_close','listo_close','listitem_close','listcontent_close', - 'table_close','tablerow_close','tablecell_close','tableheader_close','tablethead_close', - 'quote_close', - 'code','file','hr','preformatted','rss', - 'htmlblock','phpblock', - 'footnote_close', - ); - - // Stacks can contain paragraphs - var $stackOpen = array( - 'section_open', - ); - - var $stackClose = array( - 'section_close', - ); - - - /** - * Constructor. Adds loaded syntax plugins to the block and stack - * arrays - * - * @author Andreas Gohr <andi@splitbrain.org> - */ - function __construct(){ - global $DOKU_PLUGINS; - //check if syntax plugins were loaded - if(empty($DOKU_PLUGINS['syntax'])) return; - foreach($DOKU_PLUGINS['syntax'] as $n => $p){ - $ptype = $p->getPType(); - if($ptype == 'block'){ - $this->blockOpen[] = 'plugin_'.$n; - $this->blockClose[] = 'plugin_'.$n; - }elseif($ptype == 'stack'){ - $this->stackOpen[] = 'plugin_'.$n; - $this->stackClose[] = 'plugin_'.$n; - } - } - } - - function openParagraph($pos){ - if ($this->inParagraph) return; - $this->calls[] = array('p_open',array(), $pos); - $this->inParagraph = true; - $this->skipEol = true; - } - - /** - * Close a paragraph if needed - * - * This function makes sure there are no empty paragraphs on the stack - * - * @author Andreas Gohr <andi@splitbrain.org> - * - * @param string|integer $pos - */ - function closeParagraph($pos){ - if (!$this->inParagraph) return; - // look back if there was any content - we don't want empty paragraphs - $content = ''; - $ccount = count($this->calls); - for($i=$ccount-1; $i>=0; $i--){ - if($this->calls[$i][0] == 'p_open'){ - break; - }elseif($this->calls[$i][0] == 'cdata'){ - $content .= $this->calls[$i][1][0]; - }else{ - $content = 'found markup'; - break; - } - } - - if(trim($content)==''){ - //remove the whole paragraph - //array_splice($this->calls,$i); // <- this is much slower than the loop below - for($x=$ccount; $x>$i; $x--) array_pop($this->calls); - }else{ - // remove ending linebreaks in the paragraph - $i=count($this->calls)-1; - if ($this->calls[$i][0] == 'cdata') $this->calls[$i][1][0] = rtrim($this->calls[$i][1][0],DOKU_PARSER_EOL); - $this->calls[] = array('p_close',array(), $pos); - } - - $this->inParagraph = false; - $this->skipEol = true; - } - - function addCall($call) { - $key = count($this->calls); - if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) { - $this->calls[$key-1][1][0] .= $call[1][0]; - } else { - $this->calls[] = $call; - } - } - - // simple version of addCall, without checking cdata - function storeCall($call) { - $this->calls[] = $call; - } - - /** - * Processes the whole instruction stack to open and close paragraphs - * - * @author Harry Fuecks <hfuecks@gmail.com> - * @author Andreas Gohr <andi@splitbrain.org> - * - * @param array $calls - * - * @return array - */ - function process($calls) { - // open first paragraph - $this->openParagraph(0); - foreach ( $calls as $key => $call ) { - $cname = $call[0]; - if ($cname == 'plugin') { - $cname='plugin_'.$call[1][0]; - $plugin = true; - $plugin_open = (($call[1][2] == DOKU_LEXER_ENTER) || ($call[1][2] == DOKU_LEXER_SPECIAL)); - $plugin_close = (($call[1][2] == DOKU_LEXER_EXIT) || ($call[1][2] == DOKU_LEXER_SPECIAL)); - } else { - $plugin = false; - } - /* stack */ - if ( in_array($cname,$this->stackClose ) && (!$plugin || $plugin_close)) { - $this->closeParagraph($call[2]); - $this->storeCall($call); - $this->openParagraph($call[2]); - continue; - } - if ( in_array($cname,$this->stackOpen ) && (!$plugin || $plugin_open) ) { - $this->closeParagraph($call[2]); - $this->storeCall($call); - $this->openParagraph($call[2]); - continue; - } - /* block */ - // If it's a substition it opens and closes at the same call. - // To make sure next paragraph is correctly started, let close go first. - if ( in_array($cname, $this->blockClose) && (!$plugin || $plugin_close)) { - $this->closeParagraph($call[2]); - $this->storeCall($call); - $this->openParagraph($call[2]); - continue; - } - if ( in_array($cname, $this->blockOpen) && (!$plugin || $plugin_open)) { - $this->closeParagraph($call[2]); - $this->storeCall($call); - continue; - } - /* eol */ - if ( $cname == 'eol' ) { - // Check this isn't an eol instruction to skip... - if ( !$this->skipEol ) { - // Next is EOL => double eol => mark as paragraph - if ( isset($calls[$key+1]) && $calls[$key+1][0] == 'eol' ) { - $this->closeParagraph($call[2]); - $this->openParagraph($call[2]); - } else { - //if this is just a single eol make a space from it - $this->addCall(array('cdata',array(DOKU_PARSER_EOL), $call[2])); - } - } - continue; - } - /* normal */ - $this->addCall($call); - $this->skipEol = false; - } - // close last paragraph - $call = end($this->calls); - $this->closeParagraph($call[2]); - return $this->calls; - } -} - -//Setup VIM: ex: et ts=4 : diff --git a/inc/parser/lexer.php b/inc/parser/lexer.php deleted file mode 100644 index ba6a65397..000000000 --- a/inc/parser/lexer.php +++ /dev/null @@ -1,614 +0,0 @@ -<?php -/** - * Author Markus Baker: http://www.lastcraft.com - * Version adapted from Simple Test: http://sourceforge.net/projects/simpletest/ - * For an intro to the Lexer see: - * https://web.archive.org/web/20120125041816/http://www.phppatterns.com/docs/develop/simple_test_lexer_notes - * @author Marcus Baker - * @package Doku - * @subpackage Lexer - * @version $Id: lexer.php,v 1.1 2005/03/23 23:14:09 harryf Exp $ - */ - -/** - * Init path constant - */ -if(!defined('DOKU_INC')) die('meh.'); - -/**#@+ - * lexer mode constant - */ -define("DOKU_LEXER_ENTER", 1); -define("DOKU_LEXER_MATCHED", 2); -define("DOKU_LEXER_UNMATCHED", 3); -define("DOKU_LEXER_EXIT", 4); -define("DOKU_LEXER_SPECIAL", 5); -/**#@-*/ - -/** - * Compounded regular expression. Any of - * the contained patterns could match and - * when one does it's label is returned. - * - * @package Doku - * @subpackage Lexer - */ -class Doku_LexerParallelRegex { - var $_patterns; - var $_labels; - var $_regex; - var $_case; - - /** - * Constructor. Starts with no patterns. - * - * @param boolean $case True for case sensitive, false - * for insensitive. - * @access public - */ - function __construct($case) { - $this->_case = $case; - $this->_patterns = array(); - $this->_labels = array(); - $this->_regex = null; - } - - /** - * Adds a pattern with an optional label. - * - * @param mixed $pattern Perl style regex. Must be UTF-8 - * encoded. If its a string, the (, ) - * lose their meaning unless they - * form part of a lookahead or - * lookbehind assertation. - * @param bool|string $label Label of regex to be returned - * on a match. Label must be ASCII - * @access public - */ - function addPattern($pattern, $label = true) { - $count = count($this->_patterns); - $this->_patterns[$count] = $pattern; - $this->_labels[$count] = $label; - $this->_regex = null; - } - - /** - * Attempts to match all patterns at once against a string. - * - * @param string $subject String to match against. - * @param string $match First matched portion of - * subject. - * @return boolean True on success. - * @access public - */ - function match($subject, &$match) { - if (count($this->_patterns) == 0) { - return false; - } - if (! preg_match($this->_getCompoundedRegex(), $subject, $matches)) { - $match = ""; - return false; - } - - $match = $matches[0]; - $size = count($matches); - for ($i = 1; $i < $size; $i++) { - if ($matches[$i] && isset($this->_labels[$i - 1])) { - return $this->_labels[$i - 1]; - } - } - return true; - } - - /** - * Attempts to split the string against all patterns at once - * - * @param string $subject String to match against. - * @param array $split The split result: array containing, pre-match, match & post-match strings - * @return boolean True on success. - * @access public - * - * @author Christopher Smith <chris@jalakai.co.uk> - */ - function split($subject, &$split) { - if (count($this->_patterns) == 0) { - return false; - } - - if (! preg_match($this->_getCompoundedRegex(), $subject, $matches)) { - if(function_exists('preg_last_error')){ - $err = preg_last_error(); - switch($err){ - case PREG_BACKTRACK_LIMIT_ERROR: - msg('A PCRE backtrack error occured. Try to increase the pcre.backtrack_limit in php.ini',-1); - break; - case PREG_RECURSION_LIMIT_ERROR: - msg('A PCRE recursion error occured. Try to increase the pcre.recursion_limit in php.ini',-1); - break; - case PREG_BAD_UTF8_ERROR: - msg('A PCRE UTF-8 error occured. This might be caused by a faulty plugin',-1); - break; - case PREG_INTERNAL_ERROR: - msg('A PCRE internal error occured. This might be caused by a faulty plugin',-1); - break; - } - } - - $split = array($subject, "", ""); - return false; - } - - $idx = count($matches)-2; - list($pre, $post) = preg_split($this->_patterns[$idx].$this->_getPerlMatchingFlags(), $subject, 2); - $split = array($pre, $matches[0], $post); - - return isset($this->_labels[$idx]) ? $this->_labels[$idx] : true; - } - - /** - * Compounds the patterns into a single - * regular expression separated with the - * "or" operator. Caches the regex. - * Will automatically escape (, ) and / tokens. - * - * @internal array $_patterns List of patterns in order. - * @return null|string - * @access private - */ - function _getCompoundedRegex() { - if ($this->_regex == null) { - $cnt = count($this->_patterns); - for ($i = 0; $i < $cnt; $i++) { - - /* - * decompose the input pattern into "(", "(?", ")", - * "[...]", "[]..]", "[^]..]", "[...[:...:]..]", "\x"... - * elements. - */ - preg_match_all('/\\\\.|' . - '\(\?|' . - '[()]|' . - '\[\^?\]?(?:\\\\.|\[:[^]]*:\]|[^]\\\\])*\]|' . - '[^[()\\\\]+/', $this->_patterns[$i], $elts); - - $pattern = ""; - $level = 0; - - foreach ($elts[0] as $elt) { - /* - * for "(", ")" remember the nesting level, add "\" - * only to the non-"(?" ones. - */ - - switch($elt) { - case '(': - $pattern .= '\('; - break; - case ')': - if ($level > 0) - $level--; /* closing (? */ - else - $pattern .= '\\'; - $pattern .= ')'; - break; - case '(?': - $level++; - $pattern .= '(?'; - break; - default: - if (substr($elt, 0, 1) == '\\') - $pattern .= $elt; - else - $pattern .= str_replace('/', '\/', $elt); - } - } - $this->_patterns[$i] = "($pattern)"; - } - $this->_regex = "/" . implode("|", $this->_patterns) . "/" . $this->_getPerlMatchingFlags(); - } - return $this->_regex; - } - - /** - * Accessor for perl regex mode flags to use. - * @return string Perl regex flags. - * @access private - */ - function _getPerlMatchingFlags() { - return ($this->_case ? "msS" : "msSi"); - } -} - -/** - * States for a stack machine. - * @package Lexer - * @subpackage Lexer - */ -class Doku_LexerStateStack { - var $_stack; - - /** - * Constructor. Starts in named state. - * @param string $start Starting state name. - * @access public - */ - function __construct($start) { - $this->_stack = array($start); - } - - /** - * Accessor for current state. - * @return string State. - * @access public - */ - function getCurrent() { - return $this->_stack[count($this->_stack) - 1]; - } - - /** - * Adds a state to the stack and sets it - * to be the current state. - * @param string $state New state. - * @access public - */ - function enter($state) { - array_push($this->_stack, $state); - } - - /** - * Leaves the current state and reverts - * to the previous one. - * @return boolean False if we drop off - * the bottom of the list. - * @access public - */ - function leave() { - if (count($this->_stack) == 1) { - return false; - } - array_pop($this->_stack); - return true; - } -} - -/** - * Accepts text and breaks it into tokens. - * Some optimisation to make the sure the - * content is only scanned by the PHP regex - * parser once. Lexer modes must not start - * with leading underscores. - * @package Doku - * @subpackage Lexer - */ -class Doku_Lexer { - var $_regexes; - var $_parser; - var $_mode; - var $_mode_handlers; - var $_case; - - /** - * Sets up the lexer in case insensitive matching - * by default. - * @param Doku_Parser $parser Handling strategy by - * reference. - * @param string $start Starting handler. - * @param boolean $case True for case sensitive. - * @access public - */ - function __construct($parser, $start = "accept", $case = false) { - $this->_case = $case; - /** @var Doku_LexerParallelRegex[] _regexes */ - $this->_regexes = array(); - $this->_parser = $parser; - $this->_mode = new Doku_LexerStateStack($start); - $this->_mode_handlers = array(); - } - - /** - * Adds a token search pattern for a particular - * parsing mode. The pattern does not change the - * current mode. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @access public - */ - function addPattern($pattern, $mode = "accept") { - if (! isset($this->_regexes[$mode])) { - $this->_regexes[$mode] = new Doku_LexerParallelRegex($this->_case); - } - $this->_regexes[$mode]->addPattern($pattern); - } - - /** - * Adds a pattern that will enter a new parsing - * mode. Useful for entering parenthesis, strings, - * tags, etc. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @param string $new_mode Change parsing to this new - * nested mode. - * @access public - */ - function addEntryPattern($pattern, $mode, $new_mode) { - if (! isset($this->_regexes[$mode])) { - $this->_regexes[$mode] = new Doku_LexerParallelRegex($this->_case); - } - $this->_regexes[$mode]->addPattern($pattern, $new_mode); - } - - /** - * Adds a pattern that will exit the current mode - * and re-enter the previous one. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Mode to leave. - * @access public - */ - function addExitPattern($pattern, $mode) { - if (! isset($this->_regexes[$mode])) { - $this->_regexes[$mode] = new Doku_LexerParallelRegex($this->_case); - } - $this->_regexes[$mode]->addPattern($pattern, "__exit"); - } - - /** - * Adds a pattern that has a special mode. Acts as an entry - * and exit pattern in one go, effectively calling a special - * parser handler for this token only. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @param string $special Use this mode for this one token. - * @access public - */ - function addSpecialPattern($pattern, $mode, $special) { - if (! isset($this->_regexes[$mode])) { - $this->_regexes[$mode] = new Doku_LexerParallelRegex($this->_case); - } - $this->_regexes[$mode]->addPattern($pattern, "_$special"); - } - - /** - * Adds a mapping from a mode to another handler. - * @param string $mode Mode to be remapped. - * @param string $handler New target handler. - * @access public - */ - function mapHandler($mode, $handler) { - $this->_mode_handlers[$mode] = $handler; - } - - /** - * Splits the page text into tokens. Will fail - * if the handlers report an error or if no - * content is consumed. If successful then each - * unparsed and parsed token invokes a call to the - * held listener. - * @param string $raw Raw HTML text. - * @return boolean True on success, else false. - * @access public - */ - function parse($raw) { - if (! isset($this->_parser)) { - return false; - } - $initialLength = strlen($raw); - $length = $initialLength; - $pos = 0; - while (is_array($parsed = $this->_reduce($raw))) { - list($unmatched, $matched, $mode) = $parsed; - $currentLength = strlen($raw); - $matchPos = $initialLength - $currentLength - strlen($matched); - if (! $this->_dispatchTokens($unmatched, $matched, $mode, $pos, $matchPos)) { - return false; - } - if ($currentLength == $length) { - return false; - } - $length = $currentLength; - $pos = $initialLength - $currentLength; - } - if (!$parsed) { - return false; - } - return $this->_invokeParser($raw, DOKU_LEXER_UNMATCHED, $pos); - } - - /** - * Sends the matched token and any leading unmatched - * text to the parser changing the lexer to a new - * mode if one is listed. - * @param string $unmatched Unmatched leading portion. - * @param string $matched Actual token match. - * @param bool|string $mode Mode after match. A boolean - * false mode causes no change. - * @param int $initialPos - * @param int $matchPos - * Current byte index location in raw doc - * thats being parsed - * @return boolean False if there was any error - * from the parser. - * @access private - */ - function _dispatchTokens($unmatched, $matched, $mode = false, $initialPos, $matchPos) { - if (! $this->_invokeParser($unmatched, DOKU_LEXER_UNMATCHED, $initialPos) ){ - return false; - } - if ($this->_isModeEnd($mode)) { - if (! $this->_invokeParser($matched, DOKU_LEXER_EXIT, $matchPos)) { - return false; - } - return $this->_mode->leave(); - } - if ($this->_isSpecialMode($mode)) { - $this->_mode->enter($this->_decodeSpecial($mode)); - if (! $this->_invokeParser($matched, DOKU_LEXER_SPECIAL, $matchPos)) { - return false; - } - return $this->_mode->leave(); - } - if (is_string($mode)) { - $this->_mode->enter($mode); - return $this->_invokeParser($matched, DOKU_LEXER_ENTER, $matchPos); - } - return $this->_invokeParser($matched, DOKU_LEXER_MATCHED, $matchPos); - } - - /** - * Tests to see if the new mode is actually to leave - * the current mode and pop an item from the matching - * mode stack. - * @param string $mode Mode to test. - * @return boolean True if this is the exit mode. - * @access private - */ - function _isModeEnd($mode) { - return ($mode === "__exit"); - } - - /** - * Test to see if the mode is one where this mode - * is entered for this token only and automatically - * leaves immediately afterwoods. - * @param string $mode Mode to test. - * @return boolean True if this is the exit mode. - * @access private - */ - function _isSpecialMode($mode) { - return (strncmp($mode, "_", 1) == 0); - } - - /** - * Strips the magic underscore marking single token - * modes. - * @param string $mode Mode to decode. - * @return string Underlying mode name. - * @access private - */ - function _decodeSpecial($mode) { - return substr($mode, 1); - } - - /** - * Calls the parser method named after the current - * mode. Empty content will be ignored. The lexer - * has a parser handler for each mode in the lexer. - * @param string $content Text parsed. - * @param boolean $is_match Token is recognised rather - * than unparsed data. - * @param int $pos Current byte index location in raw doc - * thats being parsed - * @return bool - * @access private - */ - function _invokeParser($content, $is_match, $pos) { - if (($content === "") || ($content === false)) { - return true; - } - $handler = $this->_mode->getCurrent(); - if (isset($this->_mode_handlers[$handler])) { - $handler = $this->_mode_handlers[$handler]; - } - - // modes starting with plugin_ are all handled by the same - // handler but with an additional parameter - if(substr($handler,0,7)=='plugin_'){ - list($handler,$plugin) = explode('_',$handler,2); - return $this->_parser->$handler($content, $is_match, $pos, $plugin); - } - - return $this->_parser->$handler($content, $is_match, $pos); - } - - /** - * Tries to match a chunk of text and if successful - * removes the recognised chunk and any leading - * unparsed data. Empty strings will not be matched. - * @param string $raw The subject to parse. This is the - * content that will be eaten. - * @return array Three item list of unparsed - * content followed by the - * recognised token and finally the - * action the parser is to take. - * True if no match, false if there - * is a parsing error. - * @access private - */ - function _reduce(&$raw) { - if (! isset($this->_regexes[$this->_mode->getCurrent()])) { - return false; - } - if ($raw === "") { - return true; - } - if ($action = $this->_regexes[$this->_mode->getCurrent()]->split($raw, $split)) { - list($unparsed, $match, $raw) = $split; - return array($unparsed, $match, $action); - } - return true; - } -} - -/** - * Escapes regex characters other than (, ) and / - * - * @TODO - * - * @param string $str - * - * @return mixed - */ -function Doku_Lexer_Escape($str) { - //$str = addslashes($str); - $chars = array( - '/\\\\/', - '/\./', - '/\+/', - '/\*/', - '/\?/', - '/\[/', - '/\^/', - '/\]/', - '/\$/', - '/\{/', - '/\}/', - '/\=/', - '/\!/', - '/\</', - '/\>/', - '/\|/', - '/\:/' - ); - - $escaped = array( - '\\\\\\\\', - '\.', - '\+', - '\*', - '\?', - '\[', - '\^', - '\]', - '\$', - '\{', - '\}', - '\=', - '\!', - '\<', - '\>', - '\|', - '\:' - ); - return preg_replace($chars, $escaped, $str); -} - -//Setup VIM: ex: et ts=4 sw=4 : diff --git a/inc/parser/metadata.php b/inc/parser/metadata.php index f9e05bd81..5af7b0215 100644 --- a/inc/parser/metadata.php +++ b/inc/parser/metadata.php @@ -1,22 +1,5 @@ <?php /** - * Renderer for metadata - * - * @author Esther Brunner <wikidesign@gmail.com> - */ -if(!defined('DOKU_INC')) die('meh.'); - -if(!defined('DOKU_LF')) { - // Some whitespace to help View > Source - define ('DOKU_LF', "\n"); -} - -if(!defined('DOKU_TAB')) { - // Some whitespace to help View > Source - define ('DOKU_TAB', "\t"); -} - -/** * The MetaData Renderer * * Metadata is additional information about a DokuWiki page that gets extracted mainly from the page's content @@ -24,6 +7,8 @@ if(!defined('DOKU_TAB')) { * $persistent. * * Some simplified rendering to $doc is done to gather the page's (text-only) abstract. + * + * @author Esther Brunner <wikidesign@gmail.com> */ class Doku_Renderer_metadata extends Doku_Renderer { /** the approximate byte lenght to capture for the abstract */ @@ -61,7 +46,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @return string always 'metadata' */ - function getFormat() { + public function getFormat() { return 'metadata'; } @@ -70,7 +55,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * Sets up some of the persistent info about the page if it doesn't exist, yet. */ - function document_start() { + public function document_start() { global $ID; $this->headers = array(); @@ -94,7 +79,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * Stores collected data in the metadata */ - function document_end() { + public function document_end() { global $ID; // store internal info in metadata (notoc,nocache) @@ -141,7 +126,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $text the text to display * @param int $level the nesting level */ - function toc_additem($id, $text, $level) { + public function toc_additem($id, $text, $level) { global $conf; //only add items within configured levels @@ -164,7 +149,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param int $level header level * @param int $pos byte position in the original source */ - function header($text, $level, $pos) { + public function header($text, $level, $pos) { if(!isset($this->meta['title'])) $this->meta['title'] = $text; // add the header to the TOC @@ -178,28 +163,28 @@ class Doku_Renderer_metadata extends Doku_Renderer { /** * Open a paragraph */ - function p_open() { + public function p_open() { $this->cdata(DOKU_LF); } /** * Close a paragraph */ - function p_close() { + public function p_close() { $this->cdata(DOKU_LF); } /** * Create a line break */ - function linebreak() { + public function linebreak() { $this->cdata(DOKU_LF); } /** * Create a horizontal line */ - function hr() { + public function hr() { $this->cdata(DOKU_LF.'----------'.DOKU_LF); } @@ -212,7 +197,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @author Andreas Gohr <andi@splitbrain.org> */ - function footnote_open() { + public function footnote_open() { if($this->capture) { // move current content to store // this is required to ensure safe behaviour of plugins accessed within footnotes @@ -232,7 +217,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @author Andreas Gohr */ - function footnote_close() { + public function footnote_close() { if($this->capture) { // re-enable capturing $this->capturing = true; @@ -245,14 +230,14 @@ class Doku_Renderer_metadata extends Doku_Renderer { /** * Open an unordered list */ - function listu_open() { + public function listu_open() { $this->cdata(DOKU_LF); } /** * Open an ordered list */ - function listo_open() { + public function listo_open() { $this->cdata(DOKU_LF); } @@ -262,14 +247,14 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param int $level the nesting level * @param bool $node true when a node; false when a leaf */ - function listitem_open($level,$node=false) { + public function listitem_open($level,$node=false) { $this->cdata(str_repeat(DOKU_TAB, $level).'* '); } /** * Close a list item */ - function listitem_close() { + public function listitem_close() { $this->cdata(DOKU_LF); } @@ -278,21 +263,21 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @param string $text */ - function preformatted($text) { + public function preformatted($text) { $this->cdata($text); } /** * Start a block quote */ - function quote_open() { + public function quote_open() { $this->cdata(DOKU_LF.DOKU_TAB.'"'); } /** * Stop a block quote */ - function quote_close() { + public function quote_close() { $this->cdata('"'.DOKU_LF); } @@ -303,7 +288,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $lang programming language to use for syntax highlighting * @param string $file file path label */ - function file($text, $lang = null, $file = null) { + public function file($text, $lang = null, $file = null) { $this->cdata(DOKU_LF.$text.DOKU_LF); } @@ -314,7 +299,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $language programming language to use for syntax highlighting * @param string $file file path label */ - function code($text, $language = null, $file = null) { + public function code($text, $language = null, $file = null) { $this->cdata(DOKU_LF.$text.DOKU_LF); } @@ -325,7 +310,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @param string $acronym */ - function acronym($acronym) { + public function acronym($acronym) { $this->cdata($acronym); } @@ -336,7 +321,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @param string $smiley */ - function smiley($smiley) { + public function smiley($smiley) { $this->cdata($smiley); } @@ -349,7 +334,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @param string $entity */ - function entity($entity) { + public function entity($entity) { $this->cdata($entity); } @@ -361,14 +346,14 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string|int $x first value * @param string|int $y second value */ - function multiplyentity($x, $y) { + public function multiplyentity($x, $y) { $this->cdata($x.'×'.$y); } /** * Render an opening single quote char (language specific) */ - function singlequoteopening() { + public function singlequoteopening() { global $lang; $this->cdata($lang['singlequoteopening']); } @@ -376,7 +361,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { /** * Render a closing single quote char (language specific) */ - function singlequoteclosing() { + public function singlequoteclosing() { global $lang; $this->cdata($lang['singlequoteclosing']); } @@ -384,7 +369,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { /** * Render an apostrophe char (language specific) */ - function apostrophe() { + public function apostrophe() { global $lang; $this->cdata($lang['apostrophe']); } @@ -392,7 +377,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { /** * Render an opening double quote char (language specific) */ - function doublequoteopening() { + public function doublequoteopening() { global $lang; $this->cdata($lang['doublequoteopening']); } @@ -400,7 +385,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { /** * Render an closinging double quote char (language specific) */ - function doublequoteclosing() { + public function doublequoteclosing() { global $lang; $this->cdata($lang['doublequoteclosing']); } @@ -411,7 +396,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $link The link name * @see http://en.wikipedia.org/wiki/CamelCase */ - function camelcaselink($link) { + public function camelcaselink($link) { $this->internallink($link, $link); } @@ -421,7 +406,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $hash hash link identifier * @param string $name name for the link */ - function locallink($hash, $name = null) { + public function locallink($hash, $name = null) { if(is_array($name)) { $this->_firstimage($name['src']); if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']); @@ -434,7 +419,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $id page ID to link to. eg. 'wiki:syntax' * @param string|array|null $name name for the link, array for media file */ - function internallink($id, $name = null) { + public function internallink($id, $name = null) { global $ID; if(is_array($name)) { @@ -471,7 +456,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $url full URL with scheme * @param string|array|null $name name for the link, array for media file */ - function externallink($url, $name = null) { + public function externallink($url, $name = null) { if(is_array($name)) { $this->_firstimage($name['src']); if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']); @@ -492,7 +477,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $wikiName indentifier (shortcut) for the remote wiki * @param string $wikiUri the fragment parsed from the original link */ - function interwikilink($match, $name = null, $wikiName, $wikiUri) { + public function interwikilink($match, $name, $wikiName, $wikiUri) { if(is_array($name)) { $this->_firstimage($name['src']); if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']); @@ -511,7 +496,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $url the link * @param string|array $name name for the link, array for media file */ - function windowssharelink($url, $name = null) { + public function windowssharelink($url, $name = null) { if(is_array($name)) { $this->_firstimage($name['src']); if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']); @@ -531,7 +516,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $address Email-Address * @param string|array $name name for the link, array for media file */ - function emaillink($address, $name = null) { + public function emaillink($address, $name = null) { if(is_array($name)) { $this->_firstimage($name['src']); if($name['type'] == 'internalmedia') $this->_recordMediaUsage($name['src']); @@ -554,7 +539,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $cache cache|recache|nocache * @param string $linking linkonly|detail|nolink */ - function internalmedia($src, $title = null, $align = null, $width = null, + public function internalmedia($src, $title = null, $align = null, $width = null, $height = null, $cache = null, $linking = null) { if($this->capture && $title) $this->doc .= '['.$title.']'; $this->_firstimage($src); @@ -572,7 +557,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $cache cache|recache|nocache * @param string $linking linkonly|detail|nolink */ - function externalmedia($src, $title = null, $align = null, $width = null, + public function externalmedia($src, $title = null, $align = null, $width = null, $height = null, $cache = null, $linking = null) { if($this->capture && $title) $this->doc .= '['.$title.']'; $this->_firstimage($src); @@ -584,7 +569,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param string $url URL of the feed * @param array $params Finetuning of the output */ - function rss($url, $params) { + public function rss($url, $params) { $this->meta['relation']['haspart'][$url] = true; $this->meta['date']['valid']['age'] = @@ -605,7 +590,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @return mixed|string */ - function _simpleTitle($name) { + public function _simpleTitle($name) { global $conf; if(is_array($name)) return ''; @@ -622,23 +607,6 @@ class Doku_Renderer_metadata extends Doku_Renderer { } /** - * Creates a linkid from a headline - * - * @author Andreas Gohr <andi@splitbrain.org> - * @param string $title The headline title - * @param boolean $create Create a new unique ID? - * @return string - */ - function _headerToLink($title, $create = false) { - if($create) { - return sectionID($title, $this->headers); - } else { - $check = false; - return sectionID($title, $check); - } - } - - /** * Construct a title and handle images in titles * * @author Harry Fuecks <hfuecks@gmail.com> @@ -647,7 +615,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * @param null|string $id linked page id (used to extract title from first heading) * @return string title text */ - function _getLinkTitle($title, $default, $id = null) { + public function _getLinkTitle($title, $default, $id = null) { if(is_array($title)) { if($title['title']) { return '['.$title['title'].']'; @@ -670,7 +638,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @param string $src image URL or ID */ - function _firstimage($src) { + protected function _firstimage($src) { if($this->firstimage) return; global $ID; @@ -688,7 +656,7 @@ class Doku_Renderer_metadata extends Doku_Renderer { * * @param string $src media ID */ - function _recordMediaUsage($src) { + protected function _recordMediaUsage($src) { global $ID; list ($src) = explode('#', $src, 2); diff --git a/inc/parser/parser.php b/inc/parser/parser.php index 8cff2b8be..d9fc5fb8f 100644 --- a/inc/parser/parser.php +++ b/inc/parser/parser.php @@ -1,8 +1,4 @@ <?php -if(!defined('DOKU_INC')) die('meh.'); -require_once DOKU_INC . 'inc/parser/lexer.php'; -require_once DOKU_INC . 'inc/parser/handler.php'; - /** * Define various types of modes used by the parser - they are used to @@ -13,1022 +9,49 @@ $PARSER_MODES = array( // containers are complex modes that can contain many other modes // hr breaks the principle but they shouldn't be used in tables / lists // so they are put here - 'container' => array('listblock','table','quote','hr'), + 'container' => array('listblock', 'table', 'quote', 'hr'), // some mode are allowed inside the base mode only - 'baseonly' => array('header'), + 'baseonly' => array('header'), // modes for styling text -- footnote behaves similar to styling - 'formatting' => array('strong', 'emphasis', 'underline', 'monospace', - 'subscript', 'superscript', 'deleted', 'footnote'), + 'formatting' => array( + 'strong', 'emphasis', 'underline', 'monospace', + 'subscript', 'superscript', 'deleted', 'footnote' + ), // modes where the token is simply replaced - they can not contain any // other modes - 'substition' => array('acronym','smiley','wordblock','entity', - 'camelcaselink', 'internallink','media', - 'externallink','linebreak','emaillink', - 'windowssharelink','filelink','notoc', - 'nocache','multiplyentity','quotes','rss'), + 'substition' => array( + 'acronym', 'smiley', 'wordblock', 'entity', + 'camelcaselink', 'internallink', 'media', + 'externallink', 'linebreak', 'emaillink', + 'windowssharelink', 'filelink', 'notoc', + 'nocache', 'multiplyentity', 'quotes', 'rss' + ), // modes which have a start and end token but inside which // no other modes should be applied - 'protected' => array('preformatted','code','file','php','html','htmlblock','phpblock'), + 'protected' => array('preformatted', 'code', 'file', 'php', 'html', 'htmlblock', 'phpblock'), // inside this mode no wiki markup should be applied but lineendings // and whitespace isn't preserved - 'disabled' => array('unformatted'), + 'disabled' => array('unformatted'), // used to mark paragraph boundaries - 'paragraphs' => array('eol') + 'paragraphs' => array('eol') ); -//------------------------------------------------------------------- - -/** - * Sets up the Lexer with modes and points it to the Handler - * For an intro to the Lexer see: wiki:parser - */ -class Doku_Parser { - - var $Handler; - - /** - * @var Doku_Lexer $Lexer - */ - var $Lexer; - - var $modes = array(); - - var $connected = false; - - /** - * @param Doku_Parser_Mode_base $BaseMode - */ - function addBaseMode($BaseMode) { - $this->modes['base'] = $BaseMode; - if ( !$this->Lexer ) { - $this->Lexer = new Doku_Lexer($this->Handler,'base', true); - } - $this->modes['base']->Lexer = $this->Lexer; - } - - /** - * PHP preserves order of associative elements - * Mode sequence is important - * - * @param string $name - * @param Doku_Parser_Mode_Interface $Mode - */ - function addMode($name, Doku_Parser_Mode_Interface $Mode) { - if ( !isset($this->modes['base']) ) { - $this->addBaseMode(new Doku_Parser_Mode_base()); - } - $Mode->Lexer = $this->Lexer; - $this->modes[$name] = $Mode; - } - - function connectModes() { - - if ( $this->connected ) { - return; - } - - foreach ( array_keys($this->modes) as $mode ) { - - // Base isn't connected to anything - if ( $mode == 'base' ) { - continue; - } - $this->modes[$mode]->preConnect(); - - foreach ( array_keys($this->modes) as $cm ) { - - if ( $this->modes[$cm]->accepts($mode) ) { - $this->modes[$mode]->connectTo($cm); - } - - } - - $this->modes[$mode]->postConnect(); - } - - $this->connected = true; - } - - function parse($doc) { - if ( $this->Lexer ) { - $this->connectModes(); - // Normalize CRs and pad doc - $doc = "\n".str_replace("\r\n","\n",$doc)."\n"; - $this->Lexer->parse($doc); - $this->Handler->_finalize(); - return $this->Handler->calls; - } else { - return false; - } - } - -} - -//------------------------------------------------------------------- - -/** - * Class Doku_Parser_Mode_Interface - * - * Defines a mode (syntax component) in the Parser - */ -interface Doku_Parser_Mode_Interface { - /** - * returns a number used to determine in which order modes are added - */ - public function getSort(); - - /** - * Called before any calls to connectTo - * @return void - */ - function preConnect(); - - /** - * Connects the mode - * - * @param string $mode - * @return void - */ - function connectTo($mode); - - /** - * Called after all calls to connectTo - * @return void - */ - function postConnect(); - - /** - * Check if given mode is accepted inside this mode - * - * @param string $mode - * @return bool - */ - function accepts($mode); -} - -/** - * This class and all the subclasses below are used to reduce the effort required to register - * modes with the Lexer. - * - * @author Harry Fuecks <hfuecks@gmail.com> - */ -class Doku_Parser_Mode implements Doku_Parser_Mode_Interface { - /** - * @var Doku_Lexer $Lexer - */ - var $Lexer; - var $allowedModes = array(); - - function getSort() { - trigger_error('getSort() not implemented in '.get_class($this), E_USER_WARNING); - } - - function preConnect() {} - function connectTo($mode) {} - function postConnect() {} - function accepts($mode) { - return in_array($mode, (array) $this->allowedModes ); - } -} - /** - * Basically the same as Doku_Parser_Mode but extends from DokuWiki_Plugin + * Class Doku_Parser * - * Adds additional functions to syntax plugins + * @deprecated 2018-05-04 */ -class Doku_Parser_Mode_Plugin extends DokuWiki_Plugin implements Doku_Parser_Mode_Interface { - /** - * @var Doku_Lexer $Lexer - */ - var $Lexer; - var $allowedModes = array(); - - /** - * Sort for applying this mode - * - * @return int - */ - function getSort() { - trigger_error('getSort() not implemented in '.get_class($this), E_USER_WARNING); - } - - function preConnect() {} - function connectTo($mode) {} - function postConnect() {} - function accepts($mode) { - return in_array($mode, (array) $this->allowedModes ); - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_base extends Doku_Parser_Mode { - - function __construct() { - global $PARSER_MODES; - - $this->allowedModes = array_merge ( - $PARSER_MODES['container'], - $PARSER_MODES['baseonly'], - $PARSER_MODES['paragraphs'], - $PARSER_MODES['formatting'], - $PARSER_MODES['substition'], - $PARSER_MODES['protected'], - $PARSER_MODES['disabled'] - ); - } - - function getSort() { - return 0; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_footnote extends Doku_Parser_Mode { - - function __construct() { - global $PARSER_MODES; - - $this->allowedModes = array_merge ( - $PARSER_MODES['container'], - $PARSER_MODES['formatting'], - $PARSER_MODES['substition'], - $PARSER_MODES['protected'], - $PARSER_MODES['disabled'] - ); - - unset($this->allowedModes[array_search('footnote', $this->allowedModes)]); - } - - function connectTo($mode) { - $this->Lexer->addEntryPattern( - '\x28\x28(?=.*\x29\x29)',$mode,'footnote' - ); - } - - function postConnect() { - $this->Lexer->addExitPattern( - '\x29\x29','footnote' - ); - } - - function getSort() { - return 150; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_header extends Doku_Parser_Mode { - - function connectTo($mode) { - //we're not picky about the closing ones, two are enough - $this->Lexer->addSpecialPattern( - '[ \t]*={2,}[^\n]+={2,}[ \t]*(?=\n)', - $mode, - 'header' - ); - } - - function getSort() { - return 50; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_notoc extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addSpecialPattern('~~NOTOC~~',$mode,'notoc'); - } - - function getSort() { - return 30; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_nocache extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addSpecialPattern('~~NOCACHE~~',$mode,'nocache'); - } - - function getSort() { - return 40; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_linebreak extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addSpecialPattern('\x5C{2}(?:[ \t]|(?=\n))',$mode,'linebreak'); - } - - function getSort() { - return 140; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_eol extends Doku_Parser_Mode { - - function connectTo($mode) { - $badModes = array('listblock','table'); - if ( in_array($mode, $badModes) ) { - return; - } - // see FS#1652, pattern extended to swallow preceding whitespace to avoid issues with lines that only contain whitespace - $this->Lexer->addSpecialPattern('(?:^[ \t]*)?\n',$mode,'eol'); - } - - function getSort() { - return 370; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_hr extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addSpecialPattern('\n[ \t]*-{4,}[ \t]*(?=\n)',$mode,'hr'); - } - - function getSort() { - return 160; - } -} - -//------------------------------------------------------------------- -/** - * This class sets the markup for bold (=strong), - * italic (=emphasis), underline etc. - */ -class Doku_Parser_Mode_formatting extends Doku_Parser_Mode { - var $type; - - var $formatting = array ( - 'strong' => array ( - 'entry'=>'\*\*(?=.*\*\*)', - 'exit'=>'\*\*', - 'sort'=>70 - ), - - 'emphasis'=> array ( - 'entry'=>'//(?=[^\x00]*[^:])', //hack for bugs #384 #763 #1468 - 'exit'=>'//', - 'sort'=>80 - ), - - 'underline'=> array ( - 'entry'=>'__(?=.*__)', - 'exit'=>'__', - 'sort'=>90 - ), - - 'monospace'=> array ( - 'entry'=>'\x27\x27(?=.*\x27\x27)', - 'exit'=>'\x27\x27', - 'sort'=>100 - ), - - 'subscript'=> array ( - 'entry'=>'<sub>(?=.*</sub>)', - 'exit'=>'</sub>', - 'sort'=>110 - ), - - 'superscript'=> array ( - 'entry'=>'<sup>(?=.*</sup>)', - 'exit'=>'</sup>', - 'sort'=>120 - ), - - 'deleted'=> array ( - 'entry'=>'<del>(?=.*</del>)', - 'exit'=>'</del>', - 'sort'=>130 - ), - ); - - /** - * @param string $type - */ - function __construct($type) { - global $PARSER_MODES; - - if ( !array_key_exists($type, $this->formatting) ) { - trigger_error('Invalid formatting type '.$type, E_USER_WARNING); - } - - $this->type = $type; - - // formatting may contain other formatting but not it self - $modes = $PARSER_MODES['formatting']; - $key = array_search($type, $modes); - if ( is_int($key) ) { - unset($modes[$key]); - } - - $this->allowedModes = array_merge ( - $modes, - $PARSER_MODES['substition'], - $PARSER_MODES['disabled'] - ); - } - - function connectTo($mode) { - - // Can't nest formatting in itself - if ( $mode == $this->type ) { - return; - } - - $this->Lexer->addEntryPattern( - $this->formatting[$this->type]['entry'], - $mode, - $this->type - ); - } - - function postConnect() { - - $this->Lexer->addExitPattern( - $this->formatting[$this->type]['exit'], - $this->type - ); - - } - - function getSort() { - return $this->formatting[$this->type]['sort']; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_listblock extends Doku_Parser_Mode { - - function __construct() { - global $PARSER_MODES; - - $this->allowedModes = array_merge ( - $PARSER_MODES['formatting'], - $PARSER_MODES['substition'], - $PARSER_MODES['disabled'], - $PARSER_MODES['protected'] #XXX new - ); - - // $this->allowedModes[] = 'footnote'; - } - - function connectTo($mode) { - $this->Lexer->addEntryPattern('[ \t]*\n {2,}[\-\*]',$mode,'listblock'); - $this->Lexer->addEntryPattern('[ \t]*\n\t{1,}[\-\*]',$mode,'listblock'); - - $this->Lexer->addPattern('\n {2,}[\-\*]','listblock'); - $this->Lexer->addPattern('\n\t{1,}[\-\*]','listblock'); - - } - - function postConnect() { - $this->Lexer->addExitPattern('\n','listblock'); - } - - function getSort() { - return 10; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_table extends Doku_Parser_Mode { - - function __construct() { - global $PARSER_MODES; - - $this->allowedModes = array_merge ( - $PARSER_MODES['formatting'], - $PARSER_MODES['substition'], - $PARSER_MODES['disabled'], - $PARSER_MODES['protected'] - ); - } - - function connectTo($mode) { - $this->Lexer->addEntryPattern('[\t ]*\n\^',$mode,'table'); - $this->Lexer->addEntryPattern('[\t ]*\n\|',$mode,'table'); - } - - function postConnect() { - $this->Lexer->addPattern('\n\^','table'); - $this->Lexer->addPattern('\n\|','table'); - $this->Lexer->addPattern('[\t ]*:::[\t ]*(?=[\|\^])','table'); - $this->Lexer->addPattern('[\t ]+','table'); - $this->Lexer->addPattern('\^','table'); - $this->Lexer->addPattern('\|','table'); - $this->Lexer->addExitPattern('\n','table'); - } - - function getSort() { - return 60; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_unformatted extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addEntryPattern('<nowiki>(?=.*</nowiki>)',$mode,'unformatted'); - $this->Lexer->addEntryPattern('%%(?=.*%%)',$mode,'unformattedalt'); - } - - function postConnect() { - $this->Lexer->addExitPattern('</nowiki>','unformatted'); - $this->Lexer->addExitPattern('%%','unformattedalt'); - $this->Lexer->mapHandler('unformattedalt','unformatted'); - } - - function getSort() { - return 170; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_php extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addEntryPattern('<php>(?=.*</php>)',$mode,'php'); - $this->Lexer->addEntryPattern('<PHP>(?=.*</PHP>)',$mode,'phpblock'); - } - - function postConnect() { - $this->Lexer->addExitPattern('</php>','php'); - $this->Lexer->addExitPattern('</PHP>','phpblock'); - } - - function getSort() { - return 180; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_html extends Doku_Parser_Mode { +class Doku_Parser extends \dokuwiki\Parsing\Parser { - function connectTo($mode) { - $this->Lexer->addEntryPattern('<html>(?=.*</html>)',$mode,'html'); - $this->Lexer->addEntryPattern('<HTML>(?=.*</HTML>)',$mode,'htmlblock'); - } - - function postConnect() { - $this->Lexer->addExitPattern('</html>','html'); - $this->Lexer->addExitPattern('</HTML>','htmlblock'); - } - - function getSort() { - return 190; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_preformatted extends Doku_Parser_Mode { - - function connectTo($mode) { - // Has hard coded awareness of lists... - $this->Lexer->addEntryPattern('\n (?![\*\-])',$mode,'preformatted'); - $this->Lexer->addEntryPattern('\n\t(?![\*\-])',$mode,'preformatted'); - - // How to effect a sub pattern with the Lexer! - $this->Lexer->addPattern('\n ','preformatted'); - $this->Lexer->addPattern('\n\t','preformatted'); - - } - - function postConnect() { - $this->Lexer->addExitPattern('\n','preformatted'); - } - - function getSort() { - return 20; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_code extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addEntryPattern('<code\b(?=.*</code>)',$mode,'code'); - } - - function postConnect() { - $this->Lexer->addExitPattern('</code>','code'); - } - - function getSort() { - return 200; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_file extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addEntryPattern('<file\b(?=.*</file>)',$mode,'file'); - } - - function postConnect() { - $this->Lexer->addExitPattern('</file>','file'); - } - - function getSort() { - return 210; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_quote extends Doku_Parser_Mode { - - function __construct() { - global $PARSER_MODES; - - $this->allowedModes = array_merge ( - $PARSER_MODES['formatting'], - $PARSER_MODES['substition'], - $PARSER_MODES['disabled'], - $PARSER_MODES['protected'] #XXX new - ); - #$this->allowedModes[] = 'footnote'; - #$this->allowedModes[] = 'preformatted'; - #$this->allowedModes[] = 'unformatted'; - } - - function connectTo($mode) { - $this->Lexer->addEntryPattern('\n>{1,}',$mode,'quote'); - } - - function postConnect() { - $this->Lexer->addPattern('\n>{1,}','quote'); - $this->Lexer->addExitPattern('\n','quote'); - } - - function getSort() { - return 220; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_acronym extends Doku_Parser_Mode { - // A list - var $acronyms = array(); - var $pattern = ''; - - function __construct($acronyms) { - usort($acronyms,array($this,'_compare')); - $this->acronyms = $acronyms; - } - - function preConnect() { - if(!count($this->acronyms)) return; - - $bound = '[\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]'; - $acronyms = array_map('Doku_Lexer_Escape',$this->acronyms); - $this->pattern = '(?<=^|'.$bound.')(?:'.join('|',$acronyms).')(?='.$bound.')'; - } - - function connectTo($mode) { - if(!count($this->acronyms)) return; - - if ( strlen($this->pattern) > 0 ) { - $this->Lexer->addSpecialPattern($this->pattern,$mode,'acronym'); - } - } - - function getSort() { - return 240; - } - - /** - * sort callback to order by string length descending - * - * @param string $a - * @param string $b - * - * @return int - */ - function _compare($a,$b) { - $a_len = strlen($a); - $b_len = strlen($b); - if ($a_len > $b_len) { - return -1; - } else if ($a_len < $b_len) { - return 1; - } - - return 0; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_smiley extends Doku_Parser_Mode { - // A list - var $smileys = array(); - var $pattern = ''; - - function __construct($smileys) { - $this->smileys = $smileys; - } - - function preConnect() { - if(!count($this->smileys) || $this->pattern != '') return; - - $sep = ''; - foreach ( $this->smileys as $smiley ) { - $this->pattern .= $sep.'(?<=\W|^)'.Doku_Lexer_Escape($smiley).'(?=\W|$)'; - $sep = '|'; - } - } - - function connectTo($mode) { - if(!count($this->smileys)) return; - - if ( strlen($this->pattern) > 0 ) { - $this->Lexer->addSpecialPattern($this->pattern,$mode,'smiley'); - } - } - - function getSort() { - return 230; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_wordblock extends Doku_Parser_Mode { - // A list - var $badwords = array(); - var $pattern = ''; - - function __construct($badwords) { - $this->badwords = $badwords; - } - - function preConnect() { - - if ( count($this->badwords) == 0 || $this->pattern != '') { - return; - } - - $sep = ''; - foreach ( $this->badwords as $badword ) { - $this->pattern .= $sep.'(?<=\b)(?i)'.Doku_Lexer_Escape($badword).'(?-i)(?=\b)'; - $sep = '|'; - } - - } - - function connectTo($mode) { - if ( strlen($this->pattern) > 0 ) { - $this->Lexer->addSpecialPattern($this->pattern,$mode,'wordblock'); - } - } - - function getSort() { - return 250; + /** @inheritdoc */ + public function __construct(Doku_Handler $handler) { + dbg_deprecated(\dokuwiki\Parsing\Parser::class); + parent::__construct($handler); } } - -//------------------------------------------------------------------- -class Doku_Parser_Mode_entity extends Doku_Parser_Mode { - // A list - var $entities = array(); - var $pattern = ''; - - function __construct($entities) { - $this->entities = $entities; - } - - function preConnect() { - if(!count($this->entities) || $this->pattern != '') return; - - $sep = ''; - foreach ( $this->entities as $entity ) { - $this->pattern .= $sep.Doku_Lexer_Escape($entity); - $sep = '|'; - } - } - - function connectTo($mode) { - if(!count($this->entities)) return; - - if ( strlen($this->pattern) > 0 ) { - $this->Lexer->addSpecialPattern($this->pattern,$mode,'entity'); - } - } - - function getSort() { - return 260; - } -} - -//------------------------------------------------------------------- -// Implements the 640x480 replacement -class Doku_Parser_Mode_multiplyentity extends Doku_Parser_Mode { - - function connectTo($mode) { - - $this->Lexer->addSpecialPattern( - '(?<=\b)(?:[1-9]|\d{2,})[xX]\d+(?=\b)',$mode,'multiplyentity' - ); - - } - - function getSort() { - return 270; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_quotes extends Doku_Parser_Mode { - - function connectTo($mode) { - global $conf; - - $ws = '\s/\#~:+=&%@\-\x28\x29\]\[{}><"\''; // whitespace - $punc = ';,\.?!'; - - if($conf['typography'] == 2){ - $this->Lexer->addSpecialPattern( - "(?<=^|[$ws])'(?=[^$ws$punc])",$mode,'singlequoteopening' - ); - $this->Lexer->addSpecialPattern( - "(?<=^|[^$ws]|[$punc])'(?=$|[$ws$punc])",$mode,'singlequoteclosing' - ); - $this->Lexer->addSpecialPattern( - "(?<=^|[^$ws$punc])'(?=$|[^$ws$punc])",$mode,'apostrophe' - ); - } - - $this->Lexer->addSpecialPattern( - "(?<=^|[$ws])\"(?=[^$ws$punc])",$mode,'doublequoteopening' - ); - $this->Lexer->addSpecialPattern( - "\"",$mode,'doublequoteclosing' - ); - - } - - function getSort() { - return 280; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_camelcaselink extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addSpecialPattern( - '\b[A-Z]+[a-z]+[A-Z][A-Za-z]*\b',$mode,'camelcaselink' - ); - } - - function getSort() { - return 290; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_internallink extends Doku_Parser_Mode { - - function connectTo($mode) { - // Word boundaries? - $this->Lexer->addSpecialPattern("\[\[.*?\]\](?!\])",$mode,'internallink'); - } - - function getSort() { - return 300; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_media extends Doku_Parser_Mode { - - function connectTo($mode) { - // Word boundaries? - $this->Lexer->addSpecialPattern("\{\{(?:[^\}]|(?:\}[^\}]))+\}\}",$mode,'media'); - } - - function getSort() { - return 320; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_rss extends Doku_Parser_Mode { - - function connectTo($mode) { - $this->Lexer->addSpecialPattern("\{\{rss>[^\}]+\}\}",$mode,'rss'); - } - - function getSort() { - return 310; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_externallink extends Doku_Parser_Mode { - var $schemes = array(); - var $patterns = array(); - - function preConnect() { - if(count($this->patterns)) return; - - $ltrs = '\w'; - $gunk = '/\#~:.?+=&%@!\-\[\]'; - $punc = '.:?\-;,'; - $host = $ltrs.$punc; - $any = $ltrs.$gunk.$punc; - - $this->schemes = getSchemes(); - foreach ( $this->schemes as $scheme ) { - $this->patterns[] = '\b(?i)'.$scheme.'(?-i)://['.$any.']+?(?=['.$punc.']*[^'.$any.'])'; - } - - $this->patterns[] = '(?<=\s)(?i)www?(?-i)\.['.$host.']+?\.['.$host.']+?['.$any.']+?(?=['.$punc.']*[^'.$any.'])'; - $this->patterns[] = '(?<=\s)(?i)ftp?(?-i)\.['.$host.']+?\.['.$host.']+?['.$any.']+?(?=['.$punc.']*[^'.$any.'])'; - } - - function connectTo($mode) { - - foreach ( $this->patterns as $pattern ) { - $this->Lexer->addSpecialPattern($pattern,$mode,'externallink'); - } - } - - function getSort() { - return 330; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_filelink extends Doku_Parser_Mode { - - var $pattern; - - function preConnect() { - - $ltrs = '\w'; - $gunk = '/\#~:.?+=&%@!\-'; - $punc = '.:?\-;,'; - $host = $ltrs.$punc; - $any = $ltrs.$gunk.$punc; - - $this->pattern = '\b(?i)file(?-i)://['.$any.']+?['. - $punc.']*[^'.$any.']'; - } - - function connectTo($mode) { - $this->Lexer->addSpecialPattern( - $this->pattern,$mode,'filelink'); - } - - function getSort() { - return 360; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_windowssharelink extends Doku_Parser_Mode { - - var $pattern; - - function preConnect() { - $this->pattern = "\\\\\\\\\w+?(?:\\\\[\w\-$]+)+"; - } - - function connectTo($mode) { - $this->Lexer->addSpecialPattern( - $this->pattern,$mode,'windowssharelink'); - } - - function getSort() { - return 350; - } -} - -//------------------------------------------------------------------- -class Doku_Parser_Mode_emaillink extends Doku_Parser_Mode { - - function connectTo($mode) { - // pattern below is defined in inc/mail.php - $this->Lexer->addSpecialPattern('<'.PREG_PATTERN_VALID_EMAIL.'>',$mode,'emaillink'); - } - - function getSort() { - return 340; - } -} - - -//Setup VIM: ex: et ts=4 : diff --git a/inc/parser/renderer.php b/inc/parser/renderer.php index 83b51d4b1..eb4d658be 100644 --- a/inc/parser/renderer.php +++ b/inc/parser/renderer.php @@ -5,7 +5,6 @@ * @author Harry Fuecks <hfuecks@gmail.com> * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); /** * Allowed chars in $language for code highlighting @@ -24,7 +23,7 @@ define('PREG_PATTERN_VALID_LANGUAGE', '#[^a-zA-Z0-9\-_]#'); * $doc field. When all instructions are processed, the $doc field contents will be cached by * DokuWiki and sent to the user. */ -class Doku_Renderer extends DokuWiki_Plugin { +abstract class Doku_Renderer extends DokuWiki_Plugin { /** @var array Settings, control the behavior of the renderer */ public $info = array( 'cache' => true, // may the rendered result cached? @@ -40,6 +39,9 @@ class Doku_Renderer extends DokuWiki_Plugin { /** @var array contains the interwiki configuration, set in p_render() */ public $interwiki = array(); + /** @var array the list of headers used to create unique link ids */ + protected $headers = array(); + /** * @var string the rendered document, this will be cached after the renderer ran through */ @@ -51,7 +53,8 @@ class Doku_Renderer extends DokuWiki_Plugin { * This is called before each use of the renderer object and should be used to * completely reset the state of the renderer to be reused for a new document */ - function reset() { + public function reset(){ + $this->headers = array(); } /** @@ -62,7 +65,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @return bool false if the plugin has to be instantiated */ - function isSingleton() { + public function isSingleton() { return false; } @@ -73,15 +76,12 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @return string */ - function getFormat() { - trigger_error('getFormat() not implemented in '.get_class($this), E_USER_WARNING); - return ''; - } + abstract public function getFormat(); /** * Disable caching of this renderer's output */ - function nocache() { + public function nocache() { $this->info['cache'] = false; } @@ -90,7 +90,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * This might not be used for certain sub renderer */ - function notoc() { + public function notoc() { $this->info['toc'] = false; } @@ -104,7 +104,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $state matched state if any * @param string $match raw matched syntax */ - function plugin($name, $data, $state = '', $match = '') { + public function plugin($name, $data, $state = '', $match = '') { /** @var DokuWiki_Syntax_Plugin $plugin */ $plugin = plugin_load('syntax', $name); if($plugin != null) { @@ -118,7 +118,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param array $instructions */ - function nest($instructions) { + public function nest($instructions) { foreach($instructions as $instruction) { // execute the callback against ourself if(method_exists($this, $instruction[0])) { @@ -133,7 +133,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * normally the syntax mode should override this instruction when instantiating Doku_Handler_Nest - * however plugins will not be able to - as their instructions require data. */ - function nest_close() { + public function nest_close() { } #region Syntax modes - sub classes will need to implement them to fill $doc @@ -141,13 +141,13 @@ class Doku_Renderer extends DokuWiki_Plugin { /** * Initialize the document */ - function document_start() { + public function document_start() { } /** * Finalize the document */ - function document_end() { + public function document_end() { } /** @@ -155,7 +155,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @return string */ - function render_TOC() { + public function render_TOC() { return ''; } @@ -166,7 +166,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $text the text to display * @param int $level the nesting level */ - function toc_additem($id, $text, $level) { + public function toc_additem($id, $text, $level) { } /** @@ -176,7 +176,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param int $level header level * @param int $pos byte position in the original source */ - function header($text, $level, $pos) { + public function header($text, $level, $pos) { } /** @@ -184,13 +184,13 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param int $level section level (as determined by the previous header) */ - function section_open($level) { + public function section_open($level) { } /** * Close the current section */ - function section_close() { + public function section_close() { } /** @@ -198,151 +198,151 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $text */ - function cdata($text) { + public function cdata($text) { } /** * Open a paragraph */ - function p_open() { + public function p_open() { } /** * Close a paragraph */ - function p_close() { + public function p_close() { } /** * Create a line break */ - function linebreak() { + public function linebreak() { } /** * Create a horizontal line */ - function hr() { + public function hr() { } /** * Start strong (bold) formatting */ - function strong_open() { + public function strong_open() { } /** * Stop strong (bold) formatting */ - function strong_close() { + public function strong_close() { } /** * Start emphasis (italics) formatting */ - function emphasis_open() { + public function emphasis_open() { } /** * Stop emphasis (italics) formatting */ - function emphasis_close() { + public function emphasis_close() { } /** * Start underline formatting */ - function underline_open() { + public function underline_open() { } /** * Stop underline formatting */ - function underline_close() { + public function underline_close() { } /** * Start monospace formatting */ - function monospace_open() { + public function monospace_open() { } /** * Stop monospace formatting */ - function monospace_close() { + public function monospace_close() { } /** * Start a subscript */ - function subscript_open() { + public function subscript_open() { } /** * Stop a subscript */ - function subscript_close() { + public function subscript_close() { } /** * Start a superscript */ - function superscript_open() { + public function superscript_open() { } /** * Stop a superscript */ - function superscript_close() { + public function superscript_close() { } /** * Start deleted (strike-through) formatting */ - function deleted_open() { + public function deleted_open() { } /** * Stop deleted (strike-through) formatting */ - function deleted_close() { + public function deleted_close() { } /** * Start a footnote */ - function footnote_open() { + public function footnote_open() { } /** * Stop a footnote */ - function footnote_close() { + public function footnote_close() { } /** * Open an unordered list */ - function listu_open() { + public function listu_open() { } /** * Close an unordered list */ - function listu_close() { + public function listu_close() { } /** * Open an ordered list */ - function listo_open() { + public function listo_open() { } /** * Close an ordered list */ - function listo_close() { + public function listo_close() { } /** @@ -351,25 +351,25 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param int $level the nesting level * @param bool $node true when a node; false when a leaf */ - function listitem_open($level,$node=false) { + public function listitem_open($level,$node=false) { } /** * Close a list item */ - function listitem_close() { + public function listitem_close() { } /** * Start the content of a list item */ - function listcontent_open() { + public function listcontent_open() { } /** * Stop the content of a list item */ - function listcontent_close() { + public function listcontent_close() { } /** @@ -379,7 +379,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $text */ - function unformatted($text) { + public function unformatted($text) { $this->cdata($text); } @@ -391,7 +391,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $text The PHP code */ - function php($text) { + public function php($text) { } /** @@ -402,7 +402,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $text The PHP code */ - function phpblock($text) { + public function phpblock($text) { } /** @@ -412,7 +412,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $text The HTML */ - function html($text) { + public function html($text) { } /** @@ -422,7 +422,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $text The HTML */ - function htmlblock($text) { + public function htmlblock($text) { } /** @@ -430,19 +430,19 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $text */ - function preformatted($text) { + public function preformatted($text) { } /** * Start a block quote */ - function quote_open() { + public function quote_open() { } /** * Stop a block quote */ - function quote_close() { + public function quote_close() { } /** @@ -452,7 +452,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $lang programming language to use for syntax highlighting * @param string $file file path label */ - function file($text, $lang = null, $file = null) { + public function file($text, $lang = null, $file = null) { } /** @@ -462,7 +462,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $lang programming language to use for syntax highlighting * @param string $file file path label */ - function code($text, $lang = null, $file = null) { + public function code($text, $lang = null, $file = null) { } /** @@ -472,7 +472,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $acronym */ - function acronym($acronym) { + public function acronym($acronym) { } /** @@ -482,7 +482,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $smiley */ - function smiley($smiley) { + public function smiley($smiley) { } /** @@ -494,7 +494,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param string $entity */ - function entity($entity) { + public function entity($entity) { } /** @@ -505,37 +505,37 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string|int $x first value * @param string|int $y second value */ - function multiplyentity($x, $y) { + public function multiplyentity($x, $y) { } /** * Render an opening single quote char (language specific) */ - function singlequoteopening() { + public function singlequoteopening() { } /** * Render a closing single quote char (language specific) */ - function singlequoteclosing() { + public function singlequoteclosing() { } /** * Render an apostrophe char (language specific) */ - function apostrophe() { + public function apostrophe() { } /** * Render an opening double quote char (language specific) */ - function doublequoteopening() { + public function doublequoteopening() { } /** * Render an closinging double quote char (language specific) */ - function doublequoteclosing() { + public function doublequoteclosing() { } /** @@ -544,7 +544,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $link The link name * @see http://en.wikipedia.org/wiki/CamelCase */ - function camelcaselink($link) { + public function camelcaselink($link) { } /** @@ -553,7 +553,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $hash hash link identifier * @param string $name name for the link */ - function locallink($hash, $name = null) { + public function locallink($hash, $name = null) { } /** @@ -562,7 +562,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $link page ID to link to. eg. 'wiki:syntax' * @param string|array $title name for the link, array for media file */ - function internallink($link, $title = null) { + public function internallink($link, $title = null) { } /** @@ -571,7 +571,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $link full URL with scheme * @param string|array $title name for the link, array for media file */ - function externallink($link, $title = null) { + public function externallink($link, $title = null) { } /** @@ -580,7 +580,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $url URL of the feed * @param array $params Finetuning of the output */ - function rss($url, $params) { + public function rss($url, $params) { } /** @@ -593,7 +593,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $wikiName indentifier (shortcut) for the remote wiki * @param string $wikiUri the fragment parsed from the original link */ - function interwikilink($link, $title = null, $wikiName, $wikiUri) { + public function interwikilink($link, $title, $wikiName, $wikiUri) { } /** @@ -602,7 +602,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $link the link * @param string|array $title name for the link, array for media file */ - function filelink($link, $title = null) { + public function filelink($link, $title = null) { } /** @@ -611,7 +611,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $link the link * @param string|array $title name for the link, array for media file */ - function windowssharelink($link, $title = null) { + public function windowssharelink($link, $title = null) { } /** @@ -622,7 +622,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $address Email-Address * @param string|array $name name for the link, array for media file */ - function emaillink($address, $name = null) { + public function emaillink($address, $name = null) { } /** @@ -636,7 +636,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $cache cache|recache|nocache * @param string $linking linkonly|detail|nolink */ - function internalmedia($src, $title = null, $align = null, $width = null, + public function internalmedia($src, $title = null, $align = null, $width = null, $height = null, $cache = null, $linking = null) { } @@ -651,7 +651,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $cache cache|recache|nocache * @param string $linking linkonly|detail|nolink */ - function externalmedia($src, $title = null, $align = null, $width = null, + public function externalmedia($src, $title = null, $align = null, $width = null, $height = null, $cache = null, $linking = null) { } @@ -665,7 +665,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param int $height height of media in pixel * @param string $cache cache|recache|nocache */ - function internalmedialink($src, $title = null, $align = null, + public function internalmedialink($src, $title = null, $align = null, $width = null, $height = null, $cache = null) { } @@ -679,7 +679,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param int $height height of media in pixel * @param string $cache cache|recache|nocache */ - function externalmedialink($src, $title = null, $align = null, + public function externalmedialink($src, $title = null, $align = null, $width = null, $height = null, $cache = null) { } @@ -690,7 +690,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param int $numrows NOT IMPLEMENTED * @param int $pos byte position in the original source */ - function table_open($maxcols = null, $numrows = null, $pos = null) { + public function table_open($maxcols = null, $numrows = null, $pos = null) { } /** @@ -698,55 +698,55 @@ class Doku_Renderer extends DokuWiki_Plugin { * * @param int $pos byte position in the original source */ - function table_close($pos = null) { + public function table_close($pos = null) { } /** * Open a table header */ - function tablethead_open() { + public function tablethead_open() { } /** * Close a table header */ - function tablethead_close() { + public function tablethead_close() { } /** * Open a table body */ - function tabletbody_open() { + public function tabletbody_open() { } /** * Close a table body */ - function tabletbody_close() { + public function tabletbody_close() { } /** * Open a table footer */ - function tabletfoot_open() { + public function tabletfoot_open() { } /** * Close a table footer */ - function tabletfoot_close() { + public function tabletfoot_close() { } /** * Open a table row */ - function tablerow_open() { + public function tablerow_open() { } /** * Close a table row */ - function tablerow_close() { + public function tablerow_close() { } /** @@ -756,13 +756,13 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $align left|center|right * @param int $rowspan */ - function tableheader_open($colspan = 1, $align = null, $rowspan = 1) { + public function tableheader_open($colspan = 1, $align = null, $rowspan = 1) { } /** * Close a table header cell */ - function tableheader_close() { + public function tableheader_close() { } /** @@ -772,13 +772,13 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $align left|center|right * @param int $rowspan */ - function tablecell_open($colspan = 1, $align = null, $rowspan = 1) { + public function tablecell_open($colspan = 1, $align = null, $rowspan = 1) { } /** * Close a table cell */ - function tablecell_close() { + public function tablecell_close() { } #endregion @@ -786,6 +786,23 @@ class Doku_Renderer extends DokuWiki_Plugin { #region util functions, you probably won't need to reimplement them /** + * Creates a linkid from a headline + * + * @author Andreas Gohr <andi@splitbrain.org> + * @param string $title The headline title + * @param boolean $create Create a new unique ID? + * @return string + */ + public function _headerToLink($title, $create = false) { + if($create) { + return sectionID($title, $this->headers); + } else { + $check = false; + return sectionID($title, $check); + } + } + + /** * Removes any Namespace from the given name but keeps * casing and special chars * @@ -794,7 +811,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param string $name * @return string */ - function _simpleTitle($name) { + protected function _simpleTitle($name) { global $conf; //if there is a hash we use the ancor name only @@ -818,7 +835,7 @@ class Doku_Renderer extends DokuWiki_Plugin { * @param null|bool $exists reference which returns if an internal page exists * @return string interwikilink */ - function _resolveInterWiki(&$shortcut, $reference, &$exists = null) { + public function _resolveInterWiki(&$shortcut, $reference, &$exists = null) { //get interwiki URL if(isset($this->interwiki[$shortcut])) { $url = $this->interwiki[$shortcut]; diff --git a/inc/parser/xhtml.php b/inc/parser/xhtml.php index 34a7d3e64..1b4387d2b 100644 --- a/inc/parser/xhtml.php +++ b/inc/parser/xhtml.php @@ -2,25 +2,11 @@ /** * Renderer for XHTML output * + * This is DokuWiki's main renderer used to display page content in the wiki + * * @author Harry Fuecks <hfuecks@gmail.com> * @author Andreas Gohr <andi@splitbrain.org> - */ -if(!defined('DOKU_INC')) die('meh.'); - -if(!defined('DOKU_LF')) { - // Some whitespace to help View > Source - define ('DOKU_LF', "\n"); -} - -if(!defined('DOKU_TAB')) { - // Some whitespace to help View > Source - define ('DOKU_TAB', "\t"); -} - -/** - * The XHTML Renderer * - * This is DokuWiki's main renderer used to display page content in the wiki */ class Doku_Renderer_xhtml extends Doku_Renderer { /** @var array store the table of contents */ @@ -28,14 +14,13 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** @var array A stack of section edit data */ protected $sectionedits = array(); - var $date_at = ''; // link pages and media against this revision + + /** @var string|int link pages and media against this revision */ + public $date_at = ''; /** @var int last section edit id, used by startSectionEdit */ protected $lastsecid = 0; - /** @var array the list of headers used to create unique link ids */ - protected $headers = array(); - /** @var array a list of footnotes, list starts at 1! */ protected $footnotes = array(); @@ -122,23 +107,22 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @return string always 'xhtml' */ - function getFormat() { + public function getFormat() { return 'xhtml'; } /** * Initialize the document */ - function document_start() { + public function document_start() { //reset some internals $this->toc = array(); - $this->headers = array(); } /** * Finalize the document */ - function document_end() { + public function document_end() { // Finish open section edits. while(count($this->sectionedits) > 0) { if($this->sectionedits[count($this->sectionedits) - 1]['start'] <= 1) { @@ -183,7 +167,11 @@ class Doku_Renderer_xhtml extends Doku_Renderer { // Prepare the TOC global $conf; - if($this->info['toc'] && is_array($this->toc) && $conf['tocminheads'] && count($this->toc) >= $conf['tocminheads']) { + if( + $this->info['toc'] && + is_array($this->toc) && + $conf['tocminheads'] && count($this->toc) >= $conf['tocminheads'] + ) { global $TOC; $TOC = $this->toc; } @@ -199,7 +187,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param string $text the text to display * @param int $level the nesting level */ - function toc_additem($id, $text, $level) { + public function toc_additem($id, $text, $level) { global $conf; //handle TOC @@ -215,7 +203,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param int $level header level * @param int $pos byte position in the original source */ - function header($text, $level, $pos) { + public function header($text, $level, $pos) { global $conf; if(blank($text)) return; //skip empty headlines @@ -261,14 +249,14 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param int $level section level (as determined by the previous header) */ - function section_open($level) { + public function section_open($level) { $this->doc .= '<div class="level'.$level.'">'.DOKU_LF; } /** * Close the current section */ - function section_close() { + public function section_close() { $this->doc .= DOKU_LF.'</div>'.DOKU_LF; } @@ -277,133 +265,133 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param $text */ - function cdata($text) { + public function cdata($text) { $this->doc .= $this->_xmlEntities($text); } /** * Open a paragraph */ - function p_open() { + public function p_open() { $this->doc .= DOKU_LF.'<p>'.DOKU_LF; } /** * Close a paragraph */ - function p_close() { + public function p_close() { $this->doc .= DOKU_LF.'</p>'.DOKU_LF; } /** * Create a line break */ - function linebreak() { + public function linebreak() { $this->doc .= '<br/>'.DOKU_LF; } /** * Create a horizontal line */ - function hr() { + public function hr() { $this->doc .= '<hr />'.DOKU_LF; } /** * Start strong (bold) formatting */ - function strong_open() { + public function strong_open() { $this->doc .= '<strong>'; } /** * Stop strong (bold) formatting */ - function strong_close() { + public function strong_close() { $this->doc .= '</strong>'; } /** * Start emphasis (italics) formatting */ - function emphasis_open() { + public function emphasis_open() { $this->doc .= '<em>'; } /** * Stop emphasis (italics) formatting */ - function emphasis_close() { + public function emphasis_close() { $this->doc .= '</em>'; } /** * Start underline formatting */ - function underline_open() { + public function underline_open() { $this->doc .= '<em class="u">'; } /** * Stop underline formatting */ - function underline_close() { + public function underline_close() { $this->doc .= '</em>'; } /** * Start monospace formatting */ - function monospace_open() { + public function monospace_open() { $this->doc .= '<code>'; } /** * Stop monospace formatting */ - function monospace_close() { + public function monospace_close() { $this->doc .= '</code>'; } /** * Start a subscript */ - function subscript_open() { + public function subscript_open() { $this->doc .= '<sub>'; } /** * Stop a subscript */ - function subscript_close() { + public function subscript_close() { $this->doc .= '</sub>'; } /** * Start a superscript */ - function superscript_open() { + public function superscript_open() { $this->doc .= '<sup>'; } /** * Stop a superscript */ - function superscript_close() { + public function superscript_close() { $this->doc .= '</sup>'; } /** * Start deleted (strike-through) formatting */ - function deleted_open() { + public function deleted_open() { $this->doc .= '<del>'; } /** * Stop deleted (strike-through) formatting */ - function deleted_close() { + public function deleted_close() { $this->doc .= '</del>'; } @@ -416,7 +404,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @author Andreas Gohr <andi@splitbrain.org> */ - function footnote_open() { + public function footnote_open() { // move current content to store and record footnote $this->store = $this->doc; @@ -431,7 +419,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @author Andreas Gohr */ - function footnote_close() { + public function footnote_close() { /** @var $fnid int takes track of seen footnotes, assures they are unique even across multiple docs FS#2841 */ static $fnid = 0; // assign new footnote id (we start at 1) @@ -462,7 +450,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input */ - function listu_open($classes = null) { + public function listu_open($classes = null) { $class = ''; if($classes !== null) { if(is_array($classes)) $classes = join(' ', $classes); @@ -474,7 +462,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Close an unordered list */ - function listu_close() { + public function listu_close() { $this->doc .= '</ul>'.DOKU_LF; } @@ -483,7 +471,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input */ - function listo_open($classes = null) { + public function listo_open($classes = null) { $class = ''; if($classes !== null) { if(is_array($classes)) $classes = join(' ', $classes); @@ -495,7 +483,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Close an ordered list */ - function listo_close() { + public function listo_close() { $this->doc .= '</ol>'.DOKU_LF; } @@ -505,7 +493,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param int $level the nesting level * @param bool $node true when a node; false when a leaf */ - function listitem_open($level, $node=false) { + public function listitem_open($level, $node=false) { $branching = $node ? ' node' : ''; $this->doc .= '<li class="level'.$level.$branching.'">'; } @@ -513,21 +501,21 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Close a list item */ - function listitem_close() { + public function listitem_close() { $this->doc .= '</li>'.DOKU_LF; } /** * Start the content of a list item */ - function listcontent_open() { + public function listcontent_open() { $this->doc .= '<div class="li">'; } /** * Stop the content of a list item */ - function listcontent_close() { + public function listcontent_close() { $this->doc .= '</div>'.DOKU_LF; } @@ -538,7 +526,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string $text */ - function unformatted($text) { + public function unformatted($text) { $this->doc .= $this->_xmlEntities($text); } @@ -550,7 +538,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @author Andreas Gohr <andi@splitbrain.org> */ - function php($text, $wrapper = 'code') { + public function php($text, $wrapper = 'code') { global $conf; if($conf['phpok']) { @@ -571,7 +559,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string $text The PHP code */ - function phpblock($text) { + public function phpblock($text) { $this->php($text, 'pre'); } @@ -583,7 +571,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @author Andreas Gohr <andi@splitbrain.org> */ - function html($text, $wrapper = 'code') { + public function html($text, $wrapper = 'code') { global $conf; if($conf['htmlok']) { @@ -600,21 +588,21 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string $text The HTML */ - function htmlblock($text) { + public function htmlblock($text) { $this->html($text, 'pre'); } /** * Start a block quote */ - function quote_open() { + public function quote_open() { $this->doc .= '<blockquote><div class="no">'.DOKU_LF; } /** * Stop a block quote */ - function quote_close() { + public function quote_close() { $this->doc .= '</div></blockquote>'.DOKU_LF; } @@ -623,7 +611,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string $text */ - function preformatted($text) { + public function preformatted($text) { $this->doc .= '<pre class="code">'.trim($this->_xmlEntities($text), "\n\r").'</pre>'.DOKU_LF; } @@ -635,7 +623,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param string $filename file path label * @param array $options assoziative array with additional geshi options */ - function file($text, $language = null, $filename = null, $options=null) { + public function file($text, $language = null, $filename = null, $options=null) { $this->_highlight('file', $text, $language, $filename, $options); } @@ -647,7 +635,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param string $filename file path label * @param array $options assoziative array with additional geshi options */ - function code($text, $language = null, $filename = null, $options=null) { + public function code($text, $language = null, $filename = null, $options=null) { $this->_highlight('code', $text, $language, $filename, $options); } @@ -661,7 +649,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param string $filename file path label * @param array $options assoziative array with additional geshi options */ - function _highlight($type, $text, $language = null, $filename = null, $options = null) { + public function _highlight($type, $text, $language = null, $filename = null, $options = null) { global $ID; global $lang; global $INPUT; @@ -679,7 +667,12 @@ class Doku_Renderer_xhtml extends Doku_Renderer { $offset = $INPUT->str('codeblockOffset'); } $this->doc .= '<dl class="'.$type.'">'.DOKU_LF; - $this->doc .= '<dt><a href="'.exportlink($ID, 'code', array('codeblock' => $offset+$this->_codeblock)).'" title="'.$lang['download'].'" class="'.$class.'">'; + $this->doc .= '<dt><a href="' . + exportlink( + $ID, + 'code', + array('codeblock' => $offset + $this->_codeblock) + ) . '" title="' . $lang['download'] . '" class="' . $class . '">'; $this->doc .= hsc($filename); $this->doc .= '</a></dt>'.DOKU_LF.'<dd>'; } @@ -697,7 +690,9 @@ class Doku_Renderer_xhtml extends Doku_Renderer { $class = 'code'; //we always need the code class to make the syntax highlighting apply if($type != 'code') $class .= ' '.$type; - $this->doc .= "<pre class=\"$class $language\">".p_xhtml_cached_geshi($text, $language, '', $options).'</pre>'.DOKU_LF; + $this->doc .= "<pre class=\"$class $language\">" . + p_xhtml_cached_geshi($text, $language, '', $options) . + '</pre>' . DOKU_LF; } if($filename) { @@ -714,7 +709,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string $acronym */ - function acronym($acronym) { + public function acronym($acronym) { if(array_key_exists($acronym, $this->acronyms)) { @@ -735,7 +730,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string $smiley */ - function smiley($smiley) { + public function smiley($smiley) { if(array_key_exists($smiley, $this->smileys)) { $this->doc .= '<img src="'.DOKU_BASE.'lib/images/smileys/'.$this->smileys[$smiley]. '" class="icon" alt="'. @@ -754,7 +749,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string $entity */ - function entity($entity) { + public function entity($entity) { if(array_key_exists($entity, $this->entities)) { $this->doc .= $this->entities[$entity]; } else { @@ -770,14 +765,14 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param string|int $x first value * @param string|int $y second value */ - function multiplyentity($x, $y) { + public function multiplyentity($x, $y) { $this->doc .= "$x×$y"; } /** * Render an opening single quote char (language specific) */ - function singlequoteopening() { + public function singlequoteopening() { global $lang; $this->doc .= $lang['singlequoteopening']; } @@ -785,7 +780,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Render a closing single quote char (language specific) */ - function singlequoteclosing() { + public function singlequoteclosing() { global $lang; $this->doc .= $lang['singlequoteclosing']; } @@ -793,7 +788,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Render an apostrophe char (language specific) */ - function apostrophe() { + public function apostrophe() { global $lang; $this->doc .= $lang['apostrophe']; } @@ -801,7 +796,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Render an opening double quote char (language specific) */ - function doublequoteopening() { + public function doublequoteopening() { global $lang; $this->doc .= $lang['doublequoteopening']; } @@ -809,7 +804,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Render an closinging double quote char (language specific) */ - function doublequoteclosing() { + public function doublequoteclosing() { global $lang; $this->doc .= $lang['doublequoteclosing']; } @@ -823,7 +818,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @see http://en.wikipedia.org/wiki/CamelCase */ - function camelcaselink($link, $returnonly = false) { + public function camelcaselink($link, $returnonly = false) { if($returnonly) { return $this->internallink($link, $link, null, true); } else { @@ -839,7 +834,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $returnonly whether to return html or write to doc attribute * @return void|string writes to doc attribute or returns html depends on $returnonly */ - function locallink($hash, $name = null, $returnonly = false) { + public function locallink($hash, $name = null, $returnonly = false) { global $ID; $name = $this->_getLinkTitle($name, $hash, $isImage); $hash = $this->_headerToLink($hash); @@ -870,7 +865,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param string $linktype type to set use of headings * @return void|string writes to doc attribute or returns html depends on $returnonly */ - function internallink($id, $name = null, $search = null, $returnonly = false, $linktype = 'content') { + public function internallink($id, $name = null, $search = null, $returnonly = false, $linktype = 'content') { global $conf; global $ID; global $INFO; @@ -961,7 +956,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $returnonly whether to return html or write to doc attribute * @return void|string writes to doc attribute or returns html depends on $returnonly */ - function externallink($url, $name = null, $returnonly = false) { + public function externallink($url, $name = null, $returnonly = false) { global $conf; $name = $this->_getLinkTitle($name, $url, $isImage); @@ -1025,7 +1020,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $returnonly whether to return html or write to doc attribute * @return void|string writes to doc attribute or returns html depends on $returnonly */ - function interwikilink($match, $name = null, $wikiName, $wikiUri, $returnonly = false) { + public function interwikilink($match, $name, $wikiName, $wikiUri, $returnonly = false) { global $conf; $link = array(); @@ -1080,7 +1075,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $returnonly whether to return html or write to doc attribute * @return void|string writes to doc attribute or returns html depends on $returnonly */ - function windowssharelink($url, $name = null, $returnonly = false) { + public function windowssharelink($url, $name = null, $returnonly = false) { global $conf; //simple setup @@ -1120,7 +1115,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $returnonly whether to return html or write to doc attribute * @return void|string writes to doc attribute or returns html depends on $returnonly */ - function emaillink($address, $name = null, $returnonly = false) { + public function emaillink($address, $name = null, $returnonly = false) { global $conf; //simple setup $link = array(); @@ -1172,7 +1167,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $return return HTML instead of adding to $doc * @return void|string writes to doc attribute or returns html depends on $return */ - function internalmedia($src, $title = null, $align = null, $width = null, + public function internalmedia($src, $title = null, $align = null, $width = null, $height = null, $cache = null, $linking = null, $return = false) { global $ID; if (strpos($src, '#') !== false) { @@ -1186,7 +1181,15 @@ class Doku_Renderer_xhtml extends Doku_Renderer { list($ext, $mime) = mimetype($src, false); if(substr($mime, 0, 5) == 'image' && $render) { - $link['url'] = ml($src, array('id' => $ID, 'cache' => $cache, 'rev'=>$this->_getLastMediaRevisionAt($src)), ($linking == 'direct')); + $link['url'] = ml( + $src, + array( + 'id' => $ID, + 'cache' => $cache, + 'rev' => $this->_getLastMediaRevisionAt($src) + ), + ($linking == 'direct') + ); } elseif(($mime == 'application/x-shockwave-flash' || media_supportedav($mime)) && $render) { // don't link movies $noLink = true; @@ -1194,7 +1197,15 @@ class Doku_Renderer_xhtml extends Doku_Renderer { // add file icons $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext); $link['class'] .= ' mediafile mf_'.$class; - $link['url'] = ml($src, array('id' => $ID, 'cache' => $cache , 'rev'=>$this->_getLastMediaRevisionAt($src)), true); + $link['url'] = ml( + $src, + array( + 'id' => $ID, + 'cache' => $cache, + 'rev' => $this->_getLastMediaRevisionAt($src) + ), + true + ); if($exists) $link['title'] .= ' ('.filesize_h(filesize(mediaFN($src))).')'; } @@ -1228,7 +1239,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $return return HTML instead of adding to $doc * @return void|string writes to doc attribute or returns html depends on $return */ - function externalmedia($src, $title = null, $align = null, $width = null, + public function externalmedia($src, $title = null, $align = null, $width = null, $height = null, $cache = null, $linking = null, $return = false) { if(link_isinterwiki($src)){ list($shortcut, $reference) = explode('>', $src, 2); @@ -1275,7 +1286,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @author Andreas Gohr <andi@splitbrain.org> */ - function rss($url, $params) { + public function rss($url, $params) { global $lang; global $conf; @@ -1367,7 +1378,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param int $pos byte position in the original source * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input */ - function table_open($maxcols = null, $numrows = null, $pos = null, $classes = null) { + public function table_open($maxcols = null, $numrows = null, $pos = null, $classes = null) { // initialize the row counter used for classes $this->_counter['row_counter'] = 0; $class = 'table'; @@ -1392,7 +1403,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param int $pos byte position in the original source */ - function table_close($pos = null) { + public function table_close($pos = null) { $this->doc .= '</table></div>'.DOKU_LF; if($pos !== null) { $this->finishSectionEdit($pos); @@ -1402,42 +1413,42 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Open a table header */ - function tablethead_open() { + public function tablethead_open() { $this->doc .= DOKU_TAB.'<thead>'.DOKU_LF; } /** * Close a table header */ - function tablethead_close() { + public function tablethead_close() { $this->doc .= DOKU_TAB.'</thead>'.DOKU_LF; } /** * Open a table body */ - function tabletbody_open() { + public function tabletbody_open() { $this->doc .= DOKU_TAB.'<tbody>'.DOKU_LF; } /** * Close a table body */ - function tabletbody_close() { + public function tabletbody_close() { $this->doc .= DOKU_TAB.'</tbody>'.DOKU_LF; } /** * Open a table footer */ - function tabletfoot_open() { + public function tabletfoot_open() { $this->doc .= DOKU_TAB.'<tfoot>'.DOKU_LF; } /** * Close a table footer */ - function tabletfoot_close() { + public function tabletfoot_close() { $this->doc .= DOKU_TAB.'</tfoot>'.DOKU_LF; } @@ -1446,7 +1457,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input */ - function tablerow_open($classes = null) { + public function tablerow_open($classes = null) { // initialize the cell counter used for classes $this->_counter['cell_counter'] = 0; $class = 'row'.$this->_counter['row_counter']++; @@ -1460,7 +1471,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Close a table row */ - function tablerow_close() { + public function tablerow_close() { $this->doc .= DOKU_LF.DOKU_TAB.'</tr>'.DOKU_LF; } @@ -1472,7 +1483,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param int $rowspan * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input */ - function tableheader_open($colspan = 1, $align = null, $rowspan = 1, $classes = null) { + public function tableheader_open($colspan = 1, $align = null, $rowspan = 1, $classes = null) { $class = 'class="col'.$this->_counter['cell_counter']++; if(!is_null($align)) { $class .= ' '.$align.'align'; @@ -1496,7 +1507,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Close a table header cell */ - function tableheader_close() { + public function tableheader_close() { $this->doc .= '</th>'; } @@ -1508,7 +1519,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param int $rowspan * @param string|string[] $classes css classes - have to be valid, do not pass unfiltered user input */ - function tablecell_open($colspan = 1, $align = null, $rowspan = 1, $classes = null) { + public function tablecell_open($colspan = 1, $align = null, $rowspan = 1, $classes = null) { $class = 'class="col'.$this->_counter['cell_counter']++; if(!is_null($align)) { $class .= ' '.$align.'align'; @@ -1532,7 +1543,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { /** * Close a table cell */ - function tablecell_close() { + public function tablecell_close() { $this->doc .= '</td>'; } @@ -1542,7 +1553,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @return int The current header level */ - function getLastlevel() { + public function getLastlevel() { return $this->lastlevel; } @@ -1558,7 +1569,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _formatLink($link) { + public function _formatLink($link) { //make sure the url is XHTML compliant (skip mailto) if(substr($link['url'], 0, 7) != 'mailto:') { $link['url'] = str_replace('&', '&', $link['url']); @@ -1601,7 +1612,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $render should the media be embedded inline or just linked * @return string */ - function _media($src, $title = null, $align = null, $width = null, + public function _media($src, $title = null, $align = null, $width = null, $height = null, $cache = null, $render = true) { $ret = ''; @@ -1630,7 +1641,14 @@ class Doku_Renderer_xhtml extends Doku_Renderer { return $title; } //add image tag - $ret .= '<img src="'.ml($src, array('w' => $width, 'h' => $height, 'cache' => $cache, 'rev'=>$this->_getLastMediaRevisionAt($src))).'"'; + $ret .= '<img src="' . ml( + $src, + array( + 'w' => $width, 'h' => $height, + 'cache' => $cache, + 'rev' => $this->_getLastMediaRevisionAt($src) + ) + ) . '"'; $ret .= ' class="media'.$align.'"'; if($title) { @@ -1711,26 +1729,11 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param $string * @return string */ - function _xmlEntities($string) { + public function _xmlEntities($string) { return htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); } - /** - * Creates a linkid from a headline - * - * @author Andreas Gohr <andi@splitbrain.org> - * @param string $title The headline title - * @param boolean $create Create a new unique ID? - * @return string - */ - function _headerToLink($title, $create = false) { - if($create) { - return sectionID($title, $this->headers); - } else { - $check = false; - return sectionID($title, $check); - } - } + /** * Construct a title and handle images in titles @@ -1743,7 +1746,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param string $linktype content|navigation * @return string HTML of the title, might be full image tag or just escaped text */ - function _getLinkTitle($title, $default, &$isImage, $id = null, $linktype = 'content') { + public function _getLinkTitle($title, $default, &$isImage, $id = null, $linktype = 'content') { $isImage = false; if(is_array($title)) { $isImage = true; @@ -1768,7 +1771,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param array $img * @return string HTML img tag or similar */ - function _imageTitle($img) { + public function _imageTitle($img) { global $ID; // some fixes on $img['src'] @@ -1803,7 +1806,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param bool $render should the media be embedded inline or just linked * @return array associative array with link config */ - function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render) { + public function _getMediaLinkConf($src, $title, $align, $width, $height, $cache, $render) { global $conf; $link = array(); @@ -1832,7 +1835,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param array $atts - additional attributes for the <video> tag * @return string */ - function _video($src, $width, $height, $atts = null) { + public function _video($src, $width, $height, $atts = null) { // prepare width and height if(is_null($atts)) $atts = array(); $atts['width'] = (int) $width; @@ -1880,7 +1883,16 @@ class Doku_Renderer_xhtml extends Doku_Renderer { $out .= '<source src="'.hsc($url).'" type="'.$mime.'" />'.NL; // alternative content (just a link to the file) - $fallback .= $this->$linkType($file, $title, null, null, null, $cache = null, $linking = 'linkonly', $return = true); + $fallback .= $this->$linkType( + $file, + $title, + null, + null, + null, + $cache = null, + $linking = 'linkonly', + $return = true + ); } // output each track if any @@ -1906,7 +1918,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @param array $atts - additional attributes for the <audio> tag * @return string */ - function _audio($src, $atts = array()) { + public function _audio($src, $atts = array()) { $files = array(); $isExternal = media_isexternal($src); @@ -1938,7 +1950,16 @@ class Doku_Renderer_xhtml extends Doku_Renderer { $out .= '<source src="'.hsc($url).'" type="'.$mime.'" />'.NL; // alternative content (just a link to the file) - $fallback .= $this->$linkType($file, $title, null, null, null, $cache = null, $linking = 'linkonly', $return = true); + $fallback .= $this->$linkType( + $file, + $title, + null, + null, + null, + $cache = null, + $linking = 'linkonly', + $return = true + ); } // finish @@ -1956,7 +1977,7 @@ class Doku_Renderer_xhtml extends Doku_Renderer { * @access protected * @return string revision ('' for current) */ - function _getLastMediaRevisionAt($media_id){ + protected function _getLastMediaRevisionAt($media_id){ if(!$this->date_at || media_isexternal($media_id)) return ''; $pagelog = new MediaChangeLog($media_id); return $pagelog->getLastRevisionAt($this->date_at); diff --git a/inc/parser/xhtmlsummary.php b/inc/parser/xhtmlsummary.php index 867b71f6a..4641bf836 100644 --- a/inc/parser/xhtmlsummary.php +++ b/inc/parser/xhtmlsummary.php @@ -1,6 +1,4 @@ <?php -if(!defined('DOKU_INC')) die('meh.'); - /** * The summary XHTML form selects either up to the first two paragraphs * it find in a page or the first section (whichever comes first) @@ -20,32 +18,25 @@ class Doku_Renderer_xhtmlsummary extends Doku_Renderer_xhtml { // Namespace these variables to // avoid clashes with parent classes - var $sum_paragraphs = 0; - var $sum_capture = true; - var $sum_inSection = false; - var $sum_summary = ''; - var $sum_pageTitle = false; + protected $sum_paragraphs = 0; + protected $sum_capture = true; + protected $sum_inSection = false; + protected $sum_summary = ''; + protected $sum_pageTitle = false; - function document_start() { + /** @inheritdoc */ + public function document_start() { $this->doc .= DOKU_LF.'<div>'.DOKU_LF; } - function document_end() { + /** @inheritdoc */ + public function document_end() { $this->doc = $this->sum_summary; $this->doc .= DOKU_LF.'</div>'.DOKU_LF; } - // FIXME not supported anymore - function toc_open() { - $this->sum_summary .= $this->doc; - } - - // FIXME not supported anymore - function toc_close() { - $this->doc = ''; - } - - function header($text, $level, $pos) { + /** @inheritdoc */ + public function header($text, $level, $pos) { if ( !$this->sum_pageTitle ) { $this->info['sum_pagetitle'] = $text; $this->sum_pageTitle = true; @@ -55,27 +46,31 @@ class Doku_Renderer_xhtmlsummary extends Doku_Renderer_xhtml { $this->doc .= "</h$level>".DOKU_LF; } - function section_open($level) { + /** @inheritdoc */ + public function section_open($level) { if ( $this->sum_capture ) { $this->sum_inSection = true; } } - function section_close() { + /** @inheritdoc */ + public function section_close() { if ( $this->sum_capture && $this->sum_inSection ) { $this->sum_summary .= $this->doc; $this->sum_capture = false; } } - function p_open() { + /** @inheritdoc */ + public function p_open() { if ( $this->sum_capture && $this->sum_paragraphs < 2 ) { $this->sum_paragraphs++; } parent :: p_open(); } - function p_close() { + /** @inheritdoc */ + public function p_close() { parent :: p_close(); if ( $this->sum_capture && $this->sum_paragraphs >= 2 ) { $this->sum_summary .= $this->doc; diff --git a/inc/parserutils.php b/inc/parserutils.php index 5b0cab06e..a2def137a 100644 --- a/inc/parserutils.php +++ b/inc/parserutils.php @@ -7,7 +7,7 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); +use dokuwiki\Parsing\Parser; /** * How many pages shall be rendered for getting metadata during one request @@ -74,7 +74,8 @@ function p_wiki_xhtml($id, $rev='', $excuse=true,$date_at=''){ if($rev || $date_at){ if(file_exists($file)){ - $ret = p_render('xhtml',p_get_instructions(io_readWikiPage($file,$id,$rev)),$info,$date_at); //no caching on old revisions + //no caching on old revisions + $ret = p_render('xhtml',p_get_instructions(io_readWikiPage($file,$id,$rev)),$info,$date_at); }elseif($excuse){ $ret = p_locale_xhtml('norev'); } @@ -191,11 +192,8 @@ function p_get_instructions($text){ $modes = p_get_parsermodes(); - // Create the parser - $Parser = new Doku_Parser(); - - // Add the Handler - $Parser->Handler = new Doku_Handler(); + // Create the parser and handler + $Parser = new Parser(new Doku_Handler()); //add modes to parser foreach($modes as $mode){ @@ -213,7 +211,8 @@ function p_get_instructions($text){ * returns the metadata of a page * * @param string $id The id of the page the metadata should be returned from - * @param string $key The key of the metdata value that shall be read (by default everything) - separate hierarchies by " " like "date created" + * @param string $key The key of the metdata value that shall be read (by default everything) + * separate hierarchies by " " like "date created" * @param int $render If the page should be rendererd - possible values: * METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE * METADATA_RENDER_UNLIMITED (also combined with the previous two options), @@ -343,7 +342,10 @@ function p_set_metadata($id, $data, $render=false, $persistent=true){ } if($persistent) { if(isset($meta['persistent'][$key][$subkey]) && is_array($meta['persistent'][$key][$subkey])) { - $meta['persistent'][$key][$subkey] = array_replace($meta['persistent'][$key][$subkey], (array)$subvalue); + $meta['persistent'][$key][$subkey] = array_replace( + $meta['persistent'][$key][$subkey], + (array) $subvalue + ); } else { $meta['persistent'][$key][$subkey] = $subvalue; } @@ -355,10 +357,14 @@ function p_set_metadata($id, $data, $render=false, $persistent=true){ // these keys, must have subkeys - a legitimate value must be an array if (is_array($value)) { - $meta['current'][$key] = !empty($meta['current'][$key]) ? array_replace((array)$meta['current'][$key],$value) : $value; + $meta['current'][$key] = !empty($meta['current'][$key]) ? + array_replace((array)$meta['current'][$key],$value) : + $value; if ($persistent) { - $meta['persistent'][$key] = !empty($meta['persistent'][$key]) ? array_replace((array)$meta['persistent'][$key],$value) : $value; + $meta['persistent'][$key] = !empty($meta['persistent'][$key]) ? + array_replace((array)$meta['persistent'][$key],$value) : + $value; } } @@ -422,7 +428,9 @@ function p_read_metadata($id,$cache=false) { if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id]; $file = metaFN($id, '.meta'); - $meta = file_exists($file) ? unserialize(io_readFile($file, false)) : array('current'=>array(),'persistent'=>array()); + $meta = file_exists($file) ? + unserialize(io_readFile($file, false)) : + array('current'=>array(),'persistent'=>array()); if ($cache) { $cache_metadata[(string)$id] = $meta; @@ -560,7 +568,7 @@ function p_get_parsermodes(){ $std_modes[] = 'multiplyentity'; } foreach($std_modes as $m){ - $class = "Doku_Parser_Mode_$m"; + $class = 'dokuwiki\\Parsing\\ParserMode\\'.ucfirst($m); $obj = new $class(); $modes[] = array( 'sort' => $obj->getSort(), @@ -573,7 +581,7 @@ function p_get_parsermodes(){ $fmt_modes = array('strong','emphasis','underline','monospace', 'subscript','superscript','deleted'); foreach($fmt_modes as $m){ - $obj = new Doku_Parser_Mode_formatting($m); + $obj = new \dokuwiki\Parsing\ParserMode\Formatting($m); $modes[] = array( 'sort' => $obj->getSort(), 'mode' => $m, @@ -582,16 +590,16 @@ function p_get_parsermodes(){ } // add modes which need files - $obj = new Doku_Parser_Mode_smiley(array_keys(getSmileys())); + $obj = new \dokuwiki\Parsing\ParserMode\Smiley(array_keys(getSmileys())); $modes[] = array('sort' => $obj->getSort(), 'mode' => 'smiley','obj' => $obj ); - $obj = new Doku_Parser_Mode_acronym(array_keys(getAcronyms())); + $obj = new \dokuwiki\Parsing\ParserMode\Acronym(array_keys(getAcronyms())); $modes[] = array('sort' => $obj->getSort(), 'mode' => 'acronym','obj' => $obj ); - $obj = new Doku_Parser_Mode_entity(array_keys(getEntities())); + $obj = new \dokuwiki\Parsing\ParserMode\Entity(array_keys(getEntities())); $modes[] = array('sort' => $obj->getSort(), 'mode' => 'entity','obj' => $obj ); // add optional camelcase mode if($conf['camelcase']){ - $obj = new Doku_Parser_Mode_camelcaselink(); + $obj = new \dokuwiki\Parsing\ParserMode\Camelcaselink(); $modes[] = array('sort' => $obj->getSort(), 'mode' => 'camelcaselink','obj' => $obj ); } diff --git a/inc/plugincontroller.class.php b/inc/plugincontroller.class.php index fd8cd9663..1899b13fa 100644 --- a/inc/plugincontroller.class.php +++ b/inc/plugincontroller.class.php @@ -54,7 +54,9 @@ class Doku_Plugin_Controller { $this->list_bytype[$type]['disabled'] = $this->_getListByType($type,false); } - return $all ? array_merge($this->list_bytype[$type]['enabled'],$this->list_bytype[$type]['disabled']) : $this->list_bytype[$type]['enabled']; + return $all + ? array_merge($this->list_bytype[$type]['enabled'], $this->list_bytype[$type]['disabled']) + : $this->list_bytype[$type]['enabled']; } /** @@ -98,10 +100,22 @@ class Doku_Plugin_Controller { $dir = $this->get_directory($plugin); $inf = confToHash(DOKU_PLUGIN."$dir/plugin.info.txt"); if($inf['base'] && $inf['base'] != $plugin){ - msg(sprintf("Plugin installed incorrectly. Rename plugin directory '%s' to '%s'.", hsc($plugin), hsc($inf['base'])), -1); + msg( + sprintf( + "Plugin installed incorrectly. Rename plugin directory '%s' to '%s'.", + hsc($plugin), + hsc( + $inf['base'] + ) + ), -1 + ); } elseif (preg_match('/^'.DOKU_PLUGIN_NAME_REGEX.'$/', $plugin) !== 1) { - msg(sprintf("Plugin name '%s' is not a valid plugin name, only the characters a-z and 0-9 are allowed. ". - 'Maybe the plugin has been installed in the wrong directory?', hsc($plugin)), -1); + msg( + sprintf( + "Plugin name '%s' is not a valid plugin name, only the characters a-z and 0-9 are allowed. " . + 'Maybe the plugin has been installed in the wrong directory?', hsc($plugin) + ), -1 + ); } return null; } @@ -222,8 +236,10 @@ class Doku_Plugin_Controller { $local_plugins = $this->rebuildLocal(); if($local_plugins != $this->plugin_cascade['local'] || $forceSave) { $file = $this->last_local_config_file; - $out = "<?php\n/*\n * Local plugin enable/disable settings\n * Auto-generated through plugin/extension manager\n *\n". - " * NOTE: Plugins will not be added to this file unless there is a need to override a default setting. Plugins are\n". + $out = "<?php\n/*\n * Local plugin enable/disable settings\n". + " * Auto-generated through plugin/extension manager\n *\n". + " * NOTE: Plugins will not be added to this file unless there ". + "is a need to override a default setting. Plugins are\n". " * enabled by default.\n */\n"; foreach ($local_plugins as $plugin => $value) { $out .= "\$plugins['$plugin'] = $value;\n"; @@ -276,9 +292,16 @@ class Doku_Plugin_Controller { $this->last_local_config_file = array_pop($local); $this->plugin_cascade['local'] = $this->checkRequire(array($this->last_local_config_file)); if(is_array($local)) { - $this->plugin_cascade['default'] = array_merge($this->plugin_cascade['default'],$this->checkRequire($local)); + $this->plugin_cascade['default'] = array_merge( + $this->plugin_cascade['default'], + $this->checkRequire($local) + ); } - $this->tmp_plugins = array_merge($this->plugin_cascade['default'],$this->plugin_cascade['local'],$this->plugin_cascade['protected']); + $this->tmp_plugins = array_merge( + $this->plugin_cascade['default'], + $this->plugin_cascade['local'], + $this->plugin_cascade['protected'] + ); } /** @@ -290,7 +313,9 @@ class Doku_Plugin_Controller { * @return array of plugin components of requested type */ protected function _getListByType($type, $enabled) { - $master_list = $enabled ? array_keys(array_filter($this->tmp_plugins)) : array_keys(array_filter($this->tmp_plugins,array($this,'negate'))); + $master_list = $enabled + ? array_keys(array_filter($this->tmp_plugins)) + : array_keys(array_filter($this->tmp_plugins,array($this,'negate'))); $plugins = array(); foreach ($master_list as $plugin) { diff --git a/inc/pluginutils.php b/inc/pluginutils.php index a395be435..24d29a27e 100644 --- a/inc/pluginutils.php +++ b/inc/pluginutils.php @@ -8,7 +8,8 @@ // plugin related constants if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/'); -// note that only [a-z0-9]+ is officially supported, this is only to support plugins that don't follow these conventions, too +// note that only [a-z0-9]+ is officially supported, +// this is only to support plugins that don't follow these conventions, too if(!defined('DOKU_PLUGIN_NAME_REGEX')) define('DOKU_PLUGIN_NAME_REGEX', '[a-zA-Z0-9\x7f-\xff]+'); /** diff --git a/inc/search.php b/inc/search.php index 14cd0f89c..94b5cee45 100644 --- a/inc/search.php +++ b/inc/search.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * Recurse directory * @@ -20,7 +18,8 @@ if(!defined('DOKU_INC')) die('meh.'); * @param array $opts option array will be given to the Callback * @param string $dir Current directory beyond $base * @param int $lvl Recursion Level - * @param mixed $sort 'natural' to use natural order sorting (default); 'date' to sort by filemtime; leave empty to skip sorting. + * @param mixed $sort 'natural' to use natural order sorting (default); + * 'date' to sort by filemtime; leave empty to skip sorting. * @author Andreas Gohr <andi@splitbrain.org> */ function search(&$data,$base,$func,$opts,$dir='',$lvl=1,$sort='natural'){ @@ -479,7 +478,8 @@ function search_universal(&$data,$base,$file,$type,$lvl,$opts){ // are we done here maybe? if($type == 'd'){ if(empty($opts['listdirs'])) return $return; - if(empty($opts['skipacl']) && !empty($opts['sneakyacl']) && $item['perm'] < AUTH_READ) return false; //neither list nor recurse + //neither list nor recurse forbidden items: + if(empty($opts['skipacl']) && !empty($opts['sneakyacl']) && $item['perm'] < AUTH_READ) return false; if(!empty($opts['dirmatch']) && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return; if(!empty($opts['nsmatch']) && !preg_match('/'.$opts['nsmatch'].'/',$item['ns'])) return $return; }else{ diff --git a/inc/subscription.php b/inc/subscription.php index 74bec656d..3dbebcbf5 100644 --- a/inc/subscription.php +++ b/inc/subscription.php @@ -249,10 +249,10 @@ class Subscription { * * @param string $id Page ID, defaults to global $ID * @param string $user User, defaults to $_SERVER['REMOTE_USER'] - * @return array + * @return array|false * @author Adrian Lang <lang@cosmocode.de> */ - function user_subscription($id = '', $user = '') { + public function user_subscription($id = '', $user = '') { if(!$this->isenabled()) return false; global $ID; diff --git a/inc/template.php b/inc/template.php index 03c7bf96f..a74b24053 100644 --- a/inc/template.php +++ b/inc/template.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * Access a template file * @@ -1422,7 +1420,11 @@ function tpl_mediaFileDetails($image, $rev) { /** @var Input $INPUT */ global $INPUT; - $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')) && $conf['mediarevisions']); + $removed = ( + !file_exists(mediaFN($image)) && + file_exists(mediaMetaFN($image, '.changes')) && + $conf['mediarevisions'] + ); if(!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return; if($rev && !file_exists(mediaFN($image, $rev))) $rev = false; $ns = getNS($image); @@ -1450,7 +1452,8 @@ function tpl_mediaFileDetails($image, $rev) { $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext); $class = 'select mediafile mf_'.$class; $attributes = $rev ? ['rev' => $rev] : []; - $tabTitle = '<strong><a href="'.ml($image, $attributes).'" class="'.$class.'" title="'.$lang['mediaview'].'">'.$image.'</a>'.'</strong>'; + $tabTitle = '<strong><a href="'.ml($image, $attributes).'" class="'.$class.'" title="'.$lang['mediaview'].'">'. + $image.'</a>'.'</strong>'; if($opened_tab === 'view' && $rev) { printf($lang['media_viewold'], $tabTitle, dformat($rev)); } else { diff --git a/inc/toolbar.php b/inc/toolbar.php index 7cc29e866..125d4d490 100644 --- a/inc/toolbar.php +++ b/inc/toolbar.php @@ -6,8 +6,6 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) die('meh.'); - /** * Prepares and prints an JavaScript array with all toolbar buttons * @@ -213,7 +211,30 @@ function toolbar_JSdefines($varname){ 'type' => 'picker', 'title' => $lang['qb_chars'], 'icon' => 'chars.png', - 'list' => explode(' ','À à Á á  â à ã Ä ä Ǎ ǎ Ă ă Å å Ā ā Ą ą Æ æ Ć ć Ç ç Č č Ĉ ĉ Ċ ċ Ð đ ð Ď ď È è É é Ê ê Ë ë Ě ě Ē ē Ė ė Ę ę Ģ ģ Ĝ ĝ Ğ ğ Ġ ġ Ĥ ĥ Ì ì Í í Î î Ï ï Ǐ ǐ Ī ī İ ı Į į Ĵ ĵ Ķ ķ Ĺ ĺ Ļ ļ Ľ ľ Ł ł Ŀ ŀ Ń ń Ñ ñ Ņ ņ Ň ň Ò ò Ó ó Ô ô Õ õ Ö ö Ǒ ǒ Ō ō Ő ő Œ œ Ø ø Ŕ ŕ Ŗ ŗ Ř ř Ś ś Ş ş Š š Ŝ ŝ Ţ ţ Ť ť Ù ù Ú ú Û û Ü ü Ǔ ǔ Ŭ ŭ Ū ū Ů ů ǖ ǘ ǚ ǜ Ų ų Ű ű Ŵ ŵ Ý ý Ÿ ÿ Ŷ ŷ Ź ź Ž ž Ż ż Þ þ ß Ħ ħ ¿ ¡ ¢ £ ¤ ¥ € ¦ § ª ¬ ¯ ° ± ÷ ‰ ¼ ½ ¾ ¹ ² ³ µ ¶ † ‡ · • º ∀ ∂ ∃ Ə ə ∅ ∇ ∈ ∉ ∋ ∏ ∑ ‾ − ∗ × ⁄ √ ∝ ∞ ∠ ∧ ∨ ∩ ∪ ∫ ∴ ∼ ≅ ≈ ≠ ≡ ≤ ≥ ⊂ ⊃ ⊄ ⊆ ⊇ ⊕ ⊗ ⊥ ⋅ ◊ ℘ ℑ ℜ ℵ ♠ ♣ ♥ ♦ α β Γ γ Δ δ ε ζ η Θ θ ι κ Λ λ μ Ξ ξ Π π ρ Σ σ Τ τ υ Φ φ χ Ψ ψ Ω ω ★ ☆ ☎ ☚ ☛ ☜ ☝ ☞ ☟ ☹ ☺ ✔ ✘ „ “ ” ‚ ‘ ’ « » ‹ › — – … ← ↑ → ↓ ↔ ⇐ ⇑ ⇒ ⇓ ⇔ © ™ ® ′ ″ [ ] { } ~ ( ) % § $ # | @'), + 'list' => [ + 'À', 'à', 'Á', 'á', 'Â', 'â', 'Ã', 'ã', 'Ä', 'ä', 'Ǎ', 'ǎ', 'Ă', 'ă', 'Å', 'å', + 'Ā', 'ā', 'Ą', 'ą', 'Æ', 'æ', 'Ć', 'ć', 'Ç', 'ç', 'Č', 'č', 'Ĉ', 'ĉ', 'Ċ', 'ċ', + 'Ð', 'đ', 'ð', 'Ď', 'ď', 'È', 'è', 'É', 'é', 'Ê', 'ê', 'Ë', 'ë', 'Ě', 'ě', 'Ē', + 'ē', 'Ė', 'ė', 'Ę', 'ę', 'Ģ', 'ģ', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ĥ', 'ĥ', 'Ì', + 'ì', 'Í', 'í', 'Î', 'î', 'Ï', 'ï', 'Ǐ', 'ǐ', 'Ī', 'ī', 'İ', 'ı', 'Į', 'į', 'Ĵ', + 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ł', 'ł', 'Ŀ', 'ŀ', 'Ń', 'ń', 'Ñ', + 'ñ', 'Ņ', 'ņ', 'Ň', 'ň', 'Ò', 'ò', 'Ó', 'ó', 'Ô', 'ô', 'Õ', 'õ', 'Ö', 'ö', 'Ǒ', + 'ǒ', 'Ō', 'ō', 'Ő', 'ő', 'Œ', 'œ', 'Ø', 'ø', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', + 'ś', 'Ş', 'ş', 'Š', 'š', 'Ŝ', 'ŝ', 'Ţ', 'ţ', 'Ť', 'ť', 'Ù', 'ù', 'Ú', 'ú', 'Û', + 'û', 'Ü', 'ü', 'Ǔ', 'ǔ', 'Ŭ', 'ŭ', 'Ū', 'ū', 'Ů', 'ů', 'ǖ', 'ǘ', 'ǚ', 'ǜ', 'Ų', + 'ų', 'Ű', 'ű', 'Ŵ', 'ŵ', 'Ý', 'ý', 'Ÿ', 'ÿ', 'Ŷ', 'ŷ', 'Ź', 'ź', 'Ž', 'ž', 'Ż', + 'ż', 'Þ', 'þ', 'ß', 'Ħ', 'ħ', '¿', '¡', '¢', '£', '¤', '¥', '€', '¦', '§', 'ª', + '¬', '¯', '°', '±', '÷', '‰', '¼', '½', '¾', '¹', '²', '³', 'µ', '¶', '†', '‡', + '·', '•', 'º', '∀', '∂', '∃', 'Ə', 'ə', '∅', '∇', '∈', '∉', '∋', '∏', '∑', '‾', + '−', '∗', '×', '⁄', '√', '∝', '∞', '∠', '∧', '∨', '∩', '∪', '∫', '∴', '∼', '≅', + '≈', '≠', '≡', '≤', '≥', '⊂', '⊃', '⊄', '⊆', '⊇', '⊕', '⊗', '⊥', '⋅', '◊', '℘', + 'ℑ', 'ℜ', 'ℵ', '♠', '♣', '♥', '♦', 'α', 'β', 'Γ', 'γ', 'Δ', 'δ', 'ε', 'ζ', 'η', + 'Θ', 'θ', 'ι', 'κ', 'Λ', 'λ', 'μ', 'Ξ', 'ξ', 'Π', 'π', 'ρ', 'Σ', 'σ', 'Τ', 'τ', + 'υ', 'Φ', 'φ', 'χ', 'Ψ', 'ψ', 'Ω', 'ω', '★', '☆', '☎', '☚', '☛', '☜', '☝', '☞', + '☟', '☹', '☺', '✔', '✘', '„', '“', '”', '‚', '‘', '’', '«', '»', '‹', '›', '—', + '–', '…', '←', '↑', '→', '↓', '↔', '⇐', '⇑', '⇒', '⇓', '⇔', '©', '™', '®', '′', + '″', '[', ']', '{', '}', '~', '(', ')', '%', '§', '$', '#', '|', '@' + ], 'block' => false ), array( diff --git a/inc/utf8.php b/inc/utf8.php index 4de287429..3c8106599 100644 --- a/inc/utf8.php +++ b/inc/utf8.php @@ -238,7 +238,7 @@ if(!function_exists('utf8_substr')){ if ($length > 0) { - $length = min($strlen-$offset, $length); // reduce any length that would go passed the end of the string + $length = min($strlen-$offset, $length); // reduce any length that would go past the end of the string $Lx = (int)($length/65535); $Ly = $length%65535; @@ -649,7 +649,7 @@ if(!class_exists('utf8_entity_decoder')){ /** * Initializes the decoding tables */ - function __construct() { + public function __construct() { $table = get_html_translation_table(HTML_ENTITIES); $table = array_flip($table); $this->table = array_map(array(&$this,'makeutf8'), $table); @@ -661,7 +661,7 @@ if(!class_exists('utf8_entity_decoder')){ * @param string $c * @return string|false */ - function makeutf8($c) { + public function makeutf8($c) { return unicode_to_utf8(array(ord($c))); } @@ -671,7 +671,7 @@ if(!class_exists('utf8_entity_decoder')){ * @param string $ent An entity * @return string|false */ - function decode($ent) { + public function decode($ent) { if ($ent[1] == '#') { return utf8_decode_numeric($ent); } elseif (array_key_exists($ent[0],$this->table)) { @@ -1474,7 +1474,8 @@ if(empty($UTF8_ROMANIZATION)) $UTF8_ROMANIZATION = array( 'っりゃ'=>'rrya','っりぇ'=>'rrye','っりぃ'=>'rryi','っりょ'=>'rryo','っりゅ'=>'rryu', 'っしゃ'=>'ssha','っしぇ'=>'sshe','っし'=>'sshi','っしょ'=>'ssho','っしゅ'=>'sshu', - // seperate hiragana 'n' ('n' + 'i' != 'ni', normally we would write "kon'nichi wa" but the apostrophe would be converted to _ anyway) + // seperate hiragana 'n' ('n' + 'i' != 'ni', normally we would write "kon'nichi wa" but the + // apostrophe would be converted to _ anyway) 'んあ'=>'n_a','んえ'=>'n_e','んい'=>'n_i','んお'=>'n_o','んう'=>'n_u', 'んや'=>'n_ya','んよ'=>'n_yo','んゆ'=>'n_yu', @@ -1561,7 +1562,8 @@ if(empty($UTF8_ROMANIZATION)) $UTF8_ROMANIZATION = array( // Japanese katakana - // 4 character syllables: ッ doubles the consonant after, ー doubles the vowel before (usualy written with macron, but we don't want that in our URLs) + // 4 character syllables: ッ doubles the consonant after, ー doubles the vowel before + // (usualy written with macron, but we don't want that in our URLs) 'ッビャー'=>'bbyaa','ッビェー'=>'bbyee','ッビィー'=>'bbyii','ッビョー'=>'bbyoo','ッビュー'=>'bbyuu', 'ッピャー'=>'ppyaa','ッピェー'=>'ppyee','ッピィー'=>'ppyii','ッピョー'=>'ppyoo','ッピュー'=>'ppyuu', 'ッキャー'=>'kkyaa','ッキェー'=>'kkyee','ッキィー'=>'kkyii','ッキョー'=>'kkyoo','ッキュー'=>'kkyuu', diff --git a/install.php b/install.php index dfbce1de8..5e4bbf325 100644 --- a/install.php +++ b/install.php @@ -95,8 +95,11 @@ header('Content-Type: text/html; charset=utf-8'); print "</div>\n"; } ?> - <a style="background: transparent url(data/dont-panic-if-you-see-this-in-your-logs-it-means-your-directory-permissions-are-correct.png) left top no-repeat; - display: block; width:380px; height:73px; border:none; clear:both;" + <a style=" + background: transparent + url(data/dont-panic-if-you-see-this-in-your-logs-it-means-your-directory-permissions-are-correct.png) + left top no-repeat; + display: block; width:380px; height:73px; border:none; clear:both;" target="_blank" href="http://www.dokuwiki.org/security#web_access_security"></a> </div> @@ -170,10 +173,12 @@ function print_form($d){ <fieldset id="acldep"> <label for="superuser"><?php echo $lang['i_superuser']?></label> - <input class="text" type="text" name="d[superuser]" id="superuser" value="<?php echo $d['superuser'] ?>" /> + <input class="text" type="text" name="d[superuser]" id="superuser" + value="<?php echo $d['superuser'] ?>" /> <label for="fullname"><?php echo $lang['fullname']?></label> - <input class="text" type="text" name="d[fullname]" id="fullname" value="<?php echo $d['fullname'] ?>" /> + <input class="text" type="text" name="d[fullname]" id="fullname" + value="<?php echo $d['fullname'] ?>" /> <label for="email"><?php echo $lang['email']?></label> <input class="text" type="text" name="d[email]" id="email" value="<?php echo $d['email'] ?>" /> @@ -186,13 +191,17 @@ function print_form($d){ <label for="policy"><?php echo $lang['i_policy']?></label> <select class="text" name="d[policy]" id="policy"> - <option value="0" <?php echo ($d['policy'] == 0)?'selected="selected"':'' ?>><?php echo $lang['i_pol0']?></option> - <option value="1" <?php echo ($d['policy'] == 1)?'selected="selected"':'' ?>><?php echo $lang['i_pol1']?></option> - <option value="2" <?php echo ($d['policy'] == 2)?'selected="selected"':'' ?>><?php echo $lang['i_pol2']?></option> + <option value="0" <?php echo ($d['policy'] == 0)?'selected="selected"':'' ?>><?php + echo $lang['i_pol0']?></option> + <option value="1" <?php echo ($d['policy'] == 1)?'selected="selected"':'' ?>><?php + echo $lang['i_pol1']?></option> + <option value="2" <?php echo ($d['policy'] == 2)?'selected="selected"':'' ?>><?php + echo $lang['i_pol2']?></option> </select> <label for="allowreg"> - <input type="checkbox" name="d[allowreg]" id="allowreg" <?php echo(($d['allowreg'] ? ' checked="checked"' : ''));?> /> + <input type="checkbox" name="d[allowreg]" id="allowreg" <?php + echo(($d['allowreg'] ? ' checked="checked"' : ''));?> /> <?php echo $lang['i_allowreg']?> </label> </fieldset> @@ -217,8 +226,10 @@ function print_form($d){ <fieldset> <p><?php echo $lang['i_pop_field']?></p> <label for="pop"> - <input type="checkbox" name="d[pop]" id="pop" <?php echo(($d['pop'] ? ' checked="checked"' : ''));?> /> - <?php echo $lang['i_pop_label']?> <a href="http://www.dokuwiki.org/popularity" target="_blank"><sup>[?]</sup></a> + <input type="checkbox" name="d[pop]" id="pop" <?php + echo(($d['pop'] ? ' checked="checked"' : ''));?> /> + <?php echo $lang['i_pop_label']?> + <a href="http://www.dokuwiki.org/popularity" target="_blank"><sup>[?]</sup></a> </label> </fieldset> diff --git a/lib/exe/css.php b/lib/exe/css.php index 40eaf99a6..a557f79cc 100644 --- a/lib/exe/css.php +++ b/lib/exe/css.php @@ -67,7 +67,8 @@ function css_out(){ // load jQuery-UI theme if ($mediatype == 'screen') { - $files[DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/'; + $files[DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = + DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/'; } // load plugin styles $files = array_merge($files, css_pluginstyles($mediatype)); @@ -99,7 +100,16 @@ function css_out(){ } // The generated script depends on some dynamic options - $cache = new cache('styles'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].$INPUT->bool('preview').DOKU_BASE.$tpl.$type,'.css'); + $cache = new cache( + 'styles' . + $_SERVER['HTTP_HOST'] . + $_SERVER['SERVER_PORT'] . + $INPUT->bool('preview') . + DOKU_BASE . + $tpl . + $type, + '.css' + ); $cache->_event = 'CSS_CACHE_USE'; // check cache age & handle conditional request @@ -547,18 +557,50 @@ function css_compress($css){ $css = preg_replace('/ ?: /',':',$css); // number compression - $css = preg_replace('/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2$3', $css); // "0.1em" to ".1em", "1.10em" to "1.1em" - $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0" - $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0" - $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em" - $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em" + $css = preg_replace( + '/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', + '$1$2$3', + $css + ); // "0.1em" to ".1em", "1.10em" to "1.1em" + $css = preg_replace( + '/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', + '$1$2', + $css + ); // ".0em" to "0" + $css = preg_replace( + '/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', + '$1', + $css + ); // "0.0em" to "0" + $css = preg_replace( + '/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', + '$1$3', + $css + ); // "1.0em" to "1em" + $css = preg_replace( + '/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', + '$1$2$3', + $css + ); // "001em" to "1em" // shorten attributes (1em 1em 1em 1em -> 1em) - $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em" - $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em" + $css = preg_replace( + '/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', + '$1$2', + $css + ); // "1em 1em 1em 1em" to "1em" + $css = preg_replace( + '/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', + '$1$2 $3', + $css + ); // "1em 2em 1em 2em" to "1em 2em" // shorten colors - $css = preg_replace("/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/", "#\\1\\2\\3", $css); + $css = preg_replace( + "/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/", + "#\\1\\2\\3", + $css + ); return $css; } diff --git a/lib/exe/js.php b/lib/exe/js.php index 7b76efabb..b63a8598e 100644 --- a/lib/exe/js.php +++ b/lib/exe/js.php @@ -100,8 +100,12 @@ function js_out(){ 'secure' => $conf['securecookie'] && is_ssl() )).";"; // FIXME: Move those to JSINFO - print "Object.defineProperty(window, 'DOKU_UHN', { get: function() { console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead'); return JSINFO.useHeadingNavigation; } });"; - print "Object.defineProperty(window, 'DOKU_UHC', { get: function() { console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead'); return JSINFO.useHeadingContent; } });"; + print "Object.defineProperty(window, 'DOKU_UHN', { get: function() {". + "console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead');". + "return JSINFO.useHeadingNavigation; } });"; + print "Object.defineProperty(window, 'DOKU_UHC', { get: function() {". + "console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead');". + "return JSINFO.useHeadingContent; } });"; // load JS specific translations $lang['js']['plugins'] = js_pluginstrings(); diff --git a/lib/exe/xmlrpc.php b/lib/exe/xmlrpc.php index 3046f47e9..dc0438ee1 100644 --- a/lib/exe/xmlrpc.php +++ b/lib/exe/xmlrpc.php @@ -1,67 +1,15 @@ <?php -if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); - -require_once(DOKU_INC.'inc/init.php'); -session_write_close(); //close session - -if(!$conf['remote']) die((new IXR_Error(-32605, "XML-RPC server not enabled."))->getXml()); - /** - * Contains needed wrapper functions and registers all available - * XMLRPC functions. + * XMLRPC API backend */ -class dokuwiki_xmlrpc_server extends IXR_Server { - protected $remote; - - /** - * Constructor. Register methods and run Server - */ - public function __construct(){ - $this->remote = new RemoteAPI(); - $this->remote->setDateTransformation(array($this, 'toDate')); - $this->remote->setFileTransformation(array($this, 'toFile')); - parent::__construct(); - } - /** - * @param string $methodname - * @param array $args - * @return IXR_Error|mixed - */ - public function call($methodname, $args){ - try { - $result = $this->remote->call($methodname, $args); - return $result; - } catch (RemoteAccessDeniedException $e) { - if (!isset($_SERVER['REMOTE_USER'])) { - http_status(401); - return new IXR_Error(-32603, "server error. not authorized to call method $methodname"); - } else { - http_status(403); - return new IXR_Error(-32604, "server error. forbidden to call the method $methodname"); - } - } catch (RemoteException $e) { - return new IXR_Error($e->getCode(), $e->getMessage()); - } - } +use dokuwiki\Remote\XmlRpcServer; - /** - * @param string|int $data iso date(yyyy[-]mm[-]dd[ hh:mm[:ss]]) or timestamp - * @return IXR_Date - */ - public function toDate($data) { - return new IXR_Date($data); - } +if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__).'/../../'); - /** - * @param string $data - * @return IXR_Base64 - */ - public function toFile($data) { - return new IXR_Base64($data); - } -} +require_once(DOKU_INC.'inc/init.php'); +session_write_close(); //close session -$server = new dokuwiki_xmlrpc_server(); +if(!$conf['remote']) die((new IXR_Error(-32605, "XML-RPC server not enabled."))->getXml()); -// vim:ts=4:sw=4:et: +$server = new XmlRpcServer(); diff --git a/lib/plugins/acl/action.php b/lib/plugins/acl/action.php index a7226f598..b895d0b5a 100644 --- a/lib/plugins/acl/action.php +++ b/lib/plugins/acl/action.php @@ -6,13 +6,11 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * Register handler */ -class action_plugin_acl extends DokuWiki_Action_Plugin { +class action_plugin_acl extends DokuWiki_Action_Plugin +{ /** * Registers a callback function for a given event @@ -20,10 +18,10 @@ class action_plugin_acl extends DokuWiki_Action_Plugin { * @param Doku_Event_Handler $controller DokuWiki's event controller object * @return void */ - public function register(Doku_Event_Handler $controller) { - - $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax_call_acl'); + public function register(Doku_Event_Handler $controller) + { + $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleAjaxCallAcl'); } /** @@ -34,8 +32,9 @@ class action_plugin_acl extends DokuWiki_Action_Plugin { * @return void */ - public function handle_ajax_call_acl(Doku_Event &$event, $param) { - if($event->data !== 'plugin_acl') { + public function handleAjaxCallAcl(Doku_Event $event, $param) + { + if ($event->data !== 'plugin_acl') { return; } $event->stopPropagation(); @@ -44,11 +43,11 @@ class action_plugin_acl extends DokuWiki_Action_Plugin { global $ID; global $INPUT; - if(!auth_isadmin()) { + if (!auth_isadmin()) { echo 'for admins only'; return; } - if(!checkSecurityToken()) { + if (!checkSecurityToken()) { echo 'CRSF Attack'; return; } @@ -62,26 +61,27 @@ class action_plugin_acl extends DokuWiki_Action_Plugin { $ajax = $INPUT->str('ajax'); header('Content-Type: text/html; charset=utf-8'); - if($ajax == 'info') { - $acl->_html_info(); - } elseif($ajax == 'tree') { - + if ($ajax == 'info') { + $acl->printInfo(); + } elseif ($ajax == 'tree') { $ns = $INPUT->str('ns'); - if($ns == '*') { + if ($ns == '*') { $ns = ''; } $ns = cleanID($ns); $lvl = count(explode(':', $ns)); $ns = utf8_encodeFN(str_replace(':', '/', $ns)); - $data = $acl->_get_tree($ns, $ns); + $data = $acl->makeTree($ns, $ns); - foreach(array_keys($data) as $item) { + foreach (array_keys($data) as $item) { $data[$item]['level'] = $lvl + 1; } echo html_buildlist( - $data, 'acl', array($acl, '_html_list_acl'), - array($acl, '_html_li_acl') + $data, + 'acl', + array($acl, 'makeTreeItem'), + array($acl, 'makeListItem') ); } } diff --git a/lib/plugins/acl/admin.php b/lib/plugins/acl/admin.php index 6edc6c621..9dee059a3 100644 --- a/lib/plugins/acl/admin.php +++ b/lib/plugins/acl/admin.php @@ -7,16 +7,15 @@ * @author Anika Henke <anika@selfthinker.org> (concepts) * @author Frank Schubert <frank@schokilade.de> (old version) */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); /** * All DokuWiki plugins to extend the admin function * need to inherit from this class */ -class admin_plugin_acl extends DokuWiki_Admin_Plugin { - var $acl = null; - var $ns = null; +class admin_plugin_acl extends DokuWiki_Admin_Plugin +{ + public $acl = null; + protected $ns = null; /** * The currently selected item, associative array with id and type. * Populated from (in this order): @@ -25,22 +24,24 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * $ns * $ID */ - var $current_item = null; - var $who = ''; - var $usersgroups = array(); - var $specials = array(); + protected $current_item = null; + protected $who = ''; + protected $usersgroups = array(); + protected $specials = array(); /** * return prompt for admin menu */ - function getMenuText($language) { + public function getMenuText($language) + { return $this->getLang('admin_acl'); } /** * return sort order for position in admin menu */ - function getMenuSort() { + public function getMenuSort() + { return 1; } @@ -51,7 +52,8 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function handle() { + public function handle() + { global $AUTH_ACL; global $ID; global $auth; @@ -62,9 +64,9 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { $AUTH_ACL = file($config_cascade['acl']['default']); // namespace given? - if($INPUT->str('ns') == '*'){ + if ($INPUT->str('ns') == '*') { $this->ns = '*'; - }else{ + } else { $this->ns = cleanID($INPUT->str('ns')); } @@ -80,78 +82,78 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { // user or group choosen? $who = trim($INPUT->str('acl_w')); - if($INPUT->str('acl_t') == '__g__' && $who){ - $this->who = '@'.ltrim($auth->cleanGroup($who),'@'); - }elseif($INPUT->str('acl_t') == '__u__' && $who){ - $this->who = ltrim($who,'@'); - if($this->who != '%USER%' && $this->who != '%GROUP%'){ #keep wildcard as is + if ($INPUT->str('acl_t') == '__g__' && $who) { + $this->who = '@'.ltrim($auth->cleanGroup($who), '@'); + } elseif ($INPUT->str('acl_t') == '__u__' && $who) { + $this->who = ltrim($who, '@'); + if ($this->who != '%USER%' && $this->who != '%GROUP%') { #keep wildcard as is $this->who = $auth->cleanUser($this->who); } - }elseif($INPUT->str('acl_t') && + } elseif ($INPUT->str('acl_t') && $INPUT->str('acl_t') != '__u__' && - $INPUT->str('acl_t') != '__g__'){ + $INPUT->str('acl_t') != '__g__') { $this->who = $INPUT->str('acl_t'); - }elseif($who){ + } elseif ($who) { $this->who = $who; } // handle modifications - if($INPUT->has('cmd') && checkSecurityToken()){ + if ($INPUT->has('cmd') && checkSecurityToken()) { $cmd = $INPUT->extract('cmd')->str('cmd'); // scope for modifications - if($this->ns){ - if($this->ns == '*'){ + if ($this->ns) { + if ($this->ns == '*') { $scope = '*'; - }else{ + } else { $scope = $this->ns.':*'; } - }else{ + } else { $scope = $ID; } - if($cmd == 'save' && $scope && $this->who && $INPUT->has('acl')){ + if ($cmd == 'save' && $scope && $this->who && $INPUT->has('acl')) { // handle additions or single modifications - $this->_acl_del($scope, $this->who); - $this->_acl_add($scope, $this->who, $INPUT->int('acl')); - }elseif($cmd == 'del' && $scope && $this->who){ + $this->deleteACL($scope, $this->who); + $this->addACL($scope, $this->who, $INPUT->int('acl')); + } elseif ($cmd == 'del' && $scope && $this->who) { // handle single deletions - $this->_acl_del($scope, $this->who); - }elseif($cmd == 'update'){ + $this->deleteACL($scope, $this->who); + } elseif ($cmd == 'update') { $acl = $INPUT->arr('acl'); // handle update of the whole file - foreach($INPUT->arr('del') as $where => $names){ + foreach ($INPUT->arr('del') as $where => $names) { // remove all rules marked for deletion - foreach($names as $who) + foreach ($names as $who) unset($acl[$where][$who]); } // prepare lines $lines = array(); // keep header - foreach($AUTH_ACL as $line){ - if($line{0} == '#'){ + foreach ($AUTH_ACL as $line) { + if ($line{0} == '#') { $lines[] = $line; - }else{ + } else { break; } } // re-add all rules - foreach($acl as $where => $opt){ - foreach($opt as $who => $perm){ + foreach ($acl as $where => $opt) { + foreach ($opt as $who => $perm) { if ($who[0]=='@') { if ($who!='@ALL') { - $who = '@'.ltrim($auth->cleanGroup($who),'@'); + $who = '@'.ltrim($auth->cleanGroup($who), '@'); } - } elseif ($who != '%USER%' && $who != '%GROUP%'){ #keep wildcard as is + } elseif ($who != '%USER%' && $who != '%GROUP%') { #keep wildcard as is $who = $auth->cleanUser($who); } - $who = auth_nameencode($who,true); + $who = auth_nameencode($who, true); $lines[] = "$where\t$who\t$perm\n"; } } // save it - io_saveFile($config_cascade['acl']['default'], join('',$lines)); + io_saveFile($config_cascade['acl']['default'], join('', $lines)); } // reload ACL config @@ -159,7 +161,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { } // initialize ACL array - $this->_init_acl_config(); + $this->initAclConfig(); } /** @@ -171,24 +173,25 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * @author Frank Schubert <frank@schokilade.de> * @author Andreas Gohr <andi@splitbrain.org> */ - function html() { + public function html() + { echo '<div id="acl_manager">'.NL; echo '<h1>'.$this->getLang('admin_acl').'</h1>'.NL; echo '<div class="level1">'.NL; echo '<div id="acl__tree">'.NL; - $this->_html_explorer(); + $this->makeExplorer(); echo '</div>'.NL; echo '<div id="acl__detail">'.NL; - $this->_html_detail(); + $this->printDetail(); echo '</div>'.NL; echo '</div>'.NL; echo '<div class="clearer"></div>'; echo '<h2>'.$this->getLang('current').'</h2>'.NL; echo '<div class="level2">'.NL; - $this->_html_table(); + $this->printAclTable(); echo '</div>'.NL; echo '<div class="footnotes"><div class="fn">'.NL; @@ -204,15 +207,16 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _get_opts($addopts=null){ + protected function getLinkOptions($addopts = null) + { $opts = array( 'do'=>'admin', 'page'=>'acl', ); - if($this->ns) $opts['ns'] = $this->ns; - if($this->who) $opts['acl_w'] = $this->who; + if ($this->ns) $opts['ns'] = $this->ns; + if ($this->who) $opts['acl_w'] = $this->who; - if(is_null($addopts)) return $opts; + if (is_null($addopts)) return $opts; return array_merge($opts, $addopts); } @@ -221,54 +225,61 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _html_explorer(){ + protected function makeExplorer() + { global $conf; global $ID; global $lang; $ns = $this->ns; - if(empty($ns)){ - $ns = dirname(str_replace(':','/',$ID)); - if($ns == '.') $ns =''; - }elseif($ns == '*'){ + if (empty($ns)) { + $ns = dirname(str_replace(':', '/', $ID)); + if ($ns == '.') $ns =''; + } elseif ($ns == '*') { $ns =''; } - $ns = utf8_encodeFN(str_replace(':','/',$ns)); + $ns = utf8_encodeFN(str_replace(':', '/', $ns)); - $data = $this->_get_tree($ns); + $data = $this->makeTree($ns); // wrap a list with the root level around the other namespaces array_unshift($data, array( 'level' => 0, 'id' => '*', 'type' => 'd', 'open' =>'true', 'label' => '['.$lang['mediaroot'].']')); - echo html_buildlist($data,'acl', - array($this,'_html_list_acl'), - array($this,'_html_li_acl')); - + echo html_buildlist( + $data, + 'acl', + array($this, 'makeTreeItem'), + array($this, 'makeListItem') + ); } /** * get a combined list of media and page files * + * also called via AJAX + * * @param string $folder an already converted filesystem folder of the current namespace - * @param string $limit limit the search to this folder + * @param string $limit limit the search to this folder + * @return array */ - function _get_tree($folder,$limit=''){ + public function makeTree($folder, $limit = '') + { global $conf; // read tree structure from pages and media $data = array(); - search($data,$conf['datadir'],'search_index',array('ns' => $folder),$limit); + search($data, $conf['datadir'], 'search_index', array('ns' => $folder), $limit); $media = array(); - search($media,$conf['mediadir'],'search_index',array('ns' => $folder, 'nofiles' => true),$limit); - $data = array_merge($data,$media); + search($media, $conf['mediadir'], 'search_index', array('ns' => $folder, 'nofiles' => true), $limit); + $data = array_merge($data, $media); unset($media); // combine by sorting and removing duplicates - usort($data,array($this,'_tree_sort')); + usort($data, array($this, 'treeSort')); $count = count($data); - if($count>0) for($i=1; $i<$count; $i++){ - if($data[$i-1]['id'] == $data[$i]['id'] && $data[$i-1]['type'] == $data[$i]['type']) { + if ($count>0) for ($i=1; $i<$count; $i++) { + if ($data[$i-1]['id'] == $data[$i]['id'] && $data[$i-1]['type'] == $data[$i]['type']) { unset($data[$i]); $i++; // duplicate found, next $i can't be a duplicate, so skip forward one } @@ -281,7 +292,8 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * Sorts the combined trees of media and page files */ - function _tree_sort($a,$b){ + public function treeSort($a, $b) + { // handle the trivial cases first if ($a['id'] == '') return -1; if ($b['id'] == '') return 1; @@ -315,6 +327,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { // before that other part. if (empty($a_ids)) return ($a['type'] == 'd') ? -1 : 1; if (empty($b_ids)) return ($b['type'] == 'd') ? 1 : -1; + return 0; //shouldn't happen } /** @@ -323,20 +336,21 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _html_detail(){ + protected function printDetail() + { global $ID; echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL; echo '<div id="acl__user">'; echo $this->getLang('acl_perms').' '; - $inl = $this->_html_select(); - echo '<input type="text" name="acl_w" class="edit" value="'.(($inl)?'':hsc(ltrim($this->who,'@'))).'" />'.NL; + $inl = $this->makeSelect(); + echo '<input type="text" name="acl_w" class="edit" value="'.(($inl)?'':hsc(ltrim($this->who, '@'))).'" />'.NL; echo '<button type="submit">'.$this->getLang('btn_select').'</button>'.NL; echo '</div>'.NL; echo '<div id="acl__info">'; - $this->_html_info(); + $this->printInfo(); echo '</div>'; echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL; @@ -349,23 +363,26 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { /** * Print info and editor + * + * also loaded via Ajax */ - function _html_info(){ + public function printInfo() + { global $ID; - if($this->who){ - $current = $this->_get_exact_perm(); + if ($this->who) { + $current = $this->getExactPermisson(); // explain current permissions - $this->_html_explain($current); + $this->printExplanation($current); // load editor - $this->_html_acleditor($current); - }else{ + $this->printAclEditor($current); + } else { echo '<p>'; - if($this->ns){ - printf($this->getLang('p_choose_ns'),hsc($this->ns)); - }else{ - printf($this->getLang('p_choose_id'),hsc($ID)); + if ($this->ns) { + printf($this->getLang('p_choose_ns'), hsc($this->ns)); + } else { + printf($this->getLang('p_choose_id'), hsc($ID)); } echo '</p>'; @@ -378,21 +395,22 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _html_acleditor($current){ + protected function printAclEditor($current) + { global $lang; echo '<fieldset>'; - if(is_null($current)){ + if (is_null($current)) { echo '<legend>'.$this->getLang('acl_new').'</legend>'; - }else{ + } else { echo '<legend>'.$this->getLang('acl_mod').'</legend>'; } - echo $this->_html_checkboxes($current,empty($this->ns),'acl'); + echo $this->makeCheckboxes($current, empty($this->ns), 'acl'); - if(is_null($current)){ + if (is_null($current)) { echo '<button type="submit" name="cmd[save]">'.$lang['btn_save'].'</button>'.NL; - }else{ + } else { echo '<button type="submit" name="cmd[save]">'.$lang['btn_update'].'</button>'.NL; echo '<button type="submit" name="cmd[del]">'.$lang['btn_delete'].'</button>'.NL; } @@ -405,7 +423,8 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _html_explain($current){ + protected function printExplanation($current) + { global $ID; global $auth; @@ -413,69 +432,69 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { $ns = $this->ns; // prepare where to check - if($ns){ - if($ns == '*'){ + if ($ns) { + if ($ns == '*') { $check='*'; - }else{ + } else { $check=$ns.':*'; } - }else{ + } else { $check = $ID; } // prepare who to check - if($who{0} == '@'){ + if ($who{0} == '@') { $user = ''; - $groups = array(ltrim($who,'@')); - }else{ + $groups = array(ltrim($who, '@')); + } else { $user = $who; $info = $auth->getUserData($user); - if($info === false){ + if ($info === false) { $groups = array(); - }else{ + } else { $groups = $info['grps']; } } // check the permissions - $perm = auth_aclcheck($check,$user,$groups); + $perm = auth_aclcheck($check, $user, $groups); // build array of named permissions $names = array(); - if($perm){ - if($ns){ - if($perm >= AUTH_DELETE) $names[] = $this->getLang('acl_perm16'); - if($perm >= AUTH_UPLOAD) $names[] = $this->getLang('acl_perm8'); - if($perm >= AUTH_CREATE) $names[] = $this->getLang('acl_perm4'); + if ($perm) { + if ($ns) { + if ($perm >= AUTH_DELETE) $names[] = $this->getLang('acl_perm16'); + if ($perm >= AUTH_UPLOAD) $names[] = $this->getLang('acl_perm8'); + if ($perm >= AUTH_CREATE) $names[] = $this->getLang('acl_perm4'); } - if($perm >= AUTH_EDIT) $names[] = $this->getLang('acl_perm2'); - if($perm >= AUTH_READ) $names[] = $this->getLang('acl_perm1'); + if ($perm >= AUTH_EDIT) $names[] = $this->getLang('acl_perm2'); + if ($perm >= AUTH_READ) $names[] = $this->getLang('acl_perm1'); $names = array_reverse($names); - }else{ + } else { $names[] = $this->getLang('acl_perm0'); } // print permission explanation echo '<p>'; - if($user){ - if($ns){ - printf($this->getLang('p_user_ns'),hsc($who),hsc($ns),join(', ',$names)); - }else{ - printf($this->getLang('p_user_id'),hsc($who),hsc($ID),join(', ',$names)); + if ($user) { + if ($ns) { + printf($this->getLang('p_user_ns'), hsc($who), hsc($ns), join(', ', $names)); + } else { + printf($this->getLang('p_user_id'), hsc($who), hsc($ID), join(', ', $names)); } - }else{ - if($ns){ - printf($this->getLang('p_group_ns'),hsc(ltrim($who,'@')),hsc($ns),join(', ',$names)); - }else{ - printf($this->getLang('p_group_id'),hsc(ltrim($who,'@')),hsc($ID),join(', ',$names)); + } else { + if ($ns) { + printf($this->getLang('p_group_ns'), hsc(ltrim($who, '@')), hsc($ns), join(', ', $names)); + } else { + printf($this->getLang('p_group_id'), hsc(ltrim($who, '@')), hsc($ID), join(', ', $names)); } } echo '</p>'; // add note if admin - if($perm == AUTH_ADMIN){ + if ($perm == AUTH_ADMIN) { echo '<p>'.$this->getLang('p_isadmin').'</p>'; - }elseif(is_null($current)){ + } elseif (is_null($current)) { echo '<p>'.$this->getLang('p_inherited').'</p>'; } } @@ -488,46 +507,57 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _html_list_acl($item){ + protected function makeTreeItem($item) + { $ret = ''; // what to display - if(!empty($item['label'])){ + if (!empty($item['label'])) { $base = $item['label']; - }else{ + } else { $base = ':'.$item['id']; - $base = substr($base,strrpos($base,':')+1); + $base = substr($base, strrpos($base, ':')+1); } // highlight? - if( ($item['type']== $this->current_item['type'] && $item['id'] == $this->current_item['id'])) { + if (($item['type']== $this->current_item['type'] && $item['id'] == $this->current_item['id'])) { $cl = ' cur'; } else { $cl = ''; } // namespace or page? - if($item['type']=='d'){ - if($item['open']){ + if ($item['type']=='d') { + if ($item['open']) { $img = DOKU_BASE.'lib/images/minus.gif'; $alt = '−'; - }else{ + } else { $img = DOKU_BASE.'lib/images/plus.gif'; $alt = '+'; } $ret .= '<img src="'.$img.'" alt="'.$alt.'" />'; - $ret .= '<a href="'.wl('',$this->_get_opts(array('ns'=>$item['id'],'sectok'=>getSecurityToken()))).'" class="idx_dir'.$cl.'">'; + $ret .= '<a href="'. + wl('', $this->getLinkOptions(array('ns'=> $item['id'], 'sectok'=>getSecurityToken()))). + '" class="idx_dir'.$cl.'">'; $ret .= $base; $ret .= '</a>'; - }else{ - $ret .= '<a href="'.wl('',$this->_get_opts(array('id'=>$item['id'],'ns'=>'','sectok'=>getSecurityToken()))).'" class="wikilink1'.$cl.'">'; + } else { + $ret .= '<a href="'. + wl('', $this->getLinkOptions(array('id'=> $item['id'], 'ns'=>'', 'sectok'=>getSecurityToken()))). + '" class="wikilink1'.$cl.'">'; $ret .= noNS($item['id']); $ret .= '</a>'; } return $ret; } - - function _html_li_acl($item){ + /** + * List Item formatter + * + * @param array $item + * @return string + */ + public function makeListItem($item) + { return '<li class="level' . $item['level'] . ' ' . ($item['open'] ? 'open' : 'closed') . '">'; } @@ -538,7 +568,8 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _init_acl_config(){ + public function initAclConfig() + { global $AUTH_ACL; global $conf; $acl_config=array(); @@ -547,20 +578,24 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { // get special users and groups $this->specials[] = '@ALL'; $this->specials[] = '@'.$conf['defaultgroup']; - if($conf['manager'] != '!!not set!!'){ - $this->specials = array_merge($this->specials, - array_map('trim', - explode(',',$conf['manager']))); + if ($conf['manager'] != '!!not set!!') { + $this->specials = array_merge( + $this->specials, + array_map( + 'trim', + explode(',', $conf['manager']) + ) + ); } $this->specials = array_filter($this->specials); $this->specials = array_unique($this->specials); sort($this->specials); - foreach($AUTH_ACL as $line){ - $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments - if(!$line) continue; + foreach ($AUTH_ACL as $line) { + $line = trim(preg_replace('/#.*$/', '', $line)); //ignore comments + if (!$line) continue; - $acl = preg_split('/[ \t]+/',$line); + $acl = preg_split('/[ \t]+/', $line); //0 is pagename, 1 is user, 2 is acl $acl[1] = rawurldecode($acl[1]); @@ -568,7 +603,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { // store non-special users and groups for later selection dialog $ug = $acl[1]; - if(in_array($ug,$this->specials)) continue; + if (in_array($ug, $this->specials)) continue; $usersgroups[] = $ug; } @@ -585,14 +620,15 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _html_table(){ + protected function printAclTable() + { global $lang; global $ID; echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL; - if($this->ns){ + if ($this->ns) { echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL; - }else{ + } else { echo '<input type="hidden" name="id" value="'.hsc($ID).'" />'.NL; } echo '<input type="hidden" name="acl_w" value="'.hsc($this->who).'" />'.NL; @@ -607,29 +643,29 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { echo '<th>'.$this->getLang('perm').'<sup><a id="fnt__1" class="fn_top" href="#fn__1">1)</a></sup></th>'; echo '<th>'.$lang['btn_delete'].'</th>'; echo '</tr>'; - foreach($this->acl as $where => $set){ - foreach($set as $who => $perm){ + foreach ($this->acl as $where => $set) { + foreach ($set as $who => $perm) { echo '<tr>'; echo '<td>'; - if(substr($where,-1) == '*'){ + if (substr($where, -1) == '*') { echo '<span class="aclns">'.hsc($where).'</span>'; $ispage = false; - }else{ + } else { echo '<span class="aclpage">'.hsc($where).'</span>'; $ispage = true; } echo '</td>'; echo '<td>'; - if($who{0} == '@'){ + if ($who{0} == '@') { echo '<span class="aclgroup">'.hsc($who).'</span>'; - }else{ + } else { echo '<span class="acluser">'.hsc($who).'</span>'; } echo '</td>'; echo '<td>'; - echo $this->_html_checkboxes($perm,$ispage,'acl['.$where.']['.$who.']'); + echo $this->makeCheckboxes($perm, $ispage, 'acl['.$where.']['.$who.']'); echo '</td>'; echo '<td class="check">'; @@ -655,21 +691,22 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _get_exact_perm(){ + protected function getExactPermisson() + { global $ID; - if($this->ns){ - if($this->ns == '*'){ + if ($this->ns) { + if ($this->ns == '*') { $check = '*'; - }else{ + } else { $check = $this->ns.':*'; } - }else{ + } else { $check = $ID; } - if(isset($this->acl[$check][$this->who])){ + if (isset($this->acl[$check][$this->who])) { return $this->acl[$check][$this->who]; - }else{ + } else { return null; } } @@ -679,13 +716,14 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Frank Schubert <frank@schokilade.de> */ - function _acl_add($acl_scope, $acl_user, $acl_level){ + public function addACL($acl_scope, $acl_user, $acl_level) + { global $config_cascade; - $acl_user = auth_nameencode($acl_user,true); + $acl_user = auth_nameencode($acl_user, true); // max level for pagenames is edit - if(strpos($acl_scope,'*') === false) { - if($acl_level > AUTH_EDIT) $acl_level = AUTH_EDIT; + if (strpos($acl_scope, '*') === false) { + if ($acl_level > AUTH_EDIT) $acl_level = AUTH_EDIT; } $new_acl = "$acl_scope\t$acl_user\t$acl_level\n"; @@ -698,11 +736,12 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Frank Schubert <frank@schokilade.de> */ - function _acl_del($acl_scope, $acl_user){ + public function deleteACL($acl_scope, $acl_user) + { global $config_cascade; - $acl_user = auth_nameencode($acl_user,true); + $acl_user = auth_nameencode($acl_user, true); - $acl_pattern = '^'.preg_quote($acl_scope,'/').'[ \t]+'.$acl_user.'[ \t]+[0-8].*$'; + $acl_pattern = '^'.preg_quote($acl_scope, '/').'[ \t]+'.$acl_user.'[ \t]+[0-8].*$'; return io_deleteFromFile($config_cascade['acl']['default'], "/$acl_pattern/", true); } @@ -713,15 +752,16 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * @author Frank Schubert <frank@schokilade.de> * @author Andreas Gohr <andi@splitbrain.org> */ - function _html_checkboxes($setperm,$ispage,$name){ + protected function makeCheckboxes($setperm, $ispage, $name) + { global $lang; static $label = 0; //number labels $ret = ''; - if($ispage && $setperm > AUTH_EDIT) $setperm = AUTH_EDIT; + if ($ispage && $setperm > AUTH_EDIT) $setperm = AUTH_EDIT; - foreach(array(AUTH_NONE,AUTH_READ,AUTH_EDIT,AUTH_CREATE,AUTH_UPLOAD,AUTH_DELETE) as $perm){ + foreach (array(AUTH_NONE,AUTH_READ,AUTH_EDIT,AUTH_CREATE,AUTH_UPLOAD,AUTH_DELETE) as $perm) { $label += 1; //general checkbox attributes @@ -730,11 +770,11 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { 'name' => $name, 'value' => $perm ); //dynamic attributes - if(!is_null($setperm) && $setperm == $perm) $atts['checked'] = 'checked'; - if($ispage && $perm > AUTH_EDIT){ + if (!is_null($setperm) && $setperm == $perm) $atts['checked'] = 'checked'; + if ($ispage && $perm > AUTH_EDIT) { $atts['disabled'] = 'disabled'; $class = ' class="disabled"'; - }else{ + } else { $class = ''; } @@ -752,21 +792,21 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - function _html_select(){ + protected function makeSelect() + { $inlist = false; $usel = ''; $gsel = ''; - if($this->who && - !in_array($this->who,$this->usersgroups) && - !in_array($this->who,$this->specials)){ - - if($this->who{0} == '@'){ + if ($this->who && + !in_array($this->who, $this->usersgroups) && + !in_array($this->who, $this->specials)) { + if ($this->who{0} == '@') { $gsel = ' selected="selected"'; - }else{ + } else { $usel = ' selected="selected"'; } - }else{ + } else { $inlist = true; } @@ -775,17 +815,17 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { echo ' <option value="__u__" class="acluser"'.$usel.'>'.$this->getLang('acl_user').'</option>'.NL; if (!empty($this->specials)) { echo ' <optgroup label=" ">'.NL; - foreach($this->specials as $ug){ - if($ug == $this->who){ + foreach ($this->specials as $ug) { + if ($ug == $this->who) { $sel = ' selected="selected"'; $inlist = true; - }else{ + } else { $sel = ''; } - if($ug{0} == '@'){ + if ($ug{0} == '@') { echo ' <option value="'.hsc($ug).'" class="aclgroup"'.$sel.'>'.hsc($ug).'</option>'.NL; - }else{ + } else { echo ' <option value="'.hsc($ug).'" class="acluser"'.$sel.'>'.hsc($ug).'</option>'.NL; } } @@ -793,17 +833,17 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { } if (!empty($this->usersgroups)) { echo ' <optgroup label=" ">'.NL; - foreach($this->usersgroups as $ug){ - if($ug == $this->who){ + foreach ($this->usersgroups as $ug) { + if ($ug == $this->who) { $sel = ' selected="selected"'; $inlist = true; - }else{ + } else { $sel = ''; } - if($ug{0} == '@'){ + if ($ug{0} == '@') { echo ' <option value="'.hsc($ug).'" class="aclgroup"'.$sel.'>'.hsc($ug).'</option>'.NL; - }else{ + } else { echo ' <option value="'.hsc($ug).'" class="acluser"'.$sel.'>'.hsc($ug).'</option>'.NL; } } diff --git a/lib/plugins/acl/remote.php b/lib/plugins/acl/remote.php index 27c5c162a..31a8cde53 100644 --- a/lib/plugins/acl/remote.php +++ b/lib/plugins/acl/remote.php @@ -1,16 +1,20 @@ <?php +use dokuwiki\Remote\AccessDeniedException; + /** * Class remote_plugin_acl */ -class remote_plugin_acl extends DokuWiki_Remote_Plugin { +class remote_plugin_acl extends DokuWiki_Remote_Plugin +{ /** * Returns details about the remote plugin methods * - * @return array Information about all provided methods. {@see RemoteAPI} + * @return array Information about all provided methods. {@see dokuwiki\Remote\RemoteAPI} */ - public function _getMethods() { + public function _getMethods() + { return array( 'listAcls' => array( 'args' => array(), @@ -34,16 +38,20 @@ class remote_plugin_acl extends DokuWiki_Remote_Plugin { /** * List all ACL config entries * - * @throws RemoteAccessDeniedException + * @throws AccessDeniedException * @return dictionary {Scope: ACL}, where ACL = dictionnary {user/group: permissions_int} */ - public function listAcls(){ - if(!auth_isadmin()) { - throw new RemoteAccessDeniedException('You are not allowed to access ACLs, superuser permission is required', 114); + public function listAcls() + { + if (!auth_isadmin()) { + throw new AccessDeniedException( + 'You are not allowed to access ACLs, superuser permission is required', + 114 + ); } /** @var admin_plugin_acl $apa */ $apa = plugin_load('admin', 'acl'); - $apa->_init_acl_config(); + $apa->initAclConfig(); return $apa->acl; } @@ -53,17 +61,21 @@ class remote_plugin_acl extends DokuWiki_Remote_Plugin { * @param string $scope * @param string $user * @param int $level see also inc/auth.php - * @throws RemoteAccessDeniedException + * @throws AccessDeniedException * @return bool */ - public function addAcl($scope, $user, $level){ - if(!auth_isadmin()) { - throw new RemoteAccessDeniedException('You are not allowed to access ACLs, superuser permission is required', 114); + public function addAcl($scope, $user, $level) + { + if (!auth_isadmin()) { + throw new AccessDeniedException( + 'You are not allowed to access ACLs, superuser permission is required', + 114 + ); } /** @var admin_plugin_acl $apa */ $apa = plugin_load('admin', 'acl'); - return $apa->_acl_add($scope, $user, $level); + return $apa->addACL($scope, $user, $level); } /** @@ -71,17 +83,20 @@ class remote_plugin_acl extends DokuWiki_Remote_Plugin { * * @param string $scope * @param string $user - * @throws RemoteAccessDeniedException + * @throws AccessDeniedException * @return bool */ - public function delAcl($scope, $user){ - if(!auth_isadmin()) { - throw new RemoteAccessDeniedException('You are not allowed to access ACLs, superuser permission is required', 114); + public function delAcl($scope, $user) + { + if (!auth_isadmin()) { + throw new AccessDeniedException( + 'You are not allowed to access ACLs, superuser permission is required', + 114 + ); } /** @var admin_plugin_acl $apa */ $apa = plugin_load('admin', 'acl'); - return $apa->_acl_del($scope, $user); + return $apa->deleteACL($scope, $user); } } - diff --git a/lib/plugins/action.php b/lib/plugins/action.php index 23d94a509..496c56926 100644 --- a/lib/plugins/action.php +++ b/lib/plugins/action.php @@ -2,24 +2,18 @@ /** * Action Plugin Prototype * - * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) - * @author Christopher Smith <chris@jalakai.co.uk> - */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -/** * All DokuWiki plugins to interfere with the event system * need to inherit from this class + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Christopher Smith <chris@jalakai.co.uk> */ -class DokuWiki_Action_Plugin extends DokuWiki_Plugin { +abstract class DokuWiki_Action_Plugin extends DokuWiki_Plugin { /** * Registers a callback function for a given event * * @param Doku_Event_Handler $controller */ - public function register(Doku_Event_Handler $controller) { - trigger_error('register() not implemented in '.get_class($this), E_USER_WARNING); - } + abstract public function register(Doku_Event_Handler $controller); } diff --git a/lib/plugins/admin.php b/lib/plugins/admin.php index 4e1cbbb33..a1d99a412 100644 --- a/lib/plugins/admin.php +++ b/lib/plugins/admin.php @@ -2,17 +2,13 @@ /** * Admin Plugin Prototype * - * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) - * @author Christopher Smith <chris@jalakai.co.uk> - */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -/** * All DokuWiki plugins to extend the admin function * need to inherit from this class + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Christopher Smith <chris@jalakai.co.uk> */ -class DokuWiki_Admin_Plugin extends DokuWiki_Plugin { +abstract class DokuWiki_Admin_Plugin extends DokuWiki_Plugin { /** * Return the text that is displayed at the main admin menu @@ -62,15 +58,13 @@ class DokuWiki_Admin_Plugin extends DokuWiki_Plugin { * Carry out required processing */ public function handle() { - trigger_error('handle() not implemented in '.get_class($this), E_USER_WARNING); + // some plugins might not need this } /** * Output html of the admin page */ - public function html() { - trigger_error('html() not implemented in '.get_class($this), E_USER_WARNING); - } + abstract public function html(); /** * Return true for access only by admins (config:superuser) or false if managers are allowed as well diff --git a/lib/plugins/auth.php b/lib/plugins/auth.php index 0cd965b72..442580b23 100644 --- a/lib/plugins/auth.php +++ b/lib/plugins/auth.php @@ -1,7 +1,4 @@ <?php -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * Auth Plugin Prototype * @@ -12,7 +9,7 @@ if(!defined('DOKU_INC')) die(); * @author Chris Smith <chris@jalakai.co.uk> * @author Jan Schumann <js@jschumann-it.com> */ -class DokuWiki_Auth_Plugin extends DokuWiki_Plugin { +abstract class DokuWiki_Auth_Plugin extends DokuWiki_Plugin { public $success = true; /** @@ -115,7 +112,8 @@ class DokuWiki_Auth_Plugin extends DokuWiki_Plugin { * * @author Gabriel Birke <birke@d-scribe.de> * @param string $type Modification type ('create', 'modify', 'delete') - * @param array $params Parameters for the createUser, modifyUser or deleteUsers method. The content of this array depends on the modification type + * @param array $params Parameters for the createUser, modifyUser or deleteUsers method. + * The content of this array depends on the modification type * @return bool|null|int Result from the modification function or false if an event handler has canceled the action */ public function triggerUserMod($type, $params) { @@ -132,7 +130,7 @@ class DokuWiki_Auth_Plugin extends DokuWiki_Plugin { $eventdata = array('type' => $type, 'params' => $params, 'modification_result' => null); $evt = new Doku_Event('AUTH_USER_CHANGE', $eventdata); if($evt->advise_before(true)) { - $result = call_user_func_array(array($this, $validTypes[$type]), $evt->data['params']); + $result = call_user_func_array(array($this, $validTypes[$type]), $evt->data['params']); $evt->data['modification_result'] = $result; } $evt->advise_after(); diff --git a/lib/plugins/authad/action.php b/lib/plugins/authad/action.php index bc0f90c7e..a9fc01c1b 100644 --- a/lib/plugins/authad/action.php +++ b/lib/plugins/authad/action.php @@ -6,22 +6,20 @@ * @author Andreas Gohr <gohr@cosmocode.de> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * Class action_plugin_addomain */ -class action_plugin_authad extends DokuWiki_Action_Plugin { +class action_plugin_authad extends DokuWiki_Action_Plugin +{ /** * Registers a callback function for a given event */ - public function register(Doku_Event_Handler $controller) { - - $controller->register_hook('AUTH_LOGIN_CHECK', 'BEFORE', $this, 'handle_auth_login_check'); - $controller->register_hook('HTML_LOGINFORM_OUTPUT', 'BEFORE', $this, 'handle_html_loginform_output'); + public function register(Doku_Event_Handler $controller) + { + $controller->register_hook('AUTH_LOGIN_CHECK', 'BEFORE', $this, 'handleAuthLoginCheck'); + $controller->register_hook('HTML_LOGINFORM_OUTPUT', 'BEFORE', $this, 'handleHtmlLoginformOutput'); } /** @@ -30,17 +28,18 @@ class action_plugin_authad extends DokuWiki_Action_Plugin { * @param Doku_Event $event * @param array $param */ - public function handle_auth_login_check(Doku_Event &$event, $param) { + public function handleAuthLoginCheck(Doku_Event $event, $param) + { global $INPUT; /** @var auth_plugin_authad $auth */ global $auth; - if(!is_a($auth, 'auth_plugin_authad')) return; // AD not even used + if (!is_a($auth, 'auth_plugin_authad')) return; // AD not even used - if($INPUT->str('dom')) { + if ($INPUT->str('dom')) { $usr = $auth->cleanUser($event->data['user']); - $dom = $auth->_userDomain($usr); - if(!$dom) { + $dom = $auth->getUserDomain($usr); + if (!$dom) { $usr = "$usr@".$INPUT->str('dom'); } $INPUT->post->set('u', $usr); @@ -54,26 +53,27 @@ class action_plugin_authad extends DokuWiki_Action_Plugin { * @param Doku_Event $event * @param array $param */ - public function handle_html_loginform_output(Doku_Event &$event, $param) { + public function handleHtmlLoginformOutput(Doku_Event $event, $param) + { global $INPUT; /** @var auth_plugin_authad $auth */ global $auth; - if(!is_a($auth, 'auth_plugin_authad')) return; // AD not even used - $domains = $auth->_getConfiguredDomains(); - if(count($domains) <= 1) return; // no choice at all + if (!is_a($auth, 'auth_plugin_authad')) return; // AD not even used + $domains = $auth->getConfiguredDomains(); + if (count($domains) <= 1) return; // no choice at all /** @var Doku_Form $form */ $form =& $event->data; // any default? $dom = ''; - if($INPUT->has('u')) { + if ($INPUT->has('u')) { $usr = $auth->cleanUser($INPUT->str('u')); - $dom = $auth->_userDomain($usr); + $dom = $auth->getUserDomain($usr); // update user field value - if($dom) { - $usr = $auth->_userName($usr); + if ($dom) { + $usr = $auth->getUserName($usr); $pos = $form->findElementByAttribute('name', 'u'); $ele =& $form->getElementAt($pos); $ele['value'] = $usr; @@ -85,7 +85,6 @@ class action_plugin_authad extends DokuWiki_Action_Plugin { $pos = $form->findElementByAttribute('name', 'p'); $form->insertElement($pos + 1, $element); } - } -// vim:ts=4:sw=4:et:
\ No newline at end of file +// vim:ts=4:sw=4:et: diff --git a/lib/plugins/authad/auth.php b/lib/plugins/authad/auth.php index 50f708456..30c128792 100644 --- a/lib/plugins/authad/auth.php +++ b/lib/plugins/authad/auth.php @@ -1,9 +1,4 @@ <?php -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php'); -require_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php'); /** * Active Directory authentication backend for DokuWiki @@ -41,7 +36,8 @@ require_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php'); * @author Andreas Gohr <andi@splitbrain.org> * @author Jan Schumann <js@schumann-it.com> */ -class auth_plugin_authad extends DokuWiki_Auth_Plugin { +class auth_plugin_authad extends DokuWiki_Auth_Plugin +{ /** * @var array hold connection data for a specific AD domain @@ -66,52 +62,55 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { /** * @var array filter patterns for listing users */ - protected $_pattern = array(); + protected $pattern = array(); - protected $_actualstart = 0; + protected $actualstart = 0; - protected $_grpsusers = array(); + protected $grpsusers = array(); /** * Constructor */ - public function __construct() { + public function __construct() + { global $INPUT; parent::__construct(); + require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php'); + require_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php'); + // we load the config early to modify it a bit here $this->loadConfig(); // additional information fields - if(isset($this->conf['additional'])) { + if (isset($this->conf['additional'])) { $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']); $this->conf['additional'] = explode(',', $this->conf['additional']); } else $this->conf['additional'] = array(); // ldap extension is needed - if(!function_exists('ldap_connect')) { - if($this->conf['debug']) + if (!function_exists('ldap_connect')) { + if ($this->conf['debug']) msg("AD Auth: PHP LDAP extension not found.", -1); $this->success = false; return; } // Prepare SSO - if(!empty($_SERVER['REMOTE_USER'])) { - + if (!empty($_SERVER['REMOTE_USER'])) { // make sure the right encoding is used - if($this->getConf('sso_charset')) { + if ($this->getConf('sso_charset')) { $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']); - } elseif(!utf8_check($_SERVER['REMOTE_USER'])) { + } elseif (!utf8_check($_SERVER['REMOTE_USER'])) { $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']); } // trust the incoming user - if($this->conf['sso']) { + if ($this->conf['sso']) { $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']); // we need to simulate a login - if(empty($_COOKIE[DOKU_COOKIE])) { + if (empty($_COOKIE[DOKU_COOKIE])) { $INPUT->set('u', $_SERVER['REMOTE_USER']); $INPUT->set('p', 'sso_only'); } @@ -130,10 +129,11 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param string $cap * @return bool */ - public function canDo($cap) { + public function canDo($cap) + { //capabilities depend on config, which may change depending on domain - $domain = $this->_userDomain($_SERVER['REMOTE_USER']); - $this->_loadServerConfig($domain); + $domain = $this->getUserDomain($_SERVER['REMOTE_USER']); + $this->loadServerConfig($domain); return parent::canDo($cap); } @@ -149,16 +149,22 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param string $pass * @return bool */ - public function checkPass($user, $pass) { - if($_SERVER['REMOTE_USER'] && + public function checkPass($user, $pass) + { + if ($_SERVER['REMOTE_USER'] && $_SERVER['REMOTE_USER'] == $user && $this->conf['sso'] ) return true; - $adldap = $this->_adldap($this->_userDomain($user)); - if(!$adldap) return false; + $adldap = $this->initAdLdap($this->getUserDomain($user)); + if (!$adldap) return false; - return $adldap->authenticate($this->_userName($user), $pass); + try { + return $adldap->authenticate($this->getUserName($user), $pass); + } catch (adLDAPException $e) { + // shouldn't really happen + return false; + } } /** @@ -186,14 +192,15 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin * @return array */ - public function getUserData($user, $requireGroups=true) { + public function getUserData($user, $requireGroups = true) + { global $conf; global $lang; global $ID; - $adldap = $this->_adldap($this->_userDomain($user)); - if(!$adldap) return false; + $adldap = $this->initAdLdap($this->getUserDomain($user)); + if (!$adldap) return array(); - if($user == '') return array(); + if ($user == '') return array(); $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol'); @@ -203,8 +210,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { $fields = array_filter($fields); //get info for given user - $result = $adldap->user()->info($this->_userName($user), $fields); - if($result == false){ + $result = $adldap->user()->info($this->getUserName($user), $fields); + if ($result == false) { return array(); } @@ -220,52 +227,56 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD // additional information - foreach($this->conf['additional'] as $field) { - if(isset($result[0][strtolower($field)])) { + foreach ($this->conf['additional'] as $field) { + if (isset($result[0][strtolower($field)])) { $info[$field] = $result[0][strtolower($field)][0]; } } // handle ActiveDirectory memberOf - $info['grps'] = $adldap->user()->groups($this->_userName($user),(bool) $this->opts['recursive_groups']); + $info['grps'] = $adldap->user()->groups($this->getUserName($user), (bool) $this->opts['recursive_groups']); - if(is_array($info['grps'])) { - foreach($info['grps'] as $ndx => $group) { + if (is_array($info['grps'])) { + foreach ($info['grps'] as $ndx => $group) { $info['grps'][$ndx] = $this->cleanGroup($group); } } // always add the default group to the list of groups - if(!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) { + if (!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) { $info['grps'][] = $conf['defaultgroup']; } // add the user's domain to the groups - $domain = $this->_userDomain($user); - if($domain && !in_array("domain-$domain", (array) $info['grps'])) { + $domain = $this->getUserDomain($user); + if ($domain && !in_array("domain-$domain", (array) $info['grps'])) { $info['grps'][] = $this->cleanGroup("domain-$domain"); } // check expiry time - if($info['expires'] && $this->conf['expirywarn']){ - $expiry = $adldap->user()->passwordExpiry($user); - if(is_array($expiry)){ - $info['expiresat'] = $expiry['expiryts']; - $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60)); - - // if this is the current user, warn him (once per request only) - if(($_SERVER['REMOTE_USER'] == $user) && - ($info['expiresin'] <= $this->conf['expirywarn']) && - !$this->msgshown - ) { - $msg = sprintf($this->getLang('authpwdexpire'), $info['expiresin']); - if($this->canDo('modPass')) { - $url = wl($ID, array('do'=> 'profile')); - $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>'; + if ($info['expires'] && $this->conf['expirywarn']) { + try { + $expiry = $adldap->user()->passwordExpiry($user); + if (is_array($expiry)) { + $info['expiresat'] = $expiry['expiryts']; + $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60)); + + // if this is the current user, warn him (once per request only) + if (($_SERVER['REMOTE_USER'] == $user) && + ($info['expiresin'] <= $this->conf['expirywarn']) && + !$this->msgshown + ) { + $msg = sprintf($this->getLang('authpwdexpire'), $info['expiresin']); + if ($this->canDo('modPass')) { + $url = wl($ID, array('do'=> 'profile')); + $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>'; + } + msg($msg); + $this->msgshown = true; } - msg($msg); - $this->msgshown = true; } + } catch (adLDAPException $e) { + // ignore. should usually not happen } } @@ -281,7 +292,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param string $group * @return string */ - public function cleanGroup($group) { + public function cleanGroup($group) + { $group = str_replace('\\', '', $group); $group = str_replace('#', '', $group); $group = preg_replace('[\s]', '_', $group); @@ -298,27 +310,28 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param string $user * @return string */ - public function cleanUser($user) { + public function cleanUser($user) + { $domain = ''; // get NTLM or Kerberos domain part list($dom, $user) = explode('\\', $user, 2); - if(!$user) $user = $dom; - if($dom) $domain = $dom; + if (!$user) $user = $dom; + if ($dom) $domain = $dom; list($user, $dom) = explode('@', $user, 2); - if($dom) $domain = $dom; + if ($dom) $domain = $dom; // clean up both $domain = utf8_strtolower(trim($domain)); $user = utf8_strtolower(trim($user)); // is this a known, valid domain? if not discard - if(!is_array($this->conf[$domain])) { + if (!is_array($this->conf[$domain])) { $domain = ''; } // reattach domain - if($domain) $user = "$user@$domain"; + if ($domain) $user = "$user@$domain"; return $user; } @@ -327,7 +340,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * * @return bool */ - public function isCaseSensitive() { + public function isCaseSensitive() + { return false; } @@ -337,11 +351,12 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param array $filter * @return string */ - protected function _constructSearchString($filter){ - if (!$filter){ + protected function constructSearchString($filter) + { + if (!$filter) { return '*'; } - $adldapUtils = new adLDAPUtils($this->_adldap(null)); + $adldapUtils = new adLDAPUtils($this->initAdLdap(null)); $result = '*'; if (isset($filter['name'])) { $result .= ')(displayname=*' . $adldapUtils->ldapSlashes($filter['name']) . '*'; @@ -366,32 +381,41 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param array $filter $filter array of field/pattern pairs, empty array for no filter * @return int number of users */ - public function getUserCount($filter = array()) { - $adldap = $this->_adldap(null); - if(!$adldap) { + public function getUserCount($filter = array()) + { + $adldap = $this->initAdLdap(null); + if (!$adldap) { dbglog("authad/auth.php getUserCount(): _adldap not set."); return -1; } if ($filter == array()) { $result = $adldap->user()->all(); } else { - $searchString = $this->_constructSearchString($filter); + $searchString = $this->constructSearchString($filter); $result = $adldap->user()->all(false, $searchString); if (isset($filter['grps'])) { $this->users = array_fill_keys($result, false); + /** @var admin_plugin_usermanager $usermanager */ $usermanager = plugin_load("admin", "usermanager", false); $usermanager->setLastdisabled(true); - if (!isset($this->_grpsusers[$this->_filterToString($filter)])){ - $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize()); - } elseif (count($this->_grpsusers[$this->_filterToString($filter)]) < $usermanager->getStart() + 3*$usermanager->getPagesize()) { - $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize() - count($this->_grpsusers[$this->_filterToString($filter)])); + if (!isset($this->grpsusers[$this->filterToString($filter)])) { + $this->fillGroupUserArray($filter, $usermanager->getStart() + 3*$usermanager->getPagesize()); + } elseif (count($this->grpsusers[$this->filterToString($filter)]) < + $usermanager->getStart() + 3*$usermanager->getPagesize() + ) { + $this->fillGroupUserArray( + $filter, + $usermanager->getStart() + + 3*$usermanager->getPagesize() - + count($this->grpsusers[$this->filterToString($filter)]) + ); } - $result = $this->_grpsusers[$this->_filterToString($filter)]; + $result = $this->grpsusers[$this->filterToString($filter)]; } else { + /** @var admin_plugin_usermanager $usermanager */ $usermanager = plugin_load("admin", "usermanager", false); $usermanager->setLastdisabled(false); } - } if (!$result) { @@ -407,7 +431,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param array $filter * @return string */ - protected function _filterToString ($filter) { + protected function filterToString($filter) + { $result = ''; if (isset($filter['user'])) { $result .= 'user-' . $filter['user']; @@ -433,24 +458,25 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param int $numberOfAdds additional number of users requested * @return int number of Users actually add to Array */ - protected function _fillGroupUserArray($filter, $numberOfAdds){ - $this->_grpsusers[$this->_filterToString($filter)]; + protected function fillGroupUserArray($filter, $numberOfAdds) + { + $this->grpsusers[$this->filterToString($filter)]; $i = 0; $count = 0; - $this->_constructPattern($filter); + $this->constructPattern($filter); foreach ($this->users as $user => &$info) { - if($i++ < $this->_actualstart) { + if ($i++ < $this->actualstart) { continue; } - if($info === false) { + if ($info === false) { $info = $this->getUserData($user); } - if($this->_filter($user, $info)) { - $this->_grpsusers[$this->_filterToString($filter)][$user] = $info; - if(($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break; + if ($this->filter($user, $info)) { + $this->grpsusers[$this->filterToString($filter)][$user] = $info; + if (($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break; } } - $this->_actualstart = $i; + $this->actualstart = $i; return $count; } @@ -464,13 +490,14 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param array $filter array of field/pattern pairs, null for no filter * @return array userinfo (refer getUserData for internal userinfo details) */ - public function retrieveUsers($start = 0, $limit = 0, $filter = array()) { - $adldap = $this->_adldap(null); - if(!$adldap) return false; + public function retrieveUsers($start = 0, $limit = 0, $filter = array()) + { + $adldap = $this->initAdLdap(null); + if (!$adldap) return array(); - if(!$this->users) { + if (!$this->users) { //get info for given user - $result = $adldap->user()->all(false, $this->_constructSearchString($filter)); + $result = $adldap->user()->all(false, $this->constructSearchString($filter)); if (!$result) return array(); $this->users = array_fill_keys($result, false); } @@ -480,34 +507,40 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { $result = array(); if (!isset($filter['grps'])) { + /** @var admin_plugin_usermanager $usermanager */ $usermanager = plugin_load("admin", "usermanager", false); $usermanager->setLastdisabled(false); - $this->_constructPattern($filter); - foreach($this->users as $user => &$info) { - if($i++ < $start) { + $this->constructPattern($filter); + foreach ($this->users as $user => &$info) { + if ($i++ < $start) { continue; } - if($info === false) { + if ($info === false) { $info = $this->getUserData($user); } $result[$user] = $info; - if(($limit > 0) && (++$count >= $limit)) break; + if (($limit > 0) && (++$count >= $limit)) break; } } else { + /** @var admin_plugin_usermanager $usermanager */ $usermanager = plugin_load("admin", "usermanager", false); $usermanager->setLastdisabled(true); - if (!isset($this->_grpsusers[$this->_filterToString($filter)]) || count($this->_grpsusers[$this->_filterToString($filter)]) < ($start+$limit)) { - $this->_fillGroupUserArray($filter,$start+$limit - count($this->_grpsusers[$this->_filterToString($filter)]) +1); + if (!isset($this->grpsusers[$this->filterToString($filter)]) || + count($this->grpsusers[$this->filterToString($filter)]) < ($start+$limit) + ) { + $this->fillGroupUserArray( + $filter, + $start+$limit - count($this->grpsusers[$this->filterToString($filter)]) +1 + ); } - if (!$this->_grpsusers[$this->_filterToString($filter)]) return false; - foreach($this->_grpsusers[$this->_filterToString($filter)] as $user => &$info) { - if($i++ < $start) { + if (!$this->grpsusers[$this->filterToString($filter)]) return array(); + foreach ($this->grpsusers[$this->filterToString($filter)] as $user => &$info) { + if ($i++ < $start) { continue; } $result[$user] = $info; - if(($limit > 0) && (++$count >= $limit)) break; + if (($limit > 0) && (++$count >= $limit)) break; } - } return $result; } @@ -519,45 +552,46 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param array $changes array of field/value pairs to be changed * @return bool */ - public function modifyUser($user, $changes) { + public function modifyUser($user, $changes) + { $return = true; - $adldap = $this->_adldap($this->_userDomain($user)); - if(!$adldap) { + $adldap = $this->initAdLdap($this->getUserDomain($user)); + if (!$adldap) { msg($this->getLang('connectfail'), -1); return false; } // password changing - if(isset($changes['pass'])) { + if (isset($changes['pass'])) { try { - $return = $adldap->user()->password($this->_userName($user),$changes['pass']); + $return = $adldap->user()->password($this->getUserName($user), $changes['pass']); } catch (adLDAPException $e) { if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1); $return = false; } - if(!$return) msg($this->getLang('passchangefail'), -1); + if (!$return) msg($this->getLang('passchangefail'), -1); } // changing user data $adchanges = array(); - if(isset($changes['name'])) { + if (isset($changes['name'])) { // get first and last name $parts = explode(' ', $changes['name']); $adchanges['surname'] = array_pop($parts); $adchanges['firstname'] = join(' ', $parts); $adchanges['display_name'] = $changes['name']; } - if(isset($changes['mail'])) { + if (isset($changes['mail'])) { $adchanges['email'] = $changes['mail']; } - if(count($adchanges)) { + if (count($adchanges)) { try { - $return = $return & $adldap->user()->modify($this->_userName($user),$adchanges); + $return = $return & $adldap->user()->modify($this->getUserName($user), $adchanges); } catch (adLDAPException $e) { if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1); $return = false; } - if(!$return) msg($this->getLang('userchangefail'), -1); + if (!$return) msg($this->getLang('userchangefail'), -1); } return $return; @@ -573,20 +607,21 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param string|null $domain The AD domain to use * @return adLDAP|bool true if a connection was established */ - protected function _adldap($domain) { - if(is_null($domain) && is_array($this->opts)) { + protected function initAdLdap($domain) + { + if (is_null($domain) && is_array($this->opts)) { $domain = $this->opts['domain']; } - $this->opts = $this->_loadServerConfig((string) $domain); - if(isset($this->adldap[$domain])) return $this->adldap[$domain]; + $this->opts = $this->loadServerConfig((string) $domain); + if (isset($this->adldap[$domain])) return $this->adldap[$domain]; // connect try { $this->adldap[$domain] = new adLDAP($this->opts); return $this->adldap[$domain]; - } catch(adLDAPException $e) { - if($this->conf['debug']) { + } catch (Exception $e) { + if ($this->conf['debug']) { msg('AD Auth: '.$e->getMessage(), -1); } $this->success = false; @@ -601,7 +636,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param string $user * @return string */ - public function _userDomain($user) { + public function getUserDomain($user) + { list(, $domain) = explode('@', $user, 2); return $domain; } @@ -612,7 +648,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param string $user * @return string */ - public function _userName($user) { + public function getUserName($user) + { list($name) = explode('@', $user, 2); return $name; } @@ -623,14 +660,15 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param string $domain current AD domain * @return array */ - protected function _loadServerConfig($domain) { + protected function loadServerConfig($domain) + { // prepare adLDAP standard configuration $opts = $this->conf; $opts['domain'] = $domain; // add possible domain specific configuration - if($domain && is_array($this->conf[$domain])) foreach($this->conf[$domain] as $key => $val) { + if ($domain && is_array($this->conf[$domain])) foreach ($this->conf[$domain] as $key => $val) { $opts[$key] = $val; } @@ -640,23 +678,27 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { $opts['domain_controllers'] = array_filter($opts['domain_controllers']); // compatibility with old option name - if(empty($opts['admin_username']) && !empty($opts['ad_username'])) $opts['admin_username'] = $opts['ad_username']; - if(empty($opts['admin_password']) && !empty($opts['ad_password'])) $opts['admin_password'] = $opts['ad_password']; + if (empty($opts['admin_username']) && !empty($opts['ad_username'])) { + $opts['admin_username'] = $opts['ad_username']; + } + if (empty($opts['admin_password']) && !empty($opts['ad_password'])) { + $opts['admin_password'] = $opts['ad_password']; + } $opts['admin_password'] = conf_decodeString($opts['admin_password']); // deobfuscate // we can change the password if SSL is set - if($opts['use_ssl'] || $opts['use_tls']) { + if ($opts['use_ssl'] || $opts['use_tls']) { $this->cando['modPass'] = true; } else { $this->cando['modPass'] = false; } // adLDAP expects empty user/pass as NULL, we're less strict FS#2781 - if(empty($opts['admin_username'])) $opts['admin_username'] = null; - if(empty($opts['admin_password'])) $opts['admin_password'] = null; + if (empty($opts['admin_username'])) $opts['admin_username'] = null; + if (empty($opts['admin_password'])) $opts['admin_password'] = null; // user listing needs admin priviledges - if(!empty($opts['admin_username']) && !empty($opts['admin_password'])) { + if (!empty($opts['admin_username']) && !empty($opts['admin_password'])) { $this->cando['getUsers'] = true; } else { $this->cando['getUsers'] = false; @@ -672,16 +714,17 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * * @return array associative array(key => domain) */ - public function _getConfiguredDomains() { + public function getConfiguredDomains() + { $domains = array(); - if(empty($this->conf['account_suffix'])) return $domains; // not configured yet + if (empty($this->conf['account_suffix'])) return $domains; // not configured yet // add default domain, using the name from account suffix $domains[''] = ltrim($this->conf['account_suffix'], '@'); // find additional domains - foreach($this->conf as $key => $val) { - if(is_array($val) && isset($val['account_suffix'])) { + foreach ($this->conf as $key => $val) { + if (is_array($val) && isset($val['account_suffix'])) { $domains[$key] = ltrim($val['account_suffix'], '@'); } } @@ -701,14 +744,15 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * @param array $info * @return bool */ - protected function _filter($user, $info) { - foreach($this->_pattern as $item => $pattern) { - if($item == 'user') { - if(!preg_match($pattern, $user)) return false; - } else if($item == 'grps') { - if(!count(preg_grep($pattern, $info['grps']))) return false; + protected function filter($user, $info) + { + foreach ($this->pattern as $item => $pattern) { + if ($item == 'user') { + if (!preg_match($pattern, $user)) return false; + } elseif ($item == 'grps') { + if (!count(preg_grep($pattern, $info['grps']))) return false; } else { - if(!preg_match($pattern, $info[$item])) return false; + if (!preg_match($pattern, $info[$item])) return false; } } return true; @@ -721,10 +765,11 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin { * * @param array $filter */ - protected function _constructPattern($filter) { - $this->_pattern = array(); - foreach($filter as $item => $pattern) { - $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters + protected function constructPattern($filter) + { + $this->pattern = array(); + foreach ($filter as $item => $pattern) { + $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters } } } diff --git a/lib/plugins/authldap/auth.php b/lib/plugins/authldap/auth.php index 52f9ba50d..e71faa3c5 100644 --- a/lib/plugins/authldap/auth.php +++ b/lib/plugins/authldap/auth.php @@ -1,6 +1,4 @@ <?php -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); /** * LDAP authentication backend @@ -10,8 +8,9 @@ if(!defined('DOKU_INC')) die(); * @author Chris Smith <chris@jalakaic.co.uk> * @author Jan Schumann <js@schumann-it.com> */ -class auth_plugin_authldap extends DokuWiki_Auth_Plugin { - /* @var resource $con holds the LDAP connection*/ +class auth_plugin_authldap extends DokuWiki_Auth_Plugin +{ + /* @var resource $con holds the LDAP connection */ protected $con = null; /* @var int $bound What type of connection does already exist? */ @@ -20,18 +19,19 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { /* @var array $users User data cache */ protected $users = null; - /* @var array $_pattern User filter pattern */ - protected $_pattern = null; + /* @var array $pattern User filter pattern */ + protected $pattern = null; /** * Constructor */ - public function __construct() { + public function __construct() + { parent::__construct(); // ldap extension is needed - if(!function_exists('ldap_connect')) { - $this->_debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__); + if (!function_exists('ldap_connect')) { + $this->debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__); $this->success = false; return; } @@ -52,68 +52,67 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * @param string $pass * @return bool */ - public function checkPass($user, $pass) { + public function checkPass($user, $pass) + { // reject empty password - if(empty($pass)) return false; - if(!$this->_openLDAP()) return false; + if (empty($pass)) return false; + if (!$this->openLDAP()) return false; // indirect user bind - if($this->getConf('binddn') && $this->getConf('bindpw')) { + if ($this->getConf('binddn') && $this->getConf('bindpw')) { // use superuser credentials - if(!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) { - $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) { + $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); return false; } $this->bound = 2; - } else if($this->getConf('binddn') && + } elseif ($this->getConf('binddn') && $this->getConf('usertree') && $this->getConf('userfilter') ) { // special bind string - $dn = $this->_makeFilter( + $dn = $this->makeFilter( $this->getConf('binddn'), - array('user'=> $user, 'server'=> $this->getConf('server')) + array('user' => $user, 'server' => $this->getConf('server')) ); - - } else if(strpos($this->getConf('usertree'), '%{user}')) { + } elseif (strpos($this->getConf('usertree'), '%{user}')) { // direct user bind - $dn = $this->_makeFilter( + $dn = $this->makeFilter( $this->getConf('usertree'), - array('user'=> $user, 'server'=> $this->getConf('server')) + array('user' => $user, 'server' => $this->getConf('server')) ); - } else { // Anonymous bind - if(!@ldap_bind($this->con)) { + if (!@ldap_bind($this->con)) { msg("LDAP: can not bind anonymously", -1); - $this->_debug('LDAP anonymous bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + $this->debug('LDAP anonymous bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); return false; } } // Try to bind to with the dn if we have one. - if(!empty($dn)) { + if (!empty($dn)) { // User/Password bind - if(!@ldap_bind($this->con, $dn, $pass)) { - $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__); - $this->_debug('LDAP user dn bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + if (!@ldap_bind($this->con, $dn, $pass)) { + $this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__); + $this->debug('LDAP user dn bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); return false; } $this->bound = 1; return true; } else { // See if we can find the user - $info = $this->_getUserData($user, true); - if(empty($info['dn'])) { + $info = $this->fetchUserData($user, true); + if (empty($info['dn'])) { return false; } else { $dn = $info['dn']; } // Try to bind with the dn provided - if(!@ldap_bind($this->con, $dn, $pass)) { - $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__); - $this->_debug('LDAP user bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + if (!@ldap_bind($this->con, $dn, $pass)) { + $this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__); + $this->debug('LDAP user bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); return false; } $this->bound = 1; @@ -146,105 +145,110 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * @author Steffen Schoch <schoch@dsb.net> * * @param string $user - * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin + * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin * @return array containing user data or false */ - public function getUserData($user, $requireGroups=true) { - return $this->_getUserData($user); + public function getUserData($user, $requireGroups = true) + { + return $this->fetchUserData($user); } /** * @param string $user - * @param bool $inbind authldap specific, true if in bind phase + * @param bool $inbind authldap specific, true if in bind phase * @return array containing user data or false */ - protected function _getUserData($user, $inbind = false) { + protected function fetchUserData($user, $inbind = false) + { global $conf; - if(!$this->_openLDAP()) return false; + if (!$this->openLDAP()) return array(); // force superuser bind if wanted and not bound as superuser yet - if($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) { + if ($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) { // use superuser credentials - if(!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) { - $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); - return false; + if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) { + $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); + return array(); } $this->bound = 2; - } elseif($this->bound == 0 && !$inbind) { + } elseif ($this->bound == 0 && !$inbind) { // in some cases getUserData is called outside the authentication workflow // eg. for sending email notification on subscribed pages. This data might not // be accessible anonymously, so we try to rebind the current user here list($loginuser, $loginsticky, $loginpass) = auth_getCookie(); - if($loginuser && $loginpass) { + if ($loginuser && $loginpass) { $loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true)); $this->checkPass($loginuser, $loginpass); } } $info = array(); - $info['user'] = $user; - $this->_debug('LDAP user to find: '.htmlspecialchars($info['user']), 0, __LINE__, __FILE__); + $info['user'] = $user; + $this->debug('LDAP user to find: ' . hsc($info['user']), 0, __LINE__, __FILE__); $info['server'] = $this->getConf('server'); - $this->_debug('LDAP Server: '.htmlspecialchars($info['server']), 0, __LINE__, __FILE__); - + $this->debug('LDAP Server: ' . hsc($info['server']), 0, __LINE__, __FILE__); //get info for given user - $base = $this->_makeFilter($this->getConf('usertree'), $info); - if($this->getConf('userfilter')) { - $filter = $this->_makeFilter($this->getConf('userfilter'), $info); + $base = $this->makeFilter($this->getConf('usertree'), $info); + if ($this->getConf('userfilter')) { + $filter = $this->makeFilter($this->getConf('userfilter'), $info); } else { $filter = "(ObjectClass=*)"; } - $this->_debug('LDAP Filter: '.htmlspecialchars($filter), 0, __LINE__, __FILE__); + $this->debug('LDAP Filter: ' . hsc($filter), 0, __LINE__, __FILE__); - $this->_debug('LDAP user search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); - $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__); - $sr = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('userscope')); + $this->debug('LDAP user search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); + $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__); + $sr = $this->ldapSearch($this->con, $base, $filter, $this->getConf('userscope')); - $result = @ldap_get_entries($this->con, $sr); + $result = @ldap_get_entries($this->con, $sr); // if result is not an array - if(!is_array($result)) { - // no objects found - $this->_debug('LDAP search returned non-array result: '.htmlspecialchars(print($result)), -1, __LINE__, __FILE__); - return false; + if (!is_array($result)) { + // no objects found + $this->debug('LDAP search returned non-array result: ' . hsc(print($result)), -1, __LINE__, __FILE__); + return array(); } - // Don't accept more or less than one response - if ($result['count'] != 1) { - $this->_debug('LDAP search returned '.htmlspecialchars($result['count']).' results while it should return 1!', -1, __LINE__, __FILE__); - //for($i = 0; $i < $result["count"]; $i++) { - //$this->_debug('result: '.htmlspecialchars(print_r($result[$i])), 0, __LINE__, __FILE__); - //} - return false; - } - + // Don't accept more or less than one response + if ($result['count'] != 1) { + $this->debug( + 'LDAP search returned ' . hsc($result['count']) . ' results while it should return 1!', + -1, + __LINE__, + __FILE__ + ); + //for($i = 0; $i < $result["count"]; $i++) { + //$this->_debug('result: '.hsc(print_r($result[$i])), 0, __LINE__, __FILE__); + //} + return array(); + } - $this->_debug('LDAP search found single result !', 0, __LINE__, __FILE__); + $this->debug('LDAP search found single result !', 0, __LINE__, __FILE__); $user_result = $result[0]; ldap_free_result($sr); // general user info - $info['dn'] = $user_result['dn']; - $info['gid'] = $user_result['gidnumber'][0]; + $info['dn'] = $user_result['dn']; + $info['gid'] = $user_result['gidnumber'][0]; $info['mail'] = $user_result['mail'][0]; $info['name'] = $user_result['cn'][0]; $info['grps'] = array(); // overwrite if other attribs are specified. - if(is_array($this->getConf('mapping'))) { - foreach($this->getConf('mapping') as $localkey => $key) { - if(is_array($key)) { + if (is_array($this->getConf('mapping'))) { + foreach ($this->getConf('mapping') as $localkey => $key) { + if (is_array($key)) { // use regexp to clean up user_result // $key = array($key=>$regexp), only handles the first key-value $regexp = current($key); $key = key($key); - if($user_result[$key]) foreach($user_result[$key] as $grpkey => $grp) { - if($grpkey !== 'count' && preg_match($regexp, $grp, $match)) { - if($localkey == 'grps') { + if ($user_result[$key]) foreach ($user_result[$key] as $grpkey => $grp) { + if ($grpkey !== 'count' && preg_match($regexp, $grp, $match)) { + if ($localkey == 'grps') { $info[$localkey][] = $match[1]; } else { $info[$localkey] = $match[1]; @@ -259,38 +263,44 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { $user_result = array_merge($info, $user_result); //get groups for given user if grouptree is given - if($this->getConf('grouptree') || $this->getConf('groupfilter')) { - $base = $this->_makeFilter($this->getConf('grouptree'), $user_result); - $filter = $this->_makeFilter($this->getConf('groupfilter'), $user_result); - $sr = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('groupscope'), array($this->getConf('groupkey'))); - $this->_debug('LDAP group search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); - $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__); - - if(!$sr) { + if ($this->getConf('grouptree') || $this->getConf('groupfilter')) { + $base = $this->makeFilter($this->getConf('grouptree'), $user_result); + $filter = $this->makeFilter($this->getConf('groupfilter'), $user_result); + $sr = $this->ldapSearch( + $this->con, + $base, + $filter, + $this->getConf('groupscope'), + array($this->getConf('groupkey')) + ); + $this->debug('LDAP group search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); + $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__); + + if (!$sr) { msg("LDAP: Reading group memberships failed", -1); - return false; + return array(); } $result = ldap_get_entries($this->con, $sr); ldap_free_result($sr); - if(is_array($result)) foreach($result as $grp) { - if(!empty($grp[$this->getConf('groupkey')])) { + if (is_array($result)) foreach ($result as $grp) { + if (!empty($grp[$this->getConf('groupkey')])) { $group = $grp[$this->getConf('groupkey')]; - if(is_array($group)){ + if (is_array($group)) { $group = $group[0]; } else { - $this->_debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__); + $this->debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__); } - if($group === '') continue; + if ($group === '') continue; - $this->_debug('LDAP usergroup: '.htmlspecialchars($group), 0, __LINE__, __FILE__); + $this->debug('LDAP usergroup: ' . hsc($group), 0, __LINE__, __FILE__); $info['grps'][] = $group; } } } // always add the default group to the list of groups - if(!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) { + if (!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) { $info['grps'][] = $conf['defaultgroup']; } return $info; @@ -299,47 +309,51 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { /** * Definition of the function modifyUser in order to modify the password * - * @param string $user nick of the user to be changed - * @param array $changes array of field/value pairs to be changed (password will be clear text) + * @param string $user nick of the user to be changed + * @param array $changes array of field/value pairs to be changed (password will be clear text) * @return bool true on success, false on error */ - - function modifyUser($user,$changes){ + public function modifyUser($user, $changes) + { // open the connection to the ldap - if(!$this->_openLDAP()){ - $this->_debug('LDAP cannot connect: '. htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + if (!$this->openLDAP()) { + $this->debug('LDAP cannot connect: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); return false; } // find the information about the user, in particular the "dn" - $info = $this->getUserData($user,true); - if(empty($info['dn'])) { - $this->_debug('LDAP cannot find your user dn', 0, __LINE__, __FILE__); + $info = $this->getUserData($user, true); + if (empty($info['dn'])) { + $this->debug('LDAP cannot find your user dn', 0, __LINE__, __FILE__); return false; } $dn = $info['dn']; // find the old password of the user - list($loginuser,$loginsticky,$loginpass) = auth_getCookie(); + list($loginuser, $loginsticky, $loginpass) = auth_getCookie(); if ($loginuser !== null) { // the user is currently logged in $secret = auth_cookiesalt(!$loginsticky, true); - $pass = auth_decrypt($loginpass, $secret); + $pass = auth_decrypt($loginpass, $secret); // bind with the ldap - if(!@ldap_bind($this->con, $dn, $pass)){ - $this->_debug('LDAP user bind failed: '. htmlspecialchars($dn) .': '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + if (!@ldap_bind($this->con, $dn, $pass)) { + $this->debug( + 'LDAP user bind failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)), + 0, + __LINE__, + __FILE__ + ); return false; } } elseif ($this->getConf('binddn') && $this->getConf('bindpw')) { // we are changing the password on behalf of the user (eg: forgotten password) // bind with the superuser ldap - if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))){ - $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) { + $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); return false; } - } - else { + } else { return false; // no otherway } @@ -348,8 +362,13 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { $hash = $phash->hash_ssha($changes['pass']); // change the password - if(!@ldap_mod_replace($this->con, $dn,array('userpassword' => $hash))){ - $this->_debug('LDAP mod replace failed: '. htmlspecialchars($dn) .': '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + if (!@ldap_mod_replace($this->con, $dn, array('userpassword' => $hash))) { + $this->debug( + 'LDAP mod replace failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)), + 0, + __LINE__, + __FILE__ + ); return false; } @@ -361,7 +380,8 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * * @return bool */ - public function isCaseSensitive() { + public function isCaseSensitive() + { return false; } @@ -369,48 +389,49 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * Bulk retrieval of user data * * @author Dominik Eckelmann <dokuwiki@cosmocode.de> - * @param int $start index of first user to be returned - * @param int $limit max number of users to be returned - * @param array $filter array of field/pattern pairs, null for no filter + * @param int $start index of first user to be returned + * @param int $limit max number of users to be returned + * @param array $filter array of field/pattern pairs, null for no filter * @return array of userinfo (refer getUserData for internal userinfo details) */ - function retrieveUsers($start = 0, $limit = 0, $filter = array()) { - if(!$this->_openLDAP()) return false; + public function retrieveUsers($start = 0, $limit = 0, $filter = array()) + { + if (!$this->openLDAP()) return array(); - if(is_null($this->users)) { + if (is_null($this->users)) { // Perform the search and grab all their details - if($this->getConf('userfilter')) { + if ($this->getConf('userfilter')) { $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter')); } else { $all_filter = "(ObjectClass=*)"; } - $sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter); - $entries = ldap_get_entries($this->con, $sr); + $sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter); + $entries = ldap_get_entries($this->con, $sr); $users_array = array(); - $userkey = $this->getConf('userkey'); - for($i = 0; $i < $entries["count"]; $i++) { + $userkey = $this->getConf('userkey'); + for ($i = 0; $i < $entries["count"]; $i++) { array_push($users_array, $entries[$i][$userkey][0]); } asort($users_array); $result = $users_array; - if(!$result) return array(); + if (!$result) return array(); $this->users = array_fill_keys($result, false); } - $i = 0; + $i = 0; $count = 0; - $this->_constructPattern($filter); + $this->constructPattern($filter); $result = array(); - foreach($this->users as $user => &$info) { - if($i++ < $start) { + foreach ($this->users as $user => &$info) { + if ($i++ < $start) { continue; } - if($info === false) { + if ($info === false) { $info = $this->getUserData($user); } - if($this->_filter($user, $info)) { + if ($this->filter($user, $info)) { $result[$user] = $info; - if(($limit > 0) && (++$count >= $limit)) break; + if (($limit > 0) && (++$count >= $limit)) break; } } return $result; @@ -424,21 +445,22 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * * @author Troels Liebe Bentsen <tlb@rapanden.dk> * @param string $filter ldap search filter with placeholders - * @param array $placeholders placeholders to fill in + * @param array $placeholders placeholders to fill in * @return string */ - protected function _makeFilter($filter, $placeholders) { + protected function makeFilter($filter, $placeholders) + { preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER); //replace each match - foreach($matches[1] as $match) { + foreach ($matches[1] as $match) { //take first element if array - if(is_array($placeholders[$match])) { + if (is_array($placeholders[$match])) { $value = $placeholders[$match][0]; } else { $value = $placeholders[$match]; } - $value = $this->_filterEscape($value); - $filter = str_replace('%{'.$match.'}', $value, $filter); + $value = $this->filterEscape($value); + $filter = str_replace('%{' . $match . '}', $value, $filter); } return $filter; } @@ -449,17 +471,18 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * @author Chris Smith <chris@jalakai.co.uk> * * @param string $user the user's login name - * @param array $info the user's userinfo array + * @param array $info the user's userinfo array * @return bool */ - protected function _filter($user, $info) { - foreach($this->_pattern as $item => $pattern) { - if($item == 'user') { - if(!preg_match($pattern, $user)) return false; - } else if($item == 'grps') { - if(!count(preg_grep($pattern, $info['grps']))) return false; + protected function filter($user, $info) + { + foreach ($this->pattern as $item => $pattern) { + if ($item == 'user') { + if (!preg_match($pattern, $user)) return false; + } elseif ($item == 'grps') { + if (!count(preg_grep($pattern, $info['grps']))) return false; } else { - if(!preg_match($pattern, $info[$item])) return false; + if (!preg_match($pattern, $info[$item])) return false; } } return true; @@ -473,10 +496,11 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * @param $filter * @return void */ - protected function _constructPattern($filter) { - $this->_pattern = array(); - foreach($filter as $item => $pattern) { - $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters + protected function constructPattern($filter) + { + $this->pattern = array(); + foreach ($filter as $item => $pattern) { + $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters } } @@ -489,12 +513,13 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * @param string $string * @return string */ - protected function _filterEscape($string) { + protected function filterEscape($string) + { // see https://github.com/adldap/adLDAP/issues/22 return preg_replace_callback( '/([\x00-\x1F\*\(\)\\\\])/', function ($matches) { - return "\\".join("", unpack("H2", $matches[1])); + return "\\" . join("", unpack("H2", $matches[1])); }, $string ); @@ -506,22 +531,23 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - protected function _openLDAP() { - if($this->con) return true; // connection already established + protected function openLDAP() + { + if ($this->con) return true; // connection already established - if($this->getConf('debug')) { - ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); + if ($this->getConf('debug')) { + ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7); } $this->bound = 0; - $port = $this->getConf('port'); - $bound = false; + $port = $this->getConf('port'); + $bound = false; $servers = explode(',', $this->getConf('server')); - foreach($servers as $server) { - $server = trim($server); + foreach ($servers as $server) { + $server = trim($server); $this->con = @ldap_connect($server, $port); - if(!$this->con) { + if (!$this->con) { continue; } @@ -534,62 +560,64 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { */ //set protocol version and dependend options - if($this->getConf('version')) { - if(!@ldap_set_option( - $this->con, LDAP_OPT_PROTOCOL_VERSION, + if ($this->getConf('version')) { + if (!@ldap_set_option( + $this->con, + LDAP_OPT_PROTOCOL_VERSION, $this->getConf('version') ) ) { - msg('Setting LDAP Protocol version '.$this->getConf('version').' failed', -1); - $this->_debug('LDAP version set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + msg('Setting LDAP Protocol version ' . $this->getConf('version') . ' failed', -1); + $this->debug('LDAP version set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); } else { //use TLS (needs version 3) - if($this->getConf('starttls')) { - if(!@ldap_start_tls($this->con)) { + if ($this->getConf('starttls')) { + if (!@ldap_start_tls($this->con)) { msg('Starting TLS failed', -1); - $this->_debug('LDAP TLS set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + $this->debug('LDAP TLS set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); } } // needs version 3 - if($this->getConf('referrals') > -1) { - if(!@ldap_set_option( - $this->con, LDAP_OPT_REFERRALS, + if ($this->getConf('referrals') > -1) { + if (!@ldap_set_option( + $this->con, + LDAP_OPT_REFERRALS, $this->getConf('referrals') ) ) { msg('Setting LDAP referrals failed', -1); - $this->_debug('LDAP referal set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + $this->debug('LDAP referal set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); } } } } //set deref mode - if($this->getConf('deref')) { - if(!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) { - msg('Setting LDAP Deref mode '.$this->getConf('deref').' failed', -1); - $this->_debug('LDAP deref set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); + if ($this->getConf('deref')) { + if (!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) { + msg('Setting LDAP Deref mode ' . $this->getConf('deref') . ' failed', -1); + $this->debug('LDAP deref set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); } } /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */ - if(defined('LDAP_OPT_NETWORK_TIMEOUT')) { + if (defined('LDAP_OPT_NETWORK_TIMEOUT')) { ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1); } - if($this->getConf('binddn') && $this->getConf('bindpw')) { + if ($this->getConf('binddn') && $this->getConf('bindpw')) { $bound = @ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw'))); $this->bound = 2; } else { $bound = @ldap_bind($this->con); } - if($bound) { + if ($bound) { break; } } - if(!$bound) { + if (!$bound) { msg("LDAP: couldn't connect to LDAP server", -1); - $this->_debug(ldap_error($this->con), 0, __LINE__, __FILE__); + $this->debug(ldap_error($this->con), 0, __LINE__, __FILE__); return false; } @@ -601,33 +629,52 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * Wraps around ldap_search, ldap_list or ldap_read depending on $scope * * @author Andreas Gohr <andi@splitbrain.org> - * @param resource $link_identifier - * @param string $base_dn - * @param string $filter - * @param string $scope can be 'base', 'one' or 'sub' + * @param resource $link_identifier + * @param string $base_dn + * @param string $filter + * @param string $scope can be 'base', 'one' or 'sub' * @param null|array $attributes - * @param int $attrsonly - * @param int $sizelimit + * @param int $attrsonly + * @param int $sizelimit * @return resource */ - protected function _ldapsearch($link_identifier, $base_dn, $filter, $scope = 'sub', $attributes = null, - $attrsonly = 0, $sizelimit = 0) { - if(is_null($attributes)) $attributes = array(); - - if($scope == 'base') { + protected function ldapSearch( + $link_identifier, + $base_dn, + $filter, + $scope = 'sub', + $attributes = null, + $attrsonly = 0, + $sizelimit = 0 + ) { + if (is_null($attributes)) $attributes = array(); + + if ($scope == 'base') { return @ldap_read( - $link_identifier, $base_dn, $filter, $attributes, - $attrsonly, $sizelimit + $link_identifier, + $base_dn, + $filter, + $attributes, + $attrsonly, + $sizelimit ); - } elseif($scope == 'one') { + } elseif ($scope == 'one') { return @ldap_list( - $link_identifier, $base_dn, $filter, $attributes, - $attrsonly, $sizelimit + $link_identifier, + $base_dn, + $filter, + $attributes, + $attrsonly, + $sizelimit ); } else { return @ldap_search( - $link_identifier, $base_dn, $filter, $attributes, - $attrsonly, $sizelimit + $link_identifier, + $base_dn, + $filter, + $attributes, + $attrsonly, + $sizelimit ); } } @@ -636,14 +683,14 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin { * Wrapper around msg() but outputs only when debug is enabled * * @param string $message - * @param int $err - * @param int $line + * @param int $err + * @param int $line * @param string $file * @return void */ - protected function _debug($message, $err, $line, $file) { - if(!$this->getConf('debug')) return; + protected function debug($message, $err, $line, $file) + { + if (!$this->getConf('debug')) return; msg($message, $err, $line, $file); } - } diff --git a/lib/plugins/authpdo/_test/sqlite.test.php b/lib/plugins/authpdo/_test/sqlite.test.php index 35b612604..89cc9f60d 100644 --- a/lib/plugins/authpdo/_test/sqlite.test.php +++ b/lib/plugins/authpdo/_test/sqlite.test.php @@ -10,8 +10,8 @@ class testable_auth_plugin_authpdo extends auth_plugin_authpdo { return 'authpdo'; } - public function _selectGroups() { - return parent::_selectGroups(); + public function selectGroups() { + return parent::selectGroups(); } public function addGroup($group) { @@ -96,7 +96,7 @@ class sqlite_plugin_authpdo_test extends DokuWikiTest { public function test_internals() { $auth = new testable_auth_plugin_authpdo(); - $groups = $auth->_selectGroups(); + $groups = $auth->selectGroups(); $this->assertArrayHasKey('user', $groups); $this->assertEquals(1, $groups['user']['gid']); $this->assertArrayHasKey('admin', $groups); @@ -104,7 +104,7 @@ class sqlite_plugin_authpdo_test extends DokuWikiTest { $ok = $auth->addGroup('test'); $this->assertTrue($ok); - $groups = $auth->_selectGroups(); + $groups = $auth->selectGroups(); $this->assertArrayHasKey('test', $groups); $this->assertEquals(3, $groups['test']['gid']); } diff --git a/lib/plugins/authpdo/auth.php b/lib/plugins/authpdo/auth.php index dfe125473..2b01ba752 100644 --- a/lib/plugins/authpdo/auth.php +++ b/lib/plugins/authpdo/auth.php @@ -6,13 +6,11 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * Class auth_plugin_authpdo */ -class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { +class auth_plugin_authpdo extends DokuWiki_Auth_Plugin +{ /** @var PDO */ protected $pdo; @@ -23,17 +21,18 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { /** * Constructor. */ - public function __construct() { + public function __construct() + { parent::__construct(); // for compatibility - if(!class_exists('PDO')) { - $this->_debug('PDO extension for PHP not found.', -1, __LINE__); + if (!class_exists('PDO')) { + $this->debugMsg('PDO extension for PHP not found.', -1, __LINE__); $this->success = false; return; } - if(!$this->getConf('dsn')) { - $this->_debug('No DSN specified', -1, __LINE__); + if (!$this->getConf('dsn')) { + $this->debugMsg('No DSN specified', -1, __LINE__); $this->success = false; return; } @@ -49,15 +48,15 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // we want exceptions, not error codes ) ); - } catch(PDOException $e) { - $this->_debug($e); + } catch (PDOException $e) { + $this->debugMsg($e); msg($this->getLang('connectfail'), -1); $this->success = false; return; } // can Users be created? - $this->cando['addUser'] = $this->_chkcnf( + $this->cando['addUser'] = $this->checkConfig( array( 'select-user', 'select-user-groups', @@ -69,7 +68,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { ); // can Users be deleted? - $this->cando['delUser'] = $this->_chkcnf( + $this->cando['delUser'] = $this->checkConfig( array( 'select-user', 'select-user-groups', @@ -80,7 +79,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { ); // can login names be changed? - $this->cando['modLogin'] = $this->_chkcnf( + $this->cando['modLogin'] = $this->checkConfig( array( 'select-user', 'select-user-groups', @@ -89,7 +88,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { ); // can passwords be changed? - $this->cando['modPass'] = $this->_chkcnf( + $this->cando['modPass'] = $this->checkConfig( array( 'select-user', 'select-user-groups', @@ -98,7 +97,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { ); // can real names be changed? - $this->cando['modName'] = $this->_chkcnf( + $this->cando['modName'] = $this->checkConfig( array( 'select-user', 'select-user-groups', @@ -107,7 +106,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { ); // can real email be changed? - $this->cando['modMail'] = $this->_chkcnf( + $this->cando['modMail'] = $this->checkConfig( array( 'select-user', 'select-user-groups', @@ -116,7 +115,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { ); // can groups be changed? - $this->cando['modGroups'] = $this->_chkcnf( + $this->cando['modGroups'] = $this->checkConfig( array( 'select-user', 'select-user-groups', @@ -128,21 +127,21 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { ); // can a filtered list of users be retrieved? - $this->cando['getUsers'] = $this->_chkcnf( + $this->cando['getUsers'] = $this->checkConfig( array( 'list-users' ) ); // can the number of users be retrieved? - $this->cando['getUserCount'] = $this->_chkcnf( + $this->cando['getUserCount'] = $this->checkConfig( array( 'count-users' ) ); // can a list of available groups be retrieved? - $this->cando['getGroups'] = $this->_chkcnf( + $this->cando['getGroups'] = $this->checkConfig( array( 'select-groups' ) @@ -158,22 +157,23 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param string $pass the clear text password * @return bool */ - public function checkPass($user, $pass) { + public function checkPass($user, $pass) + { - $userdata = $this->_selectUser($user); - if($userdata == false) return false; + $userdata = $this->selectUser($user); + if ($userdata == false) return false; // password checking done in SQL? - if($this->_chkcnf(array('check-pass'))) { + if ($this->checkConfig(array('check-pass'))) { $userdata['clear'] = $pass; $userdata['hash'] = auth_cryptPassword($pass); - $result = $this->_query($this->getConf('check-pass'), $userdata); - if($result === false) return false; + $result = $this->query($this->getConf('check-pass'), $userdata); + if ($result === false) return false; return (count($result) == 1); } // we do password checking on our own - if(isset($userdata['hash'])) { + if (isset($userdata['hash'])) { // hashed password $passhash = new PassHash(); return $passhash->verify_hash($pass, $userdata['hash']); @@ -197,16 +197,17 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param bool $requireGroups whether or not the returned data must include groups * @return array|bool containing user data or false */ - public function getUserData($user, $requireGroups = true) { - $data = $this->_selectUser($user); - if($data == false) return false; + public function getUserData($user, $requireGroups = true) + { + $data = $this->selectUser($user); + if ($data == false) return false; - if(isset($data['hash'])) unset($data['hash']); - if(isset($data['clean'])) unset($data['clean']); + if (isset($data['hash'])) unset($data['hash']); + if (isset($data['clean'])) unset($data['clean']); - if($requireGroups) { - $data['grps'] = $this->_selectUserGroups($data); - if($data['grps'] === false) return false; + if ($requireGroups) { + $data['grps'] = $this->selectUserGroups($data); + if ($data['grps'] === false) return false; } return $data; @@ -230,16 +231,17 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param null|array $grps * @return bool|null */ - public function createUser($user, $clear, $name, $mail, $grps = null) { + public function createUser($user, $clear, $name, $mail, $grps = null) + { global $conf; - if(($info = $this->getUserData($user, false)) !== false) { + if (($info = $this->getUserData($user, false)) !== false) { msg($this->getLang('userexists'), -1); return false; // user already exists } // prepare data - if($grps == null) $grps = array(); + if ($grps == null) $grps = array(); array_unshift($grps, $conf['defaultgroup']); $grps = array_unique($grps); $hash = auth_cryptPassword($clear); @@ -249,26 +251,26 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { $this->pdo->beginTransaction(); { // insert the user - $ok = $this->_query($this->getConf('insert-user'), $userdata); - if($ok === false) goto FAIL; + $ok = $this->query($this->getConf('insert-user'), $userdata); + if ($ok === false) goto FAIL; $userdata = $this->getUserData($user, false); - if($userdata === false) goto FAIL; + if ($userdata === false) goto FAIL; // create all groups that do not exist, the refetch the groups - $allgroups = $this->_selectGroups(); - foreach($grps as $group) { - if(!isset($allgroups[$group])) { - $ok = $this->addGroup($group); - if($ok === false) goto FAIL; - } + $allgroups = $this->selectGroups(); + foreach ($grps as $group) { + if (!isset($allgroups[$group])) { + $ok = $this->addGroup($group); + if ($ok === false) goto FAIL; } - $allgroups = $this->_selectGroups(); + } + $allgroups = $this->selectGroups(); // add user to the groups - foreach($grps as $group) { - $ok = $this->_joinGroup($userdata, $allgroups[$group]); - if($ok === false) goto FAIL; - } + foreach ($grps as $group) { + $ok = $this->joinGroup($userdata, $allgroups[$group]); + if ($ok === false) goto FAIL; + } } $this->pdo->commit(); return true; @@ -276,7 +278,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { // something went wrong, rollback FAIL: $this->pdo->rollBack(); - $this->_debug('Transaction rolled back', 0, __LINE__); + $this->debugMsg('Transaction rolled back', 0, __LINE__); msg($this->getLang('writefail'), -1); return null; // return error } @@ -288,7 +290,8 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param array $changes array of field/value pairs to be changed (password will be clear text) * @return bool */ - public function modifyUser($user, $changes) { + public function modifyUser($user, $changes) + { // secure everything in transaction $this->pdo->beginTransaction(); { @@ -297,67 +300,67 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { unset($olddata['grps']); // changing the user name? - if(isset($changes['user'])) { - if($this->getUserData($changes['user'], false)) goto FAIL; - $params = $olddata; - $params['newlogin'] = $changes['user']; + if (isset($changes['user'])) { + if ($this->getUserData($changes['user'], false)) goto FAIL; + $params = $olddata; + $params['newlogin'] = $changes['user']; - $ok = $this->_query($this->getConf('update-user-login'), $params); - if($ok === false) goto FAIL; - } + $ok = $this->query($this->getConf('update-user-login'), $params); + if ($ok === false) goto FAIL; + } // changing the password? - if(isset($changes['pass'])) { - $params = $olddata; - $params['clear'] = $changes['pass']; - $params['hash'] = auth_cryptPassword($changes['pass']); + if (isset($changes['pass'])) { + $params = $olddata; + $params['clear'] = $changes['pass']; + $params['hash'] = auth_cryptPassword($changes['pass']); - $ok = $this->_query($this->getConf('update-user-pass'), $params); - if($ok === false) goto FAIL; - } + $ok = $this->query($this->getConf('update-user-pass'), $params); + if ($ok === false) goto FAIL; + } // changing info? - if(isset($changes['mail']) || isset($changes['name'])) { - $params = $olddata; - if(isset($changes['mail'])) $params['mail'] = $changes['mail']; - if(isset($changes['name'])) $params['name'] = $changes['name']; + if (isset($changes['mail']) || isset($changes['name'])) { + $params = $olddata; + if (isset($changes['mail'])) $params['mail'] = $changes['mail']; + if (isset($changes['name'])) $params['name'] = $changes['name']; - $ok = $this->_query($this->getConf('update-user-info'), $params); - if($ok === false) goto FAIL; - } + $ok = $this->query($this->getConf('update-user-info'), $params); + if ($ok === false) goto FAIL; + } // changing groups? - if(isset($changes['grps'])) { - $allgroups = $this->_selectGroups(); - - // remove membership for previous groups - foreach($oldgroups as $group) { - if(!in_array($group, $changes['grps']) && isset($allgroups[$group])) { - $ok = $this->_leaveGroup($olddata, $allgroups[$group]); - if($ok === false) goto FAIL; - } + if (isset($changes['grps'])) { + $allgroups = $this->selectGroups(); + + // remove membership for previous groups + foreach ($oldgroups as $group) { + if (!in_array($group, $changes['grps']) && isset($allgroups[$group])) { + $ok = $this->leaveGroup($olddata, $allgroups[$group]); + if ($ok === false) goto FAIL; } + } - // create all new groups that are missing - $added = 0; - foreach($changes['grps'] as $group) { - if(!isset($allgroups[$group])) { - $ok = $this->addGroup($group); - if($ok === false) goto FAIL; - $added++; - } + // create all new groups that are missing + $added = 0; + foreach ($changes['grps'] as $group) { + if (!isset($allgroups[$group])) { + $ok = $this->addGroup($group); + if ($ok === false) goto FAIL; + $added++; } - // reload group info - if($added > 0) $allgroups = $this->_selectGroups(); - - // add membership for new groups - foreach($changes['grps'] as $group) { - if(!in_array($group, $oldgroups)) { - $ok = $this->_joinGroup($olddata, $allgroups[$group]); - if($ok === false) goto FAIL; - } + } + // reload group info + if ($added > 0) $allgroups = $this->selectGroups(); + + // add membership for new groups + foreach ($changes['grps'] as $group) { + if (!in_array($group, $oldgroups)) { + $ok = $this->joinGroup($olddata, $allgroups[$group]); + if ($ok === false) goto FAIL; } } + } } $this->pdo->commit(); @@ -366,7 +369,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { // something went wrong, rollback FAIL: $this->pdo->rollBack(); - $this->_debug('Transaction rolled back', 0, __LINE__); + $this->debugMsg('Transaction rolled back', 0, __LINE__); msg($this->getLang('writefail'), -1); return false; // return error } @@ -379,10 +382,11 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param array $users * @return int number of users deleted */ - public function deleteUsers($users) { + public function deleteUsers($users) + { $count = 0; - foreach($users as $user) { - if($this->_deleteUser($user)) $count++; + foreach ($users as $user) { + if ($this->deleteUser($user)) $count++; } return $count; } @@ -397,13 +401,14 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param array $filter array of field/pattern pairs, null for no filter * @return array list of userinfo (refer getUserData for internal userinfo details) */ - public function retrieveUsers($start = 0, $limit = -1, $filter = null) { - if($limit < 0) $limit = 10000; // we don't support no limit - if(is_null($filter)) $filter = array(); - - if(isset($filter['grps'])) $filter['group'] = $filter['grps']; - foreach(array('user', 'name', 'mail', 'group') as $key) { - if(!isset($filter[$key])) { + public function retrieveUsers($start = 0, $limit = -1, $filter = null) + { + if ($limit < 0) $limit = 10000; // we don't support no limit + if (is_null($filter)) $filter = array(); + + if (isset($filter['grps'])) $filter['group'] = $filter['grps']; + foreach (array('user', 'name', 'mail', 'group') as $key) { + if (!isset($filter[$key])) { $filter[$key] = '%'; } else { $filter[$key] = '%' . $filter[$key] . '%'; @@ -413,12 +418,12 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { $filter['end'] = (int) $start + $limit; $filter['limit'] = (int) $limit; - $result = $this->_query($this->getConf('list-users'), $filter); - if(!$result) return array(); + $result = $this->query($this->getConf('list-users'), $filter); + if (!$result) return array(); $users = array(); - foreach($result as $row) { - if(!isset($row['user'])) { - $this->_debug("Statement did not return 'user' attribute", -1, __LINE__); + foreach ($result as $row) { + if (!isset($row['user'])) { + $this->debugMsg("Statement did not return 'user' attribute", -1, __LINE__); return array(); } $users[] = $this->getUserData($row['user']); @@ -432,21 +437,22 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param array $filter array of field/pattern pairs, empty array for no filter * @return int */ - public function getUserCount($filter = array()) { - if(is_null($filter)) $filter = array(); + public function getUserCount($filter = array()) + { + if (is_null($filter)) $filter = array(); - if(isset($filter['grps'])) $filter['group'] = $filter['grps']; - foreach(array('user', 'name', 'mail', 'group') as $key) { - if(!isset($filter[$key])) { + if (isset($filter['grps'])) $filter['group'] = $filter['grps']; + foreach (array('user', 'name', 'mail', 'group') as $key) { + if (!isset($filter[$key])) { $filter[$key] = '%'; } else { $filter[$key] = '%' . $filter[$key] . '%'; } } - $result = $this->_query($this->getConf('count-users'), $filter); - if(!$result || !isset($result[0]['count'])) { - $this->_debug("Statement did not return 'count' attribute", -1, __LINE__); + $result = $this->query($this->getConf('count-users'), $filter); + if (!$result || !isset($result[0]['count'])) { + $this->debugMsg("Statement did not return 'count' attribute", -1, __LINE__); } return (int) $result[0]['count']; } @@ -457,12 +463,13 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param string $group * @return bool */ - public function addGroup($group) { + public function addGroup($group) + { $sql = $this->getConf('insert-group'); - $result = $this->_query($sql, array(':group' => $group)); - $this->_clearGroupCache(); - if($result === false) return false; + $result = $this->query($sql, array(':group' => $group)); + $this->clearGroupCache(); + if ($result === false) return false; return true; } @@ -475,11 +482,12 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param int $limit * @return array */ - public function retrieveGroups($start = 0, $limit = 0) { - $groups = array_keys($this->_selectGroups()); - if($groups === false) return array(); + public function retrieveGroups($start = 0, $limit = 0) + { + $groups = array_keys($this->selectGroups()); + if ($groups === false) return array(); - if(!$limit) { + if (!$limit) { return array_splice($groups, $start); } else { return array_splice($groups, $start, $limit); @@ -492,38 +500,39 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param string $user the user name * @return bool|array user data, false on error */ - protected function _selectUser($user) { + protected function selectUser($user) + { $sql = $this->getConf('select-user'); - $result = $this->_query($sql, array(':user' => $user)); - if(!$result) return false; + $result = $this->query($sql, array(':user' => $user)); + if (!$result) return false; - if(count($result) > 1) { - $this->_debug('Found more than one matching user', -1, __LINE__); + if (count($result) > 1) { + $this->debugMsg('Found more than one matching user', -1, __LINE__); return false; } $data = array_shift($result); $dataok = true; - if(!isset($data['user'])) { - $this->_debug("Statement did not return 'user' attribute", -1, __LINE__); + if (!isset($data['user'])) { + $this->debugMsg("Statement did not return 'user' attribute", -1, __LINE__); $dataok = false; } - if(!isset($data['hash']) && !isset($data['clear']) && !$this->_chkcnf(array('check-pass'))) { - $this->_debug("Statement did not return 'clear' or 'hash' attribute", -1, __LINE__); + if (!isset($data['hash']) && !isset($data['clear']) && !$this->checkConfig(array('check-pass'))) { + $this->debugMsg("Statement did not return 'clear' or 'hash' attribute", -1, __LINE__); $dataok = false; } - if(!isset($data['name'])) { - $this->_debug("Statement did not return 'name' attribute", -1, __LINE__); + if (!isset($data['name'])) { + $this->debugMsg("Statement did not return 'name' attribute", -1, __LINE__); $dataok = false; } - if(!isset($data['mail'])) { - $this->_debug("Statement did not return 'mail' attribute", -1, __LINE__); + if (!isset($data['mail'])) { + $this->debugMsg("Statement did not return 'mail' attribute", -1, __LINE__); $dataok = false; } - if(!$dataok) return false; + if (!$dataok) return false; return $data; } @@ -533,22 +542,23 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param string $user * @return bool true when the user was deleted */ - protected function _deleteUser($user) { + protected function deleteUser($user) + { $this->pdo->beginTransaction(); { $userdata = $this->getUserData($user); - if($userdata === false) goto FAIL; - $allgroups = $this->_selectGroups(); + if ($userdata === false) goto FAIL; + $allgroups = $this->selectGroups(); // remove group memberships (ignore errors) - foreach($userdata['grps'] as $group) { - if(isset($allgroups[$group])) { - $this->_leaveGroup($userdata, $allgroups[$group]); - } + foreach ($userdata['grps'] as $group) { + if (isset($allgroups[$group])) { + $this->leaveGroup($userdata, $allgroups[$group]); } + } - $ok = $this->_query($this->getConf('delete-user'), $userdata); - if($ok === false) goto FAIL; + $ok = $this->query($this->getConf('delete-user'), $userdata); + if ($ok === false) goto FAIL; } $this->pdo->commit(); return true; @@ -564,16 +574,17 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param array $userdata The userdata as returned by _selectUser() * @return array|bool list of group names, false on error */ - protected function _selectUserGroups($userdata) { + protected function selectUserGroups($userdata) + { global $conf; $sql = $this->getConf('select-user-groups'); - $result = $this->_query($sql, $userdata); - if($result === false) return false; + $result = $this->query($sql, $userdata); + if ($result === false) return false; $groups = array($conf['defaultgroup']); // always add default config - foreach($result as $row) { - if(!isset($row['group'])) { - $this->_debug("No 'group' field returned in select-user-groups statement"); + foreach ($result as $row) { + if (!isset($row['group'])) { + $this->debugMsg("No 'group' field returned in select-user-groups statement"); return false; } $groups[] = $row['group']; @@ -589,17 +600,18 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * * @return array|bool list of all available groups and their properties */ - protected function _selectGroups() { - if($this->groupcache) return $this->groupcache; + protected function selectGroups() + { + if ($this->groupcache) return $this->groupcache; $sql = $this->getConf('select-groups'); - $result = $this->_query($sql); - if($result === false) return false; + $result = $this->query($sql); + if ($result === false) return false; $groups = array(); - foreach($result as $row) { - if(!isset($row['group'])) { - $this->_debug("No 'group' field returned from select-groups statement", -1, __LINE__); + foreach ($result as $row) { + if (!isset($row['group'])) { + $this->debugMsg("No 'group' field returned from select-groups statement", -1, __LINE__); return false; } @@ -615,7 +627,8 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { /** * Remove all entries from the group cache */ - protected function _clearGroupCache() { + protected function clearGroupCache() + { $this->groupcache = null; } @@ -626,11 +639,12 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param array $groupdata all the group data * @return bool */ - protected function _joinGroup($userdata, $groupdata) { + protected function joinGroup($userdata, $groupdata) + { $data = array_merge($userdata, $groupdata); $sql = $this->getConf('join-group'); - $result = $this->_query($sql, $data); - if($result === false) return false; + $result = $this->query($sql, $data); + if ($result === false) return false; return true; } @@ -641,11 +655,12 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param array $groupdata all the group data * @return bool */ - protected function _leaveGroup($userdata, $groupdata) { + protected function leaveGroup($userdata, $groupdata) + { $data = array_merge($userdata, $groupdata); $sql = $this->getConf('leave-group'); - $result = $this->_query($sql, $data); - if($result === false) return false; + $result = $this->query($sql, $data); + if ($result === false) return false; return true; } @@ -656,10 +671,11 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param array $arguments Named parameters to be used in the statement * @return array|int|bool The result as associative array for SELECTs, affected rows for others, false on error */ - protected function _query($sql, $arguments = array()) { + protected function query($sql, $arguments = array()) + { $sql = trim($sql); - if(empty($sql)) { - $this->_debug('No SQL query given', -1, __LINE__); + if (empty($sql)) { + $this->debugMsg('No SQL query given', -1, __LINE__); return false; } @@ -668,13 +684,13 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { $sth = $this->pdo->prepare($sql); try { // prepare parameters - we only use those that exist in the SQL - foreach($arguments as $key => $value) { - if(is_array($value)) continue; - if(is_object($value)) continue; - if($key[0] != ':') $key = ":$key"; // prefix with colon if needed - if(strpos($sql, $key) === false) continue; // skip if parameter is missing + foreach ($arguments as $key => $value) { + if (is_array($value)) continue; + if (is_object($value)) continue; + if ($key[0] != ':') $key = ":$key"; // prefix with colon if needed + if (strpos($sql, $key) === false) continue; // skip if parameter is missing - if(is_int($value)) { + if (is_int($value)) { $sth->bindValue($key, $value, PDO::PARAM_INT); } else { $sth->bindValue($key, $value); @@ -683,18 +699,18 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { } $sth->execute(); - if(strtolower(substr($sql, 0, 6)) == 'select') { + if (strtolower(substr($sql, 0, 6)) == 'select') { $result = $sth->fetchAll(); } else { $result = $sth->rowCount(); } - } catch(Exception $e) { + } catch (Exception $e) { // report the caller's line $trace = debug_backtrace(); $line = $trace[0]['line']; - $dsql = $this->_debugSQL($sql, $params, !defined('DOKU_UNITTEST')); - $this->_debug($e, -1, $line); - $this->_debug("SQL: <pre>$dsql</pre>", -1, $line); + $dsql = $this->debugSQL($sql, $params, !defined('DOKU_UNITTEST')); + $this->debugMsg($e, -1, $line); + $this->debugMsg("SQL: <pre>$dsql</pre>", -1, $line); $result = false; } $sth->closeCursor(); @@ -710,17 +726,18 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param int $err * @param int $line */ - protected function _debug($message, $err = 0, $line = 0) { - if(!$this->getConf('debug')) return; - if(is_a($message, 'Exception')) { + protected function debugMsg($message, $err = 0, $line = 0) + { + if (!$this->getConf('debug')) return; + if (is_a($message, 'Exception')) { $err = -1; $msg = $message->getMessage(); - if(!$line) $line = $message->getLine(); + if (!$line) $line = $message->getLine(); } else { $msg = $message; } - if(defined('DOKU_UNITTEST')) { + if (defined('DOKU_UNITTEST')) { printf("\n%s, %s:%d\n", $msg, __FILE__, $line); } else { msg('authpdo: ' . $msg, $err, $line, __FILE__); @@ -735,17 +752,18 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param string[] $keys * @return bool */ - protected function _chkcnf($keys) { - foreach($keys as $key) { + protected function checkConfig($keys) + { + foreach ($keys as $key) { $params = explode(':', $key); $key = array_shift($params); $sql = trim($this->getConf($key)); // check if sql is set - if(!$sql) return false; + if (!$sql) return false; // check if needed params are there - foreach($params as $param) { - if(strpos($sql, ":$param") === false) return false; + foreach ($params as $param) { + if (strpos($sql, ":$param") === false) return false; } } @@ -760,20 +778,21 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { * @param bool $htmlescape Should the result be escaped for output in HTML? * @return string */ - protected function _debugSQL($sql, $params, $htmlescape = true) { - foreach($params as $key => $val) { - if(is_int($val)) { + protected function debugSQL($sql, $params, $htmlescape = true) + { + foreach ($params as $key => $val) { + if (is_int($val)) { $val = $this->pdo->quote($val, PDO::PARAM_INT); - } elseif(is_bool($val)) { + } elseif (is_bool($val)) { $val = $this->pdo->quote($val, PDO::PARAM_BOOL); - } elseif(is_null($val)) { + } elseif (is_null($val)) { $val = 'NULL'; } else { $val = $this->pdo->quote($val); } $sql = str_replace($key, $val, $sql); } - if($htmlescape) $sql = hsc($sql); + if ($htmlescape) $sql = hsc($sql); return $sql; } } diff --git a/lib/plugins/authpdo/conf/metadata.php b/lib/plugins/authpdo/conf/metadata.php index 7c2ee8cdc..34e60a40e 100644 --- a/lib/plugins/authpdo/conf/metadata.php +++ b/lib/plugins/authpdo/conf/metadata.php @@ -23,5 +23,3 @@ $meta['update-user-pass'] = array('', '_caution' => 'danger'); $meta['insert-group'] = array('', '_caution' => 'danger'); $meta['join-group'] = array('', '_caution' => 'danger'); $meta['leave-group'] = array('', '_caution' => 'danger'); - - diff --git a/lib/plugins/authplain/_test/escaping.test.php b/lib/plugins/authplain/_test/escaping.test.php index a38940e1a..be4d06b4e 100644 --- a/lib/plugins/authplain/_test/escaping.test.php +++ b/lib/plugins/authplain/_test/escaping.test.php @@ -114,14 +114,14 @@ class auth_plugin_authplainharness extends auth_plugin_authplain { * @param boolean $bool */ public function setPregsplit_safe($bool) { - $this->_pregsplit_safe = $bool; + $this->pregsplit_safe = $bool; } /** * @return bool|mixed */ public function getPregsplit_safe(){ - return $this->_pregsplit_safe; + return $this->pregsplit_safe; } /** @@ -129,6 +129,6 @@ class auth_plugin_authplainharness extends auth_plugin_authplain { * @return array */ public function splitUserData($line){ - return $this->_splitUserData($line); + return parent::splitUserData($line); } } diff --git a/lib/plugins/authplain/auth.php b/lib/plugins/authplain/auth.php index 7dfa43a4f..374e7179c 100644 --- a/lib/plugins/authplain/auth.php +++ b/lib/plugins/authplain/auth.php @@ -1,6 +1,4 @@ <?php -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); /** * Plaintext authentication backend @@ -10,15 +8,16 @@ if(!defined('DOKU_INC')) die(); * @author Chris Smith <chris@jalakai.co.uk> * @author Jan Schumann <js@schumann-it.com> */ -class auth_plugin_authplain extends DokuWiki_Auth_Plugin { +class auth_plugin_authplain extends DokuWiki_Auth_Plugin +{ /** @var array user cache */ protected $users = null; /** @var array filter pattern */ - protected $_pattern = array(); + protected $pattern = array(); /** @var bool safe version of preg_split */ - protected $_pregsplit_safe = false; + protected $pregsplit_safe = false; /** * Constructor @@ -28,14 +27,15 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * * @author Christopher Smith <chris@jalakai.co.uk> */ - public function __construct() { + public function __construct() + { parent::__construct(); global $config_cascade; - if(!@is_readable($config_cascade['plainauth.users']['default'])) { + if (!@is_readable($config_cascade['plainauth.users']['default'])) { $this->success = false; } else { - if(@is_writable($config_cascade['plainauth.users']['default'])) { + if (@is_writable($config_cascade['plainauth.users']['default'])) { $this->cando['addUser'] = true; $this->cando['delUser'] = true; $this->cando['modLogin'] = true; @@ -48,7 +48,7 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { $this->cando['getUserCount'] = true; } - $this->_pregsplit_safe = version_compare(PCRE_VERSION,'6.7','>='); + $this->pregsplit_safe = version_compare(PCRE_VERSION, '6.7', '>='); } /** @@ -62,9 +62,10 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param string $pass * @return bool */ - public function checkPass($user, $pass) { + public function checkPass($user, $pass) + { $userinfo = $this->getUserData($user); - if($userinfo === false) return false; + if ($userinfo === false) return false; return auth_verifyPassword($pass, $this->users[$user]['pass']); } @@ -84,8 +85,9 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param bool $requireGroups (optional) ignored by this plugin, grps info always supplied * @return array|false */ - public function getUserData($user, $requireGroups=true) { - if($this->users === null) $this->_loadUserData(); + public function getUserData($user, $requireGroups = true) + { + if ($this->users === null) $this->loadUserData(); return isset($this->users[$user]) ? $this->users[$user] : false; } @@ -101,7 +103,8 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param array $grps list of groups the user is in * @return string */ - protected function _createUserLine($user, $pass, $name, $mail, $grps) { + protected function createUserLine($user, $pass, $name, $mail, $grps) + { $groups = join(',', $grps); $userline = array($user, $pass, $name, $mail, $groups); $userline = str_replace('\\', '\\\\', $userline); // escape \ as \\ @@ -129,12 +132,13 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param array $grps * @return bool|null|string */ - public function createUser($user, $pwd, $name, $mail, $grps = null) { + public function createUser($user, $pwd, $name, $mail, $grps = null) + { global $conf; global $config_cascade; // user mustn't already exist - if($this->getUserData($user) !== false) { + if ($this->getUserData($user) !== false) { msg($this->getLang('userexists'), -1); return false; } @@ -142,12 +146,12 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { $pass = auth_cryptPassword($pwd); // set default group if no groups specified - if(!is_array($grps)) $grps = array($conf['defaultgroup']); + if (!is_array($grps)) $grps = array($conf['defaultgroup']); // prepare user line - $userline = $this->_createUserLine($user, $pass, $name, $mail, $grps); + $userline = $this->createUserLine($user, $pass, $name, $mail, $grps); - if(!io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) { + if (!io_saveFile($config_cascade['plainauth.users']['default'], $userline, true)) { msg($this->getLang('writefail'), -1); return null; } @@ -164,38 +168,45 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param array $changes array of field/value pairs to be changed (password will be clear text) * @return bool */ - public function modifyUser($user, $changes) { + public function modifyUser($user, $changes) + { global $ACT; global $config_cascade; // sanity checks, user must already exist and there must be something to change - if(($userinfo = $this->getUserData($user)) === false) { + if (($userinfo = $this->getUserData($user)) === false) { msg($this->getLang('usernotexists'), -1); return false; } // don't modify protected users - if(!empty($userinfo['protected'])) { + if (!empty($userinfo['protected'])) { msg(sprintf($this->getLang('protected'), hsc($user)), -1); return false; } - if(!is_array($changes) || !count($changes)) return true; + if (!is_array($changes) || !count($changes)) return true; // update userinfo with new data, remembering to encrypt any password $newuser = $user; - foreach($changes as $field => $value) { - if($field == 'user') { + foreach ($changes as $field => $value) { + if ($field == 'user') { $newuser = $value; continue; } - if($field == 'pass') $value = auth_cryptPassword($value); + if ($field == 'pass') $value = auth_cryptPassword($value); $userinfo[$field] = $value; } - $userline = $this->_createUserLine($newuser, $userinfo['pass'], $userinfo['name'], $userinfo['mail'], $userinfo['grps']); + $userline = $this->createUserLine( + $newuser, + $userinfo['pass'], + $userinfo['name'], + $userinfo['mail'], + $userinfo['grps'] + ); - if(!io_replaceInFile($config_cascade['plainauth.users']['default'], '/^'.$user.':/', $userline, true)) { + if (!io_replaceInFile($config_cascade['plainauth.users']['default'], '/^'.$user.':/', $userline, true)) { msg('There was an error modifying your user data. You may need to register again.', -1); // FIXME, io functions should be fail-safe so existing data isn't lost $ACT = 'register'; @@ -213,24 +224,25 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param array $users array of users to be deleted * @return int the number of users deleted */ - public function deleteUsers($users) { + public function deleteUsers($users) + { global $config_cascade; - if(!is_array($users) || empty($users)) return 0; + if (!is_array($users) || empty($users)) return 0; - if($this->users === null) $this->_loadUserData(); + if ($this->users === null) $this->loadUserData(); $deleted = array(); - foreach($users as $user) { + foreach ($users as $user) { // don't delete protected users - if(!empty($this->users[$user]['protected'])) { + if (!empty($this->users[$user]['protected'])) { msg(sprintf($this->getLang('protected'), hsc($user)), -1); continue; } - if(isset($this->users[$user])) $deleted[] = preg_quote($user, '/'); + if (isset($this->users[$user])) $deleted[] = preg_quote($user, '/'); } - if(empty($deleted)) return 0; + if (empty($deleted)) return 0; $pattern = '/^('.join('|', $deleted).'):/'; if (!io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) { @@ -240,7 +252,7 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { // reload the user list and count the difference $count = count($this->users); - $this->_loadUserData(); + $this->loadUserData(); $count -= count($this->users); return $count; } @@ -253,17 +265,18 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param array $filter * @return int */ - public function getUserCount($filter = array()) { + public function getUserCount($filter = array()) + { - if($this->users === null) $this->_loadUserData(); + if ($this->users === null) $this->loadUserData(); - if(!count($filter)) return count($this->users); + if (!count($filter)) return count($this->users); $count = 0; - $this->_constructPattern($filter); + $this->constructPattern($filter); - foreach($this->users as $user => $info) { - $count += $this->_filter($user, $info); + foreach ($this->users as $user => $info) { + $count += $this->filter($user, $info); } return $count; @@ -279,23 +292,24 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param array $filter array of field/pattern pairs * @return array userinfo (refer getUserData for internal userinfo details) */ - public function retrieveUsers($start = 0, $limit = 0, $filter = array()) { + public function retrieveUsers($start = 0, $limit = 0, $filter = array()) + { - if($this->users === null) $this->_loadUserData(); + if ($this->users === null) $this->loadUserData(); ksort($this->users); $i = 0; $count = 0; $out = array(); - $this->_constructPattern($filter); + $this->constructPattern($filter); - foreach($this->users as $user => $info) { - if($this->_filter($user, $info)) { - if($i >= $start) { + foreach ($this->users as $user => $info) { + if ($this->filter($user, $info)) { + if ($i >= $start) { $out[$user] = $info; $count++; - if(($limit > 0) && ($count >= $limit)) break; + if (($limit > 0) && ($count >= $limit)) break; } $i++; } @@ -310,7 +324,8 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param string $user * @return string */ - public function cleanUser($user) { + public function cleanUser($user) + { global $conf; return cleanID(str_replace(':', $conf['sepchar'], $user)); } @@ -321,7 +336,8 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param string $group * @return string */ - public function cleanGroup($group) { + public function cleanGroup($group) + { global $conf; return cleanID(str_replace(':', $conf['sepchar'], $group)); } @@ -333,15 +349,16 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * * @author Andreas Gohr <andi@splitbrain.org> */ - protected function _loadUserData() { + protected function loadUserData() + { global $config_cascade; - $this->users = $this->_readUserFile($config_cascade['plainauth.users']['default']); + $this->users = $this->readUserFile($config_cascade['plainauth.users']['default']); // support protected users - if(!empty($config_cascade['plainauth.users']['protected'])) { - $protected = $this->_readUserFile($config_cascade['plainauth.users']['protected']); - foreach(array_keys($protected) as $key) { + if (!empty($config_cascade['plainauth.users']['protected'])) { + $protected = $this->readUserFile($config_cascade['plainauth.users']['protected']); + foreach (array_keys($protected) as $key) { $protected[$key]['protected'] = true; } $this->users = array_merge($this->users, $protected); @@ -356,17 +373,18 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param string $file the file to load data from * @return array */ - protected function _readUserFile($file) { + protected function readUserFile($file) + { $users = array(); - if(!file_exists($file)) return $users; + if (!file_exists($file)) return $users; $lines = file($file); - foreach($lines as $line) { + foreach ($lines as $line) { $line = preg_replace('/#.*$/', '', $line); //ignore comments $line = trim($line); - if(empty($line)) continue; + if (empty($line)) continue; - $row = $this->_splitUserData($line); + $row = $this->splitUserData($line); $row = str_replace('\\:', ':', $row); $row = str_replace('\\\\', '\\', $row); @@ -380,22 +398,29 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { return $users; } - protected function _splitUserData($line){ + /** + * Get the user line split into it's parts + * + * @param string $line + * @return string[] + */ + protected function splitUserData($line) + { // due to a bug in PCRE 6.6, preg_split will fail with the regex we use here // refer github issues 877 & 885 - if ($this->_pregsplit_safe){ + if ($this->pregsplit_safe) { return preg_split('/(?<![^\\\\]\\\\)\:/', $line, 5); // allow for : escaped as \: } $row = array(); $piece = ''; $len = strlen($line); - for($i=0; $i<$len; $i++){ - if ($line[$i]=='\\'){ + for ($i=0; $i<$len; $i++) { + if ($line[$i]=='\\') { $piece .= $line[$i]; $i++; if ($i>=$len) break; - } else if ($line[$i]==':'){ + } elseif ($line[$i]==':') { $row[] = $piece; $piece = ''; continue; @@ -416,14 +441,15 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * @param array $info User's userinfo array * @return bool */ - protected function _filter($user, $info) { - foreach($this->_pattern as $item => $pattern) { - if($item == 'user') { - if(!preg_match($pattern, $user)) return false; - } else if($item == 'grps') { - if(!count(preg_grep($pattern, $info['grps']))) return false; + protected function filter($user, $info) + { + foreach ($this->pattern as $item => $pattern) { + if ($item == 'user') { + if (!preg_match($pattern, $user)) return false; + } elseif ($item == 'grps') { + if (!count(preg_grep($pattern, $info['grps']))) return false; } else { - if(!preg_match($pattern, $info[$item])) return false; + if (!preg_match($pattern, $info[$item])) return false; } } return true; @@ -434,10 +460,11 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { * * @param array $filter */ - protected function _constructPattern($filter) { - $this->_pattern = array(); - foreach($filter as $item => $pattern) { - $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters + protected function constructPattern($filter) + { + $this->pattern = array(); + foreach ($filter as $item => $pattern) { + $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters } } } diff --git a/lib/plugins/config/_test/configuration.test.php b/lib/plugins/config/_test/configuration.test.php index 7455461a4..62ac23433 100644 --- a/lib/plugins/config/_test/configuration.test.php +++ b/lib/plugins/config/_test/configuration.test.php @@ -25,7 +25,7 @@ class plugin_config_configuration_test extends DokuWikiTest { function test_readconfig() { $confmgr = new configuration($this->meta); - $conf = $confmgr->_read_config($this->config); + $conf = $this->callInaccessibleMethod($confmgr, '_read_config', [$this->config]); // var_dump($conf); @@ -44,7 +44,7 @@ class plugin_config_configuration_test extends DokuWikiTest { function test_readconfig_onoff() { $confmgr = new configuration($this->meta); - $conf = $confmgr->_read_config($this->config); + $conf = $this->callInaccessibleMethod($confmgr, '_read_config', [$this->config]); // var_dump($conf); diff --git a/lib/plugins/config/admin.php b/lib/plugins/config/admin.php index 76ecae24c..e2fb622ab 100644 --- a/lib/plugins/config/admin.php +++ b/lib/plugins/config/admin.php @@ -6,8 +6,6 @@ * @author Christopher Smith <chris@jalakai.co.uk> * @author Ben Coburn <btcoburn@silicodon.net> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); define('CM_KEYMARKER','____'); // used for settings with multiple dimensions of array indices @@ -150,9 +148,16 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { // config settings list($label,$input) = $setting->html($this, $this->_error); - $class = $setting->is_default() ? ' class="default"' : ($setting->is_protected() ? ' class="protected"' : ''); - $error = $setting->error() ? ' class="value error"' : ' class="value"'; - $icon = $setting->caution() ? '<img src="'.DOKU_PLUGIN_IMAGES.$setting->caution().'.png" alt="'.$setting->caution().'" title="'.$this->getLang($setting->caution()).'" />' : ''; + $class = $setting->is_default() + ? ' class="default"' + : ($setting->is_protected() ? ' class="protected"' : ''); + $error = $setting->error() + ? ' class="value error"' + : ' class="value"'; + $icon = $setting->caution() + ? '<img src="'.DOKU_PLUGIN_IMAGES.$setting->caution().'.png" '. + 'alt="'.$setting->caution().'" title="'.$this->getLang($setting->caution()).'" />' + : ''; ptln(' <tr'.$class.'>'); ptln(' <td class="label">'); @@ -190,13 +195,20 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { ptln('<table class="inline">'); $undefined_setting_match = array(); foreach($undefined_settings as $setting) { - if (preg_match('/^(?:plugin|tpl)'.CM_KEYMARKER.'.*?'.CM_KEYMARKER.'(.*)$/', $setting->_key, $undefined_setting_match)) { + if ( + preg_match( + '/^(?:plugin|tpl)'.CM_KEYMARKER.'.*?'.CM_KEYMARKER.'(.*)$/', + $setting->_key, + $undefined_setting_match + ) + ) { $undefined_setting_key = $undefined_setting_match[1]; } else { $undefined_setting_key = $setting->_key; } ptln(' <tr>'); - ptln(' <td class="label"><span title="$meta[\''.$undefined_setting_key.'\']">$'.$this->_config->_name.'[\''.$setting->_out_key().'\']</span></td>'); + ptln(' <td class="label"><span title="$meta[\''.$undefined_setting_key.'\']">$'. + $this->_config->_name.'[\''.$setting->_out_key().'\']</span></td>'); ptln(' <td>'.$this->getLang('_msg_'.get_class($setting)).'</td>'); ptln(' </tr>'); } diff --git a/lib/plugins/config/settings/config.class.php b/lib/plugins/config/settings/config.class.php index 3196d7527..0d39eb2c5 100644 --- a/lib/plugins/config/settings/config.class.php +++ b/lib/plugins/config/settings/config.class.php @@ -15,22 +15,22 @@ if (!class_exists('configuration')) { */ class configuration { - var $_name = 'conf'; // name of the config variable found in the files (overridden by $config['varname']) - var $_format = 'php'; // format of the config file, supported formats - php (overridden by $config['format']) - var $_heading = ''; // heading string written at top of config file - don't include comment indicators - var $_loaded = false; // set to true after configuration files are loaded - var $_metadata = array(); // holds metadata describing the settings + protected $_name = 'conf'; // name of the config variable found in the files (overridden by $config['varname']) + protected $_format = 'php'; // format of the config file, supported formats - php (overridden by $config['format']) + protected $_heading = ''; // heading string written at top of config file - don't include comment indicators + protected $_loaded = false; // set to true after configuration files are loaded + protected $_metadata = array();// holds metadata describing the settings /** @var setting[] */ - var $setting = array(); // array of setting objects - var $locked = false; // configuration is considered locked if it can't be updated - var $show_disabled_plugins = false; + public $setting = array(); // array of setting objects + public $locked = false; // configuration is considered locked if it can't be updated + public $show_disabled_plugins = false; // configuration filenames - var $_default_files = array(); - var $_local_files = array(); // updated configuration is written to the first file - var $_protected_files = array(); + protected $_default_files = array(); + protected $_local_files = array(); // updated configuration is written to the first file + protected $_protected_files = array(); - var $_plugin_list = null; + protected $_plugin_list = null; /** * constructor @@ -45,6 +45,7 @@ if (!class_exists('configuration')) { return; } $meta = array(); + /** @var array $config gets loaded via include here */ include($datafile); if (isset($config['varname'])) $this->_name = $config['varname']; @@ -68,11 +69,19 @@ if (!class_exists('configuration')) { $no_default_check = array('setting_fieldset', 'setting_undefined', 'setting_no_class'); if (!$this->_loaded) { - $default = array_merge($this->get_plugintpl_default($conf['template']), $this->_read_config_group($this->_default_files)); + $default = array_merge( + $this->get_plugintpl_default($conf['template']), + $this->_read_config_group($this->_default_files) + ); $local = $this->_read_config_group($this->_local_files); $protected = $this->_read_config_group($this->_protected_files); - $keys = array_merge(array_keys($this->_metadata),array_keys($default), array_keys($local), array_keys($protected)); + $keys = array_merge( + array_keys($this->_metadata), + array_keys($default), + array_keys($local), + array_keys($protected) + ); $keys = array_unique($keys); $param = null; @@ -188,7 +197,7 @@ if (!class_exists('configuration')) { * @param string $file file path * @return array config settings */ - function _read_config($file) { + protected function _read_config($file) { if (!$file) return array(); @@ -345,7 +354,7 @@ if (!class_exists('configuration')) { * @return array plugin names * @triggers PLUGIN_CONFIG_PLUGINLIST event */ - function get_plugin_list() { + protected function get_plugin_list() { if (is_null($this->_plugin_list)) { $list = plugin_list('',$this->show_disabled_plugins); @@ -366,7 +375,7 @@ if (!class_exists('configuration')) { * @param string $tpl name of active template * @return array metadata of settings */ - function get_plugintpl_metadata($tpl){ + protected function get_plugintpl_metadata($tpl){ $file = '/conf/metadata.php'; $class = '/conf/settings.class.php'; $metadata = array(); @@ -378,7 +387,7 @@ if (!class_exists('configuration')) { @include(DOKU_PLUGIN.$plugin_dir.$file); @include(DOKU_PLUGIN.$plugin_dir.$class); if (!empty($meta)) { - $metadata['plugin'.CM_KEYMARKER.$plugin.CM_KEYMARKER.'plugin_settings_name'] = array('fieldset'); + $metadata['plugin'.CM_KEYMARKER.$plugin.CM_KEYMARKER.'plugin_settings_name'] = ['fieldset']; } foreach ($meta as $key => $value){ if ($value[0]=='fieldset') { continue; } //plugins only get one fieldset @@ -410,7 +419,7 @@ if (!class_exists('configuration')) { * @param string $tpl name of active template * @return array default settings */ - function get_plugintpl_default($tpl){ + protected function get_plugintpl_default($tpl){ $file = '/conf/default.php'; $default = array(); @@ -444,17 +453,17 @@ if (!class_exists('setting')) { */ class setting { - var $_key = ''; - var $_default = null; - var $_local = null; - var $_protected = null; + protected $_key = ''; + protected $_default = null; + protected $_local = null; + protected $_protected = null; - var $_pattern = ''; - var $_error = false; // only used by those classes which error check - var $_input = null; // only used by those classes which error check - var $_caution = null; // used by any setting to provide an alert along with the setting - // valid alerts, 'warning', 'danger', 'security' - // images matching the alerts are in the plugin's images directory + protected $_pattern = ''; + protected $_error = false; // only used by those classes which error check + protected $_input = null; // only used by those classes which error check + protected $_caution = null; // used by any setting to provide an alert along with the setting + // valid alerts, 'warning', 'danger', 'security' + // images matching the alerts are in the plugin's images directory static protected $_validCautions = array('warning','danger','security'); @@ -535,7 +544,8 @@ if (!class_exists('setting')) { $value = formText($value); $label = '<label for="config___'.$key.'">'.$this->prompt($plugin).'</label>'; - $input = '<textarea rows="3" cols="40" id="config___'.$key.'" name="config['.$key.']" class="edit" '.$disable.'>'.$value.'</textarea>'; + $input = '<textarea rows="3" cols="40" id="config___'.$key. + '" name="config['.$key.']" class="edit" '.$disable.'>'.$value.'</textarea>'; return array($label,$input); } @@ -603,7 +613,10 @@ if (!class_exists('setting')) { public function caution() { if (!empty($this->_caution)) { if (!in_array($this->_caution, setting::$_validCautions)) { - trigger_error('Invalid caution string ('.$this->_caution.') in metadata for setting "'.$this->_key.'"', E_USER_WARNING); + trigger_error( + 'Invalid caution string ('.$this->_caution.') in metadata for setting "'.$this->_key.'"', + E_USER_WARNING + ); return false; } return $this->_caution; @@ -681,7 +694,7 @@ if (!class_exists('setting_array')) { * @param string $input * @return bool true if changed, false otherwise (incl. on error) */ - function update($input) { + public function update($input) { if (is_null($input)) return false; if ($this->is_protected()) return false; @@ -720,7 +733,7 @@ if (!class_exists('setting_array')) { * @param string $fmt save format * @return string */ - function out($var, $fmt='php') { + public function out($var, $fmt='php') { if ($this->is_protected()) return ''; if (is_null($this->_local) || ($this->_default == $this->_local)) return ''; @@ -742,7 +755,7 @@ if (!class_exists('setting_array')) { * @param bool $echo true: show inputted value, when error occurred, otherwise the stored setting * @return string[] with content array(string $label_html, string $input_html) */ - function html(admin_plugin_config $plugin, $echo=false) { + public function html(admin_plugin_config $plugin, $echo=false) { $disable = ''; if ($this->is_protected()) { @@ -760,7 +773,8 @@ if (!class_exists('setting_array')) { $value = htmlspecialchars($this->_from_array($value)); $label = '<label for="config___'.$key.'">'.$this->prompt($plugin).'</label>'; - $input = '<input id="config___'.$key.'" name="config['.$key.']" type="text" class="edit" value="'.$value.'" '.$disable.'/>'; + $input = '<input id="config___'.$key.'" name="config['.$key. + ']" type="text" class="edit" value="'.$value.'" '.$disable.'/>'; return array($label,$input); } } @@ -778,7 +792,7 @@ if (!class_exists('setting_string')) { * @param bool $echo true: show inputted value, when error occurred, otherwise the stored setting * @return string[] with content array(string $label_html, string $input_html) */ - function html(admin_plugin_config $plugin, $echo=false) { + public function html(admin_plugin_config $plugin, $echo=false) { $disable = ''; if ($this->is_protected()) { @@ -796,7 +810,8 @@ if (!class_exists('setting_string')) { $value = htmlspecialchars($value); $label = '<label for="config___'.$key.'">'.$this->prompt($plugin).'</label>'; - $input = '<input id="config___'.$key.'" name="config['.$key.']" type="text" class="edit" value="'.$value.'" '.$disable.'/>'; + $input = '<input id="config___'.$key.'" name="config['.$key. + ']" type="text" class="edit" value="'.$value.'" '.$disable.'/>'; return array($label,$input); } } @@ -808,7 +823,7 @@ if (!class_exists('setting_password')) { */ class setting_password extends setting_string { - var $_code = 'plain'; // mechanism to be used to obscure passwords + protected $_code = 'plain'; // mechanism to be used to obscure passwords /** * update changed setting with user provided value $input @@ -818,7 +833,7 @@ if (!class_exists('setting_password')) { * @param mixed $input the new value * @return boolean true if changed, false otherwise (also on error) */ - function update($input) { + public function update($input) { if ($this->is_protected()) return false; if (!$input) return false; @@ -839,14 +854,15 @@ if (!class_exists('setting_password')) { * @param bool $echo true: show inputted value, when error occurred, otherwise the stored setting * @return string[] with content array(string $label_html, string $input_html) */ - function html(admin_plugin_config $plugin, $echo=false) { + public function html(admin_plugin_config $plugin, $echo=false) { $disable = $this->is_protected() ? 'disabled="disabled"' : ''; $key = htmlspecialchars($this->_key); $label = '<label for="config___'.$key.'">'.$this->prompt($plugin).'</label>'; - $input = '<input id="config___'.$key.'" name="config['.$key.']" autocomplete="off" type="password" class="edit" value="" '.$disable.' />'; + $input = '<input id="config___'.$key.'" name="config['.$key. + ']" autocomplete="off" type="password" class="edit" value="" '.$disable.' />'; return array($label,$input); } } @@ -857,8 +873,8 @@ if (!class_exists('setting_email')) { * Class setting_email */ class setting_email extends setting_string { - var $_multiple = false; - var $_placeholders = false; + protected $_multiple = false; + protected $_placeholders = false; /** * update setting with user provided value $input @@ -867,7 +883,7 @@ if (!class_exists('setting_email')) { * @param mixed $input * @return boolean true if changed, false otherwise (incl. on error) */ - function update($input) { + public function update($input) { if (is_null($input)) return false; if ($this->is_protected()) return false; @@ -923,9 +939,9 @@ if (!class_exists('setting_numeric')) { // This allows for many PHP syntax errors... // var $_pattern = '/^[-+\/*0-9 ]*$/'; // much more restrictive, but should eliminate syntax errors. - var $_pattern = '/^[-+]? *[0-9]+ *(?:[-+*] *[0-9]+ *)*$/'; - var $_min = null; - var $_max = null; + protected $_pattern = '/^[-+]? *[0-9]+ *(?:[-+*] *[0-9]+ *)*$/'; + protected $_min = null; + protected $_max = null; /** * update changed setting with user provided value $input @@ -935,7 +951,7 @@ if (!class_exists('setting_numeric')) { * @param mixed $input the new value * @return boolean true if changed, false otherwise (also on error) */ - function update($input) { + public function update($input) { $local = $this->_local; $valid = parent::update($input); if ($valid && !(is_null($this->_min) && is_null($this->_max))) { @@ -958,7 +974,7 @@ if (!class_exists('setting_numeric')) { * @param string $fmt save format * @return string */ - function out($var, $fmt='php') { + public function out($var, $fmt='php') { if ($this->is_protected()) return ''; if (is_null($this->_local) || ($this->_default == $this->_local)) return ''; @@ -981,7 +997,7 @@ if (!class_exists('setting_numericopt')) { */ class setting_numericopt extends setting_numeric { // just allow an empty config - var $_pattern = '/^(|[-]?[0-9]+(?:[-+*][0-9]+)*)$/'; + protected $_pattern = '/^(|[-]?[0-9]+(?:[-+*][0-9]+)*)$/'; /** @@ -991,7 +1007,7 @@ if (!class_exists('setting_numericopt')) { * * @return bool */ - function update($input) { + public function update($input) { if ($input === '') { return true; } @@ -1013,7 +1029,7 @@ if (!class_exists('setting_onoff')) { * @param bool $echo true: show inputted value, when error occurred, otherwise the stored setting * @return string[] with content array(string $label_html, string $input_html) */ - function html(admin_plugin_config $plugin, $echo = false) { + public function html(admin_plugin_config $plugin, $echo = false) { $disable = ''; if ($this->is_protected()) { @@ -1027,7 +1043,8 @@ if (!class_exists('setting_onoff')) { $checked = ($value) ? ' checked="checked"' : ''; $label = '<label for="config___'.$key.'">'.$this->prompt($plugin).'</label>'; - $input = '<div class="input"><input id="config___'.$key.'" name="config['.$key.']" type="checkbox" class="checkbox" value="1"'.$checked.$disable.'/></div>'; + $input = '<div class="input"><input id="config___'.$key.'" name="config['.$key. + ']" type="checkbox" class="checkbox" value="1"'.$checked.$disable.'/></div>'; return array($label,$input); } @@ -1039,7 +1056,7 @@ if (!class_exists('setting_onoff')) { * @param mixed $input the new value * @return boolean true if changed, false otherwise (also on error) */ - function update($input) { + public function update($input) { if ($this->is_protected()) return false; $input = ($input) ? 1 : 0; @@ -1057,8 +1074,8 @@ if (!class_exists('setting_multichoice')) { * Class setting_multichoice */ class setting_multichoice extends setting_string { - var $_choices = array(); - var $lang; //some custom language strings are stored in setting + protected $_choices = array(); + public $lang; //some custom language strings are stored in setting /** * Build html for label and input of setting @@ -1067,7 +1084,7 @@ if (!class_exists('setting_multichoice')) { * @param bool $echo true: show inputted value, when error occurred, otherwise the stored setting * @return string[] with content array(string $label_html, string $input_html) */ - function html(admin_plugin_config $plugin, $echo = false) { + public function html(admin_plugin_config $plugin, $echo = false) { $disable = ''; $nochoice = ''; @@ -1097,7 +1114,9 @@ if (!class_exists('setting_multichoice')) { foreach ($this->_choices as $choice) { $selected = ($value == $choice) ? ' selected="selected"' : ''; $option = $plugin->getLang($this->_key.'_o_'.$choice); - if (!$option && isset($this->lang[$this->_key.'_o_'.$choice])) $option = $this->lang[$this->_key.'_o_'.$choice]; + if (!$option && isset($this->lang[$this->_key.'_o_'.$choice])) { + $option = $this->lang[$this->_key . '_o_' . $choice]; + } if (!$option) $option = $choice; $choice = htmlspecialchars($choice); @@ -1118,7 +1137,7 @@ if (!class_exists('setting_multichoice')) { * @param mixed $input the new value * @return boolean true if changed, false otherwise (also on error) */ - function update($input) { + public function update($input) { if (is_null($input)) return false; if ($this->is_protected()) return false; @@ -1140,7 +1159,7 @@ if (!class_exists('setting_dirchoice')) { */ class setting_dirchoice extends setting_multichoice { - var $_dir = ''; + protected $_dir = ''; /** * Receives current values for the setting $key @@ -1149,7 +1168,7 @@ if (!class_exists('setting_dirchoice')) { * @param mixed $local local setting value * @param mixed $protected protected setting value */ - function initialize($default,$local,$protected) { + public function initialize($default,$local,$protected) { // populate $this->_choices with a list of directories $list = array(); @@ -1228,9 +1247,9 @@ if (!class_exists('setting_multicheckbox')) { */ class setting_multicheckbox extends setting_string { - var $_choices = array(); - var $_combine = array(); - var $_other = 'always'; + protected $_choices = array(); + protected $_combine = array(); + protected $_other = 'always'; /** * update changed setting with user provided value $input @@ -1240,7 +1259,7 @@ if (!class_exists('setting_multicheckbox')) { * @param mixed $input the new value * @return boolean true if changed, false otherwise (also on error) */ - function update($input) { + public function update($input) { if ($this->is_protected()) return false; // split any combined values + convert from array to comma separated string @@ -1267,7 +1286,7 @@ if (!class_exists('setting_multicheckbox')) { * @param bool $echo true: show input value, when error occurred, otherwise the stored setting * @return string[] with content array(string $label_html, string $input_html) */ - function html(admin_plugin_config $plugin, $echo=false) { + public function html(admin_plugin_config $plugin, $echo=false) { $disable = ''; @@ -1303,7 +1322,8 @@ if (!class_exists('setting_multicheckbox')) { $input .= '<div class="selection'.$class.'">'."\n"; $input .= '<label for="config___'.$key.'_'.$choice.'">'.$prompt."</label>\n"; - $input .= '<input id="config___'.$key.'_'.$choice.'" name="config['.$key.'][]" type="checkbox" class="checkbox" value="'.$choice.'" '.$disable.' '.$checked."/>\n"; + $input .= '<input id="config___'.$key.'_'.$choice.'" name="config['.$key. + '][]" type="checkbox" class="checkbox" value="'.$choice.'" '.$disable.' '.$checked."/>\n"; $input .= "</div>\n"; // remove this action from the disabledactions array @@ -1318,12 +1338,16 @@ if (!class_exists('setting_multicheckbox')) { // use != 'exists' rather than == 'always' to ensure invalid values default to 'always' if ($this->_other != 'exists' || $other) { - $class = ((count($default) == count($value)) && (count($value) == count(array_intersect($value,$default)))) ? + $class = ( + (count($default) == count($value)) && + (count($value) == count(array_intersect($value,$default))) + ) ? " selectiondefault" : ""; $input .= '<div class="other'.$class.'">'."\n"; $input .= '<label for="config___'.$key.'_other">'.$plugin->getLang($key.'_other')."</label>\n"; - $input .= '<input id="config___'.$key.'_other" name="config['.$key.'][other]" type="text" class="edit" value="'.htmlspecialchars($other).'" '.$disable." />\n"; + $input .= '<input id="config___'.$key.'_other" name="config['.$key. + '][other]" type="text" class="edit" value="'.htmlspecialchars($other).'" '.$disable." />\n"; $input .= "</div>\n"; } } @@ -1337,7 +1361,7 @@ if (!class_exists('setting_multicheckbox')) { * @param string $str * @return array */ - function _str2array($str) { + protected function _str2array($str) { $array = explode(',',$str); if (!empty($this->_combine)) { @@ -1363,7 +1387,7 @@ if (!class_exists('setting_multicheckbox')) { * @param array $input * @return string */ - function _array2str($input) { + protected function _array2str($input) { // handle other $other = trim($input['other']); @@ -1395,8 +1419,8 @@ if (!class_exists('setting_regex')){ */ class setting_regex extends setting_string { - var $_delimiter = '/'; // regex delimiter to be used in testing input - var $_pregflags = 'ui'; // regex pattern modifiers to be used in testing input + protected $_delimiter = '/'; // regex delimiter to be used in testing input + protected $_pregflags = 'ui'; // regex pattern modifiers to be used in testing input /** * update changed setting with user provided value $input @@ -1406,7 +1430,7 @@ if (!class_exists('setting_regex')){ * @param mixed $input the new value * @return boolean true if changed, false otherwise (incl. on error) */ - function update($input) { + public function update($input) { // let parent do basic checks, value, not changed, etc. $local = $this->_local; diff --git a/lib/plugins/config/settings/config.metadata.php b/lib/plugins/config/settings/config.metadata.php index acdf93ba7..8c1add7d1 100644 --- a/lib/plugins/config/settings/config.metadata.php +++ b/lib/plugins/config/settings/config.metadata.php @@ -122,7 +122,10 @@ $meta['fullpath'] = array('onoff','_caution' => 'security'); $meta['typography'] = array('multichoice','_choices' => array(0,1,2)); $meta['dformat'] = array('string'); $meta['signature'] = array('string'); -$meta['showuseras'] = array('multichoice','_choices' => array('loginname','username','username_link','email','email_link')); +$meta['showuseras'] = array( + 'multichoice', + '_choices' => array('loginname', 'username', 'username_link', 'email', 'email_link') +); $meta['toptoclevel'] = array('multichoice','_choices' => array(1,2,3,4,5)); // 5 toc levels $meta['tocminheads'] = array('multichoice','_choices' => array(0,1,2,3,4,5,10,15,20)); $meta['maxtoclevel'] = array('multichoice','_choices' => array(0,1,2,3,4,5)); @@ -146,9 +149,29 @@ $meta['superuser'] = array('string','_caution' => 'danger'); $meta['manager'] = array('string'); $meta['profileconfirm'] = array('onoff'); $meta['rememberme'] = array('onoff'); -$meta['disableactions'] = array('disableactions', - '_choices' => array('backlink','index','recent','revisions','search','subscription','register','resendpwd','profile','profile_delete','edit','wikicode','check', 'rss'), - '_combine' => array('subscription' => array('subscribe','unsubscribe'), 'wikicode' => array('source','export_raw'))); +$meta['disableactions'] = array( + 'disableactions', + '_choices' => array( + 'backlink', + 'index', + 'recent', + 'revisions', + 'search', + 'subscription', + 'register', + 'resendpwd', + 'profile', + 'profile_delete', + 'edit', + 'wikicode', + 'check', + 'rss' + ), + '_combine' => array( + 'subscription' => array('subscribe', 'unsubscribe'), + 'wikicode' => array('source', 'export_raw') + ) +); $meta['auth_security_timeout'] = array('numeric'); $meta['securecookie'] = array('onoff'); $meta['remote'] = array('onoff','_caution' => 'security'); diff --git a/lib/plugins/config/settings/extra.class.php b/lib/plugins/config/settings/extra.class.php index 41af42247..5f963fb81 100644 --- a/lib/plugins/config/settings/extra.class.php +++ b/lib/plugins/config/settings/extra.class.php @@ -15,7 +15,7 @@ if (!class_exists('setting_sepchar')) { * @param string $key * @param array|null $param array with metadata of setting */ - function __construct($key,$param=null) { + public function __construct($key,$param=null) { $str = '_-.'; for ($i=0;$i<strlen($str);$i++) $this->_choices[] = $str{$i}; @@ -39,7 +39,7 @@ if (!class_exists('setting_savedir')) { * @param mixed $input the new value * @return boolean true if changed, false otherwise (also on error) */ - function update($input) { + public function update($input) { if ($this->is_protected()) return false; $value = is_null($this->_local) ? $this->_default : $this->_local; @@ -70,7 +70,7 @@ if (!class_exists('setting_authtype')) { * @param mixed $local local setting value * @param mixed $protected protected setting value */ - function initialize($default,$local,$protected) { + public function initialize($default,$local,$protected) { /** @var $plugin_controller Doku_Plugin_Controller */ global $plugin_controller; @@ -90,7 +90,7 @@ if (!class_exists('setting_authtype')) { * @param mixed $input the new value * @return boolean true if changed, false otherwise (also on error) */ - function update($input) { + public function update($input) { /** @var $plugin_controller Doku_Plugin_Controller */ global $plugin_controller; @@ -143,7 +143,7 @@ if (!class_exists('setting_im_convert')) { * @param mixed $input the new value * @return boolean true if changed, false otherwise (also on error) */ - function update($input) { + public function update($input) { if ($this->is_protected()) return false; $input = trim($input); @@ -176,7 +176,7 @@ if (!class_exists('setting_disableactions')) { * @param bool $echo true: show inputted value, when error occurred, otherwise the stored setting * @return array with content array(string $label_html, string $input_html) */ - function html(admin_plugin_config $plugin, $echo=false) { + public function html(admin_plugin_config $plugin, $echo=false) { global $lang; // make some language adjustments (there must be a better way) @@ -197,7 +197,7 @@ if (!class_exists('setting_compression')) { */ class setting_compression extends setting_multichoice { - var $_choices = array('0'); // 0 = no compression, always supported + protected $_choices = array('0'); // 0 = no compression, always supported /** * Receives current values for the setting $key @@ -206,7 +206,7 @@ if (!class_exists('setting_compression')) { * @param mixed $local local setting value * @param mixed $protected protected setting value */ - function initialize($default,$local,$protected) { + public function initialize($default,$local,$protected) { // populate _choices with the compression methods supported by this php installation if (function_exists('gzopen')) $this->_choices[] = 'gz'; @@ -223,7 +223,7 @@ if (!class_exists('setting_license')) { */ class setting_license extends setting_multichoice { - var $_choices = array(''); // none choosen + protected $_choices = array(''); // none choosen /** * Receives current values for the setting $key @@ -232,7 +232,7 @@ if (!class_exists('setting_license')) { * @param mixed $local local setting value * @param mixed $protected protected setting value */ - function initialize($default,$local,$protected) { + public function initialize($default,$local,$protected) { global $license; foreach($license as $key => $data){ @@ -251,8 +251,8 @@ if (!class_exists('setting_renderer')) { * Class setting_renderer */ class setting_renderer extends setting_multichoice { - var $_prompts = array(); - var $_format = null; + protected $_prompts = array(); + protected $_format = null; /** * Receives current values for the setting $key @@ -261,7 +261,7 @@ if (!class_exists('setting_renderer')) { * @param mixed $local local setting value * @param mixed $protected protected setting value */ - function initialize($default,$local,$protected) { + public function initialize($default,$local,$protected) { $format = $this->_format; foreach (plugin_list('renderer') as $plugin) { @@ -284,7 +284,7 @@ if (!class_exists('setting_renderer')) { * @param bool $echo true: show inputted value, when error occurred, otherwise the stored setting * @return array with content array(string $label_html, string $input_html) */ - function html(admin_plugin_config $plugin, $echo=false) { + public function html(admin_plugin_config $plugin, $echo=false) { // make some language adjustments (there must be a better way) // transfer some plugin names to the config plugin diff --git a/lib/plugins/extension/_test/extension.test.php b/lib/plugins/extension/_test/extension.test.php index d4f13201d..1f8e2fca7 100644 --- a/lib/plugins/extension/_test/extension.test.php +++ b/lib/plugins/extension/_test/extension.test.php @@ -6,8 +6,8 @@ * makes protected methods accessible */ class mock_helper_plugin_extension_extension extends helper_plugin_extension_extension { - public function find_folders(&$result, $base, $default_type = 'plugin', $dir = '') { - return parent::find_folders($result, $base, $default_type, $dir); + public function findFolders(&$result, $base, $default_type = 'plugin', $dir = '') { + return parent::findFolders($result, $base, $default_type, $dir); } } @@ -78,7 +78,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $tdir = dirname(__FILE__).'/testdata'; $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/plugin1", 'plugin'); + $ok = $extension->findFolders($result, "$tdir/plugin1", 'plugin'); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -86,7 +86,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('plugin1', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/plugin2", 'plugin'); + $ok = $extension->findFolders($result, "$tdir/plugin2", 'plugin'); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('plugin', $result['new'][0]['type']); @@ -94,7 +94,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('plugin2', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/plgsub3", 'plugin'); + $ok = $extension->findFolders($result, "$tdir/plgsub3", 'plugin'); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -102,7 +102,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('plgsub3/plugin3', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/plgsub4", 'plugin'); + $ok = $extension->findFolders($result, "$tdir/plgsub4", 'plugin'); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('plugin', $result['new'][0]['type']); @@ -110,7 +110,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('plgsub4/plugin4', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/plgfoo5", 'plugin'); + $ok = $extension->findFolders($result, "$tdir/plgfoo5", 'plugin'); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('plugin', $result['new'][0]['type']); @@ -118,7 +118,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('plgfoo5', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/plgsub6/plgfoo6", 'plugin'); + $ok = $extension->findFolders($result, "$tdir/plgsub6/plgfoo6", 'plugin'); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('plugin', $result['new'][0]['type']); @@ -126,7 +126,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('plgsub6/plgfoo6', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/either1", 'plugin'); + $ok = $extension->findFolders($result, "$tdir/either1", 'plugin'); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -134,7 +134,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('either1', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/eithersub2/either2", 'plugin'); + $ok = $extension->findFolders($result, "$tdir/eithersub2/either2", 'plugin'); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -147,7 +147,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $tdir = dirname(__FILE__).'/testdata'; $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/template1", 'template'); + $ok = $extension->findFolders($result, "$tdir/template1", 'template'); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -155,7 +155,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('template1', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/template2", 'template'); + $ok = $extension->findFolders($result, "$tdir/template2", 'template'); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('template', $result['new'][0]['type']); @@ -163,7 +163,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('template2', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/tplsub3", 'template'); + $ok = $extension->findFolders($result, "$tdir/tplsub3", 'template'); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -171,7 +171,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('tplsub3/template3', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/tplsub4", 'template'); + $ok = $extension->findFolders($result, "$tdir/tplsub4", 'template'); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('template', $result['new'][0]['type']); @@ -179,7 +179,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('tplsub4/template4', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/tplfoo5", 'template'); + $ok = $extension->findFolders($result, "$tdir/tplfoo5", 'template'); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('template', $result['new'][0]['type']); @@ -187,7 +187,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('tplfoo5', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/tplsub6/tplfoo6", 'template'); + $ok = $extension->findFolders($result, "$tdir/tplsub6/tplfoo6", 'template'); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('template', $result['new'][0]['type']); @@ -195,7 +195,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('tplsub6/tplfoo6', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/either1", 'template'); + $ok = $extension->findFolders($result, "$tdir/either1", 'template'); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -203,7 +203,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('either1', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/eithersub2/either2", 'template'); + $ok = $extension->findFolders($result, "$tdir/eithersub2/either2", 'template'); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -216,7 +216,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $tdir = dirname(__FILE__).'/testdata'; $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/template1"); + $ok = $extension->findFolders($result, "$tdir/template1"); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -224,7 +224,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('template1', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/template2"); + $ok = $extension->findFolders($result, "$tdir/template2"); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('template', $result['new'][0]['type']); @@ -232,7 +232,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('template2', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/tplsub3"); + $ok = $extension->findFolders($result, "$tdir/tplsub3"); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -240,7 +240,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('tplsub3/template3', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/tplsub4"); + $ok = $extension->findFolders($result, "$tdir/tplsub4"); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('template', $result['new'][0]['type']); @@ -248,7 +248,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('tplsub4/template4', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/tplfoo5"); + $ok = $extension->findFolders($result, "$tdir/tplfoo5"); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('template', $result['new'][0]['type']); @@ -256,7 +256,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('tplfoo5', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/tplsub6/tplfoo6"); + $ok = $extension->findFolders($result, "$tdir/tplsub6/tplfoo6"); $this->assertTrue($ok); $this->assertEquals(1, count($result['new'])); $this->assertEquals('template', $result['new'][0]['type']); @@ -264,7 +264,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('tplsub6/tplfoo6', $this->extdir($result['new'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/either1"); + $ok = $extension->findFolders($result, "$tdir/either1"); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -272,7 +272,7 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $this->assertEquals('either1', $this->extdir($result['old'][0]['tmp'])); $result = array('old' => array(), 'new' => array()); - $ok = $extension->find_folders($result, "$tdir/eithersub2/either2"); + $ok = $extension->findFolders($result, "$tdir/eithersub2/either2"); $this->assertTrue($ok); $this->assertEquals(0, count($result['new'])); $this->assertEquals(1, count($result['old'])); @@ -292,4 +292,4 @@ class helper_plugin_extension_extension_test extends DokuWikiTest { $dir = trim(substr($dir, $len), '/'); return $dir; } -}
\ No newline at end of file +} diff --git a/lib/plugins/extension/action.php b/lib/plugins/extension/action.php index 9e48f134b..75f5009ed 100644 --- a/lib/plugins/extension/action.php +++ b/lib/plugins/extension/action.php @@ -5,10 +5,8 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -class action_plugin_extension extends DokuWiki_Action_Plugin { +class action_plugin_extension extends DokuWiki_Action_Plugin +{ /** * Registers a callback function for a given event @@ -16,10 +14,10 @@ class action_plugin_extension extends DokuWiki_Action_Plugin { * @param Doku_Event_Handler $controller DokuWiki's event controller object * @return void */ - public function register(Doku_Event_Handler $controller) { + public function register(Doku_Event_Handler $controller) + { $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'info'); - } /** @@ -28,22 +26,23 @@ class action_plugin_extension extends DokuWiki_Action_Plugin { * @param Doku_Event $event * @param $param */ - public function info(Doku_Event &$event, $param) { + public function info(Doku_Event &$event, $param) + { global $USERINFO; global $INPUT; - if($event->data != 'plugin_extension') return; + if ($event->data != 'plugin_extension') return; $event->preventDefault(); $event->stopPropagation(); - if(empty($_SERVER['REMOTE_USER']) || !auth_isadmin($_SERVER['REMOTE_USER'], $USERINFO['grps'])) { + if (empty($_SERVER['REMOTE_USER']) || !auth_isadmin($_SERVER['REMOTE_USER'], $USERINFO['grps'])) { http_status(403); echo 'Forbidden'; exit; } $ext = $INPUT->str('ext'); - if(!$ext) { + if (!$ext) { http_status(400); echo 'no extension given'; return; @@ -54,7 +53,7 @@ class action_plugin_extension extends DokuWiki_Action_Plugin { $extension->setExtension($ext); $act = $INPUT->str('act'); - switch($act) { + switch ($act) { case 'enable': case 'disable': $json = new JSON(); @@ -77,9 +76,7 @@ class action_plugin_extension extends DokuWiki_Action_Plugin { /** @var helper_plugin_extension_list $list */ $list = plugin_load('helper', 'extension_list'); header('Content-Type: text/html; charset=utf-8'); - echo $list->make_info($extension); + echo $list->makeInfo($extension); } } - } - diff --git a/lib/plugins/extension/admin.php b/lib/plugins/extension/admin.php index 71257cf43..eb2009b4c 100644 --- a/lib/plugins/extension/admin.php +++ b/lib/plugins/extension/admin.php @@ -6,13 +6,11 @@ * @author Michael Hamann <michael@content-space.de> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * Admin part of the extension manager */ -class admin_plugin_extension extends DokuWiki_Admin_Plugin { +class admin_plugin_extension extends DokuWiki_Admin_Plugin +{ protected $infoFor = null; /** @var helper_plugin_extension_gui */ protected $gui; @@ -22,39 +20,43 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin { * * loads additional helpers */ - public function __construct() { + public function __construct() + { $this->gui = plugin_load('helper', 'extension_gui'); } /** * @return int sort number in admin menu */ - public function getMenuSort() { + public function getMenuSort() + { return 0; } /** * @return bool true if only access for superuser, false is for superusers and moderators */ - public function forAdminOnly() { + public function forAdminOnly() + { return true; } /** * Execute the requested action(s) and initialize the plugin repository */ - public function handle() { + public function handle() + { global $INPUT; // initialize the remote repository /* @var helper_plugin_extension_repository $repository */ $repository = $this->loadHelper('extension_repository'); - if(!$repository->hasAccess()) { + if (!$repository->hasAccess()) { $url = $this->gui->tabURL('', array('purge' => 1)); msg($this->getLang('repo_error').' [<a href="'.$url.'">'.$this->getLang('repo_retry').'</a>]', -1); } - if(!in_array('ssl', stream_get_transports())) { + if (!in_array('ssl', stream_get_transports())) { msg($this->getLang('nossl'), -1); } @@ -62,42 +64,60 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin { $extension = $this->loadHelper('extension_extension'); try { - if($INPUT->post->has('fn') && checkSecurityToken()) { + if ($INPUT->post->has('fn') && checkSecurityToken()) { $actions = $INPUT->post->arr('fn'); - foreach($actions as $action => $extensions) { - foreach($extensions as $extname => $label) { - switch($action) { + foreach ($actions as $action => $extensions) { + foreach ($extensions as $extname => $label) { + switch ($action) { case 'install': case 'reinstall': case 'update': $extension->setExtension($extname); $installed = $extension->installOrUpdate(); - foreach($installed as $ext => $info) { - msg(sprintf($this->getLang('msg_'.$info['type'].'_'.$info['action'].'_success'), $info['base']), 1); + foreach ($installed as $ext => $info) { + msg( + sprintf( + $this->getLang('msg_' . $info['type'] . '_' . $info['action'] . '_success'), + $info['base'] + ), + 1 + ); } break; case 'uninstall': $extension->setExtension($extname); $status = $extension->uninstall(); - if($status) { - msg(sprintf($this->getLang('msg_delete_success'), hsc($extension->getDisplayName())), 1); + if ($status) { + msg( + sprintf( + $this->getLang('msg_delete_success'), + hsc($extension->getDisplayName()) + ), + 1 + ); } else { - msg(sprintf($this->getLang('msg_delete_failed'), hsc($extension->getDisplayName())), -1); + msg( + sprintf( + $this->getLang('msg_delete_failed'), + hsc($extension->getDisplayName()) + ), + -1 + ); } break; - case 'enable'; + case 'enable': $extension->setExtension($extname); $status = $extension->enable(); - if($status !== true) { + if ($status !== true) { msg($status, -1); } else { msg(sprintf($this->getLang('msg_enabled'), hsc($extension->getDisplayName())), 1); } break; - case 'disable'; + case 'disable': $extension->setExtension($extname); $status = $extension->disable(); - if($status !== true) { + if ($status !== true) { msg($status, -1); } else { msg(sprintf($this->getLang('msg_disabled'), hsc($extension->getDisplayName())), 1); @@ -107,37 +127,36 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin { } } send_redirect($this->gui->tabURL('', array(), '&', true)); - } elseif($INPUT->post->str('installurl') && checkSecurityToken()) { + } elseif ($INPUT->post->str('installurl') && checkSecurityToken()) { $installed = $extension->installFromURL($INPUT->post->str('installurl')); - foreach($installed as $ext => $info) { + foreach ($installed as $ext => $info) { msg(sprintf($this->getLang('msg_'.$info['type'].'_'.$info['action'].'_success'), $info['base']), 1); } send_redirect($this->gui->tabURL('', array(), '&', true)); - } elseif(isset($_FILES['installfile']) && checkSecurityToken()) { + } elseif (isset($_FILES['installfile']) && checkSecurityToken()) { $installed = $extension->installFromUpload('installfile'); - foreach($installed as $ext => $info) { + foreach ($installed as $ext => $info) { msg(sprintf($this->getLang('msg_'.$info['type'].'_'.$info['action'].'_success'), $info['base']), 1); } send_redirect($this->gui->tabURL('', array(), '&', true)); } - - } catch(Exception $e) { + } catch (Exception $e) { msg($e->getMessage(), -1); send_redirect($this->gui->tabURL('', array(), '&', true)); } - } /** * Render HTML output */ - public function html() { + public function html() + { ptln('<h1>'.$this->getLang('menu').'</h1>'); ptln('<div id="extension__manager">'); $this->gui->tabNavigation(); - switch($this->gui->currentTab()) { + switch ($this->gui->currentTab()) { case 'search': $this->gui->tabSearch(); break; @@ -156,4 +175,4 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin { } } -// vim:ts=4:sw=4:et:
\ No newline at end of file +// vim:ts=4:sw=4:et: diff --git a/lib/plugins/extension/helper/extension.php b/lib/plugins/extension/helper/extension.php index e77528b97..a80a8244b 100644 --- a/lib/plugins/extension/helper/extension.php +++ b/lib/plugins/extension/helper/extension.php @@ -6,14 +6,11 @@ * @author Michael Hamann <michael@content-space.de> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); -if(!defined('DOKU_TPLLIB')) define('DOKU_TPLLIB', DOKU_INC.'lib/tpl/'); - /** * Class helper_plugin_extension_extension represents a single extension (plugin or template) */ -class helper_plugin_extension_extension extends DokuWiki_Plugin { +class helper_plugin_extension_extension extends DokuWiki_Plugin +{ private $id; private $base; private $is_template = false; @@ -26,13 +23,25 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { /** @var array list of temporary directories */ private $temporary = array(); + /** @var string where templates are installed to */ + private $tpllib = ''; + + /** + * helper_plugin_extension_extension constructor. + */ + public function __construct() + { + $this->tpllib = dirname(tpl_incdir()).'/'; + } + /** * Destructor * * deletes any dangling temporary directories */ - public function __destruct() { - foreach($this->temporary as $dir){ + public function __destruct() + { + foreach ($this->temporary as $dir) { io_rmdir($dir, true); } } @@ -40,7 +49,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { /** * @return bool false, this component is not a singleton */ - public function isSingleton() { + public function isSingleton() + { return false; } @@ -50,12 +60,13 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @param string $id The id of the extension (prefixed with template: for templates) * @return bool If some (local or remote) data was found */ - public function setExtension($id) { + public function setExtension($id) + { $id = cleanID($id); $this->id = $id; $this->base = $id; - if(substr($id, 0 , 9) == 'template:'){ + if (substr($id, 0, 9) == 'template:') { $this->base = substr($id, 9); $this->is_template = true; } else { @@ -85,7 +96,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool If the extension is installed locally */ - public function isInstalled() { + public function isInstalled() + { return is_dir($this->getInstallDir()); } @@ -94,8 +106,9 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool */ - public function isGitControlled() { - if(!$this->isInstalled()) return false; + public function isGitControlled() + { + if (!$this->isInstalled()) return false; return is_dir($this->getInstallDir().'/.git'); } @@ -104,12 +117,16 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool If the extension is bundled */ - public function isBundled() { + public function isBundled() + { if (!empty($this->remoteInfo['bundled'])) return $this->remoteInfo['bundled']; - return in_array($this->id, - array( - 'authad', 'authldap', 'authmysql', 'authpdo', 'authpgsql', 'authplain', 'acl', 'info', 'extension', - 'revert', 'popularity', 'config', 'safefnrecode', 'styling', 'testing', 'template:dokuwiki' + return in_array( + $this->id, + array( + 'authad', 'authldap', 'authmysql', 'authpdo', + 'authpgsql', 'authplain', 'acl', 'info', 'extension', + 'revert', 'popularity', 'config', 'safefnrecode', 'styling', + 'testing', 'template:dokuwiki' ) ); } @@ -119,7 +136,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool if the extension is protected */ - public function isProtected() { + public function isProtected() + { // never allow deinstalling the current auth plugin: global $conf; if ($this->id == $conf['authtype']) return true; @@ -135,7 +153,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool If the extension is installed in the correct directory */ - public function isInWrongFolder() { + public function isInWrongFolder() + { return $this->base != $this->getBase(); } @@ -144,9 +163,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool If the extension is enabled */ - public function isEnabled() { + public function isEnabled() + { global $conf; - if($this->isTemplate()){ + if ($this->isTemplate()) { return ($conf['template'] == $this->getBase()); } @@ -160,9 +180,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool If an update is available */ - public function updateAvailable() { - if(!$this->isInstalled()) return false; - if($this->isBundled()) return false; + public function updateAvailable() + { + if (!$this->isInstalled()) return false; + if ($this->isBundled()) return false; $lastupdate = $this->getLastUpdate(); if ($lastupdate === false) return false; $installed = $this->getInstalledVersion(); @@ -175,7 +196,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool If this extension is a template */ - public function isTemplate() { + public function isTemplate() + { return $this->is_template; } @@ -186,7 +208,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string */ - public function getID() { + public function getID() + { return $this->id; } @@ -195,7 +218,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string The name of the installation directory */ - public function getInstallName() { + public function getInstallName() + { return $this->base; } @@ -205,7 +229,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string The basename */ - public function getBase() { + public function getBase() + { if (!empty($this->localInfo['base'])) return $this->localInfo['base']; return $this->base; } @@ -215,7 +240,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string The display name */ - public function getDisplayName() { + public function getDisplayName() + { if (!empty($this->localInfo['name'])) return $this->localInfo['name']; if (!empty($this->remoteInfo['name'])) return $this->remoteInfo['name']; return $this->base; @@ -226,7 +252,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The name of the author or false if there is none */ - public function getAuthor() { + public function getAuthor() + { if (!empty($this->localInfo['author'])) return $this->localInfo['author']; if (!empty($this->remoteInfo['author'])) return $this->remoteInfo['author']; return false; @@ -237,7 +264,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The email address or false if there is none */ - public function getEmail() { + public function getEmail() + { // email is only in the local data if (!empty($this->localInfo['email'])) return $this->localInfo['email']; return false; @@ -248,7 +276,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The md5sum of the email if there is any, false otherwise */ - public function getEmailID() { + public function getEmailID() + { if (!empty($this->remoteInfo['emailid'])) return $this->remoteInfo['emailid']; if (!empty($this->localInfo['email'])) return md5($this->localInfo['email']); return false; @@ -259,7 +288,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string The description */ - public function getDescription() { + public function getDescription() + { if (!empty($this->localInfo['desc'])) return $this->localInfo['desc']; if (!empty($this->remoteInfo['description'])) return $this->remoteInfo['description']; return ''; @@ -270,7 +300,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string The URL */ - public function getURL() { + public function getURL() + { if (!empty($this->localInfo['url'])) return $this->localInfo['url']; return 'https://www.dokuwiki.org/'.($this->isTemplate() ? 'template' : 'plugin').':'.$this->getBase(); } @@ -280,7 +311,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The version, usually in the form yyyy-mm-dd if there is any */ - public function getInstalledVersion() { + public function getInstalledVersion() + { if (!empty($this->localInfo['date'])) return $this->localInfo['date']; if ($this->isInstalled()) return $this->getLang('unknownversion'); return false; @@ -291,7 +323,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The date of the last update or false if not available */ - public function getUpdateDate() { + public function getUpdateDate() + { if (!empty($this->managerData['updated'])) return $this->managerData['updated']; return $this->getInstallDate(); } @@ -301,7 +334,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The date of the installation or false if not available */ - public function getInstallDate() { + public function getInstallDate() + { if (!empty($this->managerData['installed'])) return $this->managerData['installed']; return false; } @@ -311,7 +345,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return array The base names of the dependencies */ - public function getDependencies() { + public function getDependencies() + { if (!empty($this->remoteInfo['dependencies'])) return $this->remoteInfo['dependencies']; return array(); } @@ -321,7 +356,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return array The base names of the missing dependencies */ - public function getMissingDependencies() { + public function getMissingDependencies() + { /* @var Doku_Plugin_Controller $plugin_controller */ global $plugin_controller; $dependencies = $this->getDependencies(); @@ -339,7 +375,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return array The names of the conflicting extensions */ - public function getConflicts() { + public function getConflicts() + { if (!empty($this->remoteInfo['conflicts'])) return $this->remoteInfo['conflicts']; return array(); } @@ -349,7 +386,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return array The names of similar extensions */ - public function getSimilarExtensions() { + public function getSimilarExtensions() + { if (!empty($this->remoteInfo['similar'])) return $this->remoteInfo['similar']; return array(); } @@ -359,7 +397,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return array The names of the tags of the extension */ - public function getTags() { + public function getTags() + { if (!empty($this->remoteInfo['tags'])) return $this->remoteInfo['tags']; return array(); } @@ -369,7 +408,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return float|bool The popularity information or false if it isn't available */ - public function getPopularity() { + public function getPopularity() + { if (!empty($this->remoteInfo['popularity'])) return $this->remoteInfo['popularity']; return false; } @@ -380,7 +420,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The security warning if there is any, false otherwise */ - public function getSecurityWarning() { + public function getSecurityWarning() + { if (!empty($this->remoteInfo['securitywarning'])) return $this->remoteInfo['securitywarning']; return false; } @@ -390,7 +431,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The security issue if there is any, false otherwise */ - public function getSecurityIssue() { + public function getSecurityIssue() + { if (!empty($this->remoteInfo['securityissue'])) return $this->remoteInfo['securityissue']; return false; } @@ -400,7 +442,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The screenshot URL if there is any, false otherwise */ - public function getScreenshotURL() { + public function getScreenshotURL() + { if (!empty($this->remoteInfo['screenshoturl'])) return $this->remoteInfo['screenshoturl']; return false; } @@ -410,7 +453,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The thumbnail URL if there is any, false otherwise */ - public function getThumbnailURL() { + public function getThumbnailURL() + { if (!empty($this->remoteInfo['thumbnailurl'])) return $this->remoteInfo['thumbnailurl']; return false; } @@ -419,7 +463,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The previously used download URL, false if the extension has been installed manually */ - public function getLastDownloadURL() { + public function getLastDownloadURL() + { if (!empty($this->managerData['downloadurl'])) return $this->managerData['downloadurl']; return false; } @@ -429,7 +474,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The download URL if there is any, false otherwise */ - public function getDownloadURL() { + public function getDownloadURL() + { if (!empty($this->remoteInfo['downloadurl'])) return $this->remoteInfo['downloadurl']; return false; } @@ -439,7 +485,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool If the download URL has changed */ - public function hasDownloadURLChanged() { + public function hasDownloadURLChanged() + { $lasturl = $this->getLastDownloadURL(); $currenturl = $this->getDownloadURL(); return ($lasturl && $currenturl && $lasturl != $currenturl); @@ -450,7 +497,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The bug tracker URL if there is any, false otherwise */ - public function getBugtrackerURL() { + public function getBugtrackerURL() + { if (!empty($this->remoteInfo['bugtracker'])) return $this->remoteInfo['bugtracker']; return false; } @@ -460,7 +508,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The URL of the source repository if there is any, false otherwise */ - public function getSourcerepoURL() { + public function getSourcerepoURL() + { if (!empty($this->remoteInfo['sourcerepo'])) return $this->remoteInfo['sourcerepo']; return false; } @@ -470,7 +519,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The donation URL if there is any, false otherwise */ - public function getDonationURL() { + public function getDonationURL() + { if (!empty($this->remoteInfo['donationurl'])) return $this->remoteInfo['donationurl']; return false; } @@ -480,7 +530,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return array The type(s) as array of strings */ - public function getTypes() { + public function getTypes() + { if (!empty($this->remoteInfo['types'])) return $this->remoteInfo['types']; if ($this->isTemplate()) return array(32 => 'template'); return array(); @@ -491,7 +542,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return array The versions in the form yyyy-mm-dd => ('label' => label, 'implicit' => implicit) */ - public function getCompatibleVersions() { + public function getCompatibleVersions() + { if (!empty($this->remoteInfo['compatible'])) return $this->remoteInfo['compatible']; return array(); } @@ -501,7 +553,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string|bool The last available update in the form yyyy-mm-dd if there is any, false otherwise */ - public function getLastUpdate() { + public function getLastUpdate() + { if (!empty($this->remoteInfo['lastupdate'])) return $this->remoteInfo['lastupdate']; return false; } @@ -511,9 +564,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string The base path of the extension */ - public function getInstallDir() { + public function getInstallDir() + { if ($this->isTemplate()) { - return DOKU_TPLLIB.$this->base; + return $this->tpllib.$this->base; } else { return DOKU_PLUGIN.$this->base; } @@ -524,7 +578,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return string One of "none", "manual", "git" or "automatic" */ - public function getInstallType() { + public function getInstallType() + { if (!$this->isInstalled()) return 'none'; if (!empty($this->managerData)) return 'automatic'; if (is_dir($this->getInstallDir().'/.git')) return 'git'; @@ -536,17 +591,17 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool|string True or error string */ - public function canModify() { - if($this->isInstalled()) { - if(!is_writable($this->getInstallDir())) { + public function canModify() + { + if ($this->isInstalled()) { + if (!is_writable($this->getInstallDir())) { return 'noperms'; } } - if($this->isTemplate() && !is_writable(DOKU_TPLLIB)) { + if ($this->isTemplate() && !is_writable($this->tpllib)) { return 'notplperms'; - - } elseif(!is_writable(DOKU_PLUGIN)) { + } elseif (!is_writable(DOKU_PLUGIN)) { return 'nopluginperms'; } return true; @@ -559,20 +614,21 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @throws Exception when something goes wrong * @return array The list of installed extensions */ - public function installFromUpload($field){ - if($_FILES[$field]['error']){ + public function installFromUpload($field) + { + if ($_FILES[$field]['error']) { throw new Exception($this->getLang('msg_upload_failed').' ('.$_FILES[$field]['error'].')'); } $tmp = $this->mkTmpDir(); - if(!$tmp) throw new Exception($this->getLang('error_dircreate')); + if (!$tmp) throw new Exception($this->getLang('error_dircreate')); // filename may contain the plugin name for old style plugins... $basename = basename($_FILES[$field]['name']); $basename = preg_replace('/\.(tar\.gz|tar\.bz|tar\.bz2|tar|tgz|tbz|zip)$/', '', $basename); $basename = preg_replace('/[\W]+/', '', $basename); - if(!move_uploaded_file($_FILES[$field]['tmp_name'], "$tmp/upload.archive")){ + if (!move_uploaded_file($_FILES[$field]['tmp_name'], "$tmp/upload.archive")) { throw new Exception($this->getLang('msg_upload_failed')); } @@ -582,7 +638,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { $this->removeDeletedfiles($installed); // purge cache $this->purgeCache(); - }catch (Exception $e){ + } catch (Exception $e) { throw $e; } return $installed; @@ -595,7 +651,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @throws Exception when something goes wrong * @return array The list of installed extensions */ - public function installFromURL($url){ + public function installFromURL($url) + { try { $path = $this->download($url); $installed = $this->installArchive($path, true); @@ -604,7 +661,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { // purge cache $this->purgeCache(); - }catch (Exception $e){ + } catch (Exception $e) { throw $e; } return $installed; @@ -616,7 +673,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @throws \Exception when something goes wrong * @return array The list of installed extensions */ - public function installOrUpdate() { + public function installOrUpdate() + { $url = $this->getDownloadURL(); $path = $this->download($url); $installed = $this->installArchive($path, $this->isInstalled(), $this->getBase()); @@ -637,7 +695,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool If the plugin was sucessfully uninstalled */ - public function uninstall() { + public function uninstall() + { $this->purgeCache(); return io_rmdir($this->getInstallDir(), true); } @@ -647,7 +706,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool|string True or an error message */ - public function enable() { + public function enable() + { if ($this->isTemplate()) return $this->getLang('notimplemented'); if (!$this->isInstalled()) return $this->getLang('notinstalled'); if ($this->isEnabled()) return $this->getLang('alreadyenabled'); @@ -667,7 +727,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return bool|string True or an error message */ - public function disable() { + public function disable() + { if ($this->isTemplate()) return $this->getLang('notimplemented'); /* @var Doku_Plugin_Controller $plugin_controller */ @@ -685,7 +746,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { /** * Purge the cache by touching the main configuration file */ - protected function purgeCache() { + protected function purgeCache() + { global $config_cascade; // expire dokuwiki caches @@ -696,7 +758,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { /** * Read local extension data either from info.txt or getInfo() */ - protected function readLocalData() { + protected function readLocalData() + { if ($this->isTemplate()) { $infopath = $this->getInstallDir().'/template.info.txt'; } else { @@ -710,15 +773,15 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { $path = $this->getInstallDir().'/'; $plugin = null; - foreach($plugin_types as $type) { - if(file_exists($path.$type.'.php')) { + foreach ($plugin_types as $type) { + if (file_exists($path.$type.'.php')) { $plugin = plugin_load($type, $this->base); if ($plugin) break; } - if($dh = @opendir($path.$type.'/')) { - while(false !== ($cp = readdir($dh))) { - if($cp == '.' || $cp == '..' || strtolower(substr($cp, -4)) != '.php') continue; + if ($dh = @opendir($path.$type.'/')) { + while (false !== ($cp = readdir($dh))) { + if ($cp == '.' || $cp == '..' || strtolower(substr($cp, -4)) != '.php') continue; $plugin = plugin_load($type, $this->base.'_'.substr($cp, 0, -4)); if ($plugin) break; @@ -741,21 +804,22 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @param string $url Where the extension was downloaded from. (empty for manual installs via upload) * @param array $installed Optional list of installed plugins */ - protected function updateManagerData($url = '', $installed = null) { + protected function updateManagerData($url = '', $installed = null) + { $origID = $this->getID(); - if(is_null($installed)) { + if (is_null($installed)) { $installed = array($origID); } - foreach($installed as $ext => $info) { - if($this->getID() != $ext) $this->setExtension($ext); - if($url) { + foreach ($installed as $ext => $info) { + if ($this->getID() != $ext) $this->setExtension($ext); + if ($url) { $this->managerData['downloadurl'] = $url; - } elseif(isset($this->managerData['downloadurl'])) { + } elseif (isset($this->managerData['downloadurl'])) { unset($this->managerData['downloadurl']); } - if(isset($this->managerData['installed'])) { + if (isset($this->managerData['installed'])) { $this->managerData['updated'] = date('r'); } else { $this->managerData['installed'] = date('r'); @@ -763,23 +827,24 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { $this->writeManagerData(); } - if($this->getID() != $origID) $this->setExtension($origID); + if ($this->getID() != $origID) $this->setExtension($origID); } /** * Read the manager.dat file */ - protected function readManagerData() { + protected function readManagerData() + { $managerpath = $this->getInstallDir().'/manager.dat'; if (is_readable($managerpath)) { $file = @file($managerpath); - if(!empty($file)) { - foreach($file as $line) { + if (!empty($file)) { + foreach ($file as $line) { list($key, $value) = explode('=', trim($line, DOKU_LF), 2); $key = trim($key); $value = trim($value); // backwards compatible with old plugin manager - if($key == 'url') $key = 'downloadurl'; + if ($key == 'url') $key = 'downloadurl'; $this->managerData[$key] = $value; } } @@ -789,7 +854,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { /** * Write the manager.data file */ - protected function writeManagerData() { + protected function writeManagerData() + { $managerpath = $this->getInstallDir().'/manager.dat'; $data = ''; foreach ($this->managerData as $k => $v) { @@ -805,9 +871,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @return false|string */ - protected function mkTmpDir(){ + protected function mkTmpDir() + { $dir = io_mktmpdir(); - if(!$dir) return false; + if (!$dir) return false; $this->temporary[] = $dir; return $dir; } @@ -819,27 +886,28 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @throws Exception when something goes wrong * @return string The path where the archive was saved */ - public function download($url) { + public function download($url) + { // check the url - if(!preg_match('/https?:\/\//i', $url)){ + if (!preg_match('/https?:\/\//i', $url)) { throw new Exception($this->getLang('error_badurl')); } // try to get the file from the path (used as plugin name fallback) $file = parse_url($url, PHP_URL_PATH); - if(is_null($file)){ + if (is_null($file)) { $file = md5($url); - }else{ + } else { $file = utf8_basename($file); } // create tmp directory for download - if(!($tmp = $this->mkTmpDir())) { + if (!($tmp = $this->mkTmpDir())) { throw new Exception($this->getLang('error_dircreate')); } // download - if(!$file = io_download($url, $tmp.'/', true, $file, 0)) { + if (!$file = io_download($url, $tmp.'/', true, $file, 0)) { io_rmdir($tmp, true); throw new Exception(sprintf($this->getLang('error_download'), '<bdi>'.hsc($url).'</bdi>')); } @@ -854,16 +922,17 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @throws Exception when something went wrong * @return array list of installed extensions */ - public function installArchive($file, $overwrite=false, $base = '') { + public function installArchive($file, $overwrite = false, $base = '') + { $installed_extensions = array(); // create tmp directory for decompression - if(!($tmp = $this->mkTmpDir())) { + if (!($tmp = $this->mkTmpDir())) { throw new Exception($this->getLang('error_dircreate')); } // add default base folder if specified to handle case where zip doesn't contain this - if($base && !@mkdir($tmp.'/'.$base)) { + if ($base && !@mkdir($tmp.'/'.$base)) { throw new Exception($this->getLang('error_dircreate')); } @@ -874,33 +943,33 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { // move the folder(s) to lib/.. $result = array('old'=>array(), 'new'=>array()); $default = ($this->isTemplate() ? 'template' : 'plugin'); - if(!$this->find_folders($result, $tmp.'/'.$base, $default)) { + if (!$this->findFolders($result, $tmp.'/'.$base, $default)) { throw new Exception($this->getLang('error_findfolder')); } // choose correct result array - if(count($result['new'])) { + if (count($result['new'])) { $install = $result['new']; - }else{ + } else { $install = $result['old']; } - if(!count($install)){ + if (!count($install)) { throw new Exception($this->getLang('error_findfolder')); } // now install all found items - foreach($install as $item) { + foreach ($install as $item) { // where to install? - if($item['type'] == 'template') { - $target_base_dir = DOKU_TPLLIB; - }else{ + if ($item['type'] == 'template') { + $target_base_dir = $this->tpllib; + } else { $target_base_dir = DOKU_PLUGIN; } - if(!empty($item['base'])) { + if (!empty($item['base'])) { // use base set in info.txt - } elseif($base && count($install) == 1) { + } elseif ($base && count($install) == 1) { $item['base'] = $base; } else { // default - use directory as found in zip @@ -911,7 +980,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { // check to make sure we aren't overwriting anything $target = $target_base_dir.$item['base']; - if(!$overwrite && file_exists($target)) { + if (!$overwrite && file_exists($target)) { // TODO remember our settings, ask the user to confirm overwrite continue; } @@ -919,10 +988,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { $action = file_exists($target) ? 'update' : 'install'; // copy action - if($this->dircopy($item['tmp'], $target)) { + if ($this->dircopy($item['tmp'], $target)) { // return info $id = $item['base']; - if($item['type'] == 'template') { + if ($item['type'] == 'template') { $id = 'template:'.$id; } $installed_extensions[$id] = array( @@ -936,7 +1005,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { } // cleanup - if($tmp) io_rmdir($tmp, true); + if ($tmp) io_rmdir($tmp, true); return $installed_extensions; } @@ -962,20 +1031,20 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @param string $subdir - a subdirectory. do not set. used by recursion * @return bool - false on error */ - protected function find_folders(&$result, $directory, $default_type='plugin', $subdir='') { + protected function findFolders(&$result, $directory, $default_type = 'plugin', $subdir = '') + { $this_dir = "$directory$subdir"; $dh = @opendir($this_dir); - if(!$dh) return false; + if (!$dh) return false; $found_dirs = array(); $found_files = 0; $found_template_parts = 0; while (false !== ($f = readdir($dh))) { - if($f == '.' || $f == '..') continue; + if ($f == '.' || $f == '..') continue; - if(is_dir("$this_dir/$f")) { + if (is_dir("$this_dir/$f")) { $found_dirs[] = "$subdir/$f"; - } else { // it's a file -> check for config $found_files++; @@ -1004,11 +1073,11 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { closedir($dh); // files where found but no info.txt - use old method - if($found_files){ + if ($found_files) { $info = array(); $info['tmp'] = $this_dir; // does this look like a template or should we use the default type? - if($found_template_parts >= 2) { + if ($found_template_parts >= 2) { $info['type'] = 'template'; } else { $info['type'] = $default_type; @@ -1020,7 +1089,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { // we have no files yet -> recurse foreach ($found_dirs as $found_dir) { - $this->find_folders($result, $directory, $default_type, "$found_dir"); + $this->findFolders($result, $directory, $default_type, "$found_dir"); } return true; } @@ -1035,13 +1104,13 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @throws Exception * @return bool */ - private function decompress($file, $target) { + private function decompress($file, $target) + { // decompression library doesn't like target folders ending in "/" - if(substr($target, -1) == "/") $target = substr($target, 0, -1); - - $ext = $this->guess_archive($file); - if(in_array($ext, array('tar', 'bz', 'gz'))) { + if (substr($target, -1) == "/") $target = substr($target, 0, -1); + $ext = $this->guessArchiveType($file); + if (in_array($ext, array('tar', 'bz', 'gz'))) { try { $tar = new \splitbrain\PHPArchive\Tar(); $tar->open($file); @@ -1051,8 +1120,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { } return true; - } elseif($ext == 'zip') { - + } elseif ($ext == 'zip') { try { $zip = new \splitbrain\PHPArchive\Zip(); $zip->open($file); @@ -1078,15 +1146,16 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @param string $file The file to analyze * @return string|false false if the file can't be read, otherwise an "extension" */ - private function guess_archive($file) { + private function guessArchiveType($file) + { $fh = fopen($file, 'rb'); - if(!$fh) return false; + if (!$fh) return false; $magic = fread($fh, 5); fclose($fh); - if(strpos($magic, "\x42\x5a") === 0) return 'bz'; - if(strpos($magic, "\x1f\x8b") === 0) return 'gz'; - if(strpos($magic, "\x50\x4b\x03\x04") === 0) return 'zip'; + if (strpos($magic, "\x42\x5a") === 0) return 'bz'; + if (strpos($magic, "\x1f\x8b") === 0) return 'gz'; + if (strpos($magic, "\x50\x4b\x03\x04") === 0) return 'zip'; return 'tar'; } @@ -1097,27 +1166,27 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * @param string $dst filename path to file * @return bool|int|string */ - private function dircopy($src, $dst) { + private function dircopy($src, $dst) + { global $conf; - if(is_dir($src)) { - if(!$dh = @opendir($src)) return false; + if (is_dir($src)) { + if (!$dh = @opendir($src)) return false; - if($ok = io_mkdir_p($dst)) { + if ($ok = io_mkdir_p($dst)) { while ($ok && (false !== ($f = readdir($dh)))) { - if($f == '..' || $f == '.') continue; + if ($f == '..' || $f == '.') continue; $ok = $this->dircopy("$src/$f", "$dst/$f"); } } closedir($dh); return $ok; - } else { $exists = file_exists($dst); - if(!@copy($src, $dst)) return false; - if(!$exists && !empty($conf['fperm'])) chmod($dst, $conf['fperm']); + if (!@copy($src, $dst)) return false; + if (!$exists && !empty($conf['fperm'])) chmod($dst, $conf['fperm']); @touch($dst, filemtime($src)); } @@ -1129,29 +1198,30 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { * * @param array $installed */ - private function removeDeletedfiles($installed) { - foreach($installed as $id => $extension) { + private function removeDeletedfiles($installed) + { + foreach ($installed as $id => $extension) { // only on update - if($extension['action'] == 'install') continue; + if ($extension['action'] == 'install') continue; // get definition file - if($extension['type'] == 'template') { - $extensiondir = DOKU_TPLLIB; - }else{ + if ($extension['type'] == 'template') { + $extensiondir = $this->tpllib; + } else { $extensiondir = DOKU_PLUGIN; } $extensiondir = $extensiondir . $extension['base'] .'/'; $definitionfile = $extensiondir . 'deleted.files'; - if(!file_exists($definitionfile)) continue; + if (!file_exists($definitionfile)) continue; // delete the old files $list = file($definitionfile); - foreach($list as $line) { + foreach ($list as $line) { $line = trim(preg_replace('/#.*$/', '', $line)); - if(!$line) continue; + if (!$line) continue; $file = $extensiondir . $line; - if(!file_exists($file)) continue; + if (!file_exists($file)) continue; io_rmdir($file, true); } diff --git a/lib/plugins/extension/helper/gui.php b/lib/plugins/extension/helper/gui.php index 4ec6fec85..f646b9cd1 100644 --- a/lib/plugins/extension/helper/gui.php +++ b/lib/plugins/extension/helper/gui.php @@ -6,13 +6,11 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * Class helper_plugin_extension_list takes care of the overall GUI */ -class helper_plugin_extension_gui extends DokuWiki_Plugin { +class helper_plugin_extension_gui extends DokuWiki_Plugin +{ protected $tabs = array('plugins', 'templates', 'search', 'install'); @@ -24,7 +22,8 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { * * initializes requested info window */ - public function __construct() { + public function __construct() + { global $INPUT; $this->infoFor = $INPUT->str('info'); } @@ -32,7 +31,8 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { /** * display the plugin tab */ - public function tabPlugins() { + public function tabPlugins() + { /* @var Doku_Plugin_Controller $plugin_controller */ global $plugin_controller; @@ -46,19 +46,20 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { $extension = $this->loadHelper('extension_extension'); /* @var helper_plugin_extension_list $list */ $list = $this->loadHelper('extension_list'); - $list->start_form(); - foreach($pluginlist as $name) { + $list->startForm(); + foreach ($pluginlist as $name) { $extension->setExtension($name); - $list->add_row($extension, $extension->getID() == $this->infoFor); + $list->addRow($extension, $extension->getID() == $this->infoFor); } - $list->end_form(); + $list->endForm(); $list->render(); } /** * Display the template tab */ - public function tabTemplates() { + public function tabTemplates() + { echo '<div class="panelHeader">'; echo $this->locale_xhtml('intro_templates'); echo '</div>'; @@ -72,19 +73,20 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { $extension = $this->loadHelper('extension_extension'); /* @var helper_plugin_extension_list $list */ $list = $this->loadHelper('extension_list'); - $list->start_form(); - foreach($tpllist as $name) { + $list->startForm(); + foreach ($tpllist as $name) { $extension->setExtension("template:$name"); - $list->add_row($extension, $extension->getID() == $this->infoFor); + $list->addRow($extension, $extension->getID() == $this->infoFor); } - $list->end_form(); + $list->endForm(); $list->render(); } /** * Display the search tab */ - public function tabSearch() { + public function tabSearch() + { global $INPUT; echo '<div class="panelHeader">'; echo $this->locale_xhtml('intro_search'); @@ -95,7 +97,7 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { $form->addElement(form_makeButton('submit', '', $this->getLang('search'))); $form->printForm(); - if(!$INPUT->bool('q')) return; + if (!$INPUT->bool('q')) return; /* @var helper_plugin_extension_repository $repository FIXME should we use some gloabl instance? */ $repository = $this->loadHelper('extension_repository'); @@ -105,29 +107,35 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { $extension = $this->loadHelper('extension_extension'); /* @var helper_plugin_extension_list $list */ $list = $this->loadHelper('extension_list'); - $list->start_form(); - if($result){ - foreach($result as $name) { + $list->startForm(); + if ($result) { + foreach ($result as $name) { $extension->setExtension($name); - $list->add_row($extension, $extension->getID() == $this->infoFor); + $list->addRow($extension, $extension->getID() == $this->infoFor); } } else { - $list->nothing_found(); + $list->nothingFound(); } - $list->end_form(); + $list->endForm(); $list->render(); - } /** * Display the template tab */ - public function tabInstall() { + public function tabInstall() + { echo '<div class="panelHeader">'; echo $this->locale_xhtml('intro_install'); echo '</div>'; - $form = new Doku_Form(array('action' => $this->tabURL('', array(), '&'), 'enctype' => 'multipart/form-data', 'class' => 'install')); + $form = new Doku_Form( + array( + 'action' => $this->tabURL('', array(), '&'), + 'enctype' => 'multipart/form-data', + 'class' => 'install' + ) + ); $form->addElement(form_makeTextField('installurl', '', $this->getLang('install_url'), '', 'block')); $form->addElement(form_makeFileField('installfile', $this->getLang('install_upload'), '', 'block')); $form->addElement(form_makeButton('submit', '', $this->getLang('btn_install'))); @@ -139,11 +147,12 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { * * @fixme style active one */ - public function tabNavigation() { + public function tabNavigation() + { echo '<ul class="tabs">'; - foreach($this->tabs as $tab) { + foreach ($this->tabs as $tab) { $url = $this->tabURL($tab); - if($this->currentTab() == $tab) { + if ($this->currentTab() == $tab) { $class = ' active'; } else { $class = ''; @@ -158,11 +167,12 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { * * @return string */ - public function currentTab() { + public function currentTab() + { global $INPUT; $tab = $INPUT->str('tab', 'plugins', true); - if(!in_array($tab, $this->tabs)) $tab = 'plugins'; + if (!in_array($tab, $this->tabs)) $tab = 'plugins'; return $tab; } @@ -175,19 +185,19 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin { * @param bool $absolute create absolute URLs? * @return string */ - public function tabURL($tab = '', $params = array(), $sep = '&', $absolute = false) { + public function tabURL($tab = '', $params = array(), $sep = '&', $absolute = false) + { global $ID; global $INPUT; - if(!$tab) $tab = $this->currentTab(); + if (!$tab) $tab = $this->currentTab(); $defaults = array( 'do' => 'admin', 'page' => 'extension', 'tab' => $tab, ); - if($tab == 'search') $defaults['q'] = $INPUT->str('q'); + if ($tab == 'search') $defaults['q'] = $INPUT->str('q'); return wl($ID, array_merge($defaults, $params), $absolute, $sep); } - } diff --git a/lib/plugins/extension/helper/list.php b/lib/plugins/extension/helper/list.php index 656b4ea09..d895941cb 100644 --- a/lib/plugins/extension/helper/list.php +++ b/lib/plugins/extension/helper/list.php @@ -6,13 +6,11 @@ * @author Michael Hamann <michael@content-space.de> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * Class helper_plugin_extension_list takes care of creating a HTML list of extensions */ -class helper_plugin_extension_list extends DokuWiki_Plugin { +class helper_plugin_extension_list extends DokuWiki_Plugin +{ protected $form = ''; /** @var helper_plugin_extension_gui */ protected $gui; @@ -22,30 +20,38 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * * loads additional helpers */ - public function __construct(){ + public function __construct() + { $this->gui = plugin_load('helper', 'extension_gui'); } - function start_form() { + /** + * Initialize the extension table form + */ + public function startForm() + { $this->form .= '<form id="extension__list" accept-charset="utf-8" method="post" action="">'; $hidden = array( 'do'=>'admin', 'page'=>'extension', 'sectok'=>getSecurityToken() ); - $this->add_hidden($hidden); + $this->addHidden($hidden); $this->form .= '<ul class="extensionList">'; } + /** * Build single row of extension table + * * @param helper_plugin_extension_extension $extension The extension that shall be added * @param bool $showinfo Show the info area */ - function add_row(helper_plugin_extension_extension $extension, $showinfo = false) { - $this->start_row($extension); - $this->populate_column('legend', $this->make_legend($extension, $showinfo)); - $this->populate_column('actions', $this->make_actions($extension)); - $this->end_row(); + public function addRow(helper_plugin_extension_extension $extension, $showinfo = false) + { + $this->startRow($extension); + $this->populateColumn('legend', $this->makeLegend($extension, $showinfo)); + $this->populateColumn('actions', $this->makeActions($extension)); + $this->endRow(); } /** @@ -55,7 +61,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param string $header The content of the header * @param int $level The level of the header */ - function add_header($id, $header, $level = 2) { + public function addHeader($id, $header, $level = 2) + { $this->form .='<h'.$level.' id="'.$id.'">'.hsc($header).'</h'.$level.'>'.DOKU_LF; } @@ -64,17 +71,20 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * * @param string $data The content */ - function add_p($data) { + public function addParagraph($data) + { $this->form .= '<p>'.hsc($data).'</p>'.DOKU_LF; } /** * Add hidden fields to the form with the given data - * @param array $array + * + * @param array $data key-value list of fields and their values to add */ - function add_hidden(array $array) { + public function addHidden(array $data) + { $this->form .= '<div class="no">'; - foreach ($array as $key => $value) { + foreach ($data as $key => $value) { $this->form .= '<input type="hidden" name="'.hsc($key).'" value="'.hsc($value).'" />'; } $this->form .= '</div>'.DOKU_LF; @@ -83,7 +93,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { /** * Add closing tags */ - function end_form() { + public function endForm() + { $this->form .= '</ul>'; $this->form .= '</form>'.DOKU_LF; } @@ -91,7 +102,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { /** * Show message when no results are found */ - function nothing_found() { + public function nothingFound() + { global $lang; $this->form .= '<li class="notfound">'.$lang['nothingfound'].'</li>'; } @@ -99,7 +111,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { /** * Print the form */ - function render() { + public function render() + { echo $this->form; } @@ -108,8 +121,10 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * * @param helper_plugin_extension_extension $extension The extension */ - private function start_row(helper_plugin_extension_extension $extension) { - $this->form .= '<li id="extensionplugin__'.hsc($extension->getID()).'" class="'.$this->make_class($extension).'">'; + private function startRow(helper_plugin_extension_extension $extension) + { + $this->form .= '<li id="extensionplugin__'.hsc($extension->getID()). + '" class="'.$this->makeClass($extension).'">'; } /** @@ -117,14 +132,16 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param string $class The class name * @param string $html The content */ - private function populate_column($class, $html) { + private function populateColumn($class, $html) + { $this->form .= '<div class="'.$class.' col">'.$html.'</div>'.DOKU_LF; } /** * End the row */ - private function end_row() { + private function endRow() + { $this->form .= '</li>'.DOKU_LF; } @@ -134,7 +151,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension * @return string The HTML code */ - function make_homepagelink(helper_plugin_extension_extension $extension) { + public function makeHomepageLink(helper_plugin_extension_extension $extension) + { $text = $this->getLang('homepage_link'); $url = hsc($extension->getURL()); return '<a href="'.$url.'" title="'.$url.'" class ="urlextern">'.$text.'</a> '; @@ -146,15 +164,16 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension object * @return string The class name */ - function make_class(helper_plugin_extension_extension $extension) { + public function makeClass(helper_plugin_extension_extension $extension) + { $class = ($extension->isTemplate()) ? 'template' : 'plugin'; - if($extension->isInstalled()) { + if ($extension->isInstalled()) { $class.=' installed'; $class.= ($extension->isEnabled()) ? ' enabled':' disabled'; - if($extension->updateAvailable()) $class .= ' updatable'; + if ($extension->updateAvailable()) $class .= ' updatable'; } - if(!$extension->canModify()) $class.= ' notselect'; - if($extension->isProtected()) $class.= ' protected'; + if (!$extension->canModify()) $class.= ' notselect'; + if ($extension->isProtected()) $class.= ' protected'; //if($this->showinfo) $class.= ' showinfo'; return $class; } @@ -165,17 +184,16 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension object * @return string The HTML code of the link */ - function make_author(helper_plugin_extension_extension $extension) { - global $ID; - - if($extension->getAuthor()) { - + public function makeAuthor(helper_plugin_extension_extension $extension) + { + if ($extension->getAuthor()) { $mailid = $extension->getEmailID(); - if($mailid){ + if ($mailid) { $url = $this->gui->tabURL('search', array('q' => 'authorid:'.$mailid)); - return '<bdi><a href="'.$url.'" class="author" title="'.$this->getLang('author_hint').'" ><img src="//www.gravatar.com/avatar/'.$mailid.'?s=20&d=mm" width="20" height="20" alt="" /> '.hsc($extension->getAuthor()).'</a></bdi>'; - - }else{ + return '<bdi><a href="'.$url.'" class="author" title="'.$this->getLang('author_hint').'" >'. + '<img src="//www.gravatar.com/avatar/'.$mailid.'?s=20&d=mm" width="20" height="20" alt="" /> '. + hsc($extension->getAuthor()).'</a></bdi>'; + } else { return '<bdi><span class="author">'.hsc($extension->getAuthor()).'</span></bdi>'; } } @@ -188,11 +206,12 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension object * @return string The HTML code */ - function make_screenshot(helper_plugin_extension_extension $extension) { + public function makeScreenshot(helper_plugin_extension_extension $extension) + { $screen = $extension->getScreenshotURL(); $thumb = $extension->getThumbnailURL(); - if($screen) { + if ($screen) { // use protocol independent URLs for images coming from us #595 $screen = str_replace('http://www.dokuwiki.org', '//www.dokuwiki.org', $screen); $thumb = str_replace('http://www.dokuwiki.org', '//www.dokuwiki.org', $thumb); @@ -201,11 +220,12 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { $img = '<a href="'.hsc($screen).'" target="_blank" class="extension_screenshot">'. '<img alt="'.$title.'" width="120" height="70" src="'.hsc($thumb).'" />'. '</a>'; - } elseif($extension->isTemplate()) { - $img = '<img alt="" width="120" height="70" src="'.DOKU_BASE.'lib/plugins/extension/images/template.png" />'; - + } elseif ($extension->isTemplate()) { + $img = '<img alt="" width="120" height="70" src="'.DOKU_BASE. + 'lib/plugins/extension/images/template.png" />'; } else { - $img = '<img alt="" width="120" height="70" src="'.DOKU_BASE.'lib/plugins/extension/images/plugin.png" />'; + $img = '<img alt="" width="120" height="70" src="'.DOKU_BASE. + 'lib/plugins/extension/images/plugin.png" />'; } return '<div class="screenshot" >'.$img.'<span></span></div>'.DOKU_LF; } @@ -217,41 +237,51 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param bool $showinfo Show the info section * @return string The HTML code */ - function make_legend(helper_plugin_extension_extension $extension, $showinfo = false) { + public function makeLegend(helper_plugin_extension_extension $extension, $showinfo = false) + { $return = '<div>'; $return .= '<h2>'; - $return .= sprintf($this->getLang('extensionby'), '<bdi>'.hsc($extension->getDisplayName()).'</bdi>', $this->make_author($extension)); + $return .= sprintf( + $this->getLang('extensionby'), + '<bdi>'.hsc($extension->getDisplayName()).'</bdi>', + $this->makeAuthor($extension) + ); $return .= '</h2>'.DOKU_LF; - $return .= $this->make_screenshot($extension); + $return .= $this->makeScreenshot($extension); $popularity = $extension->getPopularity(); if ($popularity !== false && !$extension->isBundled()) { $popularityText = sprintf($this->getLang('popularity'), round($popularity*100, 2)); - $return .= '<div class="popularity" title="'.$popularityText.'"><div style="width: '.($popularity * 100).'%;"><span class="a11y">'.$popularityText.'</span></div></div>'.DOKU_LF; + $return .= '<div class="popularity" title="'.$popularityText.'">'. + '<div style="width: '.($popularity * 100).'%;">'. + '<span class="a11y">'.$popularityText.'</span>'. + '</div></div>'.DOKU_LF; } - if($extension->getDescription()) { + if ($extension->getDescription()) { $return .= '<p><bdi>'; $return .= hsc($extension->getDescription()).' '; $return .= '</bdi></p>'.DOKU_LF; } - $return .= $this->make_linkbar($extension); + $return .= $this->makeLinkbar($extension); - if($showinfo){ + if ($showinfo) { $url = $this->gui->tabURL(''); $class = 'close'; - }else{ + } else { $url = $this->gui->tabURL('', array('info' => $extension->getID())); $class = ''; } - $return .= ' <a href="'.$url.'#extensionplugin__'.$extension->getID().'" class="info '.$class.'" title="'.$this->getLang('btn_info').'" data-extid="'.$extension->getID().'">'.$this->getLang('btn_info').'</a>'; + $return .= ' <a href="'.$url.'#extensionplugin__'.$extension->getID(). + '" class="info '.$class.'" title="'.$this->getLang('btn_info'). + '" data-extid="'.$extension->getID().'">'.$this->getLang('btn_info').'</a>'; if ($showinfo) { - $return .= $this->make_info($extension); + $return .= $this->makeInfo($extension); } - $return .= $this->make_noticearea($extension); + $return .= $this->makeNoticeArea($extension); $return .= '</div>'.DOKU_LF; return $return; } @@ -262,17 +292,20 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension instance * @return string The HTML code */ - function make_linkbar(helper_plugin_extension_extension $extension) { + public function makeLinkbar(helper_plugin_extension_extension $extension) + { $return = '<div class="linkbar">'; - $return .= $this->make_homepagelink($extension); + $return .= $this->makeHomepageLink($extension); if ($extension->getBugtrackerURL()) { - $return .= ' <a href="'.hsc($extension->getBugtrackerURL()).'" title="'.hsc($extension->getBugtrackerURL()).'" class ="bugs">'.$this->getLang('bugs_features').'</a> '; + $return .= ' <a href="'.hsc($extension->getBugtrackerURL()). + '" title="'.hsc($extension->getBugtrackerURL()).'" class ="bugs">'. + $this->getLang('bugs_features').'</a> '; } - if ($extension->getTags()){ + if ($extension->getTags()) { $first = true; $return .= '<span class="tags">'.$this->getLang('tags').' '; foreach ($extension->getTags() as $tag) { - if (!$first){ + if (!$first) { $return .= ', '; } else { $first = false; @@ -292,37 +325,49 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension * @return string The HTML code */ - function make_noticearea(helper_plugin_extension_extension $extension) { + public function makeNoticeArea(helper_plugin_extension_extension $extension) + { $return = ''; $missing_dependencies = $extension->getMissingDependencies(); - if(!empty($missing_dependencies)) { - $return .= '<div class="msg error">'. - sprintf($this->getLang('missing_dependency'), '<bdi>'.implode(', ', /*array_map(array($this->helper, 'make_extensionsearchlink'),*/ $missing_dependencies).'</bdi>'). + if (!empty($missing_dependencies)) { + $return .= '<div class="msg error">' . + sprintf( + $this->getLang('missing_dependency'), + '<bdi>' . implode(', ', $missing_dependencies) . '</bdi>' + ) . '</div>'; } - if($extension->isInWrongFolder()) { - $return .= '<div class="msg error">'. - sprintf($this->getLang('wrong_folder'), '<bdi>'.hsc($extension->getInstallName()).'</bdi>', '<bdi>'.hsc($extension->getBase()).'</bdi>'). + if ($extension->isInWrongFolder()) { + $return .= '<div class="msg error">' . + sprintf( + $this->getLang('wrong_folder'), + '<bdi>' . hsc($extension->getInstallName()) . '</bdi>', + '<bdi>' . hsc($extension->getBase()) . '</bdi>' + ) . '</div>'; } - if(($securityissue = $extension->getSecurityIssue()) !== false) { + if (($securityissue = $extension->getSecurityIssue()) !== false) { $return .= '<div class="msg error">'. sprintf($this->getLang('security_issue'), '<bdi>'.hsc($securityissue).'</bdi>'). '</div>'; } - if(($securitywarning = $extension->getSecurityWarning()) !== false) { + if (($securitywarning = $extension->getSecurityWarning()) !== false) { $return .= '<div class="msg notify">'. sprintf($this->getLang('security_warning'), '<bdi>'.hsc($securitywarning).'</bdi>'). '</div>'; } - if($extension->updateAvailable()) { + if ($extension->updateAvailable()) { $return .= '<div class="msg notify">'. sprintf($this->getLang('update_available'), hsc($extension->getLastUpdate())). '</div>'; } - if($extension->hasDownloadURLChanged()) { - $return .= '<div class="msg notify">'. - sprintf($this->getLang('url_change'), '<bdi>'.hsc($extension->getDownloadURL()).'</bdi>', '<bdi>'.hsc($extension->getLastDownloadURL()).'</bdi>'). + if ($extension->hasDownloadURLChanged()) { + $return .= '<div class="msg notify">' . + sprintf( + $this->getLang('url_change'), + '<bdi>' . hsc($extension->getDownloadURL()) . '</bdi>', + '<bdi>' . hsc($extension->getLastDownloadURL()) . '</bdi>' + ) . '</div>'; } return $return.DOKU_LF; @@ -336,13 +381,14 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param string $url * @return string HTML link */ - function shortlink($url){ + public function shortlink($url) + { $link = parse_url($url); $base = $link['host']; - if(!empty($link['port'])) $base .= $base.':'.$link['port']; + if (!empty($link['port'])) $base .= $base.':'.$link['port']; $long = $link['path']; - if(!empty($link['query'])) $long .= $link['query']; + if (!empty($link['query'])) $long .= $link['query']; $name = shorten($base, $long, 55); @@ -355,17 +401,19 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension * @return string The HTML code */ - function make_info(helper_plugin_extension_extension $extension) { + public function makeInfo(helper_plugin_extension_extension $extension) + { $default = $this->getLang('unknown'); $return = '<dl class="details">'; $return .= '<dt>'.$this->getLang('status').'</dt>'; - $return .= '<dd>'.$this->make_status($extension).'</dd>'; + $return .= '<dd>'.$this->makeStatus($extension).'</dd>'; if ($extension->getDonationURL()) { $return .= '<dt>'.$this->getLang('donate').'</dt>'; $return .= '<dd>'; - $return .= '<a href="'.$extension->getDonationURL().'" class="donate">'.$this->getLang('donate_action').'</a>'; + $return .= '<a href="'.$extension->getDonationURL().'" class="donate">'. + $this->getLang('donate_action').'</a>'; $return .= '</dd>'; } @@ -407,7 +455,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { $return .= ($extension->getTypes() ? hsc(implode(', ', $extension->getTypes())) : $default); $return .= '</bdi></dd>'; - if(!$extension->isBundled() && $extension->getCompatibleVersions()) { + if (!$extension->isBundled() && $extension->getCompatibleVersions()) { $return .= '<dt>'.$this->getLang('compatible').'</dt>'; $return .= '<dd>'; foreach ($extension->getCompatibleVersions() as $date => $version) { @@ -416,24 +464,24 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { $return = rtrim($return, ', '); $return .= '</dd>'; } - if($extension->getDependencies()) { + if ($extension->getDependencies()) { $return .= '<dt>'.$this->getLang('depends').'</dt>'; $return .= '<dd>'; - $return .= $this->make_linklist($extension->getDependencies()); + $return .= $this->makeLinkList($extension->getDependencies()); $return .= '</dd>'; } - if($extension->getSimilarExtensions()) { + if ($extension->getSimilarExtensions()) { $return .= '<dt>'.$this->getLang('similar').'</dt>'; $return .= '<dd>'; - $return .= $this->make_linklist($extension->getSimilarExtensions()); + $return .= $this->makeLinkList($extension->getSimilarExtensions()); $return .= '</dd>'; } - if($extension->getConflicts()) { + if ($extension->getConflicts()) { $return .= '<dt>'.$this->getLang('conflicts').'</dt>'; $return .= '<dd>'; - $return .= $this->make_linklist($extension->getConflicts()); + $return .= $this->makeLinkList($extension->getConflicts()); $return .= '</dd>'; } $return .= '</dl>'.DOKU_LF; @@ -446,10 +494,12 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param array $ext The extensions * @return string The HTML code */ - function make_linklist($ext) { + public function makeLinkList($ext) + { $return = ''; foreach ($ext as $link) { - $return .= '<bdi><a href="'.$this->gui->tabURL('search', array('q'=>'ext:'.$link)).'">'.hsc($link).'</a></bdi>, '; + $return .= '<bdi><a href="'. + $this->gui->tabURL('search', array('q'=>'ext:'.$link)).'">'.hsc($link).'</a></bdi>, '; } return rtrim($return, ', '); } @@ -460,7 +510,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension * @return string The HTML code */ - function make_actions(helper_plugin_extension_extension $extension) { + public function makeActions(helper_plugin_extension_extension $extension) + { global $conf; $return = ''; $errors = ''; @@ -468,48 +519,52 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { if ($extension->isInstalled()) { if (($canmod = $extension->canModify()) === true) { if (!$extension->isProtected()) { - $return .= $this->make_action('uninstall', $extension); + $return .= $this->makeAction('uninstall', $extension); } if ($extension->getDownloadURL()) { if ($extension->updateAvailable()) { - $return .= $this->make_action('update', $extension); + $return .= $this->makeAction('update', $extension); } else { - $return .= $this->make_action('reinstall', $extension); + $return .= $this->makeAction('reinstall', $extension); } } - }else{ + } else { $errors .= '<p class="permerror">'.$this->getLang($canmod).'</p>'; } if (!$extension->isProtected() && !$extension->isTemplate()) { // no enable/disable for templates if ($extension->isEnabled()) { - $return .= $this->make_action('disable', $extension); + $return .= $this->makeAction('disable', $extension); } else { - $return .= $this->make_action('enable', $extension); + $return .= $this->makeAction('enable', $extension); } } - if ($extension->isGitControlled()){ + if ($extension->isGitControlled()) { $errors .= '<p class="permerror">'.$this->getLang('git').'</p>'; } - if ($extension->isEnabled() && in_array('Auth', $extension->getTypes()) && $conf['authtype'] != $extension->getID()) { + if ($extension->isEnabled() && + in_array('Auth', $extension->getTypes()) && + $conf['authtype'] != $extension->getID() + ) { $errors .= '<p class="permerror">'.$this->getLang('auth').'</p>'; } - - }else{ + } else { if (($canmod = $extension->canModify()) === true) { if ($extension->getDownloadURL()) { - $return .= $this->make_action('install', $extension); + $return .= $this->makeAction('install', $extension); } - }else{ + } else { $errors .= '<div class="permerror">'.$this->getLang($canmod).'</div>'; } } if (!$extension->isInstalled() && $extension->getDownloadURL()) { $return .= ' <span class="version">'.$this->getLang('available_version').' '; - $return .= ($extension->getLastUpdate() ? hsc($extension->getLastUpdate()) : $this->getLang('unknown')).'</span>'; + $return .= ($extension->getLastUpdate() + ? hsc($extension->getLastUpdate()) + : $this->getLang('unknown')).'</span>'; } return $return.' '.$errors.DOKU_LF; @@ -522,7 +577,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension * @return string The HTML code */ - function make_action($action, $extension) { + public function makeAction($action, $extension) + { $title = ''; switch ($action) { @@ -535,7 +591,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { $classes = 'button '.$action; $name = 'fn['.$action.']['.hsc($extension->getID()).']'; - return '<button class="'.$classes.'" name="'.$name.'" type="submit" '.$title.'>'.$this->getLang('btn_'.$action).'</button> '; + return '<button class="'.$classes.'" name="'.$name.'" type="submit" '.$title.'>'. + $this->getLang('btn_'.$action).'</button> '; } /** @@ -544,7 +601,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { * @param helper_plugin_extension_extension $extension The extension * @return string The description of all relevant statusses */ - function make_status(helper_plugin_extension_extension $extension) { + public function makeStatus(helper_plugin_extension_extension $extension) + { $status = array(); @@ -553,15 +611,16 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { if ($extension->isProtected()) { $status[] = $this->getLang('status_protected'); } else { - $status[] = $extension->isEnabled() ? $this->getLang('status_enabled') : $this->getLang('status_disabled'); + $status[] = $extension->isEnabled() + ? $this->getLang('status_enabled') + : $this->getLang('status_disabled'); } } else { $status[] = $this->getLang('status_not_installed'); } - if(!$extension->canModify()) $status[] = $this->getLang('status_unmodifiable'); - if($extension->isBundled()) $status[] = $this->getLang('status_bundled'); + if (!$extension->canModify()) $status[] = $this->getLang('status_unmodifiable'); + if ($extension->isBundled()) $status[] = $this->getLang('status_bundled'); $status[] = $extension->isTemplate() ? $this->getLang('status_template') : $this->getLang('status_plugin'); return join(', ', $status); } - } diff --git a/lib/plugins/extension/helper/repository.php b/lib/plugins/extension/helper/repository.php index 5dc2707cf..afe413a58 100644 --- a/lib/plugins/extension/helper/repository.php +++ b/lib/plugins/extension/helper/repository.php @@ -6,24 +6,22 @@ * @author Michael Hamann <michael@content-space.de> */ -#define('EXTENSION_REPOSITORY_API', 'http://localhost/dokuwiki/lib/plugins/pluginrepo/api.php'); - -if (!defined('EXTENSION_REPOSITORY_API_ENDPOINT')) - define('EXTENSION_REPOSITORY_API', 'http://www.dokuwiki.org/lib/plugins/pluginrepo/api.php'); - -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * Class helper_plugin_extension_repository provides access to the extension repository on dokuwiki.org */ -class helper_plugin_extension_repository extends DokuWiki_Plugin { +class helper_plugin_extension_repository extends DokuWiki_Plugin +{ + + const EXTENSION_REPOSITORY_API = 'http://www.dokuwiki.org/lib/plugins/pluginrepo/api.php'; + private $loaded_extensions = array(); private $has_access = null; + /** * Initialize the repository (cache), fetches data for all installed plugins */ - public function init() { + public function init() + { /* @var Doku_Plugin_Controller $plugin_controller */ global $plugin_controller; if ($this->hasAccess()) { @@ -33,7 +31,10 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin { foreach ($list as $name) { $cache = new cache('##extension_manager##'.$name, '.repo'); - if (!isset($this->loaded_extensions[$name]) && $this->hasAccess() && !$cache->useCache(array('age' => 3600 * 24))) { + if (!isset($this->loaded_extensions[$name]) && + $this->hasAccess() && + !$cache->useCache(array('age' => 3600 * 24)) + ) { $this->loaded_extensions[$name] = true; $request_data['ext'][] = $name; $request_needed = true; @@ -42,7 +43,7 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin { if ($request_needed) { $httpclient = new DokuHTTPClient(); - $data = $httpclient->post(EXTENSION_REPOSITORY_API, $request_data); + $data = $httpclient->post(self::EXTENSION_REPOSITORY_API, $request_data); if ($data !== false) { $extensions = unserialize($data); foreach ($extensions as $extension) { @@ -61,14 +62,15 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin { * * @return bool If repository access is available */ - public function hasAccess() { + public function hasAccess() + { if ($this->has_access === null) { $cache = new cache('##extension_manager###hasAccess', '.repo'); if (!$cache->useCache(array('age' => 3600 * 24, 'purge'=>1))) { $httpclient = new DokuHTTPClient(); $httpclient->timeout = 5; - $data = $httpclient->get(EXTENSION_REPOSITORY_API.'?cmd=ping'); + $data = $httpclient->get(self::EXTENSION_REPOSITORY_API.'?cmd=ping'); if ($data !== false) { $this->has_access = true; $cache->storeCache(1); @@ -89,13 +91,17 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin { * @param string $name The plugin name to get the data for, template names need to be prefix by 'template:' * @return array The data or null if nothing was found (possibly no repository access) */ - public function getData($name) { + public function getData($name) + { $cache = new cache('##extension_manager##'.$name, '.repo'); - if (!isset($this->loaded_extensions[$name]) && $this->hasAccess() && !$cache->useCache(array('age' => 3600 * 24))) { + if (!isset($this->loaded_extensions[$name]) && + $this->hasAccess() && + !$cache->useCache(array('age' => 3600 * 24)) + ) { $this->loaded_extensions[$name] = true; $httpclient = new DokuHTTPClient(); - $data = $httpclient->get(EXTENSION_REPOSITORY_API.'?fmt=php&ext[]='.urlencode($name)); + $data = $httpclient->get(self::EXTENSION_REPOSITORY_API.'?fmt=php&ext[]='.urlencode($name)); if ($data !== false) { $result = unserialize($data); $cache->storeCache(serialize($result[0])); @@ -116,19 +122,20 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin { * @param string $q the query string * @return array a list of matching extensions */ - public function search($q){ - $query = $this->parse_query($q); + public function search($q) + { + $query = $this->parseQuery($q); $query['fmt'] = 'php'; $httpclient = new DokuHTTPClient(); - $data = $httpclient->post(EXTENSION_REPOSITORY_API, $query); + $data = $httpclient->post(self::EXTENSION_REPOSITORY_API, $query); if ($data === false) return array(); $result = unserialize($data); $ids = array(); // store cache info for each extension - foreach($result as $ext){ + foreach ($result as $ext) { $name = $ext['plugin']; $cache = new cache('##extension_manager##'.$name, '.repo'); $cache->storeCache(serialize($ext)); @@ -144,7 +151,8 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin { * @param string $q * @return array */ - protected function parse_query($q){ + protected function parseQuery($q) + { $parameters = array( 'tag' => array(), 'mail' => array(), @@ -153,29 +161,29 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin { ); // extract tags - if(preg_match_all('/(^|\s)(tag:([\S]+))/', $q, $matches, PREG_SET_ORDER)){ - foreach($matches as $m){ + if (preg_match_all('/(^|\s)(tag:([\S]+))/', $q, $matches, PREG_SET_ORDER)) { + foreach ($matches as $m) { $q = str_replace($m[2], '', $q); $parameters['tag'][] = $m[3]; } } // extract author ids - if(preg_match_all('/(^|\s)(authorid:([\S]+))/', $q, $matches, PREG_SET_ORDER)){ - foreach($matches as $m){ + if (preg_match_all('/(^|\s)(authorid:([\S]+))/', $q, $matches, PREG_SET_ORDER)) { + foreach ($matches as $m) { $q = str_replace($m[2], '', $q); $parameters['mail'][] = $m[3]; } } // extract extensions - if(preg_match_all('/(^|\s)(ext:([\S]+))/', $q, $matches, PREG_SET_ORDER)){ - foreach($matches as $m){ + if (preg_match_all('/(^|\s)(ext:([\S]+))/', $q, $matches, PREG_SET_ORDER)) { + foreach ($matches as $m) { $q = str_replace($m[2], '', $q); $parameters['ext'][] = $m[3]; } } // extract types - if(preg_match_all('/(^|\s)(type:([\S]+))/', $q, $matches, PREG_SET_ORDER)){ - foreach($matches as $m){ + if (preg_match_all('/(^|\s)(type:([\S]+))/', $q, $matches, PREG_SET_ORDER)) { + foreach ($matches as $m) { $q = str_replace($m[2], '', $q); $parameters['type'][] = $m[3]; } diff --git a/lib/plugins/info/syntax.php b/lib/plugins/info/syntax.php index 773256faf..3fa35e733 100644 --- a/lib/plugins/info/syntax.php +++ b/lib/plugins/info/syntax.php @@ -6,33 +6,30 @@ * @author Andreas Gohr <andi@splitbrain.org> * @author Esther Brunner <wikidesign@gmail.com> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -/** - * All DokuWiki plugins to extend the parser/rendering mechanism - * need to inherit from this class - */ -class syntax_plugin_info extends DokuWiki_Syntax_Plugin { +class syntax_plugin_info extends DokuWiki_Syntax_Plugin +{ /** * What kind of syntax are we? */ - function getType(){ + public function getType() + { return 'substition'; } /** * What about paragraphs? */ - function getPType(){ + public function getPType() + { return 'block'; } /** * Where to sort in? */ - function getSort(){ + public function getSort() + { return 155; } @@ -40,8 +37,9 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { /** * Connect pattern to lexer */ - function connectTo($mode) { - $this->Lexer->addSpecialPattern('~~INFO:\w+~~',$mode,'plugin_info'); + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern('~~INFO:\w+~~', $mode, 'plugin_info'); } /** @@ -53,8 +51,9 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { * @param Doku_Handler $handler The Doku_Handler object * @return array Return an array with all data you want to use in render */ - function handle($match, $state, $pos, Doku_Handler $handler){ - $match = substr($match,7,-2); //strip ~~INFO: from start and ~~ from end + public function handle($match, $state, $pos, Doku_Handler $handler) + { + $match = substr($match, 7, -2); //strip ~~INFO: from start and ~~ from end return array(strtolower($match)); } @@ -66,40 +65,41 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { * @param array $data data created by handler() * @return boolean rendered correctly? */ - function render($format, Doku_Renderer $renderer, $data) { - if($format == 'xhtml'){ + public function render($format, Doku_Renderer $renderer, $data) + { + if ($format == 'xhtml') { /** @var Doku_Renderer_xhtml $renderer */ //handle various info stuff - switch ($data[0]){ + switch ($data[0]) { case 'syntaxmodes': - $renderer->doc .= $this->_syntaxmodes_xhtml(); + $renderer->doc .= $this->renderSyntaxModes(); break; case 'syntaxtypes': - $renderer->doc .= $this->_syntaxtypes_xhtml(); + $renderer->doc .= $this->renderSyntaxTypes(); break; case 'syntaxplugins': - $this->_plugins_xhtml('syntax', $renderer); + $this->renderPlugins('syntax', $renderer); break; case 'adminplugins': - $this->_plugins_xhtml('admin', $renderer); + $this->renderPlugins('admin', $renderer); break; case 'actionplugins': - $this->_plugins_xhtml('action', $renderer); + $this->renderPlugins('action', $renderer); break; case 'rendererplugins': - $this->_plugins_xhtml('renderer', $renderer); + $this->renderPlugins('renderer', $renderer); break; case 'helperplugins': - $this->_plugins_xhtml('helper', $renderer); + $this->renderPlugins('helper', $renderer); break; case 'authplugins': - $this->_plugins_xhtml('auth', $renderer); + $this->renderPlugins('auth', $renderer); break; case 'remoteplugins': - $this->_plugins_xhtml('remote', $renderer); + $this->renderPlugins('remote', $renderer); break; case 'helpermethods': - $this->_helpermethods_xhtml($renderer); + $this->renderHelperMethods($renderer); break; default: $renderer->doc .= "no info about ".htmlspecialchars($data[0]); @@ -117,7 +117,8 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { * @param string $type * @param Doku_Renderer_xhtml $renderer */ - function _plugins_xhtml($type, Doku_Renderer_xhtml $renderer){ + protected function renderPlugins($type, Doku_Renderer_xhtml $renderer) + { global $lang; $renderer->doc .= '<ul>'; @@ -125,24 +126,24 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { $plginfo = array(); // remove subparts - foreach($plugins as $p){ - if (!$po = plugin_load($type,$p)) continue; - list($name,/* $part */) = explode('_',$p,2); + foreach ($plugins as $p) { + if (!$po = plugin_load($type, $p)) continue; + list($name,/* $part */) = explode('_', $p, 2); $plginfo[$name] = $po->getInfo(); } // list them - foreach($plginfo as $info){ + foreach ($plginfo as $info) { $renderer->doc .= '<li><div class="li">'; - $renderer->externallink($info['url'],$info['name']); + $renderer->externallink($info['url'], $info['name']); $renderer->doc .= ' '; $renderer->doc .= '<em>'.$info['date'].'</em>'; $renderer->doc .= ' '; $renderer->doc .= $lang['by']; $renderer->doc .= ' '; - $renderer->emaillink($info['email'],$info['author']); + $renderer->emaillink($info['email'], $info['author']); $renderer->doc .= '<br />'; - $renderer->doc .= strtr(hsc($info['desc']),array("\n"=>"<br />")); + $renderer->doc .= strtr(hsc($info['desc']), array("\n"=>"<br />")); $renderer->doc .= '</div></li>'; unset($po); } @@ -157,39 +158,40 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { * * @param Doku_Renderer_xhtml $renderer */ - function _helpermethods_xhtml(Doku_Renderer_xhtml $renderer){ + protected function renderHelperMethods(Doku_Renderer_xhtml $renderer) + { $plugins = plugin_list('helper'); - foreach($plugins as $p){ - if (!$po = plugin_load('helper',$p)) continue; + foreach ($plugins as $p) { + if (!$po = plugin_load('helper', $p)) continue; if (!method_exists($po, 'getMethods')) continue; $methods = $po->getMethods(); $info = $po->getInfo(); - $hid = $this->_addToTOC($info['name'], 2, $renderer); + $hid = $this->addToToc($info['name'], 2, $renderer); $doc = '<h2><a name="'.$hid.'" id="'.$hid.'">'.hsc($info['name']).'</a></h2>'; $doc .= '<div class="level2">'; $doc .= '<p>'.strtr(hsc($info['desc']), array("\n"=>"<br />")).'</p>'; $doc .= '<pre class="code">$'.$p." = plugin_load('helper', '".$p."');</pre>"; $doc .= '</div>'; - foreach ($methods as $method){ + foreach ($methods as $method) { $title = '$'.$p.'->'.$method['name'].'()'; - $hid = $this->_addToTOC($title, 3, $renderer); + $hid = $this->addToToc($title, 3, $renderer); $doc .= '<h3><a name="'.$hid.'" id="'.$hid.'">'.hsc($title).'</a></h3>'; $doc .= '<div class="level3">'; $doc .= '<div class="table"><table class="inline"><tbody>'; $doc .= '<tr><th>Description</th><td colspan="2">'.$method['desc']. '</td></tr>'; - if ($method['params']){ + if ($method['params']) { $c = count($method['params']); $doc .= '<tr><th rowspan="'.$c.'">Parameters</th><td>'; $params = array(); - foreach ($method['params'] as $desc => $type){ + foreach ($method['params'] as $desc => $type) { $params[] = hsc($desc).'</td><td>'.hsc($type); } $doc .= join($params, '</td></tr><tr><td>').'</td></tr>'; } - if ($method['return']){ + if ($method['return']) { $doc .= '<tr><th>Return value</th><td>'.hsc(key($method['return'])). '</td><td>'.hsc(current($method['return'])).'</td></tr>'; } @@ -207,18 +209,19 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { * * @return string */ - function _syntaxtypes_xhtml(){ + protected function renderSyntaxTypes() + { global $PARSER_MODES; $doc = ''; $doc .= '<div class="table"><table class="inline"><tbody>'; - foreach($PARSER_MODES as $mode => $modes){ + foreach ($PARSER_MODES as $mode => $modes) { $doc .= '<tr>'; $doc .= '<td class="leftalign">'; $doc .= $mode; $doc .= '</td>'; $doc .= '<td class="leftalign">'; - $doc .= join(', ',$modes); + $doc .= join(', ', $modes); $doc .= '</td>'; $doc .= '</tr>'; } @@ -231,29 +234,30 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { * * @return string */ - function _syntaxmodes_xhtml(){ + protected function renderSyntaxModes() + { $modes = p_get_parsermodes(); $compactmodes = array(); - foreach($modes as $mode){ + foreach ($modes as $mode) { $compactmodes[$mode['sort']][] = $mode['mode']; } $doc = ''; $doc .= '<div class="table"><table class="inline"><tbody>'; - foreach($compactmodes as $sort => $modes){ + foreach ($compactmodes as $sort => $modes) { $rowspan = ''; - if(count($modes) > 1) { + if (count($modes) > 1) { $rowspan = ' rowspan="'.count($modes).'"'; } - foreach($modes as $index => $mode) { + foreach ($modes as $index => $mode) { $doc .= '<tr>'; $doc .= '<td class="leftalign">'; $doc .= $mode; $doc .= '</td>'; - if($index === 0) { + if ($index === 0) { $doc .= '<td class="rightalign" '.$rowspan.'>'; $doc .= $sort; $doc .= '</td>'; @@ -274,11 +278,12 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { * @param Doku_Renderer_xhtml $renderer * @return string */ - protected function _addToTOC($text, $level, Doku_Renderer_xhtml $renderer){ + protected function addToToc($text, $level, Doku_Renderer_xhtml $renderer) + { global $conf; $hid = ''; - if (($level >= $conf['toptoclevel']) && ($level <= $conf['maxtoclevel'])){ + if (($level >= $conf['toptoclevel']) && ($level <= $conf['maxtoclevel'])) { $hid = $renderer->_headerToLink($text, true); $renderer->toc[] = array( 'hid' => $hid, diff --git a/lib/plugins/popularity/action.php b/lib/plugins/popularity/action.php index d5ec0f5c5..fac610735 100644 --- a/lib/plugins/popularity/action.php +++ b/lib/plugins/popularity/action.php @@ -5,44 +5,49 @@ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) */ -require_once(DOKU_PLUGIN.'action.php'); -require_once(DOKU_PLUGIN.'popularity/admin.php'); - -class action_plugin_popularity extends Dokuwiki_Action_Plugin { +class action_plugin_popularity extends DokuWiki_Action_Plugin +{ /** * @var helper_plugin_popularity */ - var $helper; + protected $helper; - function __construct(){ + public function __construct() + { $this->helper = $this->loadHelper('popularity', false); } - /** - * Register its handlers with the dokuwiki's event controller - */ - function register(Doku_Event_Handler $controller) { - $controller->register_hook('INDEXER_TASKS_RUN', 'AFTER', $this, '_autosubmit', array()); + /** @inheritdoc */ + public function register(Doku_Event_Handler $controller) + { + $controller->register_hook('INDEXER_TASKS_RUN', 'AFTER', $this, 'autosubmit', array()); } - function _autosubmit(Doku_Event &$event, $param){ + /** + * Event handler + * + * @param Doku_Event $event + * @param $param + */ + public function autosubmit(Doku_Event &$event, $param) + { //Do we have to send the data now - if ( !$this->helper->isAutosubmitEnabled() || $this->_isTooEarlyToSubmit() ){ + if (!$this->helper->isAutosubmitEnabled() || $this->isTooEarlyToSubmit()) { return; } //Actually send it - $status = $this->helper->sendData( $this->helper->gatherAsString() ); + $status = $this->helper->sendData($this->helper->gatherAsString()); - if ( $status !== '' ){ + if ($status !== '') { //If an error occured, log it - io_saveFile( $this->helper->autosubmitErrorFile, $status ); + io_saveFile($this->helper->autosubmitErrorFile, $status); } else { //If the data has been sent successfully, previous log of errors are useless @unlink($this->helper->autosubmitErrorFile); //Update the last time we sent data - touch ( $this->helper->autosubmitFile ); + touch($this->helper->autosubmitFile); } $event->stopPropagation(); @@ -53,7 +58,8 @@ class action_plugin_popularity extends Dokuwiki_Action_Plugin { * Check if it's time to send autosubmit data * (we should have check if autosubmit is enabled first) */ - function _isTooEarlyToSubmit(){ + protected function isTooEarlyToSubmit() + { $lastSubmit = $this->helper->lastSentTime(); return $lastSubmit + 24*60*60*30 > time(); } diff --git a/lib/plugins/popularity/admin.php b/lib/plugins/popularity/admin.php index 0cf174e0d..61d8cc3bf 100644 --- a/lib/plugins/popularity/admin.php +++ b/lib/plugins/popularity/admin.php @@ -5,43 +5,44 @@ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); +class admin_plugin_popularity extends DokuWiki_Admin_Plugin +{ -/** - * All DokuWiki plugins to extend the admin function - * need to inherit from this class - */ -class admin_plugin_popularity extends DokuWiki_Admin_Plugin { + /** @var helper_plugin_popularity */ + protected $helper; + protected $sentStatus = null; /** - * @var helper_plugin_popularity + * admin_plugin_popularity constructor. */ - var $helper; - var $sentStatus = null; - - function __construct(){ + public function __construct() + { $this->helper = $this->loadHelper('popularity', false); } /** * return prompt for admin menu + * @param $language + * @return string */ - function getMenuText($language) { + public function getMenuText($language) + { return $this->getLang('name'); } /** * return sort order for position in admin menu */ - function getMenuSort() { + public function getMenuSort() + { return 2000; } /** * Accessible for managers */ - function forAdminOnly() { + public function forAdminOnly() + { return false; } @@ -49,18 +50,19 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin { /** * handle user request */ - function handle() { + public function handle() + { global $INPUT; //Send the data - if ( $INPUT->has('data') ){ - $this->sentStatus = $this->helper->sendData( $INPUT->str('data') ); - if ( $this->sentStatus === '' ){ + if ($INPUT->has('data')) { + $this->sentStatus = $this->helper->sendData($INPUT->str('data')); + if ($this->sentStatus === '') { //Update the last time we sent the data - touch ( $this->helper->popularityLastSubmitFile ); + touch($this->helper->popularityLastSubmitFile); } //Deal with the autosubmit option - $this->_enableAutosubmit( $INPUT->has('autosubmit') ); + $this->enableAutosubmit($INPUT->has('autosubmit')); } } @@ -68,9 +70,10 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin { * Enable or disable autosubmit * @param bool $enable If TRUE, it will enable autosubmit. Else, it will disable it. */ - function _enableAutosubmit( $enable ){ - if ( $enable ){ - io_saveFile( $this->helper->autosubmitFile, ' '); + protected function enableAutosubmit($enable) + { + if ($enable) { + io_saveFile($this->helper->autosubmitFile, ' '); } else { @unlink($this->helper->autosubmitFile); } @@ -79,17 +82,18 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin { /** * Output HTML form */ - function html() { + public function html() + { global $INPUT; - if ( ! $INPUT->has('data') ){ + if (! $INPUT->has('data')) { echo $this->locale_xhtml('intro'); //If there was an error the last time we tried to autosubmit, warn the user - if ( $this->helper->isAutoSubmitEnabled() ){ - if ( file_exists($this->helper->autosubmitErrorFile) ){ + if ($this->helper->isAutoSubmitEnabled()) { + if (file_exists($this->helper->autosubmitErrorFile)) { echo $this->getLang('autosubmitError'); - echo io_readFile( $this->helper->autosubmitErrorFile ); + echo io_readFile($this->helper->autosubmitErrorFile); } } @@ -98,12 +102,12 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin { //Print the last time the data was sent $lastSent = $this->helper->lastSentTime(); - if ( $lastSent !== 0 ){ + if ($lastSent !== 0) { echo $this->getLang('lastSent') . ' ' . datetime_h($lastSent); } } else { //If we just submitted the form - if ( $this->sentStatus === '' ){ + if ($this->sentStatus === '') { //If we successfully sent the data echo $this->locale_xhtml('submitted'); } else { @@ -122,9 +126,10 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin { * @param string $data The popularity data, if it has already been computed. NULL otherwise. * @return string The form, as an html string */ - function buildForm($submissionMode, $data = null){ + protected function buildForm($submissionMode, $data = null) + { $url = ($submissionMode === 'browser' ? $this->helper->submitUrl : script()); - if ( is_null($data) ){ + if (is_null($data)) { $data = $this->helper->gatherAsString(); } @@ -135,7 +140,7 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin { .'</textarea><br />'; //If we submit via the server, we give the opportunity to suscribe to the autosubmission option - if ( $submissionMode !== 'browser' ){ + if ($submissionMode !== 'browser') { $form .= '<label for="autosubmit">' .'<input type="checkbox" name="autosubmit" id="autosubmit" ' .($this->helper->isAutosubmitEnabled() ? 'checked' : '' ) diff --git a/lib/plugins/popularity/helper.php b/lib/plugins/popularity/helper.php index b81ab7005..05e2ccb74 100644 --- a/lib/plugins/popularity/helper.php +++ b/lib/plugins/popularity/helper.php @@ -5,32 +5,36 @@ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) */ -class helper_plugin_popularity extends Dokuwiki_Plugin { +class helper_plugin_popularity extends Dokuwiki_Plugin +{ /** * The url where the data should be sent */ - var $submitUrl = 'http://update.dokuwiki.org/popularity.php'; + public $submitUrl = 'http://update.dokuwiki.org/popularity.php'; /** * Name of the file which determine if the the autosubmit is enabled, * and when it was submited for the last time */ - var $autosubmitFile; + public $autosubmitFile; /** * File where the last error which happened when we tried to autosubmit, will be log */ - var $autosubmitErrorFile; + public $autosubmitErrorFile; /** * Name of the file which determine when the popularity data was manually * submitted for the last time * (If this file doesn't exist, the data has never been sent) */ - var $popularityLastSubmitFile; + public $popularityLastSubmitFile; - - function __construct(){ + /** + * helper_plugin_popularity constructor. + */ + public function __construct() + { global $conf; $this->autosubmitFile = $conf['cachedir'].'/autosubmit.txt'; $this->autosubmitErrorFile = $conf['cachedir'].'/autosubmitError.txt'; @@ -38,46 +42,12 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { } /** - * Return methods of this helper - * - * @return array with methods description - */ - function getMethods(){ - $result = array(); - $result[] = array( - 'name' => 'isAutoSubmitEnabled', - 'desc' => 'Check if autosubmit is enabled', - 'params' => array(), - 'return' => array('result' => 'bool') - ); - $result[] = array( - 'name' => 'sendData', - 'desc' => 'Send the popularity data', - 'params' => array('data' => 'string'), - 'return' => array() - ); - $result[] = array( - 'name' => 'gatherAsString', - 'desc' => 'Gather the popularity data', - 'params' => array(), - 'return' => array('data' => 'string') - ); - $result[] = array( - 'name' => 'lastSentTime', - 'desc' => 'Compute the last time popularity data was sent', - 'params' => array(), - 'return' => array('data' => 'int') - ); - return $result; - - } - - /** * Check if autosubmit is enabled * * @return boolean TRUE if we should send data once a month, FALSE otherwise */ - function isAutoSubmitEnabled(){ + public function isAutoSubmitEnabled() + { return file_exists($this->autosubmitFile); } @@ -87,11 +57,12 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { * @param string $data The popularity data * @return string An empty string if everything worked fine, a string describing the error otherwise */ - function sendData($data){ + public function sendData($data) + { $error = ''; $httpClient = new DokuHTTPClient(); $status = $httpClient->sendRequest($this->submitUrl, array('data' => $data), 'POST'); - if ( ! $status ){ + if (! $status) { $error = $httpClient->error; } return $error; @@ -102,7 +73,8 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { * * @return int */ - function lastSentTime(){ + public function lastSentTime() + { $manualSubmission = @filemtime($this->popularityLastSubmitFile); $autoSubmission = @filemtime($this->autosubmitFile); @@ -114,13 +86,14 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { * * @return string The popularity data as a string */ - function gatherAsString(){ - $data = $this->_gather(); + public function gatherAsString() + { + $data = $this->gather(); $string = ''; - foreach($data as $key => $val){ - if(is_array($val)) foreach($val as $v){ + foreach ($data as $key => $val) { + if (is_array($val)) foreach ($val as $v) { $string .= hsc($key)."\t".hsc($v)."\n"; - }else{ + } else { $string .= hsc($key)."\t".hsc($val)."\n"; } } @@ -132,7 +105,8 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { * * @return array The popularity data as an array */ - function _gather(){ + protected function gather() + { global $conf; /** @var $auth DokuWiki_Auth_Plugin */ global $auth; @@ -156,81 +130,81 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { // number and size of pages $list = array(); - search($list,$conf['datadir'],array($this,'_search_count'),array('all'=>false),''); + search($list, $conf['datadir'], array($this, 'searchCountCallback'), array('all'=>false), ''); $data['page_count'] = $list['file_count']; $data['page_size'] = $list['file_size']; $data['page_biggest'] = $list['file_max']; $data['page_smallest'] = $list['file_min']; $data['page_nscount'] = $list['dir_count']; $data['page_nsnest'] = $list['dir_nest']; - if($list['file_count']) $data['page_avg'] = $list['file_size'] / $list['file_count']; + if ($list['file_count']) $data['page_avg'] = $list['file_size'] / $list['file_count']; $data['page_oldest'] = $list['file_oldest']; unset($list); // number and size of media $list = array(); - search($list,$conf['mediadir'],array($this,'_search_count'),array('all'=>true)); + search($list, $conf['mediadir'], array($this, 'searchCountCallback'), array('all'=>true)); $data['media_count'] = $list['file_count']; $data['media_size'] = $list['file_size']; $data['media_biggest'] = $list['file_max']; $data['media_smallest'] = $list['file_min']; $data['media_nscount'] = $list['dir_count']; $data['media_nsnest'] = $list['dir_nest']; - if($list['file_count']) $data['media_avg'] = $list['file_size'] / $list['file_count']; + if ($list['file_count']) $data['media_avg'] = $list['file_size'] / $list['file_count']; unset($list); // number and size of cache $list = array(); - search($list,$conf['cachedir'],array($this,'_search_count'),array('all'=>true)); + search($list, $conf['cachedir'], array($this, 'searchCountCallback'), array('all'=>true)); $data['cache_count'] = $list['file_count']; $data['cache_size'] = $list['file_size']; $data['cache_biggest'] = $list['file_max']; $data['cache_smallest'] = $list['file_min']; - if($list['file_count']) $data['cache_avg'] = $list['file_size'] / $list['file_count']; + if ($list['file_count']) $data['cache_avg'] = $list['file_size'] / $list['file_count']; unset($list); // number and size of index $list = array(); - search($list,$conf['indexdir'],array($this,'_search_count'),array('all'=>true)); + search($list, $conf['indexdir'], array($this, 'searchCountCallback'), array('all'=>true)); $data['index_count'] = $list['file_count']; $data['index_size'] = $list['file_size']; $data['index_biggest'] = $list['file_max']; $data['index_smallest'] = $list['file_min']; - if($list['file_count']) $data['index_avg'] = $list['file_size'] / $list['file_count']; + if ($list['file_count']) $data['index_avg'] = $list['file_size'] / $list['file_count']; unset($list); // number and size of meta $list = array(); - search($list,$conf['metadir'],array($this,'_search_count'),array('all'=>true)); + search($list, $conf['metadir'], array($this, 'searchCountCallback'), array('all'=>true)); $data['meta_count'] = $list['file_count']; $data['meta_size'] = $list['file_size']; $data['meta_biggest'] = $list['file_max']; $data['meta_smallest'] = $list['file_min']; - if($list['file_count']) $data['meta_avg'] = $list['file_size'] / $list['file_count']; + if ($list['file_count']) $data['meta_avg'] = $list['file_size'] / $list['file_count']; unset($list); // number and size of attic $list = array(); - search($list,$conf['olddir'],array($this,'_search_count'),array('all'=>true)); + search($list, $conf['olddir'], array($this, 'searchCountCallback'), array('all'=>true)); $data['attic_count'] = $list['file_count']; $data['attic_size'] = $list['file_size']; $data['attic_biggest'] = $list['file_max']; $data['attic_smallest'] = $list['file_min']; - if($list['file_count']) $data['attic_avg'] = $list['file_size'] / $list['file_count']; + if ($list['file_count']) $data['attic_avg'] = $list['file_size'] / $list['file_count']; $data['attic_oldest'] = $list['file_oldest']; unset($list); // user count - if($auth && $auth->canDo('getUserCount')){ + if ($auth && $auth->canDo('getUserCount')) { $data['user_count'] = $auth->getUserCount(); } // calculate edits per day $list = @file($conf['metadir'].'/_dokuwiki.changes'); $count = count($list); - if($count > 2){ - $first = (int) substr(array_shift($list),0,10); - $last = (int) substr(array_pop($list),0,10); + if ($count > 2) { + $first = (int) substr(array_shift($list), 0, 10); + $last = (int) substr(array_pop($list), 0, 10); $dur = ($last - $first)/(60*60*24); // number of days in the changelog $data['edits_per_day'] = $count/$dur; } @@ -240,7 +214,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { $data['plugin'] = plugin_list(); // pcre info - if(defined('PCRE_VERSION')) $data['pcre_version'] = PCRE_VERSION; + if (defined('PCRE_VERSION')) $data['pcre_version'] = PCRE_VERSION; $data['pcre_backtrack'] = ini_get('pcre.backtrack_limit'); $data['pcre_recursion'] = ini_get('pcre.recursion_limit'); @@ -249,27 +223,33 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { $data['webserver'] = $_SERVER['SERVER_SOFTWARE']; $data['php_version'] = phpversion(); $data['php_sapi'] = php_sapi_name(); - $data['php_memory'] = $this->_to_byte(ini_get('memory_limit')); + $data['php_memory'] = php_to_byte(ini_get('memory_limit')); $data['php_exectime'] = $phptime; $data['php_extension'] = get_loaded_extensions(); // plugin usage data - $this->_add_plugin_usage_data($data); + $this->addPluginUsageData($data); return $data; } - protected function _add_plugin_usage_data(&$data){ + /** + * Triggers event to let plugins add their own data + * + * @param $data + */ + protected function addPluginUsageData(&$data) + { $pluginsData = array(); trigger_event('PLUGIN_POPULARITY_DATA_SETUP', $pluginsData); - foreach($pluginsData as $plugin => $d){ - if ( is_array($d) ) { - foreach($d as $key => $value){ - $data['plugin_' . $plugin . '_' . $key] = $value; - } - } else { - $data['plugin_' . $plugin] = $d; - } + foreach ($pluginsData as $plugin => $d) { + if (is_array($d)) { + foreach ($d as $key => $value) { + $data['plugin_' . $plugin . '_' . $key] = $value; + } + } else { + $data['plugin_' . $plugin] = $d; + } } } @@ -284,57 +264,26 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { * @param array $opts option array as given to search() * @return bool */ - function _search_count(&$data,$base,$file,$type,$lvl,$opts){ + protected function searchCountCallback(&$data, $base, $file, $type, $lvl, $opts) + { // traverse - if($type == 'd'){ - if($data['dir_nest'] < $lvl) $data['dir_nest'] = $lvl; + if ($type == 'd') { + if ($data['dir_nest'] < $lvl) $data['dir_nest'] = $lvl; $data['dir_count']++; return true; } //only search txt files if 'all' option not set - if($opts['all'] || substr($file,-4) == '.txt'){ + if ($opts['all'] || substr($file, -4) == '.txt') { $size = filesize($base.'/'.$file); $date = filemtime($base.'/'.$file); $data['file_count']++; $data['file_size'] += $size; - if(!isset($data['file_min']) || $data['file_min'] > $size) $data['file_min'] = $size; - if($data['file_max'] < $size) $data['file_max'] = $size; - if(!isset($data['file_oldest']) || $data['file_oldest'] > $date) $data['file_oldest'] = $date; + if (!isset($data['file_min']) || $data['file_min'] > $size) $data['file_min'] = $size; + if ($data['file_max'] < $size) $data['file_max'] = $size; + if (!isset($data['file_oldest']) || $data['file_oldest'] > $date) $data['file_oldest'] = $date; } return false; } - - /** - * Convert php.ini shorthands to byte - * - * @author <gilthans dot NO dot SPAM at gmail dot com> - * @link http://php.net/manual/en/ini.core.php#79564 - * - * @param string $v - * @return int|string - */ - function _to_byte($v){ - $l = substr($v, -1); - $ret = substr($v, 0, -1); - switch(strtoupper($l)){ - /** @noinspection PhpMissingBreakStatementInspection */ - case 'P': - $ret *= 1024; - /** @noinspection PhpMissingBreakStatementInspection */ - case 'T': - $ret *= 1024; - /** @noinspection PhpMissingBreakStatementInspection */ - case 'G': - $ret *= 1024; - /** @noinspection PhpMissingBreakStatementInspection */ - case 'M': - $ret *= 1024; - case 'K': - $ret *= 1024; - break; - } - return $ret; - } } diff --git a/lib/plugins/remote.php b/lib/plugins/remote.php index c2253dbd5..d63f82aee 100644 --- a/lib/plugins/remote.php +++ b/lib/plugins/remote.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\Remote\Api; + /** * Class DokuWiki_Remote_Plugin */ @@ -11,7 +13,7 @@ abstract class DokuWiki_Remote_Plugin extends DokuWiki_Plugin { * Constructor */ public function __construct() { - $this->api = new RemoteAPI(); + $this->api = new Api(); } /** @@ -20,7 +22,8 @@ abstract class DokuWiki_Remote_Plugin extends DokuWiki_Plugin { * By default it exports all public methods of a remote plugin. Methods beginning * with an underscore are skipped. * - * @return array Information about all provided methods. {@see RemoteAPI}. + * @return array Information about all provided methods. {@see dokuwiki\Remote\RemoteAPI}. + * @throws ReflectionException */ public function _getMethods() { $result = array(); @@ -95,7 +98,7 @@ abstract class DokuWiki_Remote_Plugin extends DokuWiki_Plugin { } /** - * @return RemoteAPI + * @return Api */ protected function getApi() { return $this->api; diff --git a/lib/plugins/revert/admin.php b/lib/plugins/revert/admin.php index 1a0300585..e6790a962 100644 --- a/lib/plugins/revert/admin.php +++ b/lib/plugins/revert/admin.php @@ -1,66 +1,70 @@ <?php -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - /** * All DokuWiki plugins to extend the admin function * need to inherit from this class */ -class admin_plugin_revert extends DokuWiki_Admin_Plugin { - var $cmd; +class admin_plugin_revert extends DokuWiki_Admin_Plugin +{ + protected $cmd; // some vars which might need tuning later - var $max_lines = 800; // lines to read from changelog - var $max_revs = 20; // numer of old revisions to check + protected $max_lines = 800; // lines to read from changelog + protected $max_revs = 20; // numer of old revisions to check /** * Constructor */ - function __construct(){ + public function __construct() + { $this->setupLocale(); } /** * access for managers */ - function forAdminOnly(){ + public function forAdminOnly() + { return false; } /** * return sort order for position in admin menu */ - function getMenuSort() { + public function getMenuSort() + { return 40; } /** * handle user request */ - function handle() { + public function handle() + { } /** * output appropriate html */ - function html() { + public function html() + { global $INPUT; echo $this->locale_xhtml('intro'); - $this->_searchform(); + $this->printSearchForm(); - if(is_array($INPUT->param('revert')) && checkSecurityToken()){ - $this->_revert($INPUT->arr('revert'),$INPUT->str('filter')); - }elseif($INPUT->has('filter')){ - $this->_list($INPUT->str('filter')); + if (is_array($INPUT->param('revert')) && checkSecurityToken()) { + $this->revertEdits($INPUT->arr('revert'), $INPUT->str('filter')); + } elseif ($INPUT->has('filter')) { + $this->listEdits($INPUT->str('filter')); } } /** * Display the form for searching spam pages */ - function _searchform(){ + protected function printSearchForm() + { global $lang, $INPUT; echo '<form action="" method="post"><div class="no">'; echo '<label>'.$this->getLang('filter').': </label>'; @@ -73,31 +77,32 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin { /** * Start the reversion process */ - function _revert($revert,$filter){ + protected function revertEdits($revert, $filter) + { echo '<hr /><br />'; echo '<p>'.$this->getLang('revstart').'</p>'; echo '<ul>'; - foreach($revert as $id){ + foreach ($revert as $id) { global $REV; // find the last non-spammy revision $data = ''; $pagelog = new PageChangeLog($id); $old = $pagelog->getRevisions(0, $this->max_revs); - if(count($old)){ - foreach($old as $REV){ - $data = rawWiki($id,$REV); - if(strpos($data,$filter) === false) break; + if (count($old)) { + foreach ($old as $REV) { + $data = rawWiki($id, $REV); + if (strpos($data, $filter) === false) break; } } - if($data){ - saveWikiText($id,$data,'old revision restored',false); - printf('<li><div class="li">'.$this->getLang('reverted').'</div></li>',$id,$REV); - }else{ - saveWikiText($id,'','',false); - printf('<li><div class="li">'.$this->getLang('removed').'</div></li>',$id); + if ($data) { + saveWikiText($id, $data, 'old revision restored', false); + printf('<li><div class="li">'.$this->getLang('reverted').'</div></li>', $id, $REV); + } else { + saveWikiText($id, '', '', false); + printf('<li><div class="li">'.$this->getLang('removed').'</div></li>', $id); } @set_time_limit(10); flush(); @@ -110,7 +115,8 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin { /** * List recent edits matching the given filter */ - function _list($filter){ + protected function listEdits($filter) + { global $conf; global $lang; echo '<hr /><br />'; @@ -118,13 +124,13 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin { echo '<input type="hidden" name="filter" value="'.hsc($filter).'" />'; formSecurityToken(); - $recents = getRecents(0,$this->max_lines); + $recents = getRecents(0, $this->max_lines); echo '<ul>'; $cnt = 0; - foreach($recents as $recent){ - if($filter){ - if(strpos(rawWiki($recent['id']),$filter) === false) continue; + foreach ($recents as $recent) { + if ($filter) { + if (strpos(rawWiki($recent['id']), $filter) === false) continue; } $cnt++; @@ -132,10 +138,11 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin { echo ($recent['type']===DOKU_CHANGE_TYPE_MINOR_EDIT) ? '<li class="minor">' : '<li>'; echo '<div class="li">'; - echo '<input type="checkbox" name="revert[]" value="'.hsc($recent['id']).'" checked="checked" id="revert__'.$cnt.'" />'; + echo '<input type="checkbox" name="revert[]" value="'.hsc($recent['id']). + '" checked="checked" id="revert__'.$cnt.'" />'; echo ' <label for="revert__'.$cnt.'">'.$date.'</label> '; - echo '<a href="'.wl($recent['id'],"do=diff").'">'; + echo '<a href="'.wl($recent['id'], "do=diff").'">'; $p = array(); $p['src'] = DOKU_BASE.'lib/images/diff.png'; $p['width'] = 15; @@ -146,7 +153,7 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin { echo "<img $att />"; echo '</a> '; - echo '<a href="'.wl($recent['id'],"do=revisions").'">'; + echo '<a href="'.wl($recent['id'], "do=revisions").'">'; $p = array(); $p['src'] = DOKU_BASE.'lib/images/history.png'; $p['width'] = 12; @@ -157,7 +164,7 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin { echo "<img $att />"; echo '</a> '; - echo html_wikilink(':'.$recent['id'],(useHeading('navigation'))?null:$recent['id']); + echo html_wikilink(':'.$recent['id'], (useHeading('navigation'))?null:$recent['id']); echo ' – '.htmlspecialchars($recent['sum']); echo ' <span class="user">'; @@ -174,11 +181,10 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin { echo '<p>'; echo '<button type="submit">'.$this->getLang('revert').'</button> '; - printf($this->getLang('note2'),hsc($filter)); + printf($this->getLang('note2'), hsc($filter)); echo '</p>'; echo '</div></form>'; } - } //Setup VIM: ex: et ts=4 : diff --git a/lib/plugins/safefnrecode/action.php b/lib/plugins/safefnrecode/action.php index 9127f8df2..952d95c90 100644 --- a/lib/plugins/safefnrecode/action.php +++ b/lib/plugins/safefnrecode/action.php @@ -6,63 +6,63 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -// must be run within Dokuwiki -if (!defined('DOKU_INC')) die(); - -require_once DOKU_PLUGIN.'action.php'; - -class action_plugin_safefnrecode extends DokuWiki_Action_Plugin { - - public function register(Doku_Event_Handler $controller) { - - $controller->register_hook('INDEXER_TASKS_RUN', 'BEFORE', $this, 'handle_indexer_tasks_run'); +class action_plugin_safefnrecode extends DokuWiki_Action_Plugin +{ + /** @inheritdoc */ + public function register(Doku_Event_Handler $controller) + { + $controller->register_hook('INDEXER_TASKS_RUN', 'BEFORE', $this, 'handleIndexerTasksRun'); } - public function handle_indexer_tasks_run(Doku_Event &$event, $param) { + /** + * Handle indexer event + * + * @param Doku_Event $event + * @param $param + */ + public function handleIndexerTasksRun(Doku_Event $event, $param) + { global $conf; - if($conf['fnencode'] != 'safe') return; + if ($conf['fnencode'] != 'safe') return; - if(!file_exists($conf['datadir'].'_safefn.recoded')){ + if (!file_exists($conf['datadir'].'_safefn.recoded')) { $this->recode($conf['datadir']); touch($conf['datadir'].'_safefn.recoded'); } - if(!file_exists($conf['olddir'].'_safefn.recoded')){ + if (!file_exists($conf['olddir'].'_safefn.recoded')) { $this->recode($conf['olddir']); touch($conf['olddir'].'_safefn.recoded'); } - if(!file_exists($conf['metadir'].'_safefn.recoded')){ + if (!file_exists($conf['metadir'].'_safefn.recoded')) { $this->recode($conf['metadir']); touch($conf['metadir'].'_safefn.recoded'); } - if(!file_exists($conf['mediadir'].'_safefn.recoded')){ + if (!file_exists($conf['mediadir'].'_safefn.recoded')) { $this->recode($conf['mediadir']); touch($conf['mediadir'].'_safefn.recoded'); } - } /** * Recursive function to rename all safe encoded files to use the new * square bracket post indicator */ - private function recode($dir){ + private function recode($dir) + { $dh = opendir($dir); - if(!$dh) return; + if (!$dh) return; while (($file = readdir($dh)) !== false) { - if($file == '.' || $file == '..') continue; # cur and upper dir - if(is_dir("$dir/$file")) $this->recode("$dir/$file"); #recurse - if(strpos($file,'%') === false) continue; # no encoding used - $new = preg_replace('/(%[^\]]*?)\./','\1]',$file); # new post indicator - if(preg_match('/%[^\]]+$/',$new)) $new .= ']'; # fix end FS#2122 - rename("$dir/$file","$dir/$new"); # rename it + if ($file == '.' || $file == '..') continue; # cur and upper dir + if (is_dir("$dir/$file")) $this->recode("$dir/$file"); #recurse + if (strpos($file, '%') === false) continue; # no encoding used + $new = preg_replace('/(%[^\]]*?)\./', '\1]', $file); # new post indicator + if (preg_match('/%[^\]]+$/', $new)) $new .= ']'; # fix end FS#2122 + rename("$dir/$file", "$dir/$new"); # rename it } closedir($dh); } - } - -// vim:ts=4:sw=4:et: diff --git a/lib/plugins/styling/action.php b/lib/plugins/styling/action.php index 896e14bef..8b9db6979 100644 --- a/lib/plugins/styling/action.php +++ b/lib/plugins/styling/action.php @@ -5,19 +5,8 @@ * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Andreas Gohr <andi@splitbrain.org> */ - -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -/** - * Class action_plugin_styling - * - * This handles all the save actions and loading the interface - * - * All this usually would be done within an admin plugin, but we want to have this available outside - * the admin interface using our floating dialog. - */ -class action_plugin_styling extends DokuWiki_Action_Plugin { +class action_plugin_styling extends DokuWiki_Action_Plugin +{ /** * Registers a callback functions @@ -25,8 +14,9 @@ class action_plugin_styling extends DokuWiki_Action_Plugin { * @param Doku_Event_Handler $controller DokuWiki's event controller object * @return void */ - public function register(Doku_Event_Handler $controller) { - $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handle_header'); + public function register(Doku_Event_Handler $controller) + { + $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleHeader'); } /** @@ -37,24 +27,23 @@ class action_plugin_styling extends DokuWiki_Action_Plugin { * handler was registered] * @return void */ - public function handle_header(Doku_Event &$event, $param) { + public function handleHeader(Doku_Event &$event, $param) + { global $ACT; global $INPUT; - if($ACT != 'admin' || $INPUT->str('page') != 'styling') return; - if(!auth_isadmin()) return; + if ($ACT != 'admin' || $INPUT->str('page') != 'styling') return; + if (!auth_isadmin()) return; // set preview $len = count($event->data['link']); - for($i = 0; $i < $len; $i++) { - if( - $event->data['link'][$i]['rel'] == 'stylesheet' && + for ($i = 0; $i < $len; $i++) { + if ($event->data['link'][$i]['rel'] == 'stylesheet' && strpos($event->data['link'][$i]['href'], 'lib/exe/css.php') !== false ) { $event->data['link'][$i]['href'] .= '&preview=1&tseed='.time(); } } } - } // vim:ts=4:sw=4:et: diff --git a/lib/plugins/styling/admin.php b/lib/plugins/styling/admin.php index 055ac2279..2cc2618ca 100644 --- a/lib/plugins/styling/admin.php +++ b/lib/plugins/styling/admin.php @@ -5,45 +5,46 @@ * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Andreas Gohr <andi@splitbrain.org> */ - -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -class admin_plugin_styling extends DokuWiki_Admin_Plugin { +class admin_plugin_styling extends DokuWiki_Admin_Plugin +{ public $ispopup = false; /** * @return int sort number in admin menu */ - public function getMenuSort() { + public function getMenuSort() + { return 1000; } /** * @return bool true if only access for superuser, false is for superusers and moderators */ - public function forAdminOnly() { + public function forAdminOnly() + { return true; } /** * handle the different actions (also called from ajax) */ - public function handle() { + public function handle() + { global $INPUT; $run = $INPUT->extract('run')->str('run'); - if(!$run) return; - $run = "run_$run"; + if (!$run) return; + $run = 'run'.ucfirst($run); $this->$run(); } /** * Render HTML output, e.g. helpful text and a form */ - public function html() { + public function html() + { $class = 'nopopup'; - if($this->ispopup) $class = 'ispopup page'; + if ($this->ispopup) $class = 'ispopup page'; echo '<div id="plugin__styling" class="'.$class.'">'; ptln('<h1>'.$this->getLang('menu').'</h1>'); @@ -54,7 +55,8 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { /** * Create the actual editing form */ - public function form() { + public function form() + { global $conf; global $ID; @@ -62,13 +64,13 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { $styleini = $styleUtil->cssStyleini($conf['template'], true); $replacements = $styleini['replacements']; - if($this->ispopup) { + if ($this->ispopup) { $target = DOKU_BASE.'lib/plugins/styling/popup.php'; } else { $target = wl($ID, array('do' => 'admin', 'page' => 'styling')); } - if(empty($replacements)) { + if (empty($replacements)) { echo '<p class="error">'.$this->getLang('error').'</p>'; } else { echo $this->locale_xhtml('intro'); @@ -76,21 +78,24 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { echo '<form class="styling" method="post" action="'.$target.'">'; echo '<table><tbody>'; - foreach($replacements as $key => $value) { + foreach ($replacements as $key => $value) { $name = tpl_getLang($key); - if(empty($name)) $name = $this->getLang($key); - if(empty($name)) $name = $key; + if (empty($name)) $name = $this->getLang($key); + if (empty($name)) $name = $key; echo '<tr>'; echo '<td><label for="tpl__'.hsc($key).'">'.$name.'</label></td>'; - echo '<td><input type="text" name="tpl['.hsc($key).']" id="tpl__'.hsc($key).'" value="'.hsc($value).'" '.$this->colorClass($key).' dir="ltr" /></td>'; + echo '<td><input type="text" name="tpl['.hsc($key).']" id="tpl__'.hsc($key).'" + value="'.hsc($value).'" '.$this->colorClass($key).' dir="ltr" /></td>'; echo '</tr>'; } echo '</tbody></table>'; echo '<p>'; - echo '<button type="submit" name="run[preview]" class="btn_preview primary">'.$this->getLang('btn_preview').'</button> '; - echo '<button type="submit" name="run[reset]">'.$this->getLang('btn_reset').'</button>'; #FIXME only if preview.ini exists + echo '<button type="submit" name="run[preview]" class="btn_preview primary">'. + $this->getLang('btn_preview').'</button> '; + #FIXME only if preview.ini exists: + echo '<button type="submit" name="run[reset]">'.$this->getLang('btn_reset').'</button>'; echo '</p>'; echo '<p>'; @@ -98,20 +103,21 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { echo '</p>'; echo '<p>'; - echo '<button type="submit" name="run[revert]">'.$this->getLang('btn_revert').'</button>'; #FIXME only if local.ini exists + #FIXME only if local.ini exists: + echo '<button type="submit" name="run[revert]">'.$this->getLang('btn_revert').'</button>'; echo '</p>'; echo '</form>'; echo tpl_locale_xhtml('style'); - } } /** * set the color class attribute */ - protected function colorClass($key) { + protected function colorClass($key) + { static $colors = array( 'text', 'background', @@ -127,7 +133,7 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { 'missing', ); - if(preg_match('/colou?r/', $key) || in_array(trim($key,'_'), $colors)) { + if (preg_match('/colou?r/', $key) || in_array(trim($key, '_'), $colors)) { return 'class="color"'; } else { return ''; @@ -137,7 +143,8 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { /** * saves the preview.ini (alos called from ajax directly) */ - public function run_preview() { + public function runPreview() + { global $conf; $ini = $conf['cachedir'].'/preview.ini'; io_saveFile($ini, $this->makeini()); @@ -146,7 +153,8 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { /** * deletes the preview.ini */ - protected function run_reset() { + protected function runReset() + { global $conf; $ini = $conf['cachedir'].'/preview.ini'; io_saveFile($ini, ''); @@ -155,17 +163,19 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { /** * deletes the local style.ini replacements */ - protected function run_revert() { - $this->replaceini(''); - $this->run_reset(); + protected function runRevert() + { + $this->replaceIni(''); + $this->runReset(); } /** * save the local style.ini replacements */ - protected function run_save() { - $this->replaceini($this->makeini()); - $this->run_reset(); + protected function runSave() + { + $this->replaceIni($this->makeini()); + $this->runReset(); } /** @@ -173,13 +183,14 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { * * @return string */ - protected function makeini() { + protected function makeini() + { global $INPUT; $ini = "[replacements]\n"; $ini .= ";These overwrites have been generated from the Template styling Admin interface\n"; $ini .= ";Any values in this section will be overwritten by that tool again\n"; - foreach($INPUT->arr('tpl') as $key => $val) { + foreach ($INPUT->arr('tpl') as $key => $val) { $ini .= $key.' = "'.addslashes($val).'"'."\n"; } @@ -191,10 +202,11 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { * * @param string $new the new ini contents */ - protected function replaceini($new) { + protected function replaceIni($new) + { global $conf; $ini = DOKU_CONF."tpl/".$conf['template']."/style.ini"; - if(file_exists($ini)) { + if (file_exists($ini)) { $old = io_readFile($ini); $old = preg_replace('/\[replacements\]\n.*?(\n\[.*]|$)/s', '\\1', $old); $old = trim($old); @@ -205,7 +217,6 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin { io_makeFileDir($ini); io_saveFile($ini, "$old\n\n$new"); } - } // vim:ts=4:sw=4:et: diff --git a/lib/plugins/styling/popup.php b/lib/plugins/styling/popup.php index 964b19e29..b78f1af06 100644 --- a/lib/plugins/styling/popup.php +++ b/lib/plugins/styling/popup.php @@ -1,5 +1,6 @@ <?php -if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__) . '/../../../'); +// phpcs:disable PSR1.Files.SideEffects +if (!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__) . '/../../../'); require_once(DOKU_INC . 'inc/init.php'); //close session session_write_close(); @@ -8,7 +9,7 @@ header('X-UA-Compatible: IE=edge,chrome=1'); /** @var admin_plugin_styling $plugin */ $plugin = plugin_load('admin', 'styling'); -if(!auth_isadmin()) die('only admins allowed'); +if (!auth_isadmin()) die('only admins allowed'); $plugin->ispopup = true; // handle posts diff --git a/lib/plugins/syntax.php b/lib/plugins/syntax.php index 9e2913d78..b74bb5bf0 100644 --- a/lib/plugins/syntax.php +++ b/lib/plugins/syntax.php @@ -2,42 +2,36 @@ /** * Syntax Plugin Prototype * - * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) - * @author Andreas Gohr <andi@splitbrain.org> - */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -/** * All DokuWiki plugins to extend the parser/rendering mechanism * need to inherit from this class + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> */ -class DokuWiki_Syntax_Plugin extends Doku_Parser_Mode_Plugin { +abstract class DokuWiki_Syntax_Plugin extends \dokuwiki\Parsing\ParserMode\Plugin { + use DokuWiki_PluginTrait; - var $allowedModesSetup = false; + protected $allowedModesSetup = false; /** * Syntax Type * - * Needs to return one of the mode types defined in $PARSER_MODES in parser.php + * Needs to return one of the mode types defined in $PARSER_MODES in Parser.php * * @return string */ - function getType(){ - trigger_error('getType() not implemented in '.get_class($this), E_USER_WARNING); - return ''; - } + abstract public function getType(); /** * Allowed Mode Types * * Defines the mode types for other dokuwiki markup that maybe nested within the * plugin's own markup. Needs to return an array of one or more of the mode types - * defined in $PARSER_MODES in parser.php + * defined in $PARSER_MODES in Parser.php * * @return array */ - function getAllowedTypes() { + public function getAllowedTypes() { return array(); } @@ -55,7 +49,7 @@ class DokuWiki_Syntax_Plugin extends Doku_Parser_Mode_Plugin { * * @return string */ - function getPType(){ + public function getPType(){ return 'normal'; } @@ -73,9 +67,7 @@ class DokuWiki_Syntax_Plugin extends Doku_Parser_Mode_Plugin { * @param Doku_Handler $handler The Doku_Handler object * @return bool|array Return an array with all data you want to use in render, false don't add an instruction */ - function handle($match, $state, $pos, Doku_Handler $handler){ - trigger_error('handle() not implemented in '.get_class($this), E_USER_WARNING); - } + abstract public function handle($match, $state, $pos, Doku_Handler $handler); /** * Handles the actual output creation. @@ -100,10 +92,7 @@ class DokuWiki_Syntax_Plugin extends Doku_Parser_Mode_Plugin { * @param array $data data created by handler() * @return boolean rendered correctly? (however, returned value is not used at the moment) */ - function render($format, Doku_Renderer $renderer, $data) { - trigger_error('render() not implemented in '.get_class($this), E_USER_WARNING); - - } + abstract public function render($format, Doku_Renderer $renderer, $data); /** * There should be no need to override this function @@ -111,7 +100,7 @@ class DokuWiki_Syntax_Plugin extends Doku_Parser_Mode_Plugin { * @param string $mode * @return bool */ - function accepts($mode) { + public function accepts($mode) { if (!$this->allowedModesSetup) { global $PARSER_MODES; diff --git a/lib/plugins/testing/action.php b/lib/plugins/testing/action.php index a242ab0b7..d34ef1858 100644 --- a/lib/plugins/testing/action.php +++ b/lib/plugins/testing/action.php @@ -8,11 +8,12 @@ */ class action_plugin_testing extends DokuWiki_Action_Plugin { - function register(Doku_Event_Handler $controller) { + /** @inheritdoc */ + public function register(Doku_Event_Handler $controller) { $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'dokuwikiStarted'); } - function dokuwikiStarted() { + public function dokuwikiStarted() { $param = array(); trigger_event('TESTING_PLUGIN_INSTALLED', $param); msg('The testing plugin is enabled and should be disabled.',-1); diff --git a/lib/plugins/usermanager/_test/mocks.class.php b/lib/plugins/usermanager/_test/mocks.class.php index e524e451b..75ac51422 100644 --- a/lib/plugins/usermanager/_test/mocks.class.php +++ b/lib/plugins/usermanager/_test/mocks.class.php @@ -16,30 +16,30 @@ class admin_mock_usermanager extends admin_plugin_usermanager { public $lang; public function getImportFailures() { - return $this->_import_failures; + return $this->import_failures; } public function tryExport() { ob_start(); - $this->_export(); + $this->exportCSV(); return ob_get_clean(); } public function tryImport() { - return $this->_import(); + return $this->importCSV(); } // no need to send email notifications (mostly) - protected function _notifyUser($user, $password, $status_alert=true) { + protected function notifyUser($user, $password, $status_alert=true) { if ($this->mock_email_notifications) { $this->mock_email_notifications_sent++; return true; } else { - return parent::_notifyUser($user, $password, $status_alert); + return parent::notifyUser($user, $password, $status_alert); } } - protected function _isUploadedFile($file) { + protected function isUploadedFile($file) { return file_exists($file); } } diff --git a/lib/plugins/usermanager/admin.php b/lib/plugins/usermanager/admin.php index 6d9bf3b20..8e5670db3 100644 --- a/lib/plugins/usermanager/admin.php +++ b/lib/plugins/usermanager/admin.php @@ -10,52 +10,49 @@ * @author neolao <neolao@neolao.com> * @author Chris Smith <chris@jalakai.co.uk> */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); - -if(!defined('DOKU_PLUGIN_IMAGES')) define('DOKU_PLUGIN_IMAGES',DOKU_BASE.'lib/plugins/usermanager/images/'); /** * All DokuWiki plugins to extend the admin function * need to inherit from this class */ -class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { - - protected $_auth = null; // auth object - protected $_user_total = 0; // number of registered users - protected $_filter = array(); // user selection filter(s) - protected $_start = 0; // index of first user to be displayed - protected $_last = 0; // index of the last user to be displayed - protected $_pagesize = 20; // number of users to list on one page - protected $_edit_user = ''; // set to user selected for editing - protected $_edit_userdata = array(); - protected $_disabled = ''; // if disabled set to explanatory string - protected $_import_failures = array(); - protected $_lastdisabled = false; // set to true if last user is unknown and last button is hence buggy +class admin_plugin_usermanager extends DokuWiki_Admin_Plugin +{ + const IMAGE_DIR = DOKU_BASE.'lib/plugins/usermanager/images/'; + + protected $auth = null; // auth object + protected $users_total = 0; // number of registered users + protected $filter = array(); // user selection filter(s) + protected $start = 0; // index of first user to be displayed + protected $last = 0; // index of the last user to be displayed + protected $pagesize = 20; // number of users to list on one page + protected $edit_user = ''; // set to user selected for editing + protected $edit_userdata = array(); + protected $disabled = ''; // if disabled set to explanatory string + protected $import_failures = array(); + protected $lastdisabled = false; // set to true if last user is unknown and last button is hence buggy /** * Constructor */ - public function __construct(){ + public function __construct() + { /** @var DokuWiki_Auth_Plugin $auth */ global $auth; $this->setupLocale(); if (!isset($auth)) { - $this->_disabled = $this->lang['noauth']; - } else if (!$auth->canDo('getUsers')) { - $this->_disabled = $this->lang['nosupport']; + $this->disabled = $this->lang['noauth']; + } elseif (!$auth->canDo('getUsers')) { + $this->disabled = $this->lang['nosupport']; } else { - // we're good to go - $this->_auth = & $auth; - + $this->auth = & $auth; } // attempt to retrieve any import failures from the session - if (!empty($_SESSION['import_failures'])){ - $this->_import_failures = $_SESSION['import_failures']; + if (!empty($_SESSION['import_failures'])) { + $this->import_failures = $_SESSION['import_failures']; } } @@ -65,12 +62,13 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param string $language * @return string */ - public function getMenuText($language) { + public function getMenuText($language) + { - if (!is_null($this->_auth)) + if (!is_null($this->auth)) return parent::getMenuText($language); - return $this->getLang('menu').' '.$this->_disabled; + return $this->getLang('menu').' '.$this->disabled; } /** @@ -78,29 +76,33 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return int */ - public function getMenuSort() { + public function getMenuSort() + { return 2; } /** * @return int current start value for pageination */ - public function getStart() { - return $this->_start; + public function getStart() + { + return $this->start; } /** * @return int number of users per page */ - public function getPagesize() { - return $this->_pagesize; + public function getPagesize() + { + return $this->pagesize; } /** * @param boolean $lastdisabled */ - public function setLastdisabled($lastdisabled) { - $this->_lastdisabled = $lastdisabled; + public function setLastdisabled($lastdisabled) + { + $this->lastdisabled = $lastdisabled; } /** @@ -108,9 +110,10 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return bool */ - public function handle() { + public function handle() + { global $INPUT; - if (is_null($this->_auth)) return false; + if (is_null($this->auth)) return false; // extract the command and any specific parameters // submit button name is of the form - fn[cmd][param(s)] @@ -125,33 +128,56 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { } if ($cmd != "search") { - $this->_start = $INPUT->int('start', 0); - $this->_filter = $this->_retrieveFilter(); + $this->start = $INPUT->int('start', 0); + $this->filter = $this->retrieveFilter(); } - switch($cmd){ - case "add" : $this->_addUser(); break; - case "delete" : $this->_deleteUser(); break; - case "modify" : $this->_modifyUser(); break; - case "edit" : $this->_editUser($param); break; - case "search" : $this->_setFilter($param); - $this->_start = 0; - break; - case "export" : $this->_export(); break; - case "import" : $this->_import(); break; - case "importfails" : $this->_downloadImportFailures(); break; + switch ($cmd) { + case "add": + $this->addUser(); + break; + case "delete": + $this->deleteUser(); + break; + case "modify": + $this->modifyUser(); + break; + case "edit": + $this->editUser($param); + break; + case "search": + $this->setFilter($param); + $this->start = 0; + break; + case "export": + $this->exportCSV(); + break; + case "import": + $this->importCSV(); + break; + case "importfails": + $this->downloadImportFailures(); + break; } - $this->_user_total = $this->_auth->canDo('getUserCount') ? $this->_auth->getUserCount($this->_filter) : -1; + $this->users_total = $this->auth->canDo('getUserCount') ? $this->auth->getUserCount($this->filter) : -1; // page handling - switch($cmd){ - case 'start' : $this->_start = 0; break; - case 'prev' : $this->_start -= $this->_pagesize; break; - case 'next' : $this->_start += $this->_pagesize; break; - case 'last' : $this->_start = $this->_user_total; break; + switch ($cmd) { + case 'start': + $this->start = 0; + break; + case 'prev': + $this->start -= $this->pagesize; + break; + case 'next': + $this->start += $this->pagesize; + break; + case 'last': + $this->start = $this->users_total; + break; } - $this->_validatePagination(); + $this->validatePagination(); return true; } @@ -160,21 +186,22 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return bool */ - public function html() { + public function html() + { global $ID; - if(is_null($this->_auth)) { + if (is_null($this->auth)) { print $this->lang['badauth']; return false; } - $user_list = $this->_auth->retrieveUsers($this->_start, $this->_pagesize, $this->_filter); + $user_list = $this->auth->retrieveUsers($this->start, $this->pagesize, $this->filter); - $page_buttons = $this->_pagination(); - $delete_disable = $this->_auth->canDo('delUser') ? '' : 'disabled="disabled"'; + $page_buttons = $this->pagination(); + $delete_disable = $this->auth->canDo('delUser') ? '' : 'disabled="disabled"'; - $editable = $this->_auth->canDo('UserMod'); - $export_label = empty($this->_filter) ? $this->lang['export_all'] : $this->lang['export_filtered']; + $editable = $this->auth->canDo('UserMod'); + $export_label = empty($this->filter) ? $this->lang['export_all'] : $this->lang['export_filtered']; print $this->locale_xhtml('intro'); print $this->locale_xhtml('list'); @@ -182,13 +209,21 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { ptln("<div id=\"user__manager\">"); ptln("<div class=\"level2\">"); - if ($this->_user_total > 0) { - ptln("<p>".sprintf($this->lang['summary'],$this->_start+1,$this->_last,$this->_user_total,$this->_auth->getUserCount())."</p>"); + if ($this->users_total > 0) { + ptln( + "<p>" . sprintf( + $this->lang['summary'], + $this->start + 1, + $this->last, + $this->users_total, + $this->auth->getUserCount() + ) . "</p>" + ); } else { - if($this->_user_total < 0) { + if ($this->users_total < 0) { $allUserTotal = 0; } else { - $allUserTotal = $this->_auth->getUserCount(); + $allUserTotal = $this->auth->getUserCount(); } ptln("<p>".sprintf($this->lang['nonefound'], $allUserTotal)."</p>"); } @@ -198,19 +233,29 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { ptln(" <table class=\"inline\">"); ptln(" <thead>"); ptln(" <tr>"); - ptln(" <th> </th><th>".$this->lang["user_id"]."</th><th>".$this->lang["user_name"]."</th><th>".$this->lang["user_mail"]."</th><th>".$this->lang["user_groups"]."</th>"); + ptln(" <th> </th> + <th>".$this->lang["user_id"]."</th> + <th>".$this->lang["user_name"]."</th> + <th>".$this->lang["user_mail"]."</th> + <th>".$this->lang["user_groups"]."</th>"); ptln(" </tr>"); ptln(" <tr>"); - ptln(" <td class=\"rightalign\"><input type=\"image\" src=\"".DOKU_PLUGIN_IMAGES."search.png\" name=\"fn[search][new]\" title=\"".$this->lang['search_prompt']."\" alt=\"".$this->lang['search']."\" class=\"button\" /></td>"); - ptln(" <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"".$this->_htmlFilter('user')."\" /></td>"); - ptln(" <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"".$this->_htmlFilter('name')."\" /></td>"); - ptln(" <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"".$this->_htmlFilter('mail')."\" /></td>"); - ptln(" <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"".$this->_htmlFilter('grps')."\" /></td>"); + ptln(" <td class=\"rightalign\"><input type=\"image\" src=\"". + self::IMAGE_DIR."search.png\" name=\"fn[search][new]\" title=\"". + $this->lang['search_prompt']."\" alt=\"".$this->lang['search']."\" class=\"button\" /></td>"); + ptln(" <td><input type=\"text\" name=\"userid\" class=\"edit\" value=\"". + $this->htmlFilter('user')."\" /></td>"); + ptln(" <td><input type=\"text\" name=\"username\" class=\"edit\" value=\"". + $this->htmlFilter('name')."\" /></td>"); + ptln(" <td><input type=\"text\" name=\"usermail\" class=\"edit\" value=\"". + $this->htmlFilter('mail')."\" /></td>"); + ptln(" <td><input type=\"text\" name=\"usergroups\" class=\"edit\" value=\"". + $this->htmlFilter('grps')."\" /></td>"); ptln(" </tr>"); ptln(" </thead>"); - if ($this->_user_total) { + if ($this->users_total) { ptln(" <tbody>"); foreach ($user_list as $user => $userinfo) { extract($userinfo); @@ -220,11 +265,12 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @var string $mail * @var array $grps */ - $groups = join(', ',$grps); + $groups = join(', ', $grps); ptln(" <tr class=\"user_info\">"); - ptln(" <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".hsc($user)."]\" ".$delete_disable." /></td>"); + ptln(" <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".hsc($user). + "]\" ".$delete_disable." /></td>"); if ($editable) { - ptln(" <td><a href=\"".wl($ID,array('fn[edit]['.$user.']' => 1, + ptln(" <td><a href=\"".wl($ID, array('fn[edit]['.$user.']' => 1, 'do' => 'admin', 'page' => 'usermanager', 'sectok' => getSecurityToken())). @@ -241,22 +287,27 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { ptln(" <tbody>"); ptln(" <tr><td colspan=\"5\" class=\"centeralign\">"); ptln(" <span class=\"medialeft\">"); - ptln(" <button type=\"submit\" name=\"fn[delete]\" id=\"usrmgr__del\" ".$delete_disable.">".$this->lang['delete_selected']."</button>"); + ptln(" <button type=\"submit\" name=\"fn[delete]\" id=\"usrmgr__del\" ".$delete_disable.">". + $this->lang['delete_selected']."</button>"); ptln(" </span>"); ptln(" <span class=\"mediaright\">"); - ptln(" <button type=\"submit\" name=\"fn[start]\" ".$page_buttons['start'].">".$this->lang['start']."</button>"); - ptln(" <button type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev'].">".$this->lang['prev']."</button>"); - ptln(" <button type=\"submit\" name=\"fn[next]\" ".$page_buttons['next'].">".$this->lang['next']."</button>"); - ptln(" <button type=\"submit\" name=\"fn[last]\" ".$page_buttons['last'].">".$this->lang['last']."</button>"); + ptln(" <button type=\"submit\" name=\"fn[start]\" ".$page_buttons['start'].">". + $this->lang['start']."</button>"); + ptln(" <button type=\"submit\" name=\"fn[prev]\" ".$page_buttons['prev'].">". + $this->lang['prev']."</button>"); + ptln(" <button type=\"submit\" name=\"fn[next]\" ".$page_buttons['next'].">". + $this->lang['next']."</button>"); + ptln(" <button type=\"submit\" name=\"fn[last]\" ".$page_buttons['last'].">". + $this->lang['last']."</button>"); ptln(" </span>"); - if (!empty($this->_filter)) { + if (!empty($this->filter)) { ptln(" <button type=\"submit\" name=\"fn[search][clear]\">".$this->lang['clear']."</button>"); } ptln(" <button type=\"submit\" name=\"fn[export]\">".$export_label."</button>"); ptln(" <input type=\"hidden\" name=\"do\" value=\"admin\" />"); ptln(" <input type=\"hidden\" name=\"page\" value=\"usermanager\" />"); - $this->_htmlFilterSettings(2); + $this->htmlFilterSettings(2); ptln(" </td></tr>"); ptln(" </tbody>"); @@ -266,32 +317,32 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { ptln("</form>"); ptln("</div>"); - $style = $this->_edit_user ? " class=\"edit_user\"" : ""; + $style = $this->edit_user ? " class=\"edit_user\"" : ""; - if ($this->_auth->canDo('addUser')) { + if ($this->auth->canDo('addUser')) { ptln("<div".$style.">"); print $this->locale_xhtml('add'); ptln(" <div class=\"level2\">"); - $this->_htmlUserForm('add',null,array(),4); + $this->htmlUserForm('add', null, array(), 4); ptln(" </div>"); ptln("</div>"); } - if($this->_edit_user && $this->_auth->canDo('UserMod')){ + if ($this->edit_user && $this->auth->canDo('UserMod')) { ptln("<div".$style." id=\"scroll__here\">"); print $this->locale_xhtml('edit'); ptln(" <div class=\"level2\">"); - $this->_htmlUserForm('modify',$this->_edit_user,$this->_edit_userdata,4); + $this->htmlUserForm('modify', $this->edit_user, $this->edit_userdata, 4); ptln(" </div>"); ptln("</div>"); } - if ($this->_auth->canDo('addUser')) { - $this->_htmlImportForm(); + if ($this->auth->canDo('addUser')) { + $this->htmlImportForm(); } ptln("</div>"); return true; @@ -305,7 +356,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param array $userdata array with name, mail, pass and grps * @param int $indent */ - protected function _htmlUserForm($cmd,$user='',$userdata=array(),$indent=0) { + protected function htmlUserForm($cmd, $user = '', $userdata = array(), $indent = 0) + { global $conf; global $ID; global $lang; @@ -315,28 +367,76 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { if ($user) { extract($userdata); - if (!empty($grps)) $groups = join(',',$grps); + if (!empty($grps)) $groups = join(',', $grps); } else { - $notes[] = sprintf($this->lang['note_group'],$conf['defaultgroup']); + $notes[] = sprintf($this->lang['note_group'], $conf['defaultgroup']); } - ptln("<form action=\"".wl($ID)."\" method=\"post\">",$indent); + ptln("<form action=\"".wl($ID)."\" method=\"post\">", $indent); formSecurityToken(); - ptln(" <div class=\"table\">",$indent); - ptln(" <table class=\"inline\">",$indent); - ptln(" <thead>",$indent); - ptln(" <tr><th>".$this->lang["field"]."</th><th>".$this->lang["value"]."</th></tr>",$indent); - ptln(" </thead>",$indent); - ptln(" <tbody>",$indent); - - $this->_htmlInputField($cmd."_userid", "userid", $this->lang["user_id"], $user, $this->_auth->canDo("modLogin"), true, $indent+6); - $this->_htmlInputField($cmd."_userpass", "userpass", $this->lang["user_pass"], "", $this->_auth->canDo("modPass"), false, $indent+6); - $this->_htmlInputField($cmd."_userpass2", "userpass2", $lang["passchk"], "", $this->_auth->canDo("modPass"), false, $indent+6); - $this->_htmlInputField($cmd."_username", "username", $this->lang["user_name"], $name, $this->_auth->canDo("modName"), true, $indent+6); - $this->_htmlInputField($cmd."_usermail", "usermail", $this->lang["user_mail"], $mail, $this->_auth->canDo("modMail"), true, $indent+6); - $this->_htmlInputField($cmd."_usergroups","usergroups",$this->lang["user_groups"],$groups,$this->_auth->canDo("modGroups"), false, $indent+6); - - if ($this->_auth->canDo("modPass")) { + ptln(" <div class=\"table\">", $indent); + ptln(" <table class=\"inline\">", $indent); + ptln(" <thead>", $indent); + ptln(" <tr><th>".$this->lang["field"]."</th><th>".$this->lang["value"]."</th></tr>", $indent); + ptln(" </thead>", $indent); + ptln(" <tbody>", $indent); + + $this->htmlInputField( + $cmd . "_userid", + "userid", + $this->lang["user_id"], + $user, + $this->auth->canDo("modLogin"), + true, + $indent + 6 + ); + $this->htmlInputField( + $cmd . "_userpass", + "userpass", + $this->lang["user_pass"], + "", + $this->auth->canDo("modPass"), + false, + $indent + 6 + ); + $this->htmlInputField( + $cmd . "_userpass2", + "userpass2", + $lang["passchk"], + "", + $this->auth->canDo("modPass"), + false, + $indent + 6 + ); + $this->htmlInputField( + $cmd . "_username", + "username", + $this->lang["user_name"], + $name, + $this->auth->canDo("modName"), + true, + $indent + 6 + ); + $this->htmlInputField( + $cmd . "_usermail", + "usermail", + $this->lang["user_mail"], + $mail, + $this->auth->canDo("modMail"), + true, + $indent + 6 + ); + $this->htmlInputField( + $cmd . "_usergroups", + "usergroups", + $this->lang["user_groups"], + $groups, + $this->auth->canDo("modGroups"), + false, + $indent + 6 + ); + + if ($this->auth->canDo("modPass")) { if ($cmd == 'add') { $notes[] = $this->lang['note_pass']; } @@ -344,37 +444,40 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { $notes[] = $this->lang['note_notify']; } - ptln("<tr><td><label for=\"".$cmd."_usernotify\" >".$this->lang["user_notify"].": </label></td><td><input type=\"checkbox\" id=\"".$cmd."_usernotify\" name=\"usernotify\" value=\"1\" /></td></tr>", $indent); + ptln("<tr><td><label for=\"".$cmd."_usernotify\" >". + $this->lang["user_notify"].": </label></td> + <td><input type=\"checkbox\" id=\"".$cmd."_usernotify\" name=\"usernotify\" value=\"1\" /> + </td></tr>", $indent); } - ptln(" </tbody>",$indent); - ptln(" <tbody>",$indent); - ptln(" <tr>",$indent); - ptln(" <td colspan=\"2\">",$indent); - ptln(" <input type=\"hidden\" name=\"do\" value=\"admin\" />",$indent); - ptln(" <input type=\"hidden\" name=\"page\" value=\"usermanager\" />",$indent); + ptln(" </tbody>", $indent); + ptln(" <tbody>", $indent); + ptln(" <tr>", $indent); + ptln(" <td colspan=\"2\">", $indent); + ptln(" <input type=\"hidden\" name=\"do\" value=\"admin\" />", $indent); + ptln(" <input type=\"hidden\" name=\"page\" value=\"usermanager\" />", $indent); // save current $user, we need this to access details if the name is changed if ($user) - ptln(" <input type=\"hidden\" name=\"userid_old\" value=\"".hsc($user)."\" />",$indent); + ptln(" <input type=\"hidden\" name=\"userid_old\" value=\"".hsc($user)."\" />", $indent); - $this->_htmlFilterSettings($indent+10); + $this->htmlFilterSettings($indent+10); - ptln(" <button type=\"submit\" name=\"fn[".$cmd."]\">".$this->lang[$cmd]."</button>",$indent); - ptln(" </td>",$indent); - ptln(" </tr>",$indent); - ptln(" </tbody>",$indent); - ptln(" </table>",$indent); + ptln(" <button type=\"submit\" name=\"fn[".$cmd."]\">".$this->lang[$cmd]."</button>", $indent); + ptln(" </td>", $indent); + ptln(" </tr>", $indent); + ptln(" </tbody>", $indent); + ptln(" </table>", $indent); if ($notes) { ptln(" <ul class=\"notes\">"); foreach ($notes as $note) { - ptln(" <li><span class=\"li\">".$note."</li>",$indent); + ptln(" <li><span class=\"li\">".$note."</li>", $indent); } ptln(" </ul>"); } - ptln(" </div>",$indent); - ptln("</form>",$indent); + ptln(" </div>", $indent); + ptln("</form>", $indent); } /** @@ -388,17 +491,18 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param bool $required is this field required? * @param int $indent */ - protected function _htmlInputField($id, $name, $label, $value, $cando, $required, $indent=0) { + protected function htmlInputField($id, $name, $label, $value, $cando, $required, $indent = 0) + { $class = $cando ? '' : ' class="disabled"'; - echo str_pad('',$indent); + echo str_pad('', $indent); - if($name == 'userpass' || $name == 'userpass2'){ + if ($name == 'userpass' || $name == 'userpass2') { $fieldtype = 'password'; $autocomp = 'autocomplete="off"'; - }elseif($name == 'usermail'){ + } elseif ($name == 'usermail') { $fieldtype = 'email'; $autocomp = ''; - }else{ + } else { $fieldtype = 'text'; $autocomp = ''; } @@ -407,13 +511,15 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { echo "<tr $class>"; echo "<td><label for=\"$id\" >$label: </label></td>"; echo "<td>"; - if($cando){ + if ($cando) { $req = ''; - if($required) $req = 'required="required"'; - echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit\" $autocomp $req />"; - }else{ + if ($required) $req = 'required="required"'; + echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" + value=\"$value\" class=\"edit\" $autocomp $req />"; + } else { echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />"; - echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />"; + echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" + value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />"; } echo "</td>"; echo "</tr>"; @@ -425,9 +531,10 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param string $key name of search field * @return string html escaped value */ - protected function _htmlFilter($key) { - if (empty($this->_filter)) return ''; - return (isset($this->_filter[$key]) ? hsc($this->_filter[$key]) : ''); + protected function htmlFilter($key) + { + if (empty($this->filter)) return ''; + return (isset($this->filter[$key]) ? hsc($this->filter[$key]) : ''); } /** @@ -435,12 +542,13 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @param int $indent */ - protected function _htmlFilterSettings($indent=0) { + protected function htmlFilterSettings($indent = 0) + { - ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->_start."\" />",$indent); + ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->start."\" />", $indent); - foreach ($this->_filter as $key => $filter) { - ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />",$indent); + foreach ($this->filter as $key => $filter) { + ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />", $indent); } } @@ -449,57 +557,57 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @param int $indent */ - protected function _htmlImportForm($indent=0) { + protected function htmlImportForm($indent = 0) + { global $ID; - $failure_download_link = wl($ID,array('do'=>'admin','page'=>'usermanager','fn[importfails]'=>1)); + $failure_download_link = wl($ID, array('do'=>'admin','page'=>'usermanager','fn[importfails]'=>1)); - ptln('<div class="level2 import_users">',$indent); + ptln('<div class="level2 import_users">', $indent); print $this->locale_xhtml('import'); - ptln(' <form action="'.wl($ID).'" method="post" enctype="multipart/form-data">',$indent); + ptln(' <form action="'.wl($ID).'" method="post" enctype="multipart/form-data">', $indent); formSecurityToken(); - ptln(' <label>'.$this->lang['import_userlistcsv'].'<input type="file" name="import" /></label>',$indent); - ptln(' <button type="submit" name="fn[import]">'.$this->lang['import'].'</button>',$indent); - ptln(' <input type="hidden" name="do" value="admin" />',$indent); - ptln(' <input type="hidden" name="page" value="usermanager" />',$indent); + ptln(' <label>'.$this->lang['import_userlistcsv'].'<input type="file" name="import" /></label>', $indent); + ptln(' <button type="submit" name="fn[import]">'.$this->lang['import'].'</button>', $indent); + ptln(' <input type="hidden" name="do" value="admin" />', $indent); + ptln(' <input type="hidden" name="page" value="usermanager" />', $indent); - $this->_htmlFilterSettings($indent+4); - ptln(' </form>',$indent); + $this->htmlFilterSettings($indent+4); + ptln(' </form>', $indent); ptln('</div>'); // list failures from the previous import - if ($this->_import_failures) { - $digits = strlen(count($this->_import_failures)); - ptln('<div class="level3 import_failures">',$indent); + if ($this->import_failures) { + $digits = strlen(count($this->import_failures)); + ptln('<div class="level3 import_failures">', $indent); ptln(' <h3>'.$this->lang['import_header'].'</h3>'); - ptln(' <table class="import_failures">',$indent); - ptln(' <thead>',$indent); - ptln(' <tr>',$indent); - ptln(' <th class="line">'.$this->lang['line'].'</th>',$indent); - ptln(' <th class="error">'.$this->lang['error'].'</th>',$indent); - ptln(' <th class="userid">'.$this->lang['user_id'].'</th>',$indent); - ptln(' <th class="username">'.$this->lang['user_name'].'</th>',$indent); - ptln(' <th class="usermail">'.$this->lang['user_mail'].'</th>',$indent); - ptln(' <th class="usergroups">'.$this->lang['user_groups'].'</th>',$indent); - ptln(' </tr>',$indent); - ptln(' </thead>',$indent); - ptln(' <tbody>',$indent); - foreach ($this->_import_failures as $line => $failure) { - ptln(' <tr>',$indent); - ptln(' <td class="lineno"> '.sprintf('%0'.$digits.'d',$line).' </td>',$indent); + ptln(' <table class="import_failures">', $indent); + ptln(' <thead>', $indent); + ptln(' <tr>', $indent); + ptln(' <th class="line">'.$this->lang['line'].'</th>', $indent); + ptln(' <th class="error">'.$this->lang['error'].'</th>', $indent); + ptln(' <th class="userid">'.$this->lang['user_id'].'</th>', $indent); + ptln(' <th class="username">'.$this->lang['user_name'].'</th>', $indent); + ptln(' <th class="usermail">'.$this->lang['user_mail'].'</th>', $indent); + ptln(' <th class="usergroups">'.$this->lang['user_groups'].'</th>', $indent); + ptln(' </tr>', $indent); + ptln(' </thead>', $indent); + ptln(' <tbody>', $indent); + foreach ($this->import_failures as $line => $failure) { + ptln(' <tr>', $indent); + ptln(' <td class="lineno"> '.sprintf('%0'.$digits.'d', $line).' </td>', $indent); ptln(' <td class="error">' .$failure['error'].' </td>', $indent); - ptln(' <td class="field userid"> '.hsc($failure['user'][0]).' </td>',$indent); - ptln(' <td class="field username"> '.hsc($failure['user'][2]).' </td>',$indent); - ptln(' <td class="field usermail"> '.hsc($failure['user'][3]).' </td>',$indent); - ptln(' <td class="field usergroups"> '.hsc($failure['user'][4]).' </td>',$indent); - ptln(' </tr>',$indent); + ptln(' <td class="field userid"> '.hsc($failure['user'][0]).' </td>', $indent); + ptln(' <td class="field username"> '.hsc($failure['user'][2]).' </td>', $indent); + ptln(' <td class="field usermail"> '.hsc($failure['user'][3]).' </td>', $indent); + ptln(' <td class="field usergroups"> '.hsc($failure['user'][4]).' </td>', $indent); + ptln(' </tr>', $indent); } - ptln(' </tbody>',$indent); - ptln(' </table>',$indent); + ptln(' </tbody>', $indent); + ptln(' </table>', $indent); ptln(' <p><a href="'.$failure_download_link.'">'.$this->lang['import_downloadfailures'].'</a></p>'); ptln('</div>'); } - } /** @@ -507,17 +615,18 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return bool whether succesful */ - protected function _addUser(){ + protected function addUser() + { global $INPUT; if (!checkSecurityToken()) return false; - if (!$this->_auth->canDo('addUser')) return false; + if (!$this->auth->canDo('addUser')) return false; - list($user,$pass,$name,$mail,$grps,$passconfirm) = $this->_retrieveUser(); + list($user,$pass,$name,$mail,$grps,$passconfirm) = $this->retrieveUser(); if (empty($user)) return false; - if ($this->_auth->canDo('modPass')){ - if (empty($pass)){ - if($INPUT->has('usernotify')){ + if ($this->auth->canDo('modPass')) { + if (empty($pass)) { + if ($INPUT->has('usernotify')) { $pass = auth_pwgen($user); } else { msg($this->lang['add_fail'], -1); @@ -525,54 +634,53 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { return false; } } else { - if (!$this->_verifyPassword($pass,$passconfirm)) { + if (!$this->verifyPassword($pass, $passconfirm)) { msg($this->lang['add_fail'], -1); msg($this->lang['addUser_error_pass_not_identical'], -1); return false; } } } else { - if (!empty($pass)){ + if (!empty($pass)) { msg($this->lang['add_fail'], -1); msg($this->lang['addUser_error_modPass_disabled'], -1); return false; } } - if ($this->_auth->canDo('modName')){ - if (empty($name)){ + if ($this->auth->canDo('modName')) { + if (empty($name)) { msg($this->lang['add_fail'], -1); msg($this->lang['addUser_error_name_missing'], -1); return false; } } else { - if (!empty($name)){ + if (!empty($name)) { msg($this->lang['add_fail'], -1); msg($this->lang['addUser_error_modName_disabled'], -1); return false; } } - if ($this->_auth->canDo('modMail')){ - if (empty($mail)){ + if ($this->auth->canDo('modMail')) { + if (empty($mail)) { msg($this->lang['add_fail'], -1); msg($this->lang['addUser_error_mail_missing'], -1); return false; } } else { - if (!empty($mail)){ + if (!empty($mail)) { msg($this->lang['add_fail'], -1); msg($this->lang['addUser_error_modMail_disabled'], -1); return false; } } - if ($ok = $this->_auth->triggerUserMod('create', array($user,$pass,$name,$mail,$grps))) { - + if ($ok = $this->auth->triggerUserMod('create', array($user, $pass, $name, $mail, $grps))) { msg($this->lang['add_ok'], 1); if ($INPUT->has('usernotify') && $pass) { - $this->_notifyUser($user,$pass); + $this->notifyUser($user, $pass); } } else { msg($this->lang['add_fail'], -1); @@ -587,33 +695,34 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return bool whether succesful */ - protected function _deleteUser(){ + protected function deleteUser() + { global $conf, $INPUT; if (!checkSecurityToken()) return false; - if (!$this->_auth->canDo('delUser')) return false; + if (!$this->auth->canDo('delUser')) return false; $selected = $INPUT->arr('delete'); if (empty($selected)) return false; $selected = array_keys($selected); - if(in_array($_SERVER['REMOTE_USER'], $selected)) { + if (in_array($_SERVER['REMOTE_USER'], $selected)) { msg("You can't delete yourself!", -1); return false; } - $count = $this->_auth->triggerUserMod('delete', array($selected)); + $count = $this->auth->triggerUserMod('delete', array($selected)); if ($count == count($selected)) { $text = str_replace('%d', $count, $this->lang['delete_ok']); msg("$text.", 1); } else { $part1 = str_replace('%d', $count, $this->lang['delete_ok']); $part2 = str_replace('%d', (count($selected)-$count), $this->lang['delete_fail']); - msg("$part1, $part2",-1); + msg("$part1, $part2", -1); } // invalidate all sessions - io_saveFile($conf['cachedir'].'/sessionpurge',time()); + io_saveFile($conf['cachedir'].'/sessionpurge', time()); return true; } @@ -624,20 +733,21 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param string $param id of the user * @return bool whether succesful */ - protected function _editUser($param) { + protected function editUser($param) + { if (!checkSecurityToken()) return false; - if (!$this->_auth->canDo('UserMod')) return false; - $user = $this->_auth->cleanUser(preg_replace('/.*[:\/]/','',$param)); - $userdata = $this->_auth->getUserData($user); + if (!$this->auth->canDo('UserMod')) return false; + $user = $this->auth->cleanUser(preg_replace('/.*[:\/]/', '', $param)); + $userdata = $this->auth->getUserData($user); // no user found? if (!$userdata) { - msg($this->lang['edit_usermissing'],-1); + msg($this->lang['edit_usermissing'], -1); return false; } - $this->_edit_user = $user; - $this->_edit_userdata = $userdata; + $this->edit_user = $user; + $this->edit_userdata = $userdata; return true; } @@ -647,39 +757,39 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return bool whether succesful */ - protected function _modifyUser(){ + protected function modifyUser() + { global $conf, $INPUT; if (!checkSecurityToken()) return false; - if (!$this->_auth->canDo('UserMod')) return false; + if (!$this->auth->canDo('UserMod')) return false; // get currently valid user data - $olduser = $this->_auth->cleanUser(preg_replace('/.*[:\/]/','',$INPUT->str('userid_old'))); - $oldinfo = $this->_auth->getUserData($olduser); + $olduser = $this->auth->cleanUser(preg_replace('/.*[:\/]/', '', $INPUT->str('userid_old'))); + $oldinfo = $this->auth->getUserData($olduser); // get new user data subject to change - list($newuser,$newpass,$newname,$newmail,$newgrps,$passconfirm) = $this->_retrieveUser(); + list($newuser,$newpass,$newname,$newmail,$newgrps,$passconfirm) = $this->retrieveUser(); if (empty($newuser)) return false; $changes = array(); if ($newuser != $olduser) { - - if (!$this->_auth->canDo('modLogin')) { // sanity check, shouldn't be possible - msg($this->lang['update_fail'],-1); + if (!$this->auth->canDo('modLogin')) { // sanity check, shouldn't be possible + msg($this->lang['update_fail'], -1); return false; } // check if $newuser already exists - if ($this->_auth->getUserData($newuser)) { - msg(sprintf($this->lang['update_exists'],$newuser),-1); + if ($this->auth->getUserData($newuser)) { + msg(sprintf($this->lang['update_exists'], $newuser), -1); $re_edit = true; } else { $changes['user'] = $newuser; } } - if ($this->_auth->canDo('modPass')) { + if ($this->auth->canDo('modPass')) { if ($newpass || $passconfirm) { - if ($this->_verifyPassword($newpass,$passconfirm)) { + if ($this->verifyPassword($newpass, $passconfirm)) { $changes['pass'] = $newpass; } else { return false; @@ -692,33 +802,32 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { } } - if (!empty($newname) && $this->_auth->canDo('modName') && $newname != $oldinfo['name']) { + if (!empty($newname) && $this->auth->canDo('modName') && $newname != $oldinfo['name']) { $changes['name'] = $newname; } - if (!empty($newmail) && $this->_auth->canDo('modMail') && $newmail != $oldinfo['mail']) { + if (!empty($newmail) && $this->auth->canDo('modMail') && $newmail != $oldinfo['mail']) { $changes['mail'] = $newmail; } - if (!empty($newgrps) && $this->_auth->canDo('modGroups') && $newgrps != $oldinfo['grps']) { + if (!empty($newgrps) && $this->auth->canDo('modGroups') && $newgrps != $oldinfo['grps']) { $changes['grps'] = $newgrps; } - if ($ok = $this->_auth->triggerUserMod('modify', array($olduser, $changes))) { - msg($this->lang['update_ok'],1); + if ($ok = $this->auth->triggerUserMod('modify', array($olduser, $changes))) { + msg($this->lang['update_ok'], 1); if ($INPUT->has('usernotify') && !empty($changes['pass'])) { $notify = empty($changes['user']) ? $olduser : $newuser; - $this->_notifyUser($notify,$changes['pass']); + $this->notifyUser($notify, $changes['pass']); } // invalidate all sessions - io_saveFile($conf['cachedir'].'/sessionpurge',time()); - + io_saveFile($conf['cachedir'].'/sessionpurge', time()); } else { - msg($this->lang['update_fail'],-1); + msg($this->lang['update_fail'], -1); } if (!empty($re_edit)) { - $this->_editUser($olduser); + $this->editUser($olduser); } return $ok; @@ -732,9 +841,10 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param bool $status_alert whether status alert should be shown * @return bool whether succesful */ - protected function _notifyUser($user, $password, $status_alert=true) { + protected function notifyUser($user, $password, $status_alert = true) + { - if ($sent = auth_sendPassword($user,$password)) { + if ($sent = auth_sendPassword($user, $password)) { if ($status_alert) { msg($this->lang['notify_ok'], 1); } @@ -755,7 +865,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param string $confirm repeated password for confirmation * @return bool true if meets requirements, false otherwise */ - protected function _verifyPassword($password, $confirm) { + protected function verifyPassword($password, $confirm) + { global $lang; if (empty($password) && empty($confirm)) { @@ -779,7 +890,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param bool $clean whether the cleanUser method of the authentication backend is applied * @return array (user, password, full name, email, array(groups)) */ - protected function _retrieveUser($clean=true) { + protected function retrieveUser($clean = true) + { /** @var DokuWiki_Auth_Plugin $auth */ global $auth; global $INPUT; @@ -789,14 +901,14 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { $user[1] = $INPUT->str('userpass'); $user[2] = $INPUT->str('username'); $user[3] = $INPUT->str('usermail'); - $user[4] = explode(',',$INPUT->str('usergroups')); + $user[4] = explode(',', $INPUT->str('usergroups')); $user[5] = $INPUT->str('userpass2'); // repeated password for confirmation - $user[4] = array_map('trim',$user[4]); - if($clean) $user[4] = array_map(array($auth,'cleanGroup'),$user[4]); + $user[4] = array_map('trim', $user[4]); + if ($clean) $user[4] = array_map(array($auth,'cleanGroup'), $user[4]); $user[4] = array_filter($user[4]); $user[4] = array_unique($user[4]); - if(!count($user[4])) $user[4] = null; + if (!count($user[4])) $user[4] = null; return $user; } @@ -806,17 +918,18 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @param string $op 'new' or 'clear' */ - protected function _setFilter($op) { + protected function setFilter($op) + { - $this->_filter = array(); + $this->filter = array(); if ($op == 'new') { - list($user,/* $pass */,$name,$mail,$grps) = $this->_retrieveUser(false); + list($user,/* $pass */,$name,$mail,$grps) = $this->retrieveUser(false); - if (!empty($user)) $this->_filter['user'] = $user; - if (!empty($name)) $this->_filter['name'] = $name; - if (!empty($mail)) $this->_filter['mail'] = $mail; - if (!empty($grps)) $this->_filter['grps'] = join('|',$grps); + if (!empty($user)) $this->filter['user'] = $user; + if (!empty($name)) $this->filter['name'] = $name; + if (!empty($mail)) $this->filter['mail'] = $mail; + if (!empty($grps)) $this->filter['grps'] = join('|', $grps); } } @@ -825,7 +938,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return array */ - protected function _retrieveFilter() { + protected function retrieveFilter() + { global $INPUT; $t_filter = $INPUT->arr('filter'); @@ -844,14 +958,15 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { /** * Validate and improve the pagination values */ - protected function _validatePagination() { + protected function validatePagination() + { - if ($this->_start >= $this->_user_total) { - $this->_start = $this->_user_total - $this->_pagesize; + if ($this->start >= $this->users_total) { + $this->start = $this->users_total - $this->pagesize; } - if ($this->_start < 0) $this->_start = 0; + if ($this->start < 0) $this->start = 0; - $this->_last = min($this->_user_total, $this->_start + $this->_pagesize); + $this->last = min($this->users_total, $this->start + $this->pagesize); } /** @@ -859,21 +974,23 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return array with enable/disable attributes */ - protected function _pagination() { + protected function pagination() + { $disabled = 'disabled="disabled"'; $buttons = array(); - $buttons['start'] = $buttons['prev'] = ($this->_start == 0) ? $disabled : ''; + $buttons['start'] = $buttons['prev'] = ($this->start == 0) ? $disabled : ''; - if ($this->_user_total == -1) { + if ($this->users_total == -1) { $buttons['last'] = $disabled; $buttons['next'] = ''; } else { - $buttons['last'] = $buttons['next'] = (($this->_start + $this->_pagesize) >= $this->_user_total) ? $disabled : ''; + $buttons['last'] = $buttons['next'] = + (($this->start + $this->pagesize) >= $this->users_total) ? $disabled : ''; } - if ($this->_lastdisabled) { + if ($this->lastdisabled) { $buttons['last'] = $disabled; } @@ -883,9 +1000,10 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { /** * Export a list of users in csv format using the current filter criteria */ - protected function _export() { + protected function exportCSV() + { // list of users for export - based on current filter criteria - $user_list = $this->_auth->retrieveUsers(0, 0, $this->_filter); + $user_list = $this->auth->retrieveUsers(0, 0, $this->filter); $column_headings = array( $this->lang["user_id"], $this->lang["user_name"], @@ -902,14 +1020,16 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { # header('Content-type: text/plain;charset=utf-8'); // output the csv - $fd = fopen('php://output','w'); + $fd = fopen('php://output', 'w'); fputcsv($fd, $column_headings); foreach ($user_list as $user => $info) { - $line = array($user, $info['name'], $info['mail'], join(',',$info['grps'])); + $line = array($user, $info['name'], $info['mail'], join(',', $info['grps'])); fputcsv($fd, $line); } fclose($fd); - if (defined('DOKU_UNITTEST')){ return; } + if (defined('DOKU_UNITTEST')) { + return; + } die; } @@ -921,24 +1041,27 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * * @return bool whether successful */ - protected function _import() { + protected function importCSV() + { // check we are allowed to add users if (!checkSecurityToken()) return false; - if (!$this->_auth->canDo('addUser')) return false; + if (!$this->auth->canDo('addUser')) return false; // check file uploaded ok. - if (empty($_FILES['import']['size']) || !empty($_FILES['import']['error']) && $this->_isUploadedFile($_FILES['import']['tmp_name'])) { - msg($this->lang['import_error_upload'],-1); + if (empty($_FILES['import']['size']) || + !empty($_FILES['import']['error']) && $this->isUploadedFile($_FILES['import']['tmp_name']) + ) { + msg($this->lang['import_error_upload'], -1); return false; } // retrieve users from the file - $this->_import_failures = array(); + $this->import_failures = array(); $import_success_count = 0; $import_fail_count = 0; $line = 0; - $fd = fopen($_FILES['import']['tmp_name'],'r'); + $fd = fopen($_FILES['import']['tmp_name'], 'r'); if ($fd) { - while($csv = fgets($fd)){ + while ($csv = fgets($fd)) { if (!utf8_check($csv)) { $csv = utf8_encode($csv); } @@ -951,35 +1074,42 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { if (count($raw) < 4) { // need at least four fields $import_fail_count++; $error = sprintf($this->lang['import_error_fields'], count($raw)); - $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv); + $this->import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv); continue; } - array_splice($raw,1,0,auth_pwgen()); // splice in a generated password - $clean = $this->_cleanImportUser($raw, $error); - if ($clean && $this->_addImportUser($clean, $error)) { - $sent = $this->_notifyUser($clean[0],$clean[1],false); - if (!$sent){ - msg(sprintf($this->lang['import_notify_fail'],$clean[0],$clean[3]),-1); + array_splice($raw, 1, 0, auth_pwgen()); // splice in a generated password + $clean = $this->cleanImportUser($raw, $error); + if ($clean && $this->importUser($clean, $error)) { + $sent = $this->notifyUser($clean[0], $clean[1], false); + if (!$sent) { + msg(sprintf($this->lang['import_notify_fail'], $clean[0], $clean[3]), -1); } $import_success_count++; } else { $import_fail_count++; array_splice($raw, 1, 1); // remove the spliced in password - $this->_import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv); + $this->import_failures[$line] = array('error' => $error, 'user' => $raw, 'orig' => $csv); } } - msg(sprintf($this->lang['import_success_count'], ($import_success_count+$import_fail_count), $import_success_count),($import_success_count ? 1 : -1)); + msg( + sprintf( + $this->lang['import_success_count'], + ($import_success_count + $import_fail_count), + $import_success_count + ), + ($import_success_count ? 1 : -1) + ); if ($import_fail_count) { - msg(sprintf($this->lang['import_failure_count'], $import_fail_count),-1); + msg(sprintf($this->lang['import_failure_count'], $import_fail_count), -1); } } else { - msg($this->lang['import_error_readfail'],-1); + msg($this->lang['import_error_readfail'], -1); } // save import failures into the session if (!headers_sent()) { session_start(); - $_SESSION['import_failures'] = $this->_import_failures; + $_SESSION['import_failures'] = $this->import_failures; session_write_close(); } return true; @@ -992,17 +1122,18 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param string $error * @return array|false cleaned data or false */ - protected function _cleanImportUser($candidate, & $error){ + protected function cleanImportUser($candidate, & $error) + { global $INPUT; - // kludgy .... + // FIXME kludgy .... $INPUT->set('userid', $candidate[0]); $INPUT->set('userpass', $candidate[1]); $INPUT->set('username', $candidate[2]); $INPUT->set('usermail', $candidate[3]); $INPUT->set('usergroups', $candidate[4]); - $cleaned = $this->_retrieveUser(); + $cleaned = $this->retrieveUser(); list($user,/* $pass */,$name,$mail,/* $grps */) = $cleaned; if (empty($user)) { $error = $this->lang['import_error_baduserid']; @@ -1011,12 +1142,12 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { // no need to check password, handled elsewhere - if (!($this->_auth->canDo('modName') xor empty($name))){ + if (!($this->auth->canDo('modName') xor empty($name))) { $error = $this->lang['import_error_badname']; return false; } - if ($this->_auth->canDo('modMail')) { + if ($this->auth->canDo('modMail')) { if (empty($mail) || !mail_isvalid($mail)) { $error = $this->lang['import_error_badmail']; return false; @@ -1040,8 +1171,9 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param string &$error reference catched error message * @return bool whether successful */ - protected function _addImportUser($user, & $error){ - if (!$this->_auth->triggerUserMod('create', $user)) { + protected function importUser($user, &$error) + { + if (!$this->auth->triggerUserMod('create', $user)) { $error = $this->lang['import_error_create']; return false; } @@ -1052,7 +1184,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { /** * Downloads failures as csv file */ - protected function _downloadImportFailures(){ + protected function downloadImportFailures() + { // ============================================================================================== // GENERATE OUTPUT @@ -1063,8 +1196,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { # header('Content-type: text/plain;charset=utf-8'); // output the csv - $fd = fopen('php://output','w'); - foreach ($this->_import_failures as $fail) { + $fd = fopen('php://output', 'w'); + foreach ($this->import_failures as $fail) { fputs($fd, $fail['orig']); } fclose($fd); @@ -1077,7 +1210,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { * @param string $file filename * @return bool */ - protected function _isUploadedFile($file) { + protected function isUploadedFile($file) + { return is_uploaded_file($file); } } diff --git a/lib/tpl/dokuwiki/tpl_footer.php b/lib/tpl/dokuwiki/tpl_footer.php index 34e8b90f6..c7a04e155 100644 --- a/lib/tpl/dokuwiki/tpl_footer.php +++ b/lib/tpl/dokuwiki/tpl_footer.php @@ -25,7 +25,8 @@ if (!defined('DOKU_INC')) die(); <a href="//jigsaw.w3.org/css-validator/check/referer?profile=css3" title="Valid CSS" <?php echo $target?>><img src="<?php echo tpl_basedir(); ?>images/button-css.png" width="80" height="15" alt="Valid CSS" /></a> <a href="https://dokuwiki.org/" title="Driven by DokuWiki" <?php echo $target?>><img - src="<?php echo tpl_basedir(); ?>images/button-dw.png" width="80" height="15" alt="Driven by DokuWiki" /></a> + src="<?php echo tpl_basedir(); ?>images/button-dw.png" width="80" height="15" + alt="Driven by DokuWiki" /></a> </div> </div></div><!-- /footer --> |