diff options
author | Andreas Gohr <andi@splitbrain.org> | 2023-09-02 14:42:51 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-09-02 14:42:51 +0200 |
commit | 5ff5424d8c81c7123d8656a787af2ff85b3dec21 (patch) | |
tree | 322929ee01d892bb3c927e7fe1238369c647f820 /lib | |
parent | 0613df3287b82a98b1e97cf86ed9d4c8fbd16f1c (diff) | |
parent | 91560755291852b8302767d454183a7662666f7e (diff) | |
download | dokuwiki-5ff5424d8c81c7123d8656a787af2ff85b3dec21.tar.gz dokuwiki-5ff5424d8c81c7123d8656a787af2ff85b3dec21.zip |
Merge pull request #4045 from dokuwiki/autofix
Use Rector to autofix code smell
Diffstat (limited to 'lib')
95 files changed, 2672 insertions, 2447 deletions
diff --git a/lib/exe/ajax.php b/lib/exe/ajax.php index 5f49e5135..719064175 100644 --- a/lib/exe/ajax.php +++ b/lib/exe/ajax.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki AJAX call handler * @@ -6,7 +7,10 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if (!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__) . '/../../'); +use dokuwiki\Utf8\Clean; +use dokuwiki\Ajax; + +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); require_once(DOKU_INC . 'inc/init.php'); //close session @@ -18,8 +22,8 @@ header('Content-Type: text/html; charset=utf-8'); //call the requested function global $INPUT; if ($INPUT->has('call')) { - $call = $INPUT->filter([\dokuwiki\Utf8\Clean::class, 'stripspecials'])->str('call'); - new \dokuwiki\Ajax($call); + $call = $INPUT->filter([Clean::class, 'stripspecials'])->str('call'); + new Ajax($call); } else { http_status(404); } diff --git a/lib/exe/css.php b/lib/exe/css.php index 05e55bb56..2df3e6286 100644 --- a/lib/exe/css.php +++ b/lib/exe/css.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki StyleSheet creator * @@ -6,17 +7,18 @@ * @author Andreas Gohr <andi@splitbrain.org> */ +use dokuwiki\StyleUtils; use dokuwiki\Cache\Cache; use dokuwiki\Extension\Event; -if(!defined('DOKU_INC')) define('DOKU_INC', __DIR__ .'/../../'); -if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching) -if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here -if(!defined('NL')) define('NL',"\n"); -require_once(DOKU_INC.'inc/init.php'); +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); +if (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching) +if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here +if (!defined('NL')) define('NL', "\n"); +require_once(DOKU_INC . 'inc/init.php'); // Main (don't run when UNIT test) -if(!defined('SIMPLE_TEST')){ +if (!defined('SIMPLE_TEST')) { header('Content-Type: text/css; charset=utf-8'); css_out(); } @@ -29,49 +31,54 @@ if(!defined('SIMPLE_TEST')){ * * @author Andreas Gohr <andi@splitbrain.org> */ -function css_out(){ +function css_out() +{ global $conf; global $lang; global $config_cascade; global $INPUT; if ($INPUT->str('s') == 'feed') { - $mediatypes = array('feed'); + $mediatypes = ['feed']; $type = 'feed'; } else { - $mediatypes = array('screen', 'all', 'print', 'speech'); + $mediatypes = ['screen', 'all', 'print', 'speech']; $type = ''; } // decide from where to get the template - $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t'))); - if(!$tpl) $tpl = $conf['template']; + $tpl = trim(preg_replace('/[^\w-]+/', '', $INPUT->str('t'))); + if (!$tpl) { + $tpl = $conf['template']; + } // load style.ini - $styleUtil = new \dokuwiki\StyleUtils($tpl, $INPUT->bool('preview')); + $styleUtil = new StyleUtils($tpl, $INPUT->bool('preview')); $styleini = $styleUtil->cssStyleini(); // cache influencers $tplinc = tpl_incdir($tpl); $cache_files = getConfigFiles('main'); - $cache_files[] = $tplinc.'style.ini'; - $cache_files[] = DOKU_CONF."tpl/$tpl/style.ini"; + $cache_files[] = $tplinc . 'style.ini'; + $cache_files[] = DOKU_CONF . "tpl/$tpl/style.ini"; $cache_files[] = __FILE__; - if($INPUT->bool('preview')) $cache_files[] = $conf['cachedir'].'/preview.ini'; + if ($INPUT->bool('preview')) { + $cache_files[] = $conf['cachedir'] . '/preview.ini'; + } // Array of needed files and their web locations, the latter ones // are needed to fix relative paths in the stylesheets - $media_files = array(); - foreach($mediatypes as $mediatype) { - $files = array(); + $media_files = []; + foreach ($mediatypes as $mediatype) { + $files = []; // load core styles - $files[DOKU_INC.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE.'lib/styles/'; + $files[DOKU_INC . 'lib/styles/' . $mediatype . '.css'] = DOKU_BASE . 'lib/styles/'; // 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)); @@ -80,8 +87,8 @@ function css_out(){ $files = array_merge($files, $styleini['stylesheets'][$mediatype]); } // load user styles - if(isset($config_cascade['userstyle'][$mediatype]) and is_array($config_cascade['userstyle'][$mediatype])) { - foreach($config_cascade['userstyle'][$mediatype] as $userstyle) { + if (isset($config_cascade['userstyle'][$mediatype]) && is_array($config_cascade['userstyle'][$mediatype])) { + foreach ($config_cascade['userstyle'][$mediatype] as $userstyle) { $files[$userstyle] = DOKU_BASE; } } @@ -91,7 +98,7 @@ function css_out(){ $CSSEvt = new Event('CSS_STYLES_INCLUDED', $media_files[$mediatype]); // Make it preventable. - if ( $CSSEvt->advise_before() ) { + if ($CSSEvt->advise_before()) { $cache_files = array_merge($cache_files, array_keys($media_files[$mediatype]['files'])); } else { // unset if prevented. Nothing will be printed for this mediatype. @@ -117,7 +124,7 @@ function css_out(){ // check cache age & handle conditional request // This may exit if a cache can be used - $cache_ok = $cache->useCache(array('files' => $cache_files)); + $cache_ok = $cache->useCache(['files' => $cache_files]); http_cached($cache->cache, $cache_ok); // start output buffering @@ -131,30 +138,34 @@ function css_out(){ // build the stylesheet foreach ($mediatypes as $mediatype) { - // Check if there is a wrapper set for this type. - if ( !isset($media_files[$mediatype]) ) { + if (!isset($media_files[$mediatype])) { continue; } $cssData = $media_files[$mediatype]; // Print the styles. - print NL; - if ( $cssData['encapsulate'] === true ) print $cssData['encapsulationPrefix'] . ' {'; - print '/* START '.$cssData['mediatype'].' styles */'.NL; + echo NL; + if ($cssData['encapsulate'] === true) { + echo $cssData['encapsulationPrefix'] . ' {'; + } + echo '/* START ' . $cssData['mediatype'] . ' styles */' . NL; // load files - foreach($cssData['files'] as $file => $location){ + foreach ($cssData['files'] as $file => $location) { $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); - print "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; - print css_loadfile($file, $location); + echo "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; + echo css_loadfile($file, $location); } - print NL; - if ( $cssData['encapsulate'] === true ) print '} /* /@media '; - else print '/*'; - print ' END '.$cssData['mediatype'].' styles */'.NL; + echo NL; + if ($cssData['encapsulate'] === true) { + echo '} /* /@media '; + } else { + echo '/*'; + } + echo ' END ' . $cssData['mediatype'] . ' styles */' . NL; } // end output buffering and get contents @@ -171,14 +182,14 @@ function css_out(){ $css = css_parseless($css); // compress whitespace and comments - if($conf['compress']){ + if ($conf['compress']) { $css = css_compress($css); } // embed small images right into the stylesheet - if($conf['cssdatauri']){ - $base = preg_quote(DOKU_BASE,'#'); - $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css); + if ($conf['cssdatauri']) { + $base = preg_quote(DOKU_BASE, '#'); + $css = preg_replace_callback('#(url\([ \'"]*)(' . $base . ')(.*?(?:\.(png|gif)))#i', 'css_datauri', $css); } http_cached_finish($cache->cache, $css); @@ -193,43 +204,44 @@ function css_out(){ * @param string $css * @return string */ -function css_parseless($css) { +function css_parseless($css) +{ global $conf; $less = new lessc(); - $less->importDir = array(DOKU_INC); + $less->importDir = [DOKU_INC]; $less->setPreserveComments(!$conf['compress']); - if (defined('DOKU_UNITTEST')){ + if (defined('DOKU_UNITTEST')) { $less->importDir[] = TMP_DIR; } try { return $less->compile($css); - } catch(Exception $e) { + } catch (Exception $e) { // get exception message - $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage()); + $msg = str_replace(["\n", "\r", "'"], [], $e->getMessage()); // try to use line number to find affected file - if(preg_match('/line: (\d+)$/', $msg, $m)){ - $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber + if (preg_match('/line: (\d+)$/', $msg, $m)) { + $msg = substr($msg, 0, -1 * strlen($m[0])); //remove useless linenumber $lno = $m[1]; // walk upwards to last include $lines = explode("\n", $css); - for($i=$lno-1; $i>=0; $i--){ - if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){ + for ($i = $lno - 1; $i >= 0; $i--) { + if (preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)) { // we found it, add info to message - $msg .= ' in '.$m[2].' at line '.($lno-$i); + $msg .= ' in ' . $m[2] . ' at line ' . ($lno - $i); break; } } } // something went wrong - $error = 'A fatal error occured during compilation of the CSS files. '. - 'If you recently installed a new plugin or template it '. - 'might be broken and you should try disabling it again. ['.$msg.']'; + $error = 'A fatal error occured during compilation of the CSS files. ' . + 'If you recently installed a new plugin or template it ' . + 'might be broken and you should try disabling it again. [' . $msg . ']'; echo ".dokuwiki:before { content: '$error'; @@ -252,19 +264,20 @@ function css_parseless($css) { * This also adds the ini defined placeholders as less variables * (sans the surrounding __ and with a ini_ prefix) * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param string $css - * @param array $replacements array(placeholder => value) + * @param array $replacements array(placeholder => value) * @return string + * + * @author Andreas Gohr <andi@splitbrain.org> */ -function css_applystyle($css, $replacements) { +function css_applystyle($css, $replacements) +{ // we convert ini replacements to LESS variable names // and build a list of variable: value; pairs $less = ''; - foreach((array) $replacements as $key => $value) { + foreach ((array)$replacements as $key => $value) { $lkey = trim($key, '_'); - $lkey = '@ini_'.$lkey; + $lkey = '@ini_' . $lkey; $less .= "$lkey: $value;\n"; $replacements[$key] = $lkey; @@ -274,43 +287,45 @@ function css_applystyle($css, $replacements) { $css = strtr($css, $replacements); // now prepend the list of LESS variables as the very first thing - $css = $less.$css; + $css = $less . $css; return $css; } /** * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED * - * @author Gerry Weißbach <gerry.w@gammaproduction.de> - * * @param string $mediatype type ofthe current media files/content set * @param array $files set of files that define the current mediatype * @return array + * + * @author Gerry Weißbach <gerry.w@gammaproduction.de> */ -function css_filewrapper($mediatype, $files=array()){ - return array( - 'files' => $files, - 'mediatype' => $mediatype, - 'encapsulate' => $mediatype != 'all', - 'encapsulationPrefix' => '@media '.$mediatype - ); +function css_filewrapper($mediatype, $files = []) +{ + return [ + 'files' => $files, + 'mediatype' => $mediatype, + 'encapsulate' => $mediatype != 'all', + 'encapsulationPrefix' => '@media ' . $mediatype + ]; } /** * Prints the @media encapsulated default styles of DokuWiki * - * @author Gerry Weißbach <gerry.w@gammaproduction.de> - * * This function is being called by a CSS_STYLES_INCLUDED event * The event can be distinguished by the mediatype which is: * DW_DEFAULT + * + * @author Gerry Weißbach <gerry.w@gammaproduction.de> */ -function css_defaultstyles(){ +function css_defaultstyles() +{ // print the default classes for interwiki links and file downloads - print '@media screen {'; + echo '@media screen {'; css_interwiki(); css_filetypes(); - print '}'; + echo '}'; } /** @@ -324,11 +339,12 @@ function css_defaultstyles(){ * * @author Andreas Gohr <andi@splitbrain.org> */ -function css_interwiki(){ +function css_interwiki() +{ // default style echo 'a.interwiki {'; - echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.svg) 0 0 no-repeat;'; + echo ' background: transparent url(' . DOKU_BASE . 'lib/images/interwiki.svg) 0 0 no-repeat;'; echo ' background-size: 1.2em;'; echo ' padding: 0 0 0 1.4em;'; echo '}'; @@ -355,30 +371,31 @@ function css_interwiki(){ * * @author Andreas Gohr <andi@splitbrain.org> */ -function css_filetypes(){ +function css_filetypes() +{ // default style echo '.mediafile {'; - echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/svg/file.svg) 0px 1px no-repeat;'; + echo ' background: transparent url(' . DOKU_BASE . 'lib/images/fileicons/svg/file.svg) 0px 1px no-repeat;'; echo ' background-size: 1.2em;'; echo ' padding-left: 1.5em;'; echo '}'; // additional styles when icon available // scan directory for all icons - $exts = array(); - if($dh = opendir(DOKU_INC.'lib/images/fileicons/svg')){ - while(false !== ($file = readdir($dh))){ - if(preg_match('/(.*?)\.svg$/i',$file, $match)){ + $exts = []; + if ($dh = opendir(DOKU_INC . 'lib/images/fileicons/svg')) { + while (false !== ($file = readdir($dh))) { + if (preg_match('/(.*?)\.svg$/i', $file, $match)) { $exts[] = strtolower($match[1]); } } closedir($dh); } - foreach($exts as $ext){ - $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext); + foreach ($exts as $ext) { + $class = preg_replace('/[^_\-a-z0-9]+/', '_', $ext); echo ".mf_$class {"; - echo ' background-image: url('.DOKU_BASE.'lib/images/fileicons/svg/'.$ext.'.svg)'; + echo ' background-image: url(' . DOKU_BASE . 'lib/images/fileicons/svg/' . $ext . '.svg)'; echo '}'; } } @@ -391,23 +408,25 @@ function css_filetypes(){ * @param string $location * @return string */ -function css_loadfile($file,$location=''){ +function css_loadfile($file, $location = '') +{ $css_file = new DokuCssFile($file); return $css_file->load($location); } /** - * Helper class to abstract loading of css/less files + * Helper class to abstract loading of css/less files * - * @author Chris Smith <chris@jalakai.co.uk> + * @author Chris Smith <chris@jalakai.co.uk> */ -class DokuCssFile { - +class DokuCssFile +{ protected $filepath; // file system path to the CSS/Less file protected $location; // base url location of the CSS/Less file - protected $relative_path = null; + protected $relative_path; - public function __construct($file) { + public function __construct($file) + { $this->filepath = $file; } @@ -416,10 +435,11 @@ class DokuCssFile { * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC) * for less files. * - * @param string $location base url for this file - * @return string the CSS/Less contents of the file + * @param string $location base url for this file + * @return string the CSS/Less contents of the file */ - public function load($location='') { + public function load($location = '') + { if (!file_exists($this->filepath)) return ''; $css = io_readFile($this->filepath); @@ -427,8 +447,8 @@ class DokuCssFile { $this->location = $location; - $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css); - $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css); + $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#', [$this, 'replacements'], $css); + $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#', [$this, 'replacements'], $css); return $css; } @@ -438,10 +458,11 @@ class DokuCssFile { * * @return string relative file system path */ - protected function getRelativePath(){ + protected function getRelativePath() + { if (is_null($this->relative_path)) { - $basedir = array(DOKU_INC); + $basedir = [DOKU_INC]; // during testing, files may be found relative to a second base dir, TMP_DIR if (defined('DOKU_UNITTEST')) { @@ -449,7 +470,7 @@ class DokuCssFile { } $basedir = array_map('preg_quote_cb', $basedir); - $regex = '/^('.join('|',$basedir).')/'; + $regex = '/^(' . implode('|', $basedir) . ')/'; $this->relative_path = preg_replace($regex, '', dirname($this->filepath)); } @@ -460,10 +481,11 @@ class DokuCssFile { * preg_replace callback to adjust relative urls from relative to this file to relative * to the appropriate dokuwiki root location as described in the code * - * @param array see http://php.net/preg_replace_callback + * @param array $match see http://php.net/preg_replace_callback * @return string see http://php.net/preg_replace_callback */ - public function replacements($match) { + public function replacements($match) + { if (preg_match('#^(/|data:|https?://)#', $match[3])) { // not a relative url? - no adjustment required return $match[0]; @@ -475,7 +497,7 @@ class DokuCssFile { $match[3] = $this->location . $match[3]; } - return join('',array_slice($match,1)); + return implode('', array_slice($match, 1)); } } @@ -487,46 +509,48 @@ class DokuCssFile { * @param array $match * @return string */ -function css_datauri($match){ +function css_datauri($match) +{ global $conf; - $pre = unslash($match[1]); - $base = unslash($match[2]); - $url = unslash($match[3]); - $ext = unslash($match[4]); + $pre = unslash($match[1]); + $base = unslash($match[2]); + $url = unslash($match[3]); + $ext = unslash($match[4]); - $local = DOKU_INC.$url; - $size = @filesize($local); - if($size && $size < $conf['cssdatauri']){ + $local = DOKU_INC . $url; + $size = @filesize($local); + if ($size && $size < $conf['cssdatauri']) { $data = base64_encode(file_get_contents($local)); } - if (!empty($data)){ - $url = 'data:image/'.$ext.';base64,'.$data; - }else{ - $url = $base.$url; + if (!empty($data)) { + $url = 'data:image/' . $ext . ';base64,' . $data; + } else { + $url = $base . $url; } - return $pre.$url; + return $pre . $url; } /** * Returns a list of possible Plugin Styles (no existance check here) * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param string $mediatype * @return array + * @author Andreas Gohr <andi@splitbrain.org> + * */ -function css_pluginstyles($mediatype='screen'){ - $list = array(); +function css_pluginstyles($mediatype = 'screen') +{ + $list = []; $plugins = plugin_list(); - foreach ($plugins as $p){ - $list[DOKU_PLUGIN."$p/$mediatype.css"] = DOKU_BASE."lib/plugins/$p/"; - $list[DOKU_PLUGIN."$p/$mediatype.less"] = DOKU_BASE."lib/plugins/$p/"; + foreach ($plugins as $p) { + $list[DOKU_PLUGIN . "$p/$mediatype.css"] = DOKU_BASE . "lib/plugins/$p/"; + $list[DOKU_PLUGIN . "$p/$mediatype.less"] = DOKU_BASE . "lib/plugins/$p/"; // alternative for screen.css - if ($mediatype=='screen') { - $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/"; - $list[DOKU_PLUGIN."$p/style.less"] = DOKU_BASE."lib/plugins/$p/"; + if ($mediatype == 'screen') { + $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/"; + $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/"; } } return $list; @@ -535,32 +559,33 @@ function css_pluginstyles($mediatype='screen'){ /** * Very simple CSS optimizer * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param string $css * @return string + * @author Andreas Gohr <andi@splitbrain.org> + * */ -function css_compress($css){ +function css_compress($css) +{ // replace quoted strings with placeholder $quote_storage = []; $quote_cb = function ($match) use (&$quote_storage) { $quote_storage[] = $match[0]; - return '"STR'.(count($quote_storage)-1).'"'; + return '"STR' . (count($quote_storage) - 1) . '"'; }; $css = preg_replace_callback('/(([\'"]).*?(?<!\\\\)\2)/', $quote_cb, $css); // strip comments through a callback - $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css); + $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s', 'css_comment_cb', $css); // strip (incorrect but common) one line comments - $css = preg_replace_callback('/^.*\/\/.*$/m','css_onelinecomment_cb',$css); + $css = preg_replace_callback('/^.*\/\/.*$/m', 'css_onelinecomment_cb', $css); // strip whitespaces - $css = preg_replace('![\r\n\t ]+!',' ',$css); - $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css); - $css = preg_replace('/ ?: /',':',$css); + $css = preg_replace('![\r\n\t ]+!', ' ', $css); + $css = preg_replace('/ ?([;,{}\/]) ?/', '\\1', $css); + $css = preg_replace('/ ?: /', ':', $css); // number compression $css = preg_replace( @@ -624,13 +649,15 @@ function css_compress($css){ * * Keeps short comments (< 5 chars) to maintain typical browser hacks * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param array $matches * @return string + * + * @author Andreas Gohr <andi@splitbrain.org> + * */ -function css_comment_cb($matches){ - if(strlen($matches[2]) > 4) return ''; +function css_comment_cb($matches) +{ + if (strlen($matches[2]) > 4) return ''; return $matches[0]; } @@ -642,23 +669,24 @@ function css_comment_cb($matches){ * @param array $matches * @return string */ -function css_onelinecomment_cb($matches) { +function css_onelinecomment_cb($matches) +{ $line = $matches[0]; $i = 0; $len = strlen($line); - while ($i< $len){ + while ($i < $len) { $nextcom = strpos($line, '//', $i); $nexturl = stripos($line, 'url(', $i); - if($nextcom === false) { + if ($nextcom === false) { // no more comments, we're done $i = $len; break; } - if($nexturl === false || $nextcom < $nexturl) { + if ($nexturl === false || $nextcom < $nexturl) { // no url anymore, strip comment and be done $i = $nextcom; break; diff --git a/lib/exe/detail.php b/lib/exe/detail.php index 4df11fed6..96dcf9323 100644 --- a/lib/exe/detail.php +++ b/lib/exe/detail.php @@ -2,23 +2,23 @@ use dokuwiki\Extension\Event; -if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); -if(!defined('DOKU_MEDIADETAIL')) define('DOKU_MEDIADETAIL',1); +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); +if (!defined('DOKU_MEDIADETAIL')) define('DOKU_MEDIADETAIL', 1); // define all DokuWiki globals here (needed within test requests but also helps to keep track) global $INPUT, $IMG, $ID, $REV, $SRC, $ERROR, $AUTH; -require_once(DOKU_INC.'inc/init.php'); +require_once(DOKU_INC . 'inc/init.php'); -$IMG = getID('media'); -$ID = cleanID($INPUT->str('id')); -$REV = $INPUT->int('rev'); +$IMG = getID('media'); +$ID = cleanID($INPUT->str('id')); +$REV = $INPUT->int('rev'); // this makes some general info available as well as the info about the // "parent" page -$INFO = array_merge(pageinfo(),mediainfo()); +$INFO = array_merge(pageinfo(), mediainfo()); -$tmp = array(); +$tmp = []; Event::createAndTrigger('DETAIL_STARTED', $tmp); //close session @@ -27,15 +27,15 @@ session_write_close(); $ERROR = false; // check image permissions $AUTH = auth_quickaclcheck($IMG); -if($AUTH >= AUTH_READ){ +if ($AUTH >= AUTH_READ) { // check if image exists - $SRC = mediaFN($IMG,$REV); - if(!file_exists($SRC)){ + $SRC = mediaFN($IMG, $REV); + if (!file_exists($SRC)) { //doesn't exist! http_status(404); $ERROR = 'File not found'; } -}else{ +} else { // no auth $ERROR = p_locale_xhtml('denied'); } @@ -44,4 +44,3 @@ if($AUTH >= AUTH_READ){ header('Content-Type: text/html; charset=utf-8'); include(template('detail.php')); tpl_img_close(); - diff --git a/lib/exe/fetch.php b/lib/exe/fetch.php index 1b987ec10..845edc69e 100644 --- a/lib/exe/fetch.php +++ b/lib/exe/fetch.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki media passthrough file * @@ -6,122 +7,121 @@ * @author Andreas Gohr <andi@splitbrain.org> */ +use dokuwiki\Input\Input; use dokuwiki\Extension\Event; -if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__).'/../../'); +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); -require_once(DOKU_INC.'inc/init.php'); +require_once(DOKU_INC . 'inc/init.php'); session_write_close(); //close session -require_once(DOKU_INC.'inc/fetch.functions.php'); +require_once(DOKU_INC . 'inc/fetch.functions.php'); if (defined('SIMPLE_TEST')) { - $INPUT = new \dokuwiki\Input\Input(); + $INPUT = new Input(); } // BEGIN main - $mimetypes = getMimeTypes(); +$mimetypes = getMimeTypes(); - //get input - $MEDIA = stripctl(getID('media', false)); // no cleaning except control chars - maybe external - $CACHE = calc_cache($INPUT->str('cache')); - $WIDTH = $INPUT->int('w'); - $HEIGHT = $INPUT->int('h'); - $REV = & $INPUT->ref('rev'); - //sanitize revision - $REV = preg_replace('/[^0-9]/', '', $REV); +//get input +$MEDIA = stripctl(getID('media', false)); // no cleaning except control chars - maybe external +$CACHE = calc_cache($INPUT->str('cache')); +$WIDTH = $INPUT->int('w'); +$HEIGHT = $INPUT->int('h'); +$REV = &$INPUT->ref('rev'); +//sanitize revision +$REV = preg_replace('/[^0-9]/', '', $REV); - list($EXT, $MIME, $DL) = mimetype($MEDIA, false); - if($EXT === false) { - $EXT = 'unknown'; - $MIME = 'application/octet-stream'; - $DL = true; - } +[$EXT, $MIME, $DL] = mimetype($MEDIA, false); +if ($EXT === false) { + $EXT = 'unknown'; + $MIME = 'application/octet-stream'; + $DL = true; +} - // check for permissions, preconditions and cache external files - list($STATUS, $STATUSMESSAGE) = checkFileStatus($MEDIA, $FILE, $REV, $WIDTH, $HEIGHT); +// check for permissions, preconditions and cache external files +[$STATUS, $STATUSMESSAGE] = checkFileStatus($MEDIA, $FILE, $REV, $WIDTH, $HEIGHT); - // prepare data for plugin events - $data = array( - 'media' => $MEDIA, - 'file' => $FILE, - 'orig' => $FILE, - 'mime' => $MIME, - 'download' => $DL, - 'cache' => $CACHE, - 'ext' => $EXT, - 'width' => $WIDTH, - 'height' => $HEIGHT, - 'status' => $STATUS, - 'statusmessage' => $STATUSMESSAGE, - 'ispublic' => media_ispublic($MEDIA), - 'csp' => [ - 'default-src' => "'none'", - 'style-src' => "'unsafe-inline'", - 'media-src' => "'self'", - 'object-src' => "'self'", - 'font-src' => "'self' data:", - 'form-action' => "'none'", - 'frame-ancestors' => "'self'", - ], - ); +// prepare data for plugin events +$data = [ + 'media' => $MEDIA, + 'file' => $FILE, + 'orig' => $FILE, + 'mime' => $MIME, + 'download' => $DL, + 'cache' => $CACHE, + 'ext' => $EXT, + 'width' => $WIDTH, + 'height' => $HEIGHT, + 'status' => $STATUS, + 'statusmessage' => $STATUSMESSAGE, + 'ispublic' => media_ispublic($MEDIA), + 'csp' => [ + 'default-src' => "'none'", + 'style-src' => "'unsafe-inline'", + 'media-src' => "'self'", + 'object-src' => "'self'", + 'font-src' => "'self' data:", + 'form-action' => "'none'", + 'frame-ancestors' => "'self'", + ] +]; - // handle the file status - $evt = new Event('FETCH_MEDIA_STATUS', $data); - if($evt->advise_before()) { - // redirects - if($data['status'] > 300 && $data['status'] <= 304) { - if (defined('SIMPLE_TEST')) return; //TestResponse doesn't recognize redirects - send_redirect($data['statusmessage']); - } - // send any non 200 status - if($data['status'] != 200) { - http_status($data['status'], $data['statusmessage']); - } - // die on errors - if($data['status'] > 203) { - print $data['statusmessage']; - if (defined('SIMPLE_TEST')) return; - exit; - } +// handle the file status +$evt = new Event('FETCH_MEDIA_STATUS', $data); +if ($evt->advise_before()) { + // redirects + if ($data['status'] > 300 && $data['status'] <= 304) { + if (defined('SIMPLE_TEST')) return; //TestResponse doesn't recognize redirects + send_redirect($data['statusmessage']); + } + // send any non 200 status + if ($data['status'] != 200) { + http_status($data['status'], $data['statusmessage']); } - $evt->advise_after(); - unset($evt); + // die on errors + if ($data['status'] > 203) { + echo $data['statusmessage']; + if (defined('SIMPLE_TEST')) return; + exit; + } +} +$evt->advise_after(); +unset($evt); - //handle image resizing/cropping - $evt = new Event('MEDIA_RESIZE', $data); - if($evt->advise_before()) { - if( - $MIME != 'image/svg+xml' && - (substr($MIME, 0, 5) == 'image') && - ($WIDTH || $HEIGHT) - ) { - if($HEIGHT && $WIDTH) { - $data['file'] = $FILE = media_crop_image($data['file'], $EXT, $WIDTH, $HEIGHT); - } else { - $data['file'] = $FILE = media_resize_image($data['file'], $EXT, $WIDTH, $HEIGHT); - } +//handle image resizing/cropping +$evt = new Event('MEDIA_RESIZE', $data); +if ($evt->advise_before()) { + if ( + $MIME != 'image/svg+xml' && + (substr($MIME, 0, 5) == 'image') && + ($WIDTH || $HEIGHT) + ) { + if ($HEIGHT && $WIDTH) { + $data['file'] = $FILE = media_crop_image($data['file'], $EXT, $WIDTH, $HEIGHT); + } else { + $data['file'] = $FILE = media_resize_image($data['file'], $EXT, $WIDTH, $HEIGHT); } } - $evt->advise_after(); - unset($evt); +} +$evt->advise_after(); +unset($evt); - // finally send the file to the client - $evt = new Event('MEDIA_SENDFILE', $data); - if($evt->advise_before()) { - sendFile( - $data['file'], - $data['mime'], - $data['download'], - $data['cache'], - $data['ispublic'], - $data['orig'], - $data['csp'] - ); - } - // Do something after the download finished. - $evt->advise_after(); // will not be emitted on 304 or x-sendfile +// finally send the file to the client +$evt = new Event('MEDIA_SENDFILE', $data); +if ($evt->advise_before()) { + sendFile( + $data['file'], + $data['mime'], + $data['download'], + $data['cache'], + $data['ispublic'], + $data['orig'], + $data['csp'] + ); +} +// Do something after the download finished. +$evt->advise_after(); // will not be emitted on 304 or x-sendfile // END DO main - -//Setup VIM: ex: et ts=2 : diff --git a/lib/exe/indexer.php b/lib/exe/indexer.php index c5f6e4081..944c31dcf 100644 --- a/lib/exe/indexer.php +++ b/lib/exe/indexer.php @@ -1,5 +1,7 @@ <?php + /** * @deprecated 2020-06-04 use taskrunner instead */ + include __DIR__ . '/taskrunner.php'; diff --git a/lib/exe/jquery.php b/lib/exe/jquery.php index b8638ecc0..7b0fceb72 100644 --- a/lib/exe/jquery.php +++ b/lib/exe/jquery.php @@ -2,10 +2,10 @@ use dokuwiki\Cache\Cache; -if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__) . '/../../'); -if(!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching) -if(!defined('NL')) define('NL', "\n"); -if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); +if (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching) +if (!defined('NL')) define('NL', "\n"); +if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here require_once(DOKU_INC . 'inc/init.php'); // MAIN @@ -20,23 +20,24 @@ jquery_out(); * * uses cache or fills it */ -function jquery_out() { +function jquery_out() +{ $cache = new Cache('jquery', '.js'); - $files = array( + $files = [ DOKU_INC . 'lib/scripts/jquery/jquery.min.js', - DOKU_INC . 'lib/scripts/jquery/jquery-ui.min.js', - ); + DOKU_INC . 'lib/scripts/jquery/jquery-ui.min.js' + ]; $cache_files = $files; $cache_files[] = __FILE__; // check cache age & handle conditional request // This may exit if a cache can be used - $cache_ok = $cache->useCache(array('files' => $cache_files)); + $cache_ok = $cache->useCache(['files' => $cache_files]); http_cached($cache->cache, $cache_ok); $js = ''; - foreach($files as $file) { - $js .= file_get_contents($file)."\n"; + foreach ($files as $file) { + $js .= file_get_contents($file) . "\n"; } stripsourcemaps($js); diff --git a/lib/exe/js.php b/lib/exe/js.php index 1d87fb6e5..36e1814f6 100644 --- a/lib/exe/js.php +++ b/lib/exe/js.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki JavaScript creator * @@ -6,19 +7,20 @@ * @author Andreas Gohr <andi@splitbrain.org> */ +use dokuwiki\Utf8\PhpString; use dokuwiki\Cache\Cache; use dokuwiki\Extension\Event; use splitbrain\JSStrip\Exception as JSStripException; use splitbrain\JSStrip\JSStrip; -if(!defined('DOKU_INC')) define('DOKU_INC', __DIR__ .'/../../'); -if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching) -if(!defined('NL')) define('NL',"\n"); -if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here -require_once(DOKU_INC.'inc/init.php'); +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); +if (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching) +if (!defined('NL')) define('NL', "\n"); +if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here +require_once(DOKU_INC . 'inc/init.php'); // Main (don't run when UNIT test) -if(!defined('SIMPLE_TEST')){ +if (!defined('SIMPLE_TEST')) { header('Content-Type: application/javascript; charset=utf-8'); js_out(); } @@ -31,48 +33,49 @@ if(!defined('SIMPLE_TEST')){ * * @author Andreas Gohr <andi@splitbrain.org> */ -function js_out(){ +function js_out() +{ global $conf; global $lang; global $config_cascade; global $INPUT; // decide from where to get the template - $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t'))); - if(!$tpl) $tpl = $conf['template']; + $tpl = trim(preg_replace('/[^\w-]+/', '', $INPUT->str('t'))); + if (!$tpl) $tpl = $conf['template']; // array of core files - $files = array( - DOKU_INC.'lib/scripts/jquery/jquery.cookie.js', - DOKU_INC.'inc/lang/'.$conf['lang'].'/jquery.ui.datepicker.js', - DOKU_INC."lib/scripts/fileuploader.js", - DOKU_INC."lib/scripts/fileuploaderextended.js", - DOKU_INC.'lib/scripts/helpers.js', - DOKU_INC.'lib/scripts/delay.js', - DOKU_INC.'lib/scripts/cookie.js', - DOKU_INC.'lib/scripts/script.js', - DOKU_INC.'lib/scripts/qsearch.js', - DOKU_INC.'lib/scripts/search.js', - DOKU_INC.'lib/scripts/tree.js', - DOKU_INC.'lib/scripts/index.js', - DOKU_INC.'lib/scripts/textselection.js', - DOKU_INC.'lib/scripts/toolbar.js', - DOKU_INC.'lib/scripts/edit.js', - DOKU_INC.'lib/scripts/editor.js', - DOKU_INC.'lib/scripts/locktimer.js', - DOKU_INC.'lib/scripts/linkwiz.js', - DOKU_INC.'lib/scripts/media.js', - DOKU_INC.'lib/scripts/compatibility.js', -# disabled for FS#1958 DOKU_INC.'lib/scripts/hotkeys.js', - DOKU_INC.'lib/scripts/behaviour.js', - DOKU_INC.'lib/scripts/page.js', - tpl_incdir($tpl).'script.js', - ); + $files = [ + DOKU_INC . 'lib/scripts/jquery/jquery.cookie.js', + DOKU_INC . 'inc/lang/' . $conf['lang'] . '/jquery.ui.datepicker.js', + DOKU_INC . "lib/scripts/fileuploader.js", + DOKU_INC . "lib/scripts/fileuploaderextended.js", + DOKU_INC . 'lib/scripts/helpers.js', + DOKU_INC . 'lib/scripts/delay.js', + DOKU_INC . 'lib/scripts/cookie.js', + DOKU_INC . 'lib/scripts/script.js', + DOKU_INC . 'lib/scripts/qsearch.js', + DOKU_INC . 'lib/scripts/search.js', + DOKU_INC . 'lib/scripts/tree.js', + DOKU_INC . 'lib/scripts/index.js', + DOKU_INC . 'lib/scripts/textselection.js', + DOKU_INC . 'lib/scripts/toolbar.js', + DOKU_INC . 'lib/scripts/edit.js', + DOKU_INC . 'lib/scripts/editor.js', + DOKU_INC . 'lib/scripts/locktimer.js', + DOKU_INC . 'lib/scripts/linkwiz.js', + DOKU_INC . 'lib/scripts/media.js', + DOKU_INC . 'lib/scripts/compatibility.js', + # disabled for FS#1958 DOKU_INC.'lib/scripts/hotkeys.js', + DOKU_INC . 'lib/scripts/behaviour.js', + DOKU_INC . 'lib/scripts/page.js', + tpl_incdir($tpl) . 'script.js', + ]; // add possible plugin scripts and userscript - $files = array_merge($files,js_pluginscripts()); - if(is_array($config_cascade['userscript']['default'])) { - foreach($config_cascade['userscript']['default'] as $userscript) { + $files = array_merge($files, js_pluginscripts()); + if (is_array($config_cascade['userscript']['default'])) { + foreach ($config_cascade['userscript']['default'] as $userscript) { $files[] = $userscript; } } @@ -81,7 +84,7 @@ function js_out(){ Event::createAndTrigger('JS_SCRIPT_LIST', $files); // The generated script depends on some dynamic options - $cache = new Cache('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].md5(serialize($files)),'.js'); + $cache = new Cache('scripts' . $_SERVER['HTTP_HOST'] . $_SERVER['SERVER_PORT'] . md5(serialize($files)), '.js'); $cache->setEvent('JS_CACHE_USE'); $cache_files = array_merge($files, getConfigFiles('main')); @@ -89,60 +92,59 @@ function js_out(){ // check cache age & handle conditional request // This may exit if a cache can be used - $cache_ok = $cache->useCache(array('files' => $cache_files)); + $cache_ok = $cache->useCache(['files' => $cache_files]); http_cached($cache->cache, $cache_ok); // start output buffering and build the script ob_start(); // add some global variables - print "var DOKU_BASE = '".DOKU_BASE."';"; - print "var DOKU_TPL = '".tpl_basedir($tpl)."';"; - print "var DOKU_COOKIE_PARAM = " . json_encode( - array( - 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'], - 'secure' => $conf['securecookie'] && is_ssl() - )).";"; + echo "var DOKU_BASE = '" . DOKU_BASE . "';"; + echo "var DOKU_TPL = '" . tpl_basedir($tpl) . "';"; + echo "var DOKU_COOKIE_PARAM = " . json_encode([ + 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'], + 'secure' => $conf['securecookie'] && is_ssl() + ], JSON_THROW_ON_ERROR) . ";"; // 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; } });"; + echo "Object.defineProperty(window, 'DOKU_UHN', { get: function() {" . + "console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead');" . + "return JSINFO.useHeadingNavigation; } });"; + echo "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(); $templatestrings = js_templatestrings($tpl); - if(!empty($templatestrings)) { + if (!empty($templatestrings)) { $lang['js']['template'] = $templatestrings; } - echo 'LANG = '.json_encode($lang['js']).";\n"; + echo 'LANG = ' . json_encode($lang['js'], JSON_THROW_ON_ERROR) . ";\n"; // load toolbar toolbar_JSdefines('toolbar'); // load files - foreach($files as $file){ - if(!file_exists($file)) continue; - $ismin = (substr($file,-7) == '.min.js'); - $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC.'lib/scripts/') !== 0); + foreach ($files as $file) { + if (!file_exists($file)) continue; + $ismin = (substr($file, -7) == '.min.js'); + $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC . 'lib/scripts/') !== 0); - echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n"; - if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n"; + echo "\n\n/* XXXXXXXXXX begin of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n"; + if ($ismin) echo "\n/* BEGIN NOCOMPRESS */\n"; if ($debugjs) echo "\ntry {\n"; js_load($file); - if ($debugjs) echo "\n} catch (e) {\n logError(e, '".str_replace(DOKU_INC, '', $file)."');\n}\n"; - if($ismin) echo "\n/* END NOCOMPRESS */\n"; + if ($debugjs) echo "\n} catch (e) {\n logError(e, '" . str_replace(DOKU_INC, '', $file) . "');\n}\n"; + if ($ismin) echo "\n/* END NOCOMPRESS */\n"; echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n"; } // init stuff - if($conf['locktime'] != 0){ - js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")"); + if ($conf['locktime'] != 0) { + js_runonstart("dw_locktimer.init(" . ($conf['locktime'] - 60) . "," . $conf['usedraft'] . ")"); } // init hotkeys - must have been done after init of toolbar -# disabled for FS#1958 js_runonstart('initializeHotkeys()'); + # disabled for FS#1958 js_runonstart('initializeHotkeys()'); // end output buffering and get contents $js = ob_get_contents(); @@ -152,11 +154,11 @@ function js_out(){ stripsourcemaps($js); // compress whitespace and comments - if($conf['compress']){ + if ($conf['compress']) { try { $js = (new JSStrip())->compress($js); } catch (JSStripException $e) { - $js .= "\nconsole.error(".json_encode($e->getMessage()).");\n"; + $js .= "\nconsole.error(" . json_encode($e->getMessage(), JSON_THROW_ON_ERROR) . ");\n"; } } @@ -168,38 +170,39 @@ function js_out(){ /** * Load the given file, handle include calls and print it * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param string $file filename path to file + * + * @author Andreas Gohr <andi@splitbrain.org> */ -function js_load($file){ - if(!file_exists($file)) return; - static $loaded = array(); +function js_load($file) +{ + if (!file_exists($file)) return; + static $loaded = []; $data = io_readFile($file); - while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){ + while (preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#', $data, $match)) { $ifile = $match[2]; // is it a include_once? - if($match[1]){ - $base = \dokuwiki\Utf8\PhpString::basename($ifile); - if(array_key_exists($base, $loaded) && $loaded[$base] === true){ - $data = str_replace($match[0], '' ,$data); + if ($match[1]) { + $base = PhpString::basename($ifile); + if (array_key_exists($base, $loaded) && $loaded[$base] === true) { + $data = str_replace($match[0], '', $data); continue; } $loaded[$base] = true; } - if($ifile[0] != '/') $ifile = dirname($file).'/'.$ifile; + if ($ifile[0] != '/') $ifile = dirname($file) . '/' . $ifile; $idata = ''; if (file_exists($ifile)) { - $ismin = (substr($ifile, -7) == '.min.js');; + $ismin = (substr($ifile, -7) == '.min.js'); if ($ismin) $idata .= "\n/* BEGIN NOCOMPRESS */\n"; $idata .= io_readFile($ifile); if ($ismin) $idata .= "\n/* END NOCOMPRESS */\n"; } - $data = str_replace($match[0],$idata,$data); + $data = str_replace($match[0], $idata, $data); } echo "$data\n"; } @@ -207,15 +210,16 @@ function js_load($file){ /** * Returns a list of possible Plugin Scripts (no existance check here) * - * @author Andreas Gohr <andi@splitbrain.org> - * * @return array + * + * @author Andreas Gohr <andi@splitbrain.org> */ -function js_pluginscripts(){ - $list = array(); +function js_pluginscripts() +{ + $list = []; $plugins = plugin_list(); - foreach ($plugins as $p){ - $list[] = DOKU_PLUGIN."$p/script.js"; + foreach ($plugins as $p) { + $list[] = DOKU_PLUGIN . "$p/script.js"; } return $list; } @@ -226,38 +230,39 @@ function js_pluginscripts(){ * - $lang['js'] must be an array. * - Nothing is returned for plugins without an entry for $lang['js'] * + * @return array * @author Gabriel Birke <birke@d-scribe.de> * - * @return array */ -function js_pluginstrings() { +function js_pluginstrings() +{ global $conf, $config_cascade; - $pluginstrings = array(); + $pluginstrings = []; $plugins = plugin_list(); - foreach($plugins as $p) { + foreach ($plugins as $p) { $path = DOKU_PLUGIN . $p . '/lang/'; - if(isset($lang)) unset($lang); - if(file_exists($path . "en/lang.php")) { + if (isset($lang)) unset($lang); + if (file_exists($path . "en/lang.php")) { include $path . "en/lang.php"; } - foreach($config_cascade['lang']['plugin'] as $config_file) { - if(file_exists($config_file . $p . '/en/lang.php')) { + foreach ($config_cascade['lang']['plugin'] as $config_file) { + if (file_exists($config_file . $p . '/en/lang.php')) { include($config_file . $p . '/en/lang.php'); } } - if(isset($conf['lang']) && $conf['lang'] != 'en') { - if(file_exists($path . $conf['lang'] . "/lang.php")) { + if (isset($conf['lang']) && $conf['lang'] != 'en') { + if (file_exists($path . $conf['lang'] . "/lang.php")) { include($path . $conf['lang'] . '/lang.php'); } - foreach($config_cascade['lang']['plugin'] as $config_file) { - if(file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) { + foreach ($config_cascade['lang']['plugin'] as $config_file) { + if (file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) { include($config_file . $p . '/' . $conf['lang'] . '/lang.php'); } } } - if(isset($lang['js'])) { + if (isset($lang['js'])) { $pluginstrings[$p] = $lang['js']; } } @@ -273,35 +278,36 @@ function js_pluginstrings() { * @param string $tpl * @return array */ -function js_templatestrings($tpl) { +function js_templatestrings($tpl) +{ global $conf, $config_cascade; $path = tpl_incdir() . 'lang/'; - $templatestrings = array(); - if(file_exists($path . "en/lang.php")) { + $templatestrings = []; + if (file_exists($path . "en/lang.php")) { include $path . "en/lang.php"; } - foreach($config_cascade['lang']['template'] as $config_file) { - if(file_exists($config_file . $conf['template'] . '/en/lang.php')) { + foreach ($config_cascade['lang']['template'] as $config_file) { + if (file_exists($config_file . $conf['template'] . '/en/lang.php')) { include($config_file . $conf['template'] . '/en/lang.php'); } } - if(isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) { + if (isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) { include $path . $conf['lang'] . "/lang.php"; } - if(isset($conf['lang']) && $conf['lang'] != 'en') { - if(file_exists($path . $conf['lang'] . "/lang.php")) { + if (isset($conf['lang']) && $conf['lang'] != 'en') { + if (file_exists($path . $conf['lang'] . "/lang.php")) { include $path . $conf['lang'] . "/lang.php"; } - foreach($config_cascade['lang']['template'] as $config_file) { - if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) { + foreach ($config_cascade['lang']['template'] as $config_file) { + if (file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) { include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php'); } } } - if(isset($lang['js'])) { + if (isset($lang['js'])) { $templatestrings[$tpl] = $lang['js']; } return $templatestrings; @@ -311,22 +317,24 @@ function js_templatestrings($tpl) { * Escapes a String to be embedded in a JavaScript call, keeps \n * as newline * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param string $string * @return string + * + * @author Andreas Gohr <andi@splitbrain.org> */ -function js_escape($string){ - return str_replace('\\\\n','\\n',addslashes($string)); +function js_escape($string) +{ + return str_replace('\\\\n', '\\n', addslashes($string)); } /** * Adds the given JavaScript code to the window.onload() event * - * @author Andreas Gohr <andi@splitbrain.org> - * * @param string $func + * + * @author Andreas Gohr <andi@splitbrain.org> */ -function js_runonstart($func){ - echo "jQuery(function(){ $func; });".NL; +function js_runonstart($func) +{ + echo "jQuery(function(){ $func; });" . NL; } diff --git a/lib/exe/manifest.php b/lib/exe/manifest.php index 687c1937c..b3ccfb7e8 100644 --- a/lib/exe/manifest.php +++ b/lib/exe/manifest.php @@ -1,9 +1,11 @@ <?php +use dokuwiki\Manifest; + if (!defined('DOKU_INC')) { define('DOKU_INC', __DIR__ . '/../../'); } -if(!defined('NOSESSION')) define('NOSESSION',true); // no session or auth required here +if (!defined('NOSESSION')) define('NOSESSION', true); // no session or auth required here require_once(DOKU_INC . 'inc/init.php'); if (!actionOK('manifest')) { @@ -11,5 +13,5 @@ if (!actionOK('manifest')) { exit(); } -$manifest = new \dokuwiki\Manifest(); +$manifest = new Manifest(); $manifest->sendManifest(); diff --git a/lib/exe/mediamanager.php b/lib/exe/mediamanager.php index 3d8f865b0..54c6b81c1 100644 --- a/lib/exe/mediamanager.php +++ b/lib/exe/mediamanager.php @@ -2,130 +2,130 @@ use dokuwiki\Extension\Event; - if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); - define('DOKU_MEDIAMANAGER',1); - - // for multi uploader: - @ini_set('session.use_only_cookies',0); - - require_once(DOKU_INC.'inc/init.php'); - - global $INPUT; - global $lang; - global $conf; - // handle passed message - if($INPUT->str('msg1')) msg(hsc($INPUT->str('msg1')),1); - if($INPUT->str('err')) msg(hsc($INPUT->str('err')),-1); - - global $DEL; - // get namespace to display (either direct or from deletion order) - if($INPUT->str('delete')){ - $DEL = cleanID($INPUT->str('delete')); - $IMG = $DEL; - $NS = getNS($DEL); - }elseif($INPUT->str('edit')){ - $IMG = cleanID($INPUT->str('edit')); - $NS = getNS($IMG); - }elseif($INPUT->str('img')){ - $IMG = cleanID($INPUT->str('img')); - $NS = getNS($IMG); - }else{ - $NS = cleanID($INPUT->str('ns')); - $IMG = null; +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); +define('DOKU_MEDIAMANAGER', 1); + +// for multi uploader: +@ini_set('session.use_only_cookies', 0); + +require_once(DOKU_INC . 'inc/init.php'); + +global $INPUT; +global $lang; +global $conf; +// handle passed message +if ($INPUT->str('msg1')) msg(hsc($INPUT->str('msg1')), 1); +if ($INPUT->str('err')) msg(hsc($INPUT->str('err')), -1); + +global $DEL; +// get namespace to display (either direct or from deletion order) +if ($INPUT->str('delete')) { + $DEL = cleanID($INPUT->str('delete')); + $IMG = $DEL; + $NS = getNS($DEL); +} elseif ($INPUT->str('edit')) { + $IMG = cleanID($INPUT->str('edit')); + $NS = getNS($IMG); +} elseif ($INPUT->str('img')) { + $IMG = cleanID($INPUT->str('img')); + $NS = getNS($IMG); +} else { + $NS = cleanID($INPUT->str('ns')); + $IMG = null; +} + +global $INFO, $JSINFO; +$INFO = empty($INFO) ? mediainfo() : array_merge($INFO, mediainfo()); +$JSINFO['id'] = ''; +$JSINFO['namespace'] = ''; +$AUTH = $INFO['perm']; // shortcut for historical reasons + +// If this page is directly opened it means we are in popup mode not fullscreen +// $fullscreen isn't defined by default it might lead to some PHP warnings +$fullscreen ??= false; + +$tmp = []; +Event::createAndTrigger('MEDIAMANAGER_STARTED', $tmp); +session_write_close(); //close session + +// do not display the manager if user does not have read access +if ($AUTH < AUTH_READ && !$fullscreen) { + http_status(403); + die($lang['accessdenied']); +} + +// handle flash upload +if (isset($_FILES['Filedata'])) { + $_FILES['upload'] =& $_FILES['Filedata']; + $JUMPTO = media_upload($NS, $AUTH); + if ($JUMPTO == false) { + http_status(400); + echo 'Upload failed'; } - - global $INFO, $JSINFO; - $INFO = !empty($INFO) ? array_merge($INFO, mediainfo()) : mediainfo(); - $JSINFO['id'] = ''; - $JSINFO['namespace'] = ''; - $AUTH = $INFO['perm']; // shortcut for historical reasons - - // If this page is directly opened it means we are in popup mode not fullscreen - // $fullscreen isn't defined by default it might lead to some PHP warnings - $fullscreen = isset($fullscreen) ? $fullscreen : false; - - $tmp = array(); - Event::createAndTrigger('MEDIAMANAGER_STARTED', $tmp); - session_write_close(); //close session - - // do not display the manager if user does not have read access - if($AUTH < AUTH_READ && !$fullscreen) { - http_status(403); - die($lang['accessdenied']); - } - - // handle flash upload - if(isset($_FILES['Filedata'])){ - $_FILES['upload'] =& $_FILES['Filedata']; - $JUMPTO = media_upload($NS,$AUTH); - if($JUMPTO == false){ - http_status(400); - echo 'Upload failed'; - } - echo 'ok'; - exit; - } - - // give info on PHP caught upload errors - if(!empty($_FILES['upload']['error'])){ - switch($_FILES['upload']['error']){ - case 1: - case 2: - msg(sprintf($lang['uploadsize'], - filesize_h(php_to_byte(ini_get('upload_max_filesize')))),-1); - break; - default: - msg($lang['uploadfail'].' ('.$_FILES['upload']['error'].')',-1); - } - unset($_FILES['upload']); - } - - // handle upload - if(!empty($_FILES['upload']['tmp_name'])){ - $JUMPTO = media_upload($NS,$AUTH); - if($JUMPTO) $NS = getNS($JUMPTO); - } - - // handle meta saving - if($IMG && @array_key_exists('save', $INPUT->arr('do'))){ - $JUMPTO = media_metasave($IMG,$AUTH,$INPUT->arr('meta')); + echo 'ok'; + exit; +} + +// give info on PHP caught upload errors +if (!empty($_FILES['upload']['error'])) { + switch ($_FILES['upload']['error']) { + case 1: + case 2: + msg(sprintf( + $lang['uploadsize'], + filesize_h(php_to_byte(ini_get('upload_max_filesize'))) + ), -1); + break; + default: + msg($lang['uploadfail'] . ' (' . $_FILES['upload']['error'] . ')', -1); } - - if($IMG && ($INPUT->str('mediado') == 'save' || @array_key_exists('save', $INPUT->arr('mediado')))) { - $JUMPTO = media_metasave($IMG,$AUTH,$INPUT->arr('meta')); + unset($_FILES['upload']); +} + +// handle upload +if (!empty($_FILES['upload']['tmp_name'])) { + $JUMPTO = media_upload($NS, $AUTH); + if ($JUMPTO) $NS = getNS($JUMPTO); +} + +// handle meta saving +if ($IMG && @array_key_exists('save', $INPUT->arr('do'))) { + $JUMPTO = media_metasave($IMG, $AUTH, $INPUT->arr('meta')); +} + +if ($IMG && ($INPUT->str('mediado') == 'save' || @array_key_exists('save', $INPUT->arr('mediado')))) { + $JUMPTO = media_metasave($IMG, $AUTH, $INPUT->arr('meta')); +} + +if ($INPUT->int('rev') && $conf['mediarevisions']) $REV = $INPUT->int('rev'); + +if ($INPUT->str('mediado') == 'restore' && $conf['mediarevisions']) { + $JUMPTO = media_restore($INPUT->str('image'), $REV, $AUTH); +} + +// handle deletion +if ($DEL) { + $res = 0; + if (checkSecurityToken()) { + $res = media_delete($DEL, $AUTH); } - - if ($INPUT->int('rev') && $conf['mediarevisions']) $REV = $INPUT->int('rev'); - - if($INPUT->str('mediado') == 'restore' && $conf['mediarevisions']){ - $JUMPTO = media_restore($INPUT->str('image'), $REV, $AUTH); - } - - // handle deletion - if($DEL) { - $res = 0; - if(checkSecurityToken()) { - $res = media_delete($DEL,$AUTH); - } - if ($res & DOKU_MEDIA_DELETED) { - $msg = sprintf($lang['deletesucc'], noNS($DEL)); - if ($res & DOKU_MEDIA_EMPTY_NS && !$fullscreen) { - // current namespace was removed. redirecting to root ns passing msg along - send_redirect(DOKU_URL.'lib/exe/mediamanager.php?msg1='. - rawurlencode($msg).'&edid='.$INPUT->str('edid')); - } - msg($msg,1); - } elseif ($res & DOKU_MEDIA_INUSE) { - msg(sprintf($lang['mediainuse'],noNS($DEL)),0); - } else { - msg(sprintf($lang['deletefail'],noNS($DEL)),-1); + if ($res & DOKU_MEDIA_DELETED) { + $msg = sprintf($lang['deletesucc'], noNS($DEL)); + if ($res & DOKU_MEDIA_EMPTY_NS && !$fullscreen) { + // current namespace was removed. redirecting to root ns passing msg along + send_redirect(DOKU_URL . 'lib/exe/mediamanager.php?msg1=' . + rawurlencode($msg) . '&edid=' . $INPUT->str('edid')); } + msg($msg, 1); + } elseif ($res & DOKU_MEDIA_INUSE) { + msg(sprintf($lang['mediainuse'], noNS($DEL)), 0); + } else { + msg(sprintf($lang['deletefail'], noNS($DEL)), -1); } - // finished - start output - - if (!$fullscreen) { - header('Content-Type: text/html; charset=utf-8'); - include(template('mediamanager.php')); - } +} +// finished - start output -/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ +if (!$fullscreen) { + header('Content-Type: text/html; charset=utf-8'); + include(template('mediamanager.php')); +} diff --git a/lib/exe/opensearch.php b/lib/exe/opensearch.php index b00b2b771..766bdb2e6 100644 --- a/lib/exe/opensearch.php +++ b/lib/exe/opensearch.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki OpenSearch creator * @@ -8,31 +9,29 @@ * @author Andreas Gohr <andi@splitbrain.org> */ -if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); -if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching) -if(!defined('NL')) define('NL',"\n"); -require_once(DOKU_INC.'inc/init.php'); +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); +if (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching) +if (!defined('NL')) define('NL', "\n"); +require_once(DOKU_INC . 'inc/init.php'); // try to be clever about the favicon location -if(file_exists(DOKU_INC.'favicon.ico')){ - $ico = DOKU_URL.'favicon.ico'; -}elseif(file_exists(tpl_incdir().'images/favicon.ico')){ - $ico = DOKU_URL.'lib/tpl/'.$conf['template'].'/images/favicon.ico'; -}elseif(file_exists(tpl_incdir().'favicon.ico')){ - $ico = DOKU_URL.'lib/tpl/'.$conf['template'].'/favicon.ico'; -}else{ - $ico = DOKU_URL.'lib/tpl/dokuwiki/images/favicon.ico'; +if (file_exists(DOKU_INC . 'favicon.ico')) { + $ico = DOKU_URL . 'favicon.ico'; +} elseif (file_exists(tpl_incdir() . 'images/favicon.ico')) { + $ico = DOKU_URL . 'lib/tpl/' . $conf['template'] . '/images/favicon.ico'; +} elseif (file_exists(tpl_incdir() . 'favicon.ico')) { + $ico = DOKU_URL . 'lib/tpl/' . $conf['template'] . '/favicon.ico'; +} else { + $ico = DOKU_URL . 'lib/tpl/dokuwiki/images/favicon.ico'; } // output header('Content-Type: application/opensearchdescription+xml; charset=utf-8'); -echo '<?xml version="1.0"?>'.NL; -echo '<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">'.NL; -echo ' <ShortName>'.hsc($conf['title']).'</ShortName>'.NL; -echo ' <Image width="16" height="16" type="image/x-icon">'.$ico.'</Image>'.NL; -echo ' <Url type="text/html" template="'.DOKU_URL.DOKU_SCRIPT.'?do=search&id={searchTerms}" />'.NL; -echo ' <Url type="application/x-suggestions+json" template="'. - DOKU_URL.'lib/exe/ajax.php?call=suggestions&q={searchTerms}" />'.NL; -echo '</OpenSearchDescription>'.NL; - -//Setup VIM: ex: et ts=4 : +echo '<?xml version="1.0"?>' . NL; +echo '<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">' . NL; +echo ' <ShortName>' . hsc($conf['title']) . '</ShortName>' . NL; +echo ' <Image width="16" height="16" type="image/x-icon">' . $ico . '</Image>' . NL; +echo ' <Url type="text/html" template="' . DOKU_URL . DOKU_SCRIPT . '?do=search&id={searchTerms}" />' . NL; +echo ' <Url type="application/x-suggestions+json" template="' . + DOKU_URL . 'lib/exe/ajax.php?call=suggestions&q={searchTerms}" />' . NL; +echo '</OpenSearchDescription>' . NL; diff --git a/lib/exe/taskrunner.php b/lib/exe/taskrunner.php index 69ab4451a..0a62bf623 100644 --- a/lib/exe/taskrunner.php +++ b/lib/exe/taskrunner.php @@ -1,16 +1,20 @@ <?php + /** * DokuWiki indexer * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ + +use dokuwiki\TaskRunner; + if (!defined('DOKU_INC')) { define('DOKU_INC', __DIR__ . '/../../'); } -define('DOKU_DISABLE_GZIP_OUTPUT',1); -require_once DOKU_INC.'inc/init.php'; +define('DOKU_DISABLE_GZIP_OUTPUT', 1); +require_once DOKU_INC . 'inc/init.php'; session_write_close(); //close session -$taskRunner = new \dokuwiki\TaskRunner(); +$taskRunner = new TaskRunner(); $taskRunner->run(); diff --git a/lib/exe/xmlrpc.php b/lib/exe/xmlrpc.php index e90fb9eba..9fad90136 100644 --- a/lib/exe/xmlrpc.php +++ b/lib/exe/xmlrpc.php @@ -1,4 +1,5 @@ <?php + /** * XMLRPC API backend */ diff --git a/lib/images/fileicons/index.php b/lib/images/fileicons/index.php index d1f233e48..8729e515c 100644 --- a/lib/images/fileicons/index.php +++ b/lib/images/fileicons/index.php @@ -29,29 +29,30 @@ <body> <?php -$fi_list = ''; $fi_list32 = ''; +$fi_list = ''; +$fi_list32 = ''; foreach (glob('*.png') as $img) { - $fi_list .= '<img src="'.$img.'" alt="'.$img.'" title="'.$img.'" /> '; + $fi_list .= '<img src="' . $img . '" alt="' . $img . '" title="' . $img . '" /> '; } foreach (glob('32x32/*.png') as $img) { - $fi_list32 .= '<img src="'.$img.'" alt="'.$img.'" title="'.$img.'" /> '; + $fi_list32 .= '<img src="' . $img . '" alt="' . $img . '" title="' . $img . '" /> '; } echo '<div class="white box"> -'.$fi_list.' +' . $fi_list . ' </div> <div class="black box"> -'.$fi_list.' +' . $fi_list . ' </div> <br style="clear: left" /> <div class="white box"> -'.$fi_list32.' +' . $fi_list32 . ' </div> <div class="black box"> -'.$fi_list32; +' . $fi_list32; ?> </div> diff --git a/lib/images/fileicons/svg/index.php b/lib/images/fileicons/svg/index.php index 66c4835af..2df7699ae 100644 --- a/lib/images/fileicons/svg/index.php +++ b/lib/images/fileicons/svg/index.php @@ -15,7 +15,7 @@ <body> <?php foreach (glob('*.svg') as $img) { - echo '<img src="'.$img.'" alt="'.$img.'" width="32" height="32" title="'.$img.'" /> '; + echo '<img src="' . $img . '" alt="' . $img . '" width="32" height="32" title="' . $img . '" /> '; } ?> </body> diff --git a/lib/images/smileys/index.php b/lib/images/smileys/index.php index 9441c1f9f..31440fda0 100644 --- a/lib/images/smileys/index.php +++ b/lib/images/smileys/index.php @@ -31,21 +31,21 @@ <?php $smi_list = ''; foreach (glob('*.svg') as $img) { - $smi_list .= '<img src="'.$img.'" alt="'.$img.'" title="'.$img.'" /> '; + $smi_list .= '<img src="' . $img . '" alt="' . $img . '" title="' . $img . '" /> '; } -if(is_dir('local')) { +if (is_dir('local')) { $smi_list .= '<hr />'; foreach (glob('local/*.svg') as $img) { - $smi_list .= '<img src="'.$img.'" alt="'.$img.'" title="'.$img.'" /> '; + $smi_list .= '<img src="' . $img . '" alt="' . $img . '" title="' . $img . '" /> '; } } echo '<div class="white box"> -'.$smi_list.' +' . $smi_list . ' </div> <div class="black box"> -'.$smi_list; +' . $smi_list; ?> </div> diff --git a/lib/index.html b/lib/index.html index 885c954a4..36286bffc 100644 --- a/lib/index.html +++ b/lib/index.html @@ -1,9 +1,9 @@ <!DOCTYPE html> <html> <head> -<meta http-equiv="refresh" content="0; URL=../" /> -<meta name="robots" content="noindex" /> -<title>nothing here...</title> + <meta http-equiv="refresh" content="0; URL=../"/> + <meta name="robots" content="noindex"/> + <title>nothing here...</title> </head> <body> <!-- this is just here to prevent directory browsing --> diff --git a/lib/plugins/acl/action.php b/lib/plugins/acl/action.php index 86e587093..bb84ff16c 100644 --- a/lib/plugins/acl/action.php +++ b/lib/plugins/acl/action.php @@ -1,24 +1,27 @@ <?php + +use dokuwiki\Extension\ActionPlugin; +use dokuwiki\Extension\EventHandler; +use dokuwiki\Extension\Event; + /** * AJAX call handler for ACL plugin * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ - /** * Register handler */ -class action_plugin_acl extends DokuWiki_Action_Plugin +class action_plugin_acl extends ActionPlugin { - /** * Registers a callback function for a given event * - * @param Doku_Event_Handler $controller DokuWiki's event controller object + * @param EventHandler $controller DokuWiki's event controller object * @return void */ - public function register(Doku_Event_Handler $controller) + public function register(EventHandler $controller) { $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleAjaxCallAcl'); @@ -27,11 +30,11 @@ class action_plugin_acl extends DokuWiki_Action_Plugin /** * AJAX call handler for ACL plugin * - * @param Doku_Event $event event object by reference + * @param Event $event event object by reference * @param mixed $param empty * @return void */ - public function handleAjaxCallAcl(Doku_Event $event, $param) + public function handleAjaxCallAcl(Event $event, $param) { if ($event->data !== 'plugin_acl') { return; @@ -78,8 +81,8 @@ class action_plugin_acl extends DokuWiki_Action_Plugin echo html_buildlist( $data, 'acl', - array($acl, 'makeTreeItem'), - array($acl, 'makeListItem') + [$acl, 'makeTreeItem'], + [$acl, 'makeListItem'] ); } } diff --git a/lib/plugins/acl/admin.php b/lib/plugins/acl/admin.php index a295692f2..3a2857f62 100644 --- a/lib/plugins/acl/admin.php +++ b/lib/plugins/acl/admin.php @@ -1,4 +1,6 @@ <?php + +use dokuwiki\Extension\AdminPlugin; use dokuwiki\Utf8\Sort; /** @@ -14,10 +16,10 @@ use dokuwiki\Utf8\Sort; * All DokuWiki plugins to extend the admin function * need to inherit from this class */ -class admin_plugin_acl extends DokuWiki_Admin_Plugin +class admin_plugin_acl extends AdminPlugin { - public $acl = null; - protected $ns = null; + public $acl; + protected $ns; /** * The currently selected item, associative array with id and type. * Populated from (in this order): @@ -26,10 +28,10 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin * $ns * $ID */ - protected $current_item = null; + protected $current_item; protected $who = ''; - protected $usersgroups = array(); - protected $specials = array(); + protected $usersgroups = []; + protected $specials = []; /** * return prompt for admin menu @@ -73,27 +75,29 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin } if ($INPUT->str('current_ns')) { - $this->current_item = array('id' => cleanID($INPUT->str('current_ns')), 'type' => 'd'); + $this->current_item = ['id' => cleanID($INPUT->str('current_ns')), 'type' => 'd']; } elseif ($INPUT->str('current_id')) { - $this->current_item = array('id' => cleanID($INPUT->str('current_id')), 'type' => 'f'); + $this->current_item = ['id' => cleanID($INPUT->str('current_id')), 'type' => 'f']; } elseif ($this->ns) { - $this->current_item = array('id' => $this->ns, 'type' => 'd'); + $this->current_item = ['id' => $this->ns, 'type' => 'd']; } else { - $this->current_item = array('id' => $ID, 'type' => 'f'); + $this->current_item = ['id' => $ID, 'type' => 'f']; } // user or group choosen? $who = trim($INPUT->str('acl_w')); if ($INPUT->str('acl_t') == '__g__' && $who) { - $this->who = '@'.ltrim($auth->cleanGroup($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') && - $INPUT->str('acl_t') != '__u__' && - $INPUT->str('acl_t') != '__g__') { + } elseif ( + $INPUT->str('acl_t') && + $INPUT->str('acl_t') != '__u__' && + $INPUT->str('acl_t') != '__g__' + ) { $this->who = $INPUT->str('acl_t'); } elseif ($who) { $this->who = $who; @@ -108,7 +112,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin if ($this->ns == '*') { $scope = '*'; } else { - $scope = $this->ns.':*'; + $scope = $this->ns . ':*'; } } else { $scope = $ID; @@ -131,7 +135,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin unset($acl[$where][$who]); } // prepare lines - $lines = array(); + $lines = []; // keep header foreach ($AUTH_ACL as $line) { if ($line[0] == '#') { @@ -143,9 +147,9 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin // re-add all rules foreach ($acl as $where => $opt) { foreach ($opt as $who => $perm) { - if ($who[0]=='@') { - if ($who!='@ALL') { - $who = '@'.ltrim($auth->cleanGroup($who), '@'); + if ($who[0] == '@') { + if ($who != '@ALL') { + $who = '@' . ltrim($auth->cleanGroup($who), '@'); } } elseif ($who != '%USER%' && $who != '%GROUP%') { #keep wildcard as is $who = $auth->cleanUser($who); @@ -155,7 +159,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin } } // save it - io_saveFile($config_cascade['acl']['default'], join('', $lines)); + io_saveFile($config_cascade['acl']['default'], implode('', $lines)); } // reload ACL config @@ -177,31 +181,31 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin */ 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_manager">'; + echo '<h1>' . $this->getLang('admin_acl') . '</h1>'; + echo '<div class="level1">'; - echo '<div id="acl__tree">'.NL; + echo '<div id="acl__tree">'; $this->makeExplorer(); - echo '</div>'.NL; + echo '</div>'; - echo '<div id="acl__detail">'.NL; + echo '<div id="acl__detail">'; $this->printDetail(); - echo '</div>'.NL; - echo '</div>'.NL; + echo '</div>'; + echo '</div>'; echo '<div class="clearer"></div>'; - echo '<h2>'.$this->getLang('current').'</h2>'.NL; - echo '<div class="level2">'.NL; + echo '<h2>' . $this->getLang('current') . '</h2>'; + echo '<div class="level2">'; $this->printAclTable(); - echo '</div>'.NL; + echo '</div>'; - echo '<div class="footnotes"><div class="fn">'.NL; - echo '<sup><a id="fn__1" class="fn_bot" href="#fnt__1">1)</a></sup>'.NL; - echo '<div class="content">'.$this->getLang('p_include').'</div>'; + echo '<div class="footnotes"><div class="fn">'; + echo '<sup><a id="fn__1" class="fn_bot" href="#fnt__1">1)</a></sup>'; + echo '<div class="content">' . $this->getLang('p_include') . '</div>'; echo '</div></div>'; - echo '</div>'.NL; + echo '</div>'; } /** @@ -211,10 +215,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin */ protected function getLinkOptions($addopts = null) { - $opts = array( - 'do'=>'admin', - 'page'=>'acl', - ); + $opts = ['do' => 'admin', 'page' => 'acl']; if ($this->ns) $opts['ns'] = $this->ns; if ($this->who) $opts['acl_w'] = $this->who; @@ -233,26 +234,31 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin global $ID; global $lang; - $ns = $this->ns; + $ns = $this->ns; if (empty($ns)) { $ns = dirname(str_replace(':', '/', $ID)); - if ($ns == '.') $ns =''; + if ($ns == '.') $ns = ''; } elseif ($ns == '*') { - $ns =''; + $ns = ''; } - $ns = utf8_encodeFN(str_replace(':', '/', $ns)); + $ns = utf8_encodeFN(str_replace(':', '/', $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'].']')); + array_unshift($data, [ + 'level' => 0, + 'id' => '*', + 'type' => 'd', + 'open' => 'true', + 'label' => '[' . $lang['mediaroot'] . ']' + ]); echo html_buildlist( $data, 'acl', - array($this, 'makeTreeItem'), - array($this, 'makeListItem') + [$this, 'makeTreeItem'], + [$this, 'makeListItem'] ); } @@ -270,18 +276,18 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin global $conf; // read tree structure from pages and media - $data = array(); - 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 = []; + search($data, $conf['datadir'], 'search_index', ['ns' => $folder], $limit); + $media = []; + search($media, $conf['mediadir'], 'search_index', ['ns' => $folder, 'nofiles' => true], $limit); $data = array_merge($data, $media); unset($media); // combine by sorting and removing duplicates - usort($data, array($this, 'treeSort')); + usort($data, [$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 } @@ -311,14 +317,14 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin // if one of the components is the last component and is a file // and the other one is either of a deeper level or a directory, // the file has to come after the deeper level or directory - if (empty($a_ids) && $a['type'] == 'f' && (count($b_ids) || $b['type'] == 'd')) return 1; - if (empty($b_ids) && $b['type'] == 'f' && (count($a_ids) || $a['type'] == 'd')) return -1; + if ($a_ids === [] && $a['type'] == 'f' && (count($b_ids) || $b['type'] == 'd')) return 1; + if ($b_ids === [] && $b['type'] == 'f' && (count($a_ids) || $a['type'] == 'd')) return -1; return $cur_result; } } // The two ids seem to be equal. One of them might however refer // to a page, one to a namespace, the namespace needs to be first. - if (empty($a_ids) && empty($b_ids)) { + if ($a_ids === [] && $b_ids === []) { if ($a['type'] == $b['type']) return 0; if ($a['type'] == 'f') return 1; return -1; @@ -327,8 +333,8 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin // that obviously needs to be after the namespace // Or it is the namespace that contains the other part and should be // before that other part. - if (empty($a_ids)) return ($a['type'] == 'd') ? -1 : 1; - if (empty($b_ids)) return ($b['type'] == 'd') ? 1 : -1; + if ($a_ids === []) return ($a['type'] == 'd') ? -1 : 1; + if ($b_ids === []) return ($b['type'] == 'd') ? 1 : -1; return 0; //shouldn't happen } @@ -342,25 +348,28 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { global $ID; - echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL; + echo '<form action="' . wl() . '" method="post" accept-charset="utf-8"><div class="no">'; echo '<div id="acl__user">'; - echo $this->getLang('acl_perms').' '; - $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 $this->getLang('acl_perms') . ' '; + $inl = $this->makeSelect(); + echo sprintf( + '<input type="text" name="acl_w" class="edit" value="%s" />', + ($inl) ? '' : hsc(ltrim($this->who, '@')) + ); + echo '<button type="submit">' . $this->getLang('btn_select') . '</button>'; + echo '</div>'; echo '<div id="acl__info">'; $this->printInfo(); echo '</div>'; - echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL; - echo '<input type="hidden" name="id" value="'.hsc($ID).'" />'.NL; - echo '<input type="hidden" name="do" value="admin" />'.NL; - echo '<input type="hidden" name="page" value="acl" />'.NL; - echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />'.NL; - echo '</div></form>'.NL; + echo '<input type="hidden" name="ns" value="' . hsc($this->ns) . '" />'; + echo '<input type="hidden" name="id" value="' . hsc($ID) . '" />'; + echo '<input type="hidden" name="do" value="admin" />'; + echo '<input type="hidden" name="page" value="acl" />'; + echo '<input type="hidden" name="sectok" value="' . getSecurityToken() . '" />'; + echo '</div></form>'; } /** @@ -403,18 +412,18 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin echo '<fieldset>'; if (is_null($current)) { - echo '<legend>'.$this->getLang('acl_new').'</legend>'; + echo '<legend>' . $this->getLang('acl_new') . '</legend>'; } else { - echo '<legend>'.$this->getLang('acl_mod').'</legend>'; + echo '<legend>' . $this->getLang('acl_mod') . '</legend>'; } echo $this->makeCheckboxes($current, empty($this->ns), 'acl'); if (is_null($current)) { - echo '<button type="submit" name="cmd[save]">'.$lang['btn_save'].'</button>'.NL; + echo '<button type="submit" name="cmd[save]">' . $lang['btn_save'] . '</button>'; } 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; + echo '<button type="submit" name="cmd[save]">' . $lang['btn_update'] . '</button>'; + echo '<button type="submit" name="cmd[del]">' . $lang['btn_delete'] . '</button>'; } echo '</fieldset>'; @@ -431,14 +440,14 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin global $auth; $who = $this->who; - $ns = $this->ns; + $ns = $this->ns; // prepare where to check if ($ns) { if ($ns == '*') { - $check='*'; + $check = '*'; } else { - $check=$ns.':*'; + $check = $ns . ':*'; } } else { $check = $ID; @@ -446,13 +455,13 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin // prepare who to check if ($who[0] == '@') { - $user = ''; - $groups = array(ltrim($who, '@')); + $user = ''; + $groups = [ltrim($who, '@')]; } else { $user = $who; $info = $auth->getUserData($user); if ($info === false) { - $groups = array(); + $groups = []; } else { $groups = $info['grps']; } @@ -462,7 +471,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin $perm = auth_aclcheck($check, $user, $groups); // build array of named permissions - $names = array(); + $names = []; if ($perm) { if ($ns) { if ($perm >= AUTH_DELETE) $names[] = $this->getLang('acl_perm16'); @@ -480,24 +489,22 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin echo '<p>'; if ($user) { if ($ns) { - printf($this->getLang('p_user_ns'), hsc($who), hsc($ns), join(', ', $names)); + printf($this->getLang('p_user_ns'), hsc($who), hsc($ns), implode(', ', $names)); } else { - printf($this->getLang('p_user_id'), hsc($who), hsc($ID), join(', ', $names)); + printf($this->getLang('p_user_id'), hsc($who), hsc($ID), implode(', ', $names)); } + } elseif ($ns) { + printf($this->getLang('p_group_ns'), hsc(ltrim($who, '@')), hsc($ns), implode(', ', $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)); - } + printf($this->getLang('p_group_id'), hsc(ltrim($who, '@')), hsc($ID), implode(', ', $names)); } echo '</p>'; // add note if admin if ($perm == AUTH_ADMIN) { - echo '<p>'.$this->getLang('p_isadmin').'</p>'; + echo '<p>' . $this->getLang('p_isadmin') . '</p>'; } elseif (is_null($current)) { - echo '<p>'.$this->getLang('p_inherited').'</p>'; + echo '<p>' . $this->getLang('p_inherited') . '</p>'; } } @@ -516,36 +523,36 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin if (!empty($item['label'])) { $base = $item['label']; } else { - $base = ':'.$item['id']; - $base = substr($base, strrpos($base, ':')+1); + $base = ':' . $item['id']; + $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['type'] == 'd') { if ($item['open']) { - $img = DOKU_BASE.'lib/images/minus.gif'; - $alt = '−'; + $img = DOKU_BASE . 'lib/images/minus.gif'; + $alt = '−'; } else { - $img = DOKU_BASE.'lib/images/plus.gif'; - $alt = '+'; + $img = DOKU_BASE . 'lib/images/plus.gif'; + $alt = '+'; } - $ret .= '<img src="'.$img.'" alt="'.$alt.'" />'; - $ret .= '<a href="'. - wl('', $this->getLinkOptions(array('ns'=> $item['id'], 'sectok'=>getSecurityToken()))). - '" class="idx_dir'.$cl.'">'; + $ret .= '<img src="' . $img . '" alt="' . $alt . '" />'; + $ret .= '<a href="' . + wl('', $this->getLinkOptions(['ns' => $item['id'], 'sectok' => getSecurityToken()])) . + '" class="idx_dir' . $cl . '">'; $ret .= $base; $ret .= '</a>'; } else { - $ret .= '<a href="'. - wl('', $this->getLinkOptions(array('id'=> $item['id'], 'ns'=>'', 'sectok'=>getSecurityToken()))). - '" class="wikilink1'.$cl.'">'; + $ret .= '<a href="' . + wl('', $this->getLinkOptions(['id' => $item['id'], 'ns' => '', 'sectok' => getSecurityToken()])) . + '" class="wikilink1' . $cl . '">'; $ret .= noNS($item['id']); $ret .= '</a>'; } @@ -561,7 +568,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin public function makeListItem($item) { return '<li class="level' . $item['level'] . ' ' . - ($item['open'] ? 'open' : 'closed') . '">'; + ($item['open'] ? 'open' : 'closed') . '">'; } @@ -574,12 +581,12 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin { global $AUTH_ACL; global $conf; - $acl_config=array(); - $usersgroups = array(); + $acl_config = []; + $usersgroups = []; // get special users and groups $this->specials[] = '@ALL'; - $this->specials[] = '@'.$conf['defaultgroup']; + $this->specials[] = '@' . $conf['defaultgroup']; if ($conf['manager'] != '!!not set!!') { $this->specials = array_merge( $this->specials, @@ -630,51 +637,51 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin global $lang; global $ID; - echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL; + echo '<form action="' . wl() . '" method="post" accept-charset="utf-8"><div class="no">'; if ($this->ns) { - echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL; + echo '<input type="hidden" name="ns" value="' . hsc($this->ns) . '" />'; } else { - echo '<input type="hidden" name="id" value="'.hsc($ID).'" />'.NL; + echo '<input type="hidden" name="id" value="' . hsc($ID) . '" />'; } - echo '<input type="hidden" name="acl_w" value="'.hsc($this->who).'" />'.NL; - echo '<input type="hidden" name="do" value="admin" />'.NL; - echo '<input type="hidden" name="page" value="acl" />'.NL; - echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />'.NL; + echo '<input type="hidden" name="acl_w" value="' . hsc($this->who) . '" />'; + echo '<input type="hidden" name="do" value="admin" />'; + echo '<input type="hidden" name="page" value="acl" />'; + echo '<input type="hidden" name="sectok" value="' . getSecurityToken() . '" />'; echo '<div class="table">'; echo '<table class="inline">'; echo '<tr>'; - echo '<th>'.$this->getLang('where').'</th>'; - echo '<th>'.$this->getLang('who').'</th>'; - 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 '<th>' . $this->getLang('where') . '</th>'; + echo '<th>' . $this->getLang('who') . '</th>'; + 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) { echo '<tr>'; echo '<td>'; if (substr($where, -1) == '*') { - echo '<span class="aclns">'.hsc($where).'</span>'; + echo '<span class="aclns">' . hsc($where) . '</span>'; $ispage = false; } else { - echo '<span class="aclpage">'.hsc($where).'</span>'; + echo '<span class="aclpage">' . hsc($where) . '</span>'; $ispage = true; } echo '</td>'; echo '<td>'; if ($who[0] == '@') { - echo '<span class="aclgroup">'.hsc($who).'</span>'; + echo '<span class="aclgroup">' . hsc($who) . '</span>'; } else { - echo '<span class="acluser">'.hsc($who).'</span>'; + echo '<span class="acluser">' . hsc($who) . '</span>'; } echo '</td>'; echo '<td>'; - echo $this->makeCheckboxes($perm, $ispage, 'acl['.$where.']['.$who.']'); + echo $this->makeCheckboxes($perm, $ispage, 'acl[' . $where . '][' . $who . ']'); echo '</td>'; echo '<td class="check">'; - echo '<input type="checkbox" name="del['.hsc($where).'][]" value="'.hsc($who).'" />'; + echo '<input type="checkbox" name="del[' . hsc($where) . '][]" value="' . hsc($who) . '" />'; echo '</td>'; echo '</tr>'; } @@ -682,12 +689,12 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin echo '<tr>'; echo '<th class="action" colspan="4">'; - echo '<button type="submit" name="cmd[update]">'.$lang['btn_update'].'</button>'; + echo '<button type="submit" name="cmd[update]">' . $lang['btn_update'] . '</button>'; echo '</th>'; echo '</tr>'; echo '</table>'; echo '</div>'; - echo '</div></form>'.NL; + echo '</div></form>'; } /** @@ -703,7 +710,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin if ($this->ns == '*') { $check = '*'; } else { - $check = $this->ns.':*'; + $check = $this->ns . ':*'; } } else { $check = $ID; @@ -749,7 +756,7 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin global $config_cascade; $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); } @@ -769,16 +776,18 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin if ($ispage && $setperm > AUTH_EDIT) $setperm = AUTH_EDIT; - foreach (array(AUTH_NONE,AUTH_READ,AUTH_EDIT,AUTH_CREATE,AUTH_UPLOAD,AUTH_DELETE) as $perm) { - $label += 1; + foreach ([AUTH_NONE, AUTH_READ, AUTH_EDIT, AUTH_CREATE, AUTH_UPLOAD, AUTH_DELETE] as $perm) { + ++$label; //general checkbox attributes - $atts = array( 'type' => 'radio', - 'id' => 'pbox'.$label, - 'name' => $name, - 'value' => $perm ); + $atts = [ + 'type' => 'radio', + 'id' => 'pbox' . $label, + 'name' => $name, + 'value' => $perm + ]; //dynamic attributes - if (!is_null($setperm) && $setperm == $perm) $atts['checked'] = 'checked'; + if (!is_null($setperm) && $setperm == $perm) $atts['checked'] = 'checked'; if ($ispage && $perm > AUTH_EDIT) { $atts['disabled'] = 'disabled'; $class = ' class="disabled"'; @@ -787,10 +796,10 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin } //build code - $ret .= '<label for="pbox'.$label.'"'.$class.'>'; - $ret .= '<input '.buildAttributes($atts).' /> '; - $ret .= $this->getLang('acl_perm'.$perm); - $ret .= '</label>'.NL; + $ret .= '<label for="pbox' . $label . '"' . $class . '>'; + $ret .= '<input ' . buildAttributes($atts) . ' /> '; + $ret .= $this->getLang('acl_perm' . $perm); + $ret .= '</label>'; } return $ret; } @@ -806,9 +815,11 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin $usel = ''; $gsel = ''; - if ($this->who && - !in_array($this->who, $this->usersgroups) && - !in_array($this->who, $this->specials)) { + if ( + $this->who && + !in_array($this->who, $this->usersgroups) && + !in_array($this->who, $this->specials) + ) { if ($this->who[0] == '@') { $gsel = ' selected="selected"'; } else { @@ -818,46 +829,46 @@ class admin_plugin_acl extends DokuWiki_Admin_Plugin $inlist = true; } - echo '<select name="acl_t" class="edit">'.NL; - echo ' <option value="__g__" class="aclgroup"'.$gsel.'>'.$this->getLang('acl_group').'</option>'.NL; - echo ' <option value="__u__" class="acluser"'.$usel.'>'.$this->getLang('acl_user').'</option>'.NL; + echo '<select name="acl_t" class="edit">'; + echo ' <option value="__g__" class="aclgroup"' . $gsel . '>' . $this->getLang('acl_group') . '</option>'; + echo ' <option value="__u__" class="acluser"' . $usel . '>' . $this->getLang('acl_user') . '</option>'; if (!empty($this->specials)) { - echo ' <optgroup label=" ">'.NL; + echo ' <optgroup label=" ">'; foreach ($this->specials as $ug) { if ($ug == $this->who) { - $sel = ' selected="selected"'; + $sel = ' selected="selected"'; $inlist = true; } else { $sel = ''; } if ($ug[0] == '@') { - echo ' <option value="'.hsc($ug).'" class="aclgroup"'.$sel.'>'.hsc($ug).'</option>'.NL; + echo ' <option value="' . hsc($ug) . '" class="aclgroup"' . $sel . '>' . hsc($ug) . '</option>'; } else { - echo ' <option value="'.hsc($ug).'" class="acluser"'.$sel.'>'.hsc($ug).'</option>'.NL; + echo ' <option value="' . hsc($ug) . '" class="acluser"' . $sel . '>' . hsc($ug) . '</option>'; } } - echo ' </optgroup>'.NL; + echo ' </optgroup>'; } if (!empty($this->usersgroups)) { - echo ' <optgroup label=" ">'.NL; + echo ' <optgroup label=" ">'; foreach ($this->usersgroups as $ug) { if ($ug == $this->who) { - $sel = ' selected="selected"'; + $sel = ' selected="selected"'; $inlist = true; } else { $sel = ''; } if ($ug[0] == '@') { - echo ' <option value="'.hsc($ug).'" class="aclgroup"'.$sel.'>'.hsc($ug).'</option>'.NL; + echo ' <option value="' . hsc($ug) . '" class="aclgroup"' . $sel . '>' . hsc($ug) . '</option>'; } else { - echo ' <option value="'.hsc($ug).'" class="acluser"'.$sel.'>'.hsc($ug).'</option>'.NL; + echo ' <option value="' . hsc($ug) . '" class="acluser"' . $sel . '>' . hsc($ug) . '</option>'; } } - echo ' </optgroup>'.NL; + echo ' </optgroup>'; } - echo '</select>'.NL; + echo '</select>'; return $inlist; } } diff --git a/lib/plugins/acl/remote.php b/lib/plugins/acl/remote.php index 8d19add72..692e219c5 100644 --- a/lib/plugins/acl/remote.php +++ b/lib/plugins/acl/remote.php @@ -1,13 +1,13 @@ <?php +use dokuwiki\Extension\RemotePlugin; use dokuwiki\Remote\AccessDeniedException; /** * Class remote_plugin_acl */ -class remote_plugin_acl extends DokuWiki_Remote_Plugin +class remote_plugin_acl extends RemotePlugin { - /** * Returns details about the remote plugin methods * @@ -15,24 +15,26 @@ class remote_plugin_acl extends DokuWiki_Remote_Plugin */ public function _getMethods() { - return array( - 'listAcls' => array( - 'args' => array(), + return [ + 'listAcls' => [ + 'args' => [], 'return' => 'Array of ACLs {scope, user, permission}', 'name' => 'listAcls', - 'doc' => 'Get the list of all ACLs', - ),'addAcl' => array( - 'args' => array('string','string','int'), + 'doc' => 'Get the list of all ACLs' + ], + 'addAcl' => [ + 'args' => ['string', 'string', 'int'], 'return' => 'int', 'name' => 'addAcl', 'doc' => 'Adds a new ACL rule.' - ), 'delAcl' => array( - 'args' => array('string','string'), + ], + 'delAcl' => [ + 'args' => ['string', 'string'], 'return' => 'int', 'name' => 'delAcl', 'doc' => 'Delete an existing ACL rule.' - ), - ); + ] + ]; } /** diff --git a/lib/plugins/action.php b/lib/plugins/action.php index 5bf8da91e..e75f700a0 100644 --- a/lib/plugins/action.php +++ b/lib/plugins/action.php @@ -1,4 +1,9 @@ <?php -\dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction( - 'Autoloading', 1, 'require(' . basename(__FILE__) . ')' + +use dokuwiki\Debug\DebugHelper; + +DebugHelper::dbgDeprecatedFunction( + 'Autoloading', + 1, + 'require(' . basename(__FILE__) . ')' ); diff --git a/lib/plugins/admin.php b/lib/plugins/admin.php index 5bf8da91e..e75f700a0 100644 --- a/lib/plugins/admin.php +++ b/lib/plugins/admin.php @@ -1,4 +1,9 @@ <?php -\dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction( - 'Autoloading', 1, 'require(' . basename(__FILE__) . ')' + +use dokuwiki\Debug\DebugHelper; + +DebugHelper::dbgDeprecatedFunction( + 'Autoloading', + 1, + 'require(' . basename(__FILE__) . ')' ); diff --git a/lib/plugins/auth.php b/lib/plugins/auth.php index 5bf8da91e..e75f700a0 100644 --- a/lib/plugins/auth.php +++ b/lib/plugins/auth.php @@ -1,4 +1,9 @@ <?php -\dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction( - 'Autoloading', 1, 'require(' . basename(__FILE__) . ')' + +use dokuwiki\Debug\DebugHelper; + +DebugHelper::dbgDeprecatedFunction( + 'Autoloading', + 1, + 'require(' . basename(__FILE__) . ')' ); diff --git a/lib/plugins/authad/action.php b/lib/plugins/authad/action.php index 671138a98..904767f8d 100644 --- a/lib/plugins/authad/action.php +++ b/lib/plugins/authad/action.php @@ -1,4 +1,9 @@ <?php + +use dokuwiki\Extension\ActionPlugin; +use dokuwiki\Extension\EventHandler; +use dokuwiki\Extension\Event; + /** * DokuWiki Plugin addomain (Action Component) * @@ -9,13 +14,12 @@ /** * Class action_plugin_addomain */ -class action_plugin_authad extends DokuWiki_Action_Plugin +class action_plugin_authad extends ActionPlugin { - /** * Registers a callback function for a given event */ - public function register(Doku_Event_Handler $controller) + public function register(EventHandler $controller) { $controller->register_hook('AUTH_LOGIN_CHECK', 'BEFORE', $this, 'handleAuthLoginCheck'); $controller->register_hook('FORM_LOGIN_OUTPUT', 'BEFORE', $this, 'handleFormLoginOutput'); @@ -24,10 +28,10 @@ class action_plugin_authad extends DokuWiki_Action_Plugin /** * Adds the selected domain as user postfix when attempting a login * - * @param Doku_Event $event + * @param Event $event * @param array $param */ - public function handleAuthLoginCheck(Doku_Event $event, $param) + public function handleAuthLoginCheck(Event $event, $param) { global $INPUT; @@ -39,7 +43,7 @@ class action_plugin_authad extends DokuWiki_Action_Plugin $usr = $auth->cleanUser($event->data['user']); $dom = $auth->getUserDomain($usr); if (!$dom) { - $usr = "$usr@".$INPUT->str('dom'); + $usr = "$usr@" . $INPUT->str('dom'); } $INPUT->post->set('u', $usr); $event->data['user'] = $usr; @@ -49,10 +53,10 @@ class action_plugin_authad extends DokuWiki_Action_Plugin /** * Shows a domain selection in the login form when more than one domain is configured * - * @param Doku_Event $event + * @param Event $event * @param array $param */ - public function handleFormLoginOutput(Doku_Event $event, $param) + public function handleFormLoginOutput(Event $event, $param) { global $INPUT; /** @var auth_plugin_authad $auth */ @@ -82,7 +86,7 @@ class action_plugin_authad extends DokuWiki_Action_Plugin } // add locate domain selector just after the username input box - $element = $form->addDropdown('dom', $domains, $this->getLang('domain'), $pos +1); + $element = $form->addDropdown('dom', $domains, $this->getLang('domain'), $pos + 1); $element->addClass('block'); } } diff --git a/lib/plugins/authad/auth.php b/lib/plugins/authad/auth.php index 0c3690f0a..47665c31f 100644 --- a/lib/plugins/authad/auth.php +++ b/lib/plugins/authad/auth.php @@ -1,4 +1,8 @@ <?php + +use dokuwiki\Extension\AuthPlugin; +use dokuwiki\Utf8\Clean; +use dokuwiki\Utf8\PhpString; use dokuwiki\Utf8\Sort; use dokuwiki\Logger; @@ -38,18 +42,17 @@ use dokuwiki\Logger; * @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 AuthPlugin { - /** * @var array hold connection data for a specific AD domain */ - protected $opts = array(); + protected $opts = []; /** * @var array open connections for each AD domain, as adLDAP objects */ - protected $adldap = array(); + protected $adldap = []; /** * @var bool message state @@ -59,14 +62,14 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin /** * @var array user listing cache */ - protected $users = array(); + protected $users = []; /** * @var array filter patterns for listing users */ - protected $pattern = array(); + protected $pattern = []; - protected $grpsusers = array(); + protected $grpsusers = []; /** * Constructor @@ -76,8 +79,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin global $INPUT; parent::__construct(); - require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php'); - require_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php'); + 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(); @@ -86,7 +89,7 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin 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(); + } else $this->conf['additional'] = []; // ldap extension is needed if (!function_exists('ldap_connect')) { @@ -100,9 +103,11 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin if (!empty($INPUT->server->str('REMOTE_USER'))) { // make sure the right encoding is used if ($this->getConf('sso_charset')) { - $INPUT->server->set('REMOTE_USER', - iconv($this->getConf('sso_charset'), 'UTF-8', $INPUT->server->str('REMOTE_USER'))); - } elseif (!\dokuwiki\Utf8\Clean::isUtf8($INPUT->server->str('REMOTE_USER'))) { + $INPUT->server->set( + 'REMOTE_USER', + iconv($this->getConf('sso_charset'), 'UTF-8', $INPUT->server->str('REMOTE_USER')) + ); + } elseif (!Clean::isUtf8($INPUT->server->str('REMOTE_USER'))) { $INPUT->server->set('REMOTE_USER', utf8_encode($INPUT->server->str('REMOTE_USER'))); } @@ -154,7 +159,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin public function checkPass($user, $pass) { global $INPUT; - if ($INPUT->server->str('REMOTE_USER') == $user && + if ( + $INPUT->server->str('REMOTE_USER') == $user && $this->conf['sso'] ) return true; @@ -201,11 +207,11 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin global $ID; global $INPUT; $adldap = $this->initAdLdap($this->getUserDomain($user)); - if (!$adldap) return array(); + if (!$adldap) return []; - if ($user == '') return array(); + if ($user == '') return []; - $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol'); + $fields = ['mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol']; // add additional fields to read $fields = array_merge($fields, $this->conf['additional']); @@ -215,17 +221,17 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin //get info for given user $result = $adldap->user()->info($this->getUserName($user), $fields); if ($result == false) { - return array(); + return []; } //general user info - $info = array(); + $info = []; $info['name'] = $result[0]['displayname'][0]; $info['mail'] = $result[0]['mail'][0]; $info['uid'] = $result[0]['samaccountname'][0]; $info['dn'] = $result[0]['dn']; //last password set (Windows counts from January 1st 1601) - $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600; + $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10_000_000 - 11_644_473_600; //will it expire? $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD @@ -252,7 +258,7 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin // add the user's domain to the groups $domain = $this->getUserDomain($user); - if ($domain && !in_array("domain-$domain", (array) $info['grps'])) { + if ($domain && !in_array("domain-$domain", $info['grps'])) { $info['grps'][] = $this->cleanGroup("domain-$domain"); } @@ -262,17 +268,18 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin $expiry = $adldap->user()->passwordExpiry($user); if (is_array($expiry)) { $info['expiresat'] = $expiry['expiryts']; - $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60)); + $info['expiresin'] = round(($info['expiresat'] - time()) / (24 * 60 * 60)); // if this is the current user, warn him (once per request only) - if (($INPUT->server->str('REMOTE_USER') == $user) && + if ( + ($INPUT->server->str('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>'; + $url = wl($ID, ['do' => 'profile']); + $msg .= ' <a href="' . $url . '">' . $lang['btn_profile'] . '</a>'; } msg($msg); $this->msgshown = true; @@ -300,7 +307,7 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin $group = str_replace('\\', '', $group); $group = str_replace('#', '', $group); $group = preg_replace('[\s]', '_', $group); - $group = \dokuwiki\Utf8\PhpString::strtolower(trim($group)); + $group = PhpString::strtolower(trim($group)); return $group; } @@ -318,19 +325,21 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin $domain = ''; // get NTLM or Kerberos domain part - list($dom, $user) = sexplode('\\', $user, 2, ''); + [$dom, $user] = sexplode('\\', $user, 2, ''); if (!$user) $user = $dom; if ($dom) $domain = $dom; - list($user, $dom) = sexplode('@', $user, 2, ''); + [$user, $dom] = sexplode('@', $user, 2, ''); if ($dom) $domain = $dom; // clean up both - $domain = \dokuwiki\Utf8\PhpString::strtolower(trim($domain)); - $user = \dokuwiki\Utf8\PhpString::strtolower(trim($user)); + $domain = PhpString::strtolower(trim($domain)); + $user = PhpString::strtolower(trim($user)); // is this a known, valid domain or do we work without account suffix? if not discard - if ((!isset($this->conf[$domain]) || !is_array($this->conf[$domain])) && - $this->conf['account_suffix'] !== '') { + if ( + (!isset($this->conf[$domain]) || !is_array($this->conf[$domain])) && + $this->conf['account_suffix'] !== '' + ) { $domain = ''; } @@ -385,14 +394,14 @@ 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()) + public function getUserCount($filter = []) { $adldap = $this->initAdLdap(null); if (!$adldap) { Logger::debug("authad/auth.php getUserCount(): _adldap not set."); return -1; } - if ($filter == array()) { + if ($filter == []) { $result = $adldap->user()->all(); } else { $searchString = $this->constructSearchString($filter); @@ -403,14 +412,15 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin $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()); + } elseif ( + count($this->grpsusers[$this->filterToString($filter)]) < + $usermanager->getStart() + 3 * $usermanager->getPagesize() ) { $this->fillGroupUserArray( $filter, $usermanager->getStart() + - 3*$usermanager->getPagesize() - + 3 * $usermanager->getPagesize() - count($this->grpsusers[$this->filterToString($filter)]) ); } @@ -471,7 +481,7 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin $actualstart = 0; } - $i=0; + $i = 0; $count = 0; $this->constructPattern($filter); foreach ($this->users as $user => &$info) { @@ -499,21 +509,21 @@ 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()) + public function retrieveUsers($start = 0, $limit = 0, $filter = []) { $adldap = $this->initAdLdap(null); - if (!$adldap) return array(); + if (!$adldap) return []; //if (!$this->users) { //get info for given user $result = $adldap->user()->all(false, $this->constructSearchString($filter)); - if (!$result) return array(); + if (!$result) return []; $this->users = array_fill_keys($result, false); //} $i = 0; $count = 0; - $result = array(); + $result = []; if (!isset($filter['grps'])) { /** @var admin_plugin_usermanager $usermanager */ @@ -534,19 +544,20 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin /** @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) + if ( + !isset($this->grpsusers[$this->filterToString($filter)]) || + count($this->grpsusers[$this->filterToString($filter)]) < ($start + $limit) ) { - if(!isset($this->grpsusers[$this->filterToString($filter)])) { + if (!isset($this->grpsusers[$this->filterToString($filter)])) { $this->grpsusers[$this->filterToString($filter)] = []; } $this->fillGroupUserArray( $filter, - $start+$limit - count($this->grpsusers[$this->filterToString($filter)]) +1 + $start + $limit - count($this->grpsusers[$this->filterToString($filter)]) + 1 ); } - if (!$this->grpsusers[$this->filterToString($filter)]) return array(); + if (!$this->grpsusers[$this->filterToString($filter)]) return []; foreach ($this->grpsusers[$this->filterToString($filter)] as $user => &$info) { if ($i++ < $start) { continue; @@ -579,29 +590,29 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin try { $return = $adldap->user()->password($this->getUserName($user), $changes['pass']); } catch (adLDAPException $e) { - if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1); + if ($this->conf['debug']) msg('AD Auth: ' . $e->getMessage(), -1); $return = false; } if (!$return) msg($this->getLang('passchangefail'), -1); } // changing user data - $adchanges = array(); + $adchanges = []; if (isset($changes['name'])) { // get first and last name $parts = explode(' ', $changes['name']); $adchanges['surname'] = array_pop($parts); - $adchanges['firstname'] = join(' ', $parts); + $adchanges['firstname'] = implode(' ', $parts); $adchanges['display_name'] = $changes['name']; } if (isset($changes['mail'])) { $adchanges['email'] = $changes['mail']; } - if (count($adchanges)) { + if ($adchanges !== []) { try { - $return = $return & $adldap->user()->modify($this->getUserName($user), $adchanges); + $return &= $adldap->user()->modify($this->getUserName($user), $adchanges); } catch (adLDAPException $e) { - if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1); + if ($this->conf['debug']) msg('AD Auth: ' . $e->getMessage(), -1); $return = false; } if (!$return) msg($this->getLang('userchangefail'), -1); @@ -635,7 +646,7 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin return $this->adldap[$domain]; } catch (Exception $e) { if ($this->conf['debug']) { - msg('AD Auth: '.$e->getMessage(), -1); + msg('AD Auth: ' . $e->getMessage(), -1); } $this->success = false; $this->adldap[$domain] = null; @@ -651,7 +662,7 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin */ public function getUserDomain($user) { - list(, $domain) = sexplode('@', $user, 2, ''); + [, $domain] = sexplode('@', $user, 2, ''); return $domain; } @@ -666,7 +677,7 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin public function getUserName($user) { if ($this->conf['account_suffix'] !== '') { - list($user) = explode('@', $user, 2); + [$user] = explode('@', $user, 2); } return $user; } @@ -733,7 +744,7 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin */ public function getConfiguredDomains() { - $domains = array(); + $domains = []; if (empty($this->conf['account_suffix'])) return $domains; // not configured yet // add default domain, using the name from account suffix @@ -768,8 +779,8 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin 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; + } elseif (!preg_match($pattern, $info[$item])) { + return false; } } return true; @@ -784,9 +795,9 @@ class auth_plugin_authad extends DokuWiki_Auth_Plugin */ protected function constructPattern($filter) { - $this->pattern = array(); + $this->pattern = []; foreach ($filter as $item => $pattern) { - $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters + $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters } } } diff --git a/lib/plugins/authad/conf/metadata.php b/lib/plugins/authad/conf/metadata.php index 96d8937ae..aa5d92e5c 100644 --- a/lib/plugins/authad/conf/metadata.php +++ b/lib/plugins/authad/conf/metadata.php @@ -11,7 +11,7 @@ $meta['real_primarygroup'] = array('onoff','_caution' => 'danger'); $meta['use_ssl'] = array('onoff','_caution' => 'danger'); $meta['use_tls'] = array('onoff','_caution' => 'danger'); $meta['debug'] = array('onoff','_caution' => 'security'); -$meta['expirywarn'] = array('numeric', '_min'=>0,'_caution' => 'danger'); +$meta['expirywarn'] = array('numeric', '_min' => 0,'_caution' => 'danger'); $meta['additional'] = array('string','_caution' => 'danger'); $meta['update_name'] = array('onoff','_caution' => 'danger'); $meta['update_mail'] = array('onoff','_caution' => 'danger'); diff --git a/lib/plugins/authldap/auth.php b/lib/plugins/authldap/auth.php index 71b2584cb..213e43f29 100644 --- a/lib/plugins/authldap/auth.php +++ b/lib/plugins/authldap/auth.php @@ -1,4 +1,7 @@ <?php + +use dokuwiki\Extension\AuthPlugin; +use dokuwiki\PassHash; use dokuwiki\Utf8\Sort; /** @@ -9,19 +12,19 @@ use dokuwiki\Utf8\Sort; * @author Chris Smith <chris@jalakaic.co.uk> * @author Jan Schumann <js@schumann-it.com> */ -class auth_plugin_authldap extends DokuWiki_Auth_Plugin +class auth_plugin_authldap extends AuthPlugin { /* @var resource $con holds the LDAP connection */ - protected $con = null; + protected $con; /* @var int $bound What type of connection does already exist? */ protected $bound = 0; // 0: anonymous, 1: user, 2: superuser /* @var array $users User data cache */ - protected $users = null; + protected $users; /* @var array $pattern User filter pattern */ - protected $pattern = null; + protected $pattern; /** * Constructor @@ -67,28 +70,27 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin return false; } $this->bound = 2; - } elseif ($this->getConf('binddn') && + } elseif ( + $this->getConf('binddn') && $this->getConf('usertree') && $this->getConf('userfilter') ) { // special bind string $dn = $this->makeFilter( $this->getConf('binddn'), - array('user' => $user, 'server' => $this->getConf('server')) + ['user' => $user, 'server' => $this->getConf('server')] ); } elseif (strpos($this->getConf('usertree'), '%{user}')) { // direct user bind $dn = $this->makeFilter( $this->getConf('usertree'), - array('user' => $user, 'server' => $this->getConf('server')) + ['user' => $user, 'server' => $this->getConf('server')] ); - } else { + } elseif (!@ldap_bind($this->con)) { // Anonymous bind - if (!@ldap_bind($this->con)) { - msg("LDAP: can not bind anonymously", -1); - $this->debug('LDAP anonymous bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); - return false; - } + msg("LDAP: can not bind anonymously", -1); + $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. @@ -162,28 +164,28 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin protected function fetchUserData($user, $inbind = false) { global $conf; - if (!$this->openLDAP()) return array(); + if (!$this->openLDAP()) return []; // force superuser bind if wanted and not bound as superuser yet 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: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); - return array(); + return []; } $this->bound = 2; } 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(); + [$loginuser, $loginsticky, $loginpass] = auth_getCookie(); if ($loginuser && $loginpass) { $loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true)); $this->checkPass($loginuser, $loginpass); } } - $info = array(); + $info = []; $info['user'] = $user; $this->debug('LDAP user to find: ' . hsc($info['user']), 0, __LINE__, __FILE__); @@ -204,8 +206,8 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__); $sr = $this->ldapSearch($this->con, $base, $filter, $this->getConf('userscope'), $this->getConf('attributes')); if ($sr === false) { - $this->debug('User ldap_search failed. Check configuration.', 0, __LINE__, __FILE__); - return false; + $this->debug('User ldap_search failed. Check configuration.', 0, __LINE__, __FILE__); + return false; } $result = @ldap_get_entries($this->con, $sr); @@ -214,7 +216,7 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin if (!is_array($result)) { // no objects found $this->debug('LDAP search returned non-array result: ' . hsc(print($result)), -1, __LINE__, __FILE__); - return array(); + return []; } // Don't accept more or less than one response @@ -228,7 +230,7 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin //for($i = 0; $i < $result["count"]; $i++) { //$this->_debug('result: '.hsc(print_r($result[$i])), 0, __LINE__, __FILE__); //} - return array(); + return []; } $this->debug('LDAP search found single result !', 0, __LINE__, __FILE__); @@ -241,7 +243,7 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin $info['gid'] = $user_result['gidnumber'][0] ?? null; $info['mail'] = $user_result['mail'][0]; $info['name'] = $user_result['cn'][0]; - $info['grps'] = array(); + $info['grps'] = []; // overwrite if other attribs are specified. if (is_array($this->getConf('mapping'))) { @@ -276,14 +278,14 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin $base, $filter, $this->getConf('groupscope'), - array($this->getConf('groupkey')) + [$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 array(); + return []; } $result = ldap_get_entries($this->con, $sr); ldap_free_result($sr); @@ -305,7 +307,7 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin } // always add the default group to the list of groups - if (!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) { + if (!$info['grps'] || !in_array($conf['defaultgroup'], $info['grps'])) { $info['grps'][] = $conf['defaultgroup']; } return $info; @@ -336,7 +338,7 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin $dn = $info['dn']; // find the old password of the user - list($loginuser, $loginsticky, $loginpass) = auth_getCookie(); + [$loginuser, $loginsticky, $loginpass] = auth_getCookie(); if ($loginuser !== null) { // the user is currently logged in $secret = auth_cookiesalt(!$loginsticky, true); $pass = auth_decrypt($loginpass, $secret); @@ -363,11 +365,11 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin } // Generate the salted hashed password for LDAP - $phash = new \dokuwiki\PassHash(); + $phash = new PassHash(); $hash = $phash->hash_ssha($changes['pass']); // change the password - if (!@ldap_mod_replace($this->con, $dn, array('userpassword' => $hash))) { + if (!@ldap_mod_replace($this->con, $dn, ['userpassword' => $hash])) { $this->debug( 'LDAP mod replace failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)), 0, @@ -399,9 +401,9 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin * @return array of userinfo (refer getUserData for internal userinfo details) * @author Dominik Eckelmann <dokuwiki@cosmocode.de> */ - public function retrieveUsers($start = 0, $limit = 0, $filter = array()) + public function retrieveUsers($start = 0, $limit = 0, $filter = []) { - if (!$this->openLDAP()) return array(); + if (!$this->openLDAP()) return []; if (is_null($this->users)) { // Perform the search and grab all their details @@ -412,20 +414,20 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin } $sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter); $entries = ldap_get_entries($this->con, $sr); - $users_array = array(); + $users_array = []; $userkey = $this->getConf('userkey'); for ($i = 0; $i < $entries["count"]; $i++) { - array_push($users_array, $entries[$i][$userkey][0]); + $users_array[] = $entries[$i][$userkey][0]; } Sort::asort($users_array); $result = $users_array; - if (!$result) return array(); + if (!$result) return []; $this->users = array_fill_keys($result, false); } $i = 0; $count = 0; $this->constructPattern($filter); - $result = array(); + $result = []; foreach ($this->users as $user => &$info) { if ($i++ < $start) { @@ -486,8 +488,8 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin 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; + } elseif (!preg_match($pattern, $info[$item])) { + return false; } } return true; @@ -503,7 +505,7 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin */ protected function constructPattern($filter) { - $this->pattern = array(); + $this->pattern = []; foreach ($filter as $item => $pattern) { $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters } @@ -523,9 +525,7 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin // see https://github.com/adldap/adLDAP/issues/22 return preg_replace_callback( '/([\x00-\x1F\*\(\)\\\\])/', - function ($matches) { - return "\\" . join("", unpack("H2", $matches[1])); - }, + static fn($matches) => "\\" . implode("", unpack("H2", $matches[1])), $string ); } @@ -566,11 +566,12 @@ 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, - $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: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); @@ -584,11 +585,12 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin } // needs version 3 if ($this->getConf('referrals') > -1) { - if (!@ldap_set_option( - $this->con, - LDAP_OPT_REFERRALS, - $this->getConf('referrals') - ) + if ( + !@ldap_set_option( + $this->con, + LDAP_OPT_REFERRALS, + $this->getConf('referrals') + ) ) { msg('Setting LDAP referrals failed', -1); $this->debug('LDAP referal set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__); @@ -651,9 +653,8 @@ class auth_plugin_authldap extends DokuWiki_Auth_Plugin $attributes = null, $attrsonly = 0, $sizelimit = 0 - ) - { - if (is_null($attributes)) $attributes = array(); + ) { + if (is_null($attributes)) $attributes = []; if ($scope == 'base') { return @ldap_read( diff --git a/lib/plugins/authldap/conf/metadata.php b/lib/plugins/authldap/conf/metadata.php index 3a58590a8..db33d8b51 100644 --- a/lib/plugins/authldap/conf/metadata.php +++ b/lib/plugins/authldap/conf/metadata.php @@ -1,4 +1,5 @@ <?php + $meta['server'] = array('string','_caution' => 'danger'); $meta['port'] = array('numeric','_caution' => 'danger'); $meta['usertree'] = array('string','_caution' => 'danger'); @@ -10,7 +11,7 @@ $meta['starttls'] = array('onoff','_caution' => 'danger'); $meta['referrals'] = array('multichoice','_choices' => array(-1,0,1),'_caution' => 'danger'); $meta['deref'] = array('multichoice','_choices' => array(0,1,2,3),'_caution' => 'danger'); $meta['binddn'] = array('string','_caution' => 'danger'); -$meta['bindpw'] = array('password','_caution' => 'danger','_code'=>'base64'); +$meta['bindpw'] = array('password','_caution' => 'danger','_code' => 'base64'); $meta['attributes'] = array('array'); //$meta['mapping']['name'] unsupported in config manager //$meta['mapping']['grps'] unsupported in config manager diff --git a/lib/plugins/authpdo/auth.php b/lib/plugins/authpdo/auth.php index f58ad0247..47fe9cfc6 100644 --- a/lib/plugins/authpdo/auth.php +++ b/lib/plugins/authpdo/auth.php @@ -1,4 +1,7 @@ <?php + +use dokuwiki\Extension\AuthPlugin; +use dokuwiki\PassHash; use dokuwiki\Utf8\Sort; /** @@ -11,14 +14,13 @@ use dokuwiki\Utf8\Sort; /** * Class auth_plugin_authpdo */ -class auth_plugin_authpdo extends DokuWiki_Auth_Plugin +class auth_plugin_authpdo extends AuthPlugin { - /** @var PDO */ protected $pdo; /** @var null|array The list of all groups */ - protected $groupcache = null; + protected $groupcache; /** * Constructor. @@ -44,11 +46,11 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin $this->getConf('dsn'), $this->getConf('user'), conf_decodeString($this->getConf('pass')), - array( + [ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // always fetch as array PDO::ATTR_EMULATE_PREPARES => true, // emulating prepares allows us to reuse param names PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // we want exceptions, not error codes - ) + ] ); } catch (PDOException $e) { $this->debugMsg($e); @@ -59,94 +61,52 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin // can Users be created? $this->cando['addUser'] = $this->checkConfig( - array( - 'select-user', - 'select-user-groups', - 'select-groups', - 'insert-user', - 'insert-group', - 'join-group' - ) + ['select-user', 'select-user-groups', 'select-groups', 'insert-user', 'insert-group', 'join-group'] ); // can Users be deleted? $this->cando['delUser'] = $this->checkConfig( - array( - 'select-user', - 'select-user-groups', - 'select-groups', - 'leave-group', - 'delete-user' - ) + ['select-user', 'select-user-groups', 'select-groups', 'leave-group', 'delete-user'] ); // can login names be changed? $this->cando['modLogin'] = $this->checkConfig( - array( - 'select-user', - 'select-user-groups', - 'update-user-login' - ) + ['select-user', 'select-user-groups', 'update-user-login'] ); // can passwords be changed? $this->cando['modPass'] = $this->checkConfig( - array( - 'select-user', - 'select-user-groups', - 'update-user-pass' - ) + ['select-user', 'select-user-groups', 'update-user-pass'] ); // can real names be changed? $this->cando['modName'] = $this->checkConfig( - array( - 'select-user', - 'select-user-groups', - 'update-user-info:name' - ) + ['select-user', 'select-user-groups', 'update-user-info:name'] ); // can real email be changed? $this->cando['modMail'] = $this->checkConfig( - array( - 'select-user', - 'select-user-groups', - 'update-user-info:mail' - ) + ['select-user', 'select-user-groups', 'update-user-info:mail'] ); // can groups be changed? $this->cando['modGroups'] = $this->checkConfig( - array( - 'select-user', - 'select-user-groups', - 'select-groups', - 'leave-group', - 'join-group', - 'insert-group' - ) + ['select-user', 'select-user-groups', 'select-groups', 'leave-group', 'join-group', 'insert-group'] ); // can a filtered list of users be retrieved? $this->cando['getUsers'] = $this->checkConfig( - array( - 'list-users' - ) + ['list-users'] ); // can the number of users be retrieved? $this->cando['getUserCount'] = $this->checkConfig( - array( - 'count-users' - ) + ['count-users'] ); // can a list of available groups be retrieved? $this->cando['getGroups'] = $this->checkConfig( - array( - 'select-groups' - ) + ['select-groups'] ); $this->success = true; @@ -166,7 +126,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin if ($userdata == false) return false; // password checking done in SQL? - if ($this->checkConfig(array('check-pass'))) { + if ($this->checkConfig(['check-pass'])) { $userdata['clear'] = $pass; $userdata['hash'] = auth_cryptPassword($pass); $result = $this->query($this->getConf('check-pass'), $userdata); @@ -177,7 +137,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin // we do password checking on our own if (isset($userdata['hash'])) { // hashed password - $passhash = new \dokuwiki\PassHash(); + $passhash = new PassHash(); return $passhash->verify_hash($pass, $userdata['hash']); } else { // clear text password in the database O_o @@ -243,11 +203,11 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin } // prepare data - if ($grps == null) $grps = array(); + if ($grps == null) $grps = []; array_unshift($grps, $conf['defaultgroup']); $grps = array_unique($grps); $hash = auth_cryptPassword($clear); - $userdata = compact('user', 'clear', 'hash', 'name', 'mail'); + $userdata = ['user' => $user, 'clear' => $clear, 'hash' => $hash, 'name' => $name, 'mail' => $mail]; // action protected by transaction $this->pdo->beginTransaction(); @@ -260,19 +220,19 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin // 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; - } + foreach ($grps as $group) { + if (!isset($allgroups[$group])) { + $ok = $this->addGroup($group); + if ($ok === false) goto FAIL; } + } $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; @@ -302,67 +262,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(); @@ -406,10 +366,10 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin 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 (is_null($filter)) $filter = []; if (isset($filter['grps'])) $filter['group'] = $filter['grps']; - foreach (array('user', 'name', 'mail', 'group') as $key) { + foreach (['user', 'name', 'mail', 'group'] as $key) { if (!isset($filter[$key])) { $filter[$key] = '%'; } else { @@ -421,13 +381,13 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin $filter['limit'] = (int)$limit; $result = $this->query($this->getConf('list-users'), $filter); - if (!$result) return array(); - $users = array(); + if (!$result) return []; + $users = []; if (is_array($result)) { foreach ($result as $row) { if (!isset($row['user'])) { $this->debugMsg("list-users statement did not return 'user' attribute", -1, __LINE__); - return array(); + return []; } $users[] = $this->getUserData($row['user']); } @@ -443,12 +403,12 @@ 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()) + public function getUserCount($filter = []) { - if (is_null($filter)) $filter = array(); + if (is_null($filter)) $filter = []; if (isset($filter['grps'])) $filter['group'] = $filter['grps']; - foreach (array('user', 'name', 'mail', 'group') as $key) { + foreach (['user', 'name', 'mail', 'group'] as $key) { if (!isset($filter[$key])) { $filter[$key] = '%'; } else { @@ -473,7 +433,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { $sql = $this->getConf('insert-group'); - $result = $this->query($sql, array(':group' => $group)); + $result = $this->query($sql, [':group' => $group]); $this->clearGroupCache(); if ($result === false) return false; return true; @@ -491,7 +451,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin public function retrieveGroups($start = 0, $limit = 0) { $groups = array_keys($this->selectGroups()); - if ($groups === false) return array(); + if ($groups === false) return []; if (!$limit) { return array_splice($groups, $start); @@ -510,7 +470,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin { $sql = $this->getConf('select-user'); - $result = $this->query($sql, array(':user' => $user)); + $result = $this->query($sql, [':user' => $user]); if (!$result) return false; if (count($result) > 1) { @@ -525,7 +485,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin $this->debugMsg("Statement did not return 'user' attribute", -1, __LINE__); $dataok = false; } - if (!isset($data['hash']) && !isset($data['clear']) && !$this->checkConfig(array('check-pass'))) { + if (!isset($data['hash']) && !isset($data['clear']) && !$this->checkConfig(['check-pass'])) { $this->debugMsg("Statement did not return 'clear' or 'hash' attribute", -1, __LINE__); $dataok = false; } @@ -557,11 +517,11 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin $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; @@ -587,7 +547,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin $result = $this->query($sql, $userdata); if ($result === false) return false; - $groups = array($conf['defaultgroup']); // always add default config + $groups = [$conf['defaultgroup']]; // always add default config if (is_array($result)) { foreach ($result as $row) { if (!isset($row['group'])) { @@ -618,7 +578,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin $result = $this->query($sql); if ($result === false) return false; - $groups = array(); + $groups = []; if (is_array($result)) { foreach ($result as $row) { if (!isset($row['group'])) { @@ -685,7 +645,7 @@ 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 = []) { $sql = trim($sql); if (empty($sql)) { @@ -694,7 +654,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin } // execute - $params = array(); + $params = []; $sth = $this->pdo->prepare($sql); $result = false; try { @@ -703,7 +663,7 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin 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 (strpos($sql, (string) $key) === false) continue; // skip if parameter is missing if (is_int($value)) { $sth->bindValue($key, $value, PDO::PARAM_INT); @@ -742,7 +702,6 @@ class auth_plugin_authpdo extends DokuWiki_Auth_Plugin $this->debugMsg("SQL: <pre>$dsql</pre>", -1, $line); } $sth->closeCursor(); - $sth = null; return $result; } diff --git a/lib/plugins/authpdo/conf/default.php b/lib/plugins/authpdo/conf/default.php index 138ca2f10..de15979b3 100644 --- a/lib/plugins/authpdo/conf/default.php +++ b/lib/plugins/authpdo/conf/default.php @@ -1,4 +1,5 @@ <?php + /** * Default settings for the authpdo plugin * diff --git a/lib/plugins/authpdo/conf/metadata.php b/lib/plugins/authpdo/conf/metadata.php index 34e60a40e..bf427e5ba 100644 --- a/lib/plugins/authpdo/conf/metadata.php +++ b/lib/plugins/authpdo/conf/metadata.php @@ -1,4 +1,5 @@ <?php + /** * Options for the authpdo plugin * diff --git a/lib/plugins/authplain/auth.php b/lib/plugins/authplain/auth.php index e0c1b9291..370e6cfa0 100644 --- a/lib/plugins/authplain/auth.php +++ b/lib/plugins/authplain/auth.php @@ -1,5 +1,6 @@ <?php +use dokuwiki\Extension\AuthPlugin; use dokuwiki\Logger; use dokuwiki\Utf8\Sort; @@ -11,13 +12,13 @@ use dokuwiki\Utf8\Sort; * @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 AuthPlugin { /** @var array user cache */ - protected $users = null; + protected $users; /** @var array filter pattern */ - protected $pattern = array(); + protected $pattern = []; /** @var bool safe version of preg_split */ protected $pregsplit_safe = false; @@ -90,7 +91,7 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin public function getUserData($user, $requireGroups = true) { if ($this->users === null) $this->loadUserData(); - return isset($this->users[$user]) ? $this->users[$user] : false; + return $this->users[$user] ?? false; } /** @@ -107,11 +108,11 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin */ protected function createUserLine($user, $pass, $name, $mail, $grps) { - $groups = join(',', $grps); - $userline = array($user, $pass, $name, $mail, $groups); + $groups = implode(',', $grps); + $userline = [$user, $pass, $name, $mail, $groups]; $userline = str_replace('\\', '\\\\', $userline); // escape \ as \\ $userline = str_replace(':', '\\:', $userline); // escape : as \: - $userline = join(':', $userline)."\n"; + $userline = implode(':', $userline) . "\n"; return $userline; } @@ -148,7 +149,7 @@ 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 = [$conf['defaultgroup']]; // prepare user line $userline = $this->createUserLine($user, $pass, $name, $mail, $grps); @@ -158,7 +159,12 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin return null; } - $this->users[$user] = compact('pass', 'name', 'mail', 'grps'); + $this->users[$user] = [ + 'pass' => $pass, + 'name' => $name, + 'mail' => $mail, + 'grps' => $grps + ]; return $pwd; } @@ -187,7 +193,7 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin return false; } - if (!is_array($changes) || !count($changes)) return true; + if (!is_array($changes) || $changes === []) return true; // update userinfo with new data, remembering to encrypt any password $newuser = $user; @@ -208,14 +214,14 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin $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'; return false; } - if(isset($this->users[$user])) unset($this->users[$user]); + if (isset($this->users[$user])) unset($this->users[$user]); $this->users[$newuser] = $userinfo; return true; } @@ -231,11 +237,11 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin { global $config_cascade; - if (!is_array($users) || empty($users)) return 0; + if (!is_array($users) || $users === []) return 0; if ($this->users === null) $this->loadUserData(); - $deleted = array(); + $deleted = []; foreach ($users as $user) { // don't delete protected users if (!empty($this->users[$user]['protected'])) { @@ -245,9 +251,9 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin if (isset($this->users[$user])) $deleted[] = preg_quote($user, '/'); } - if (empty($deleted)) return 0; + if ($deleted === []) return 0; - $pattern = '/^('.join('|', $deleted).'):/'; + $pattern = '/^(' . implode('|', $deleted) . '):/'; if (!io_deleteFromFile($config_cascade['plainauth.users']['default'], $pattern, true)) { msg($this->getLang('writefail'), -1); return 0; @@ -268,12 +274,12 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin * @param array $filter * @return int */ - public function getUserCount($filter = array()) + public function getUserCount($filter = []) { if ($this->users === null) $this->loadUserData(); - if (!count($filter)) return count($this->users); + if ($filter === []) return count($this->users); $count = 0; $this->constructPattern($filter); @@ -295,7 +301,7 @@ 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 = []) { if ($this->users === null) $this->loadUserData(); @@ -304,7 +310,7 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin $i = 0; $count = 0; - $out = array(); + $out = []; $this->constructPattern($filter); foreach ($this->users as $user => $info) { @@ -334,12 +340,12 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin $groups = []; if ($this->users === null) $this->loadUserData(); - foreach($this->users as $user => $info) { + foreach ($this->users as $info) { $groups = array_merge($groups, array_diff($info['grps'], $groups)); } Sort::ksort($groups); - if($limit > 0) { + if ($limit > 0) { return array_splice($groups, $start, $limit); } return array_splice($groups, $start); @@ -404,7 +410,7 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin */ protected function readUserFile($file) { - $users = array(); + $users = []; if (!file_exists($file)) return $users; $lines = file($file); @@ -436,7 +442,7 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin protected function splitUserData($line) { $data = preg_split('/(?<![^\\\\]\\\\)\:/', $line, 5); // allow for : escaped as \: - if(count($data) < 5) { + if (count($data) < 5) { $data = array_pad($data, 5, ''); Logger::error('User line with less than 5 fields. Possibly corruption in your user file', $data); } @@ -459,8 +465,8 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin 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; + } elseif (!preg_match($pattern, $info[$item])) { + return false; } } return true; @@ -473,9 +479,9 @@ class auth_plugin_authplain extends DokuWiki_Auth_Plugin */ protected function constructPattern($filter) { - $this->pattern = array(); + $this->pattern = []; foreach ($filter as $item => $pattern) { - $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters + $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters } } } diff --git a/lib/plugins/cli.php b/lib/plugins/cli.php index 5bf8da91e..e75f700a0 100644 --- a/lib/plugins/cli.php +++ b/lib/plugins/cli.php @@ -1,4 +1,9 @@ <?php -\dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction( - 'Autoloading', 1, 'require(' . basename(__FILE__) . ')' + +use dokuwiki\Debug\DebugHelper; + +DebugHelper::dbgDeprecatedFunction( + 'Autoloading', + 1, + 'require(' . basename(__FILE__) . ')' ); diff --git a/lib/plugins/config/admin.php b/lib/plugins/config/admin.php index 568fc1846..a77c787f5 100644 --- a/lib/plugins/config/admin.php +++ b/lib/plugins/config/admin.php @@ -1,4 +1,5 @@ <?php + /** * Configuration Manager admin plugin * @@ -7,6 +8,7 @@ * @author Ben Coburn <btcoburn@silicodon.net> */ +use dokuwiki\Extension\AdminPlugin; use dokuwiki\plugin\config\core\Configuration; use dokuwiki\plugin\config\core\Setting\Setting; use dokuwiki\plugin\config\core\Setting\SettingFieldset; @@ -16,9 +18,9 @@ use dokuwiki\plugin\config\core\Setting\SettingHidden; * All DokuWiki plugins to extend the admin function * need to inherit from this class */ -class admin_plugin_config extends DokuWiki_Admin_Plugin { - - const IMGDIR = DOKU_BASE . 'lib/plugins/config/images/'; +class admin_plugin_config extends AdminPlugin +{ + protected const IMGDIR = DOKU_BASE . 'lib/plugins/config/images/'; /** @var Configuration */ protected $configuration; @@ -33,33 +35,34 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { /** * handle user request */ - public function handle() { + public function handle() + { global $ID, $INPUT; // always initialize the configuration $this->configuration = new Configuration(); - if(!$INPUT->bool('save') || !checkSecurityToken()) { + if (!$INPUT->bool('save') || !checkSecurityToken()) { return; } // don't go any further if the configuration is locked - if($this->configuration->isLocked()) return; + if ($this->configuration->isLocked()) return; // update settings and redirect of successful $ok = $this->configuration->updateSettings($INPUT->arr('config')); - if($ok) { // no errors + if ($ok) { // no errors try { - if($this->configuration->hasChanged()) { + if ($this->configuration->hasChanged()) { $this->configuration->save(); } else { $this->configuration->touch(); } msg($this->getLang('updated'), 1); - } catch(Exception $e) { + } catch (Exception $e) { msg($this->getLang('error'), -1); } - send_redirect(wl($ID, array('do' => 'admin', 'page' => 'config'), true, '&')); + send_redirect(wl($ID, ['do' => 'admin', 'page' => 'config'], true, '&')); } else { $this->hasErrors = true; msg($this->getLang('error'), -1); @@ -69,7 +72,8 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { /** * output appropriate html */ - public function html() { + public function html() + { $allow_debug = $GLOBALS['conf']['allowdebug']; // avoid global $conf; here. global $lang; global $ID; @@ -80,7 +84,7 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { echo '<div id="config__manager">'; - if($this->configuration->isLocked()) { + if ($this->configuration->isLocked()) { echo '<div class="info">' . $this->getLang('locked') . '</div>'; } @@ -95,22 +99,22 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { $in_fieldset = false; $first_plugin_fieldset = true; $first_template_fieldset = true; - foreach($this->configuration->getSettings() as $setting) { - if(is_a($setting, SettingHidden::class)) { + foreach ($this->configuration->getSettings() as $setting) { + if ($setting instanceof SettingHidden) { continue; - } else if(is_a($setting, settingFieldset::class)) { + } elseif ($setting instanceof SettingFieldset) { // config setting group - if($in_fieldset) { + if ($in_fieldset) { echo '</table>'; echo '</div>'; echo '</fieldset>'; } else { $in_fieldset = true; } - if($first_plugin_fieldset && $setting->getType() == 'plugin') { + if ($first_plugin_fieldset && $setting->getType() == 'plugin') { $this->printH1('plugin_settings', $this->getLang('_header_plugin')); $first_plugin_fieldset = false; - } else if($first_template_fieldset && $setting->getType() == 'template') { + } elseif ($first_template_fieldset && $setting->getType() == 'template') { $this->printH1('template_settings', $this->getLang('_header_template')); $first_template_fieldset = false; } @@ -120,7 +124,7 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { echo '<table class="inline">'; } else { // config settings - list($label, $input) = $setting->html($this, $this->hasErrors); + [$label, $input] = $setting->html($this, $this->hasErrors); $class = $setting->isDefault() ? ' class="default"' @@ -145,13 +149,13 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { echo '</table>'; echo '</div>'; - if($in_fieldset) { + if ($in_fieldset) { echo '</fieldset>'; } // show undefined settings list $undefined_settings = $this->configuration->getUndefined(); - if($allow_debug && !empty($undefined_settings)) { + if ($allow_debug && !empty($undefined_settings)) { /** * Callback for sorting settings * @@ -159,7 +163,8 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { * @param Setting $b * @return int if $a is lower/equal/higher than $b */ - function settingNaturalComparison($a, $b) { + function settingNaturalComparison($a, $b) + { return strnatcmp($a->getKey(), $b->getKey()); } @@ -168,8 +173,8 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { echo '<fieldset>'; echo '<div class="table">'; echo '<table class="inline">'; - foreach($undefined_settings as $setting) { - list($label, $input) = $setting->html($this); + foreach ($undefined_settings as $setting) { + [$label, $input] = $setting->html($this); echo '<tr>'; echo '<td class="label">' . $label . '</td>'; echo '<td>' . $input . '</td>'; @@ -185,7 +190,7 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { echo '<input type="hidden" name="do" value="admin" />'; echo '<input type="hidden" name="page" value="config" />'; - if(!$this->configuration->isLocked()) { + if (!$this->configuration->isLocked()) { echo '<input type="hidden" name="save" value="1" />'; echo '<button type="submit" name="submit" accesskey="s">' . $lang['btn_save'] . '</button>'; echo '<button type="reset">' . $lang['btn_reset'] . '</button>'; @@ -200,9 +205,10 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { /** * @param bool $prompts */ - public function setupLocale($prompts = false) { + public function setupLocale($prompts = false) + { parent::setupLocale(); - if(!$prompts || $this->promptsLocalized) return; + if (!$prompts || $this->promptsLocalized) return; $this->lang = array_merge($this->lang, $this->configuration->getLangs()); $this->promptsLocalized = true; } @@ -214,17 +220,18 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { * * @return array */ - public function getTOC() { + public function getTOC() + { $this->setupLocale(true); $allow_debug = $GLOBALS['conf']['allowdebug']; // avoid global $conf; here. - $toc = array(); + $toc = []; $check = false; // gather settings data into three sub arrays $labels = ['dokuwiki' => [], 'plugin' => [], 'template' => []]; - foreach($this->configuration->getSettings() as $setting) { - if(is_a($setting, SettingFieldset::class)) { + foreach ($this->configuration->getSettings() as $setting) { + if ($setting instanceof SettingFieldset) { $labels[$setting->getType()][] = $setting; } } @@ -234,8 +241,8 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { $toc[] = html_mktocitem(sectionID($title, $check), $title, 1); // main entries - foreach(['dokuwiki', 'plugin', 'template'] as $section) { - if(empty($labels[$section])) continue; // no entries, skip + foreach (['dokuwiki', 'plugin', 'template'] as $section) { + if (empty($labels[$section])) continue; // no entries, skip // create main header $toc[] = html_mktocitem( @@ -245,7 +252,7 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { ); // create sub headers - foreach($labels[$section] as $setting) { + foreach ($labels[$section] as $setting) { /** @var SettingFieldset $setting */ $name = $setting->prompt($this); $toc[] = html_mktocitem($setting->getKey(), $name, 2); @@ -253,7 +260,7 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { } // undefined settings if allowed - if(count($this->configuration->getUndefined()) && $allow_debug) { + if (count($this->configuration->getUndefined()) && $allow_debug) { $toc[] = html_mktocitem('undefined_settings', $this->getLang('_header_undefined'), 1); } @@ -264,7 +271,8 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { * @param string $id * @param string $text */ - protected function printH1($id, $text) { + protected function printH1($id, $text) + { echo '<h1 id="' . $id . '">' . $text . '</h1>'; } @@ -276,8 +284,9 @@ class admin_plugin_config extends DokuWiki_Admin_Plugin { * @param string $key * @param string $value */ - public function addLang($key, $value) { - if(!$this->localised) $this->setupLocale(); + public function addLang($key, $value) + { + if (!$this->localised) $this->setupLocale(); $this->lang[$key] = $value; } } diff --git a/lib/plugins/config/core/ConfigParser.php b/lib/plugins/config/core/ConfigParser.php index fd9ff2ec6..aae44d983 100644 --- a/lib/plugins/config/core/ConfigParser.php +++ b/lib/plugins/config/core/ConfigParser.php @@ -10,7 +10,8 @@ namespace dokuwiki\plugin\config\core; * * @author Chris Smith <chris@jalakai.co.uk> */ -class ConfigParser { +class ConfigParser +{ /** @var string variable to parse from the file */ protected $varname = 'conf'; /** @var string the key to mark sub arrays */ @@ -24,36 +25,38 @@ class ConfigParser { * @param string $file * @return array */ - public function parse($file) { - if(!file_exists($file)) return array(); + public function parse($file) + { + if (!file_exists($file)) return []; - $config = array(); + $config = []; $contents = @php_strip_whitespace($file); // fallback to simply including the file #3271 - if($contents === null) { + if ($contents === null) { $conf = []; include $file; return $conf; } $pattern = '/\$' . $this->varname . '\[[\'"]([^=]+)[\'"]\] ?= ?(.*?);(?=[^;]*(?:\$' . $this->varname . '|$))/s'; - $matches = array(); + $matches = []; preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER); + $counter = count($matches); - for($i = 0; $i < count($matches); $i++) { + for ($i = 0; $i < $counter; $i++) { $value = $matches[$i][2]; // merge multi-dimensional array indices using the keymarker $key = preg_replace('/.\]\[./', $this->keymarker, $matches[$i][1]); // handle arrays - if(preg_match('/^array ?\((.*)\)/', $value, $match)) { + if (preg_match('/^array ?\((.*)\)/', $value, $match)) { $arr = explode(',', $match[1]); // remove quotes from quoted strings & unescape escaped data $len = count($arr); - for($j = 0; $j < $len; $j++) { + for ($j = 0; $j < $len; $j++) { $arr[$j] = trim($arr[$j]); $arr[$j] = $this->readValue($arr[$j]); } @@ -75,17 +78,18 @@ class ConfigParser { * @param string $value * @return bool|string */ - protected function readValue($value) { + protected function readValue($value) + { $removequotes_pattern = '/^(\'|")(.*)(?<!\\\\)\1$/s'; - $unescape_pairs = array( + $unescape_pairs = [ '\\\\' => '\\', '\\\'' => '\'', '\\"' => '"' - ); + ]; - if($value == 'true') { + if ($value == 'true') { $value = true; - } elseif($value == 'false') { + } elseif ($value == 'false') { $value = false; } else { // remove quotes from quoted strings & unescape escaped data @@ -94,5 +98,4 @@ class ConfigParser { } return $value; } - } diff --git a/lib/plugins/config/core/Configuration.php b/lib/plugins/config/core/Configuration.php index c58645c5b..d2c63e3d4 100644 --- a/lib/plugins/config/core/Configuration.php +++ b/lib/plugins/config/core/Configuration.php @@ -15,14 +15,14 @@ use dokuwiki\plugin\config\core\Setting\SettingUndefined; * @author Ben Coburn <btcoburn@silicodon.net> * @author Andreas Gohr <andi@splitbrain.org> */ -class Configuration { - - const KEYMARKER = '____'; +class Configuration +{ + public const KEYMARKER = '____'; /** @var Setting[] metadata as array of Settings objects */ - protected $settings = array(); + protected $settings = []; /** @var Setting[] undefined and problematic settings */ - protected $undefined = array(); + protected $undefined = []; /** @var array all metadata */ protected $metadata; @@ -44,7 +44,8 @@ class Configuration { /** * ConfigSettings constructor. */ - public function __construct() { + public function __construct() + { $this->loader = new Loader(new ConfigParser()); $this->writer = new Writer(); @@ -61,7 +62,8 @@ class Configuration { * * @return Setting[] */ - public function getSettings() { + public function getSettings() + { return $this->settings; } @@ -70,7 +72,8 @@ class Configuration { * * @return Setting[] */ - public function getUndefined() { + public function getUndefined() + { return $this->undefined; } @@ -79,7 +82,8 @@ class Configuration { * * @return bool */ - public function hasChanged() { + public function hasChanged() + { return $this->changed; } @@ -88,7 +92,8 @@ class Configuration { * * @return bool */ - public function isLocked() { + public function isLocked() + { return $this->writer->isLocked(); } @@ -98,15 +103,16 @@ class Configuration { * @param array $input as posted * @return bool true if all updates went through, false on errors */ - public function updateSettings($input) { + public function updateSettings($input) + { $ok = true; - foreach($this->settings as $key => $obj) { - $value = isset($input[$key]) ? $input[$key] : null; - if($obj->update($value)) { + foreach ($this->settings as $key => $obj) { + $value = $input[$key] ?? null; + if ($obj->update($value)) { $this->changed = true; } - if($obj->hasError()) $ok = false; + if ($obj->hasError()) $ok = false; } return $ok; @@ -120,7 +126,8 @@ class Configuration { * * @throws \Exception */ - public function save() { + public function save() + { // only save the undefined settings that have not been handled in settings $undefined = array_diff_key($this->undefined, $this->settings); $this->writer->save(array_merge($this->settings, $undefined)); @@ -131,7 +138,8 @@ class Configuration { * * @throws \Exception */ - public function touch() { + public function touch() + { $this->writer->touch(); } @@ -140,32 +148,34 @@ class Configuration { * * @return array */ - public function getLangs() { + public function getLangs() + { return $this->loader->loadLangs(); } /** * Initalizes the $settings and $undefined properties */ - protected function initSettings() { - $keys = array_merge( - array_keys($this->metadata), - array_keys($this->default), - array_keys($this->local), - array_keys($this->protected) - ); + protected function initSettings() + { + $keys = [ + ...array_keys($this->metadata), + ...array_keys($this->default), + ...array_keys($this->local), + ...array_keys($this->protected) + ]; $keys = array_unique($keys); - foreach($keys as $key) { + foreach ($keys as $key) { $obj = $this->instantiateClass($key); - if($obj->shouldHaveDefault() && !isset($this->default[$key])) { + if ($obj->shouldHaveDefault() && !isset($this->default[$key])) { $this->undefined[$key] = new SettingNoDefault($key); } - $d = isset($this->default[$key]) ? $this->default[$key] : null; - $l = isset($this->local[$key]) ? $this->local[$key] : null; - $p = isset($this->protected[$key]) ? $this->protected[$key] : null; + $d = $this->default[$key] ?? null; + $l = $this->local[$key] ?? null; + $p = $this->protected[$key] ?? null; $obj->initialize($d, $l, $p); } @@ -179,8 +189,9 @@ class Configuration { * @param string $key * @return Setting */ - protected function instantiateClass($key) { - if(isset($this->metadata[$key])) { + protected function instantiateClass($key) + { + if (isset($this->metadata[$key])) { $param = $this->metadata[$key]; $class = $this->determineClassName(array_shift($param), $key); // first param is class $obj = new $class($key, $param); @@ -199,14 +210,15 @@ class Configuration { * @param string $key the settings key * @return string */ - protected function determineClassName($class, $key) { + protected function determineClassName($class, $key) + { // try namespaced class first - if(is_string($class)) { + if (is_string($class)) { $modern = str_replace('_', '', ucwords($class, '_')); $modern = '\\dokuwiki\\plugin\\config\\core\\Setting\\Setting' . $modern; - if($modern && class_exists($modern)) return $modern; + if ($modern && class_exists($modern)) return $modern; // try class as given - if(class_exists($class)) return $class; + if (class_exists($class)) return $class; // class wasn't found add to errors $this->undefined[$key] = new SettingNoKnownClass($key); } else { @@ -215,5 +227,4 @@ class Configuration { } return '\\dokuwiki\\plugin\\config\\core\\Setting\\Setting'; } - } diff --git a/lib/plugins/config/core/Loader.php b/lib/plugins/config/core/Loader.php index e4d7b50af..c9dbec95d 100644 --- a/lib/plugins/config/core/Loader.php +++ b/lib/plugins/config/core/Loader.php @@ -10,7 +10,8 @@ use dokuwiki\Extension\Event; * Loads configuration meta data and settings from the various files. Honors the * configuration cascade and installed plugins. */ -class Loader { +class Loader +{ /** @var ConfigParser */ protected $parser; @@ -24,7 +25,8 @@ class Loader { * @param ConfigParser $parser * @triggers PLUGIN_CONFIG_PLUGINLIST */ - public function __construct(ConfigParser $parser) { + public function __construct(ConfigParser $parser) + { global $conf; $this->parser = $parser; $this->plugins = plugin_list(); @@ -40,13 +42,14 @@ class Loader { * * @return array */ - public function loadMeta() { + public function loadMeta() + { // load main file - $meta = array(); + $meta = []; include DOKU_PLUGIN . 'config/settings/config.metadata.php'; // plugins - foreach($this->plugins as $plugin) { + foreach ($this->plugins as $plugin) { $meta = array_merge( $meta, $this->loadExtensionMeta( @@ -81,7 +84,7 @@ class Loader { { // initialize array - $conf = array(); + $conf = []; // plugins foreach ($this->plugins as $plugin) { @@ -120,11 +123,12 @@ class Loader { * * @return array */ - public function loadLangs() { - $lang = array(); + public function loadLangs() + { + $lang = []; // plugins - foreach($this->plugins as $plugin) { + foreach ($this->plugins as $plugin) { $lang = array_merge( $lang, $this->loadExtensionLang( @@ -153,7 +157,8 @@ class Loader { * * @return array */ - public function loadLocal() { + public function loadLocal() + { global $config_cascade; return $this->loadConfigs($config_cascade['main']['local']); } @@ -163,7 +168,8 @@ class Loader { * * @return array */ - public function loadProtected() { + public function loadProtected() + { global $config_cascade; return $this->loadConfigs($config_cascade['main']['protected']); } @@ -174,9 +180,10 @@ class Loader { * @param string[] $files paths to config php's * @return array */ - protected function loadConfigs($files) { - $conf = array(); - foreach($files as $file) { + protected function loadConfigs($files) + { + $conf = []; + foreach ($files as $file) { $conf = array_merge($conf, $this->parser->parse($file)); } return $conf; @@ -192,20 +199,21 @@ class Loader { * @param string $extname name of the extension * @return array */ - protected function loadExtensionMeta($file, $type, $extname) { - if(!file_exists($file)) return array(); + protected function loadExtensionMeta($file, $type, $extname) + { + if (!file_exists($file)) return []; $prefix = $type . Configuration::KEYMARKER . $extname . Configuration::KEYMARKER; // include file - $meta = array(); + $meta = []; include $file; - if(empty($meta)) return array(); + if ($meta === []) return []; // read data - $data = array(); + $data = []; $data[$prefix . $type . '_settings_name'] = ['fieldset']; - foreach($meta as $key => $value) { - if($value[0] == 'fieldset') continue; //plugins only get one fieldset + foreach ($meta as $key => $value) { + if ($value[0] == 'fieldset') continue; //plugins only get one fieldset $data[$prefix . $key] = $value; } @@ -222,17 +230,18 @@ class Loader { * @param string $extname name of the extension * @return array */ - protected function loadExtensionConf($file, $type, $extname) { - if(!file_exists($file)) return array(); + protected function loadExtensionConf($file, $type, $extname) + { + if (!file_exists($file)) return []; $prefix = $type . Configuration::KEYMARKER . $extname . Configuration::KEYMARKER; // parse file $conf = $this->parser->parse($file); - if(empty($conf)) return array(); + if (empty($conf)) return []; // read data - $data = array(); - foreach($conf as $key => $value) { + $data = []; + foreach ($conf as $key => $value) { $data[$prefix . $key] = $value; } @@ -247,23 +256,24 @@ class Loader { * @param string $extname name of the extension * @return array */ - protected function loadExtensionLang($dir, $type, $extname) { + protected function loadExtensionLang($dir, $type, $extname) + { global $conf; $ll = $conf['lang']; $prefix = $type . Configuration::KEYMARKER . $extname . Configuration::KEYMARKER; // include files - $lang = array(); - if(file_exists($dir . 'lang/en/settings.php')) { + $lang = []; + if (file_exists($dir . 'lang/en/settings.php')) { include $dir . 'lang/en/settings.php'; } - if($ll != 'en' && file_exists($dir . 'lang/' . $ll . '/settings.php')) { + if ($ll != 'en' && file_exists($dir . 'lang/' . $ll . '/settings.php')) { include $dir . 'lang/' . $ll . '/settings.php'; } // set up correct keys - $strings = array(); - foreach($lang as $key => $val) { + $strings = []; + foreach ($lang as $key => $val) { $strings[$prefix . $key] = $val; } diff --git a/lib/plugins/config/core/Setting/Setting.php b/lib/plugins/config/core/Setting/Setting.php index bbf048a85..cc22cf91a 100644 --- a/lib/plugins/config/core/Setting/Setting.php +++ b/lib/plugins/config/core/Setting/Setting.php @@ -7,24 +7,25 @@ use dokuwiki\plugin\config\core\Configuration; /** * Class Setting */ -class Setting { +class Setting +{ /** @var string unique identifier of this setting */ protected $key = ''; /** @var mixed the default value of this setting */ - protected $default = null; + protected $default; /** @var mixed the local value of this setting */ - protected $local = null; + protected $local; /** @var mixed the protected value of this setting */ - protected $protected = null; + protected $protected; /** @var array valid alerts, images matching the alerts are in the plugin's images directory */ - static protected $validCautions = array('warning', 'danger', 'security'); + protected static $validCautions = ['warning', 'danger', 'security']; 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 + protected $input; // only used by those classes which error check + protected $caution; // used by any setting to provide an alert along with the setting /** * Constructor. @@ -36,11 +37,12 @@ class Setting { * @param string $key * @param array|null $params array with metadata of setting */ - public function __construct($key, $params = null) { + public function __construct($key, $params = null) + { $this->key = $key; - if(is_array($params)) { - foreach($params as $property => $value) { + if (is_array($params)) { + foreach ($params as $property => $value) { $property = trim($property, '_'); // we don't use underscores anymore $this->$property = $value; } @@ -57,7 +59,8 @@ class Setting { * @param mixed $local local setting value * @param mixed $protected protected setting value */ - public function initialize($default = null, $local = null, $protected = null) { + public function initialize($default = null, $local = null, $protected = null) + { $this->default = $this->cleanValue($default); $this->local = $this->cleanValue($local); $this->protected = $this->cleanValue($protected); @@ -71,16 +74,17 @@ class Setting { * @param mixed $input the new value * @return boolean true if changed, false otherwise */ - public function update($input) { - if(is_null($input)) return false; - if($this->isProtected()) return false; + public function update($input) + { + if (is_null($input)) return false; + if ($this->isProtected()) return false; $input = $this->cleanValue($input); $value = is_null($this->local) ? $this->default : $this->local; - if($value == $input) return false; + if ($value == $input) return false; // validate new value - if($this->pattern && !preg_match($this->pattern, $input)) { + if ($this->pattern && !preg_match($this->pattern, $input)) { $this->error = true; $this->input = $input; return false; @@ -104,7 +108,8 @@ class Setting { * @param mixed $value * @return mixed */ - protected function cleanValue($value) { + protected function cleanValue($value) + { return $value; } @@ -113,7 +118,8 @@ class Setting { * * @return bool */ - public function shouldHaveDefault() { + public function shouldHaveDefault() + { return true; } @@ -122,7 +128,8 @@ class Setting { * * @return string */ - public function getKey() { + public function getKey() + { return $this->key; } @@ -132,10 +139,11 @@ class Setting { * @param bool $url link to dokuwiki.org manual? * @return string */ - public function getPrettyKey($url = true) { + public function getPrettyKey($url = true) + { $out = str_replace(Configuration::KEYMARKER, "»", $this->key); - if($url && !strstr($out, '»')) {//provide no urls for plugins, etc. - if($out == 'start') { + if ($url && !strstr($out, '»')) {//provide no urls for plugins, etc. + if ($out == 'start') { // exception, because this config name is clashing with our actual start page return '<a href="https://www.dokuwiki.org/config:startpage">' . $out . '</a>'; } else { @@ -152,7 +160,8 @@ class Setting { * * @return string key */ - public function getArrayKey() { + public function getArrayKey() + { return str_replace(Configuration::KEYMARKER, "']['", $this->key); } @@ -167,10 +176,11 @@ class Setting { * * @return string */ - public function getType() { - if(substr($this->getKey(), 0, 10) == 'plugin' . Configuration::KEYMARKER) { + public function getType() + { + if (substr($this->getKey(), 0, 10) == 'plugin' . Configuration::KEYMARKER) { return 'plugin'; - } else if(substr($this->getKey(), 0, 7) == 'tpl' . Configuration::KEYMARKER) { + } elseif (substr($this->getKey(), 0, 7) == 'tpl' . Configuration::KEYMARKER) { return 'template'; } else { return 'dokuwiki'; @@ -184,18 +194,17 @@ class Setting { * @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) */ - public function html(\admin_plugin_config $plugin, $echo = false) { + public function html(\admin_plugin_config $plugin, $echo = false) + { $disable = ''; - if($this->isProtected()) { + if ($this->isProtected()) { $value = $this->protected; $disable = 'disabled="disabled"'; + } elseif ($echo && $this->error) { + $value = $this->input; } else { - if($echo && $this->error) { - $value = $this->input; - } else { - $value = is_null($this->local) ? $this->default : $this->local; - } + $value = is_null($this->local) ? $this->default : $this->local; } $key = htmlspecialchars($this->key); @@ -204,7 +213,7 @@ class Setting { $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>'; - return array($label, $input); + return [$label, $input]; } /** @@ -213,10 +222,11 @@ class Setting { * @see out() to run when this returns true * @return bool */ - public function shouldBeSaved() { - if($this->isProtected()) return false; - if($this->local === null) return false; - if($this->default == $this->local) return false; + public function shouldBeSaved() + { + if ($this->isProtected()) return false; + if ($this->local === null) return false; + if ($this->default == $this->local) return false; return true; } @@ -226,8 +236,9 @@ class Setting { * @param string $string * @return string */ - protected function escape($string) { - $tr = array("\\" => '\\\\', "'" => '\\\''); + protected function escape($string) + { + $tr = ["\\" => '\\\\', "'" => '\\\'']; return "'" . strtr(cleanText($string), $tr) . "'"; } @@ -239,11 +250,12 @@ class Setting { * @param string $fmt save format * @return string */ - public function out($var, $fmt = 'php') { + public function out($var, $fmt = 'php') + { if ($fmt != 'php') return ''; if (is_array($this->local)) { - $value = 'array(' . join(', ', array_map([$this, 'escape'], $this->local)) . ')'; + $value = 'array(' . implode(', ', array_map([$this, 'escape'], $this->local)) . ')'; } else { $value = $this->escape($this->local); } @@ -259,9 +271,10 @@ class Setting { * @param \admin_plugin_config $plugin object of config plugin * @return string text */ - public function prompt(\admin_plugin_config $plugin) { + public function prompt(\admin_plugin_config $plugin) + { $prompt = $plugin->getLang($this->key); - if(!$prompt) $prompt = htmlspecialchars(str_replace(array('____', '_'), ' ', $this->key)); + if (!$prompt) $prompt = htmlspecialchars(str_replace(['____', '_'], ' ', $this->key)); return $prompt; } @@ -270,7 +283,8 @@ class Setting { * * @return bool */ - public function isProtected() { + public function isProtected() + { return !is_null($this->protected); } @@ -279,7 +293,8 @@ class Setting { * * @return bool */ - public function isDefault() { + public function isDefault() + { return !$this->isProtected() && is_null($this->local); } @@ -288,7 +303,8 @@ class Setting { * * @return bool */ - public function hasError() { + public function hasError() + { return $this->error; } @@ -297,14 +313,14 @@ class Setting { * * @return false|string caution string, otherwise false for invalid caution */ - public function caution() { - if(empty($this->caution)) return false; - if(!in_array($this->caution, Setting::$validCautions)) { + public function caution() + { + if (empty($this->caution)) return false; + if (!in_array($this->caution, Setting::$validCautions)) { throw new \RuntimeException( 'Invalid caution string (' . $this->caution . ') in metadata for setting "' . $this->key . '"' ); } return $this->caution; } - } diff --git a/lib/plugins/config/core/Setting/SettingArray.php b/lib/plugins/config/core/Setting/SettingArray.php index 8dfda0dd6..bae9e87df 100644 --- a/lib/plugins/config/core/Setting/SettingArray.php +++ b/lib/plugins/config/core/Setting/SettingArray.php @@ -5,15 +5,16 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_array */ -class SettingArray extends Setting { - +class SettingArray extends Setting +{ /** * Create an array from a string * * @param string $string * @return array */ - protected function fromString($string) { + protected function fromString($string) + { $array = explode(',', $string); $array = array_map('trim', $array); $array = array_filter($array); @@ -27,8 +28,9 @@ class SettingArray extends Setting { * @param array $array * @return string */ - protected function fromArray($array) { - return join(', ', (array) $array); + protected function fromArray($array) + { + return implode(', ', (array) $array); } /** @@ -38,17 +40,18 @@ class SettingArray extends Setting { * @param string $input * @return bool true if changed, false otherwise (incl. on error) */ - public function update($input) { - if(is_null($input)) return false; - if($this->isProtected()) return false; + public function update($input) + { + if (is_null($input)) return false; + if ($this->isProtected()) return false; $input = $this->fromString($input); $value = is_null($this->local) ? $this->default : $this->local; - if($value == $input) return false; + if ($value == $input) return false; - foreach($input as $item) { - if($this->pattern && !preg_match($this->pattern, $item)) { + foreach ($input as $item) { + if ($this->pattern && !preg_match($this->pattern, $item)) { $this->error = true; $this->input = $input; return false; @@ -60,18 +63,17 @@ class SettingArray extends Setting { } /** @inheritdoc */ - public function html(\admin_plugin_config $plugin, $echo = false) { + public function html(\admin_plugin_config $plugin, $echo = false) + { $disable = ''; - if($this->isProtected()) { + if ($this->isProtected()) { $value = $this->protected; $disable = 'disabled="disabled"'; + } elseif ($echo && $this->error) { + $value = $this->input; } else { - if($echo && $this->error) { - $value = $this->input; - } else { - $value = is_null($this->local) ? $this->default : $this->local; - } + $value = is_null($this->local) ? $this->default : $this->local; } $key = htmlspecialchars($this->key); @@ -80,6 +82,6 @@ class SettingArray extends Setting { $label = '<label for="config___' . $key . '">' . $this->prompt($plugin) . '</label>'; $input = '<input id="config___' . $key . '" name="config[' . $key . ']" type="text" class="edit" value="' . $value . '" ' . $disable . '/>'; - return array($label, $input); + return [$label, $input]; } } diff --git a/lib/plugins/config/core/Setting/SettingAuthtype.php b/lib/plugins/config/core/Setting/SettingAuthtype.php index 3a6df6fe5..1874db0a7 100644 --- a/lib/plugins/config/core/Setting/SettingAuthtype.php +++ b/lib/plugins/config/core/Setting/SettingAuthtype.php @@ -5,15 +5,16 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_authtype */ -class SettingAuthtype extends SettingMultichoice { - +class SettingAuthtype extends SettingMultichoice +{ /** @inheritdoc */ - public function initialize($default = null, $local = null, $protected = null) { + public function initialize($default = null, $local = null, $protected = null) + { /** @var $plugin_controller \dokuwiki\Extension\PluginController */ global $plugin_controller; // retrieve auth types provided by plugins - foreach($plugin_controller->getList('auth') as $plugin) { + foreach ($plugin_controller->getList('auth') as $plugin) { $this->choices[] = $plugin; } @@ -21,27 +22,28 @@ class SettingAuthtype extends SettingMultichoice { } /** @inheritdoc */ - public function update($input) { + public function update($input) + { /** @var $plugin_controller \dokuwiki\Extension\PluginController */ global $plugin_controller; // is an update possible/requested? $local = $this->local; // save this, parent::update() may change it - if(!parent::update($input)) return false; // nothing changed or an error caught by parent + if (!parent::update($input)) return false; // nothing changed or an error caught by parent $this->local = $local; // restore original, more error checking to come // attempt to load the plugin $auth_plugin = $plugin_controller->load('auth', $input); // @TODO: throw an error in plugin controller instead of returning null - if(is_null($auth_plugin)) { + if (is_null($auth_plugin)) { $this->error = true; msg('Cannot load Auth Plugin "' . $input . '"', -1); return false; } // verify proper instantiation (is this really a plugin?) @TODO use instanceof? implement interface? - if(is_object($auth_plugin) && !method_exists($auth_plugin, 'getPluginName')) { + if (is_object($auth_plugin) && !method_exists($auth_plugin, 'getPluginName')) { $this->error = true; msg('Cannot create Auth Plugin "' . $input . '"', -1); return false; @@ -49,7 +51,7 @@ class SettingAuthtype extends SettingMultichoice { // did we change the auth type? logout global $conf; - if($conf['authtype'] != $input) { + if ($conf['authtype'] != $input) { msg('Authentication system changed. Please re-login.'); auth_logoff(); } diff --git a/lib/plugins/config/core/Setting/SettingCompression.php b/lib/plugins/config/core/Setting/SettingCompression.php index f97d82801..f52405989 100644 --- a/lib/plugins/config/core/Setting/SettingCompression.php +++ b/lib/plugins/config/core/Setting/SettingCompression.php @@ -5,16 +5,17 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_compression */ -class SettingCompression extends SettingMultichoice { - - protected $choices = array('0'); // 0 = no compression, always supported +class SettingCompression extends SettingMultichoice +{ + protected $choices = ['0']; // 0 = no compression, always supported /** @inheritdoc */ - public function initialize($default = null, $local = null, $protected = null) { + public function initialize($default = null, $local = null, $protected = null) + { // populate _choices with the compression methods supported by this php installation - if(function_exists('gzopen')) $this->choices[] = 'gz'; - if(function_exists('bzopen')) $this->choices[] = 'bz2'; + if (function_exists('gzopen')) $this->choices[] = 'gz'; + if (function_exists('bzopen')) $this->choices[] = 'bz2'; parent::initialize($default, $local, $protected); } diff --git a/lib/plugins/config/core/Setting/SettingDirchoice.php b/lib/plugins/config/core/Setting/SettingDirchoice.php index dfb27f5f4..a571149f0 100644 --- a/lib/plugins/config/core/Setting/SettingDirchoice.php +++ b/lib/plugins/config/core/Setting/SettingDirchoice.php @@ -5,23 +5,24 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_dirchoice */ -class SettingDirchoice extends SettingMultichoice { - +class SettingDirchoice extends SettingMultichoice +{ protected $dir = ''; /** @inheritdoc */ - public function initialize($default = null, $local = null, $protected = null) { + public function initialize($default = null, $local = null, $protected = null) + { // populate $this->_choices with a list of directories - $list = array(); + $list = []; - if($dh = @opendir($this->dir)) { - while(false !== ($entry = readdir($dh))) { - if($entry == '.' || $entry == '..') continue; - if($this->pattern && !preg_match($this->pattern, $entry)) continue; + if ($dh = @opendir($this->dir)) { + while (false !== ($entry = readdir($dh))) { + if ($entry == '.' || $entry == '..') continue; + if ($this->pattern && !preg_match($this->pattern, $entry)) continue; $file = (is_link($this->dir . $entry)) ? readlink($this->dir . $entry) : $this->dir . $entry; - if(is_dir($file)) $list[] = $entry; + if (is_dir($file)) $list[] = $entry; } closedir($dh); } diff --git a/lib/plugins/config/core/Setting/SettingDisableactions.php b/lib/plugins/config/core/Setting/SettingDisableactions.php index 2553175bd..46427c457 100644 --- a/lib/plugins/config/core/Setting/SettingDisableactions.php +++ b/lib/plugins/config/core/Setting/SettingDisableactions.php @@ -5,17 +5,18 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_disableactions */ -class SettingDisableactions extends SettingMulticheckbox { - +class SettingDisableactions extends SettingMulticheckbox +{ /** @inheritdoc */ - public 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) // transfer some DokuWiki language strings to the plugin $plugin->addLang($this->key . '_revisions', $lang['btn_revs']); - foreach($this->choices as $choice) { - if(isset($lang['btn_' . $choice])) $plugin->addLang($this->key . '_' . $choice, $lang['btn_' . $choice]); + foreach ($this->choices as $choice) { + if (isset($lang['btn_' . $choice])) $plugin->addLang($this->key . '_' . $choice, $lang['btn_' . $choice]); } return parent::html($plugin, $echo); diff --git a/lib/plugins/config/core/Setting/SettingEmail.php b/lib/plugins/config/core/Setting/SettingEmail.php index 25a0c0e75..a1a2ab028 100644 --- a/lib/plugins/config/core/Setting/SettingEmail.php +++ b/lib/plugins/config/core/Setting/SettingEmail.php @@ -5,24 +5,26 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_email */ -class SettingEmail extends SettingString { +class SettingEmail extends SettingString +{ protected $multiple = false; protected $placeholders = false; /** @inheritdoc */ - public function update($input) { - if(is_null($input)) return false; - if($this->isProtected()) return false; + public function update($input) + { + if (is_null($input)) return false; + if ($this->isProtected()) return false; $value = is_null($this->local) ? $this->default : $this->local; - if($value == $input) return false; - if($input === '') { + if ($value == $input) return false; + if ($input === '') { $this->local = $input; return true; } $mail = $input; - if($this->placeholders) { + if ($this->placeholders) { // replace variables with pseudo values $mail = str_replace('@USER@', 'joe', $mail); $mail = str_replace('@NAME@', 'Joe Schmoe', $mail); @@ -30,22 +32,22 @@ class SettingEmail extends SettingString { } // multiple mail addresses? - if($this->multiple) { + if ($this->multiple) { $mails = array_filter(array_map('trim', explode(',', $mail))); } else { - $mails = array($mail); + $mails = [$mail]; } // check them all - foreach($mails as $mail) { + foreach ($mails as $mail) { // only check the address part - if(preg_match('#(.*?)<(.*?)>#', $mail, $matches)) { + if (preg_match('#(.*?)<(.*?)>#', $mail, $matches)) { $addr = $matches[2]; } else { $addr = $mail; } - if(!mail_isvalid($addr)) { + if (!mail_isvalid($addr)) { $this->error = true; $this->input = $input; return false; diff --git a/lib/plugins/config/core/Setting/SettingFieldset.php b/lib/plugins/config/core/Setting/SettingFieldset.php index 4e8618967..3db2962cb 100644 --- a/lib/plugins/config/core/Setting/SettingFieldset.php +++ b/lib/plugins/config/core/Setting/SettingFieldset.php @@ -7,11 +7,11 @@ namespace dokuwiki\plugin\config\core\Setting; * * Used to start a new settings "display-group". */ -class SettingFieldset extends Setting { - +class SettingFieldset extends Setting +{ /** @inheritdoc */ - public function shouldHaveDefault() { + public function shouldHaveDefault() + { return false; } - } diff --git a/lib/plugins/config/core/Setting/SettingHidden.php b/lib/plugins/config/core/Setting/SettingHidden.php index ca8a03eb9..11b800f84 100644 --- a/lib/plugins/config/core/Setting/SettingHidden.php +++ b/lib/plugins/config/core/Setting/SettingHidden.php @@ -5,6 +5,7 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_hidden */ -class SettingHidden extends Setting { +class SettingHidden extends Setting +{ // Used to explicitly ignore a setting in the configuration manager. } diff --git a/lib/plugins/config/core/Setting/SettingImConvert.php b/lib/plugins/config/core/Setting/SettingImConvert.php index 8740d94c8..985372deb 100644 --- a/lib/plugins/config/core/Setting/SettingImConvert.php +++ b/lib/plugins/config/core/Setting/SettingImConvert.php @@ -5,18 +5,19 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_im_convert */ -class SettingImConvert extends SettingString { - +class SettingImConvert extends SettingString +{ /** @inheritdoc */ - public function update($input) { - if($this->isProtected()) return false; + public function update($input) + { + if ($this->isProtected()) return false; $input = trim($input); $value = is_null($this->local) ? $this->default : $this->local; - if($value == $input) return false; + if ($value == $input) return false; - if($input && !file_exists($input)) { + if ($input && !file_exists($input)) { $this->error = true; $this->input = $input; return false; diff --git a/lib/plugins/config/core/Setting/SettingLicense.php b/lib/plugins/config/core/Setting/SettingLicense.php index 8dacf8e25..edd5a09e3 100644 --- a/lib/plugins/config/core/Setting/SettingLicense.php +++ b/lib/plugins/config/core/Setting/SettingLicense.php @@ -5,15 +5,16 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_license */ -class SettingLicense extends SettingMultichoice { - - protected $choices = array(''); // none choosen +class SettingLicense extends SettingMultichoice +{ + protected $choices = ['']; // none choosen /** @inheritdoc */ - public function initialize($default = null, $local = null, $protected = null) { + public function initialize($default = null, $local = null, $protected = null) + { global $license; - foreach($license as $key => $data) { + foreach ($license as $key => $data) { $this->choices[] = $key; $this->lang[$this->key . '_o_' . $key] = $data['name']; // stored in setting } diff --git a/lib/plugins/config/core/Setting/SettingMulticheckbox.php b/lib/plugins/config/core/Setting/SettingMulticheckbox.php index df212cca0..954a51018 100644 --- a/lib/plugins/config/core/Setting/SettingMulticheckbox.php +++ b/lib/plugins/config/core/Setting/SettingMulticheckbox.php @@ -5,24 +5,25 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_multicheckbox */ -class SettingMulticheckbox extends SettingString { - - protected $choices = array(); - protected $combine = array(); +class SettingMulticheckbox extends SettingString +{ + protected $choices = []; + protected $combine = []; protected $other = 'always'; /** @inheritdoc */ - public function update($input) { - if($this->isProtected()) return false; + public function update($input) + { + if ($this->isProtected()) return false; // split any combined values + convert from array to comma separated string - $input = ($input) ? $input : array(); + $input = $input ?: []; $input = $this->array2str($input); $value = is_null($this->local) ? $this->default : $this->local; - if($value == $input) return false; + if ($value == $input) return false; - if($this->pattern && !preg_match($this->pattern, $input)) { + if ($this->pattern && !preg_match($this->pattern, $input)) { $this->error = true; $this->input = $input; return false; @@ -33,19 +34,18 @@ class SettingMulticheckbox extends SettingString { } /** @inheritdoc */ - public function html(\admin_plugin_config $plugin, $echo = false) { + public function html(\admin_plugin_config $plugin, $echo = false) + { $disable = ''; - if($this->isProtected()) { + if ($this->isProtected()) { $value = $this->protected; $disable = 'disabled="disabled"'; + } elseif ($echo && $this->error) { + $value = $this->input; } else { - if($echo && $this->error) { - $value = $this->input; - } else { - $value = is_null($this->local) ? $this->default : $this->local; - } + $value = is_null($this->local) ? $this->default : $this->local; } $key = htmlspecialchars($this->key); @@ -55,17 +55,16 @@ class SettingMulticheckbox extends SettingString { $default = $this->str2array($this->default); $input = ''; - foreach($this->choices as $choice) { + foreach ($this->choices as $choice) { $idx = array_search($choice, $value); $idx_default = array_search($choice, $default); $checked = ($idx !== false) ? 'checked="checked"' : ''; // @todo ideally this would be handled using a second class of "default" - $class = (($idx !== false) == (false !== $idx_default)) ? " selectiondefault" : ""; + $class = (($idx !== false) === (false !== $idx_default)) ? " selectiondefault" : ""; - $prompt = ($plugin->getLang($this->key . '_' . $choice) ? - $plugin->getLang($this->key . '_' . $choice) : htmlspecialchars($choice)); + $prompt = ($plugin->getLang($this->key . '_' . $choice) ?: htmlspecialchars($choice)); $input .= '<div class="selection' . $class . '">' . "\n"; $input .= '<label for="config___' . $key . '_' . $choice . '">' . $prompt . "</label>\n"; @@ -74,20 +73,19 @@ class SettingMulticheckbox extends SettingString { $input .= "</div>\n"; // remove this action from the disabledactions array - if($idx !== false) unset($value[$idx]); - if($idx_default !== false) unset($default[$idx_default]); + if ($idx !== false) unset($value[$idx]); + if ($idx_default !== false) unset($default[$idx_default]); } // handle any remaining values - if($this->other != 'never') { - $other = join(',', $value); + if ($this->other != 'never') { + $other = implode(',', $value); // test equivalent to ($this->_other == 'always' || ($other && $this->_other == 'exists') // use != 'exists' rather than == 'always' to ensure invalid values default to 'always' - if($this->other != 'exists' || $other) { - + if ($this->other != 'exists' || $other) { $class = ( - (count($default) == count($value)) && - (count($value) == count(array_intersect($value, $default))) + (count($default) === count($value)) && + (count($value) === count(array_intersect($value, $default))) ) ? " selectiondefault" : ""; @@ -102,7 +100,7 @@ class SettingMulticheckbox extends SettingString { } } $label = '<label>' . $this->prompt($plugin) . '</label>'; - return array($label, $input); + return [$label, $input]; } /** @@ -111,18 +109,19 @@ class SettingMulticheckbox extends SettingString { * @param string $str * @return array */ - protected function str2array($str) { + protected function str2array($str) + { $array = explode(',', $str); - if(!empty($this->combine)) { - foreach($this->combine as $key => $combinators) { - $idx = array(); - foreach($combinators as $val) { - if(($idx[] = array_search($val, $array)) === false) break; + if (!empty($this->combine)) { + foreach ($this->combine as $key => $combinators) { + $idx = []; + foreach ($combinators as $val) { + if (($idx[] = array_search($val, $array)) === false) break; } - if(count($idx) && $idx[count($idx) - 1] !== false) { - foreach($idx as $i) unset($array[$i]); + if (count($idx) && $idx[count($idx) - 1] !== false) { + foreach ($idx as $i) unset($array[$i]); $array[] = $key; } } @@ -137,27 +136,27 @@ class SettingMulticheckbox extends SettingString { * @param array $input * @return string */ - protected function array2str($input) { + protected function array2str($input) + { // handle other $other = trim($input['other']); - $other = !empty($other) ? explode(',', str_replace(' ', '', $input['other'])) : array(); + $other = empty($other) ? [] : explode(',', str_replace(' ', '', $input['other'])); unset($input['other']); $array = array_unique(array_merge($input, $other)); // deconstruct any combinations - if(!empty($this->combine)) { - foreach($this->combine as $key => $combinators) { - + if (!empty($this->combine)) { + foreach ($this->combine as $key => $combinators) { $idx = array_search($key, $array); - if($idx !== false) { + if ($idx !== false) { unset($array[$idx]); $array = array_merge($array, $combinators); } } } - return join(',', array_unique($array)); + return implode(',', array_unique($array)); } } diff --git a/lib/plugins/config/core/Setting/SettingMultichoice.php b/lib/plugins/config/core/Setting/SettingMultichoice.php index 3a50857e0..7d29a0e2b 100644 --- a/lib/plugins/config/core/Setting/SettingMultichoice.php +++ b/lib/plugins/config/core/Setting/SettingMultichoice.php @@ -5,16 +5,18 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_multichoice */ -class SettingMultichoice extends SettingString { - protected $choices = array(); +class SettingMultichoice extends SettingString +{ + protected $choices = []; public $lang; //some custom language strings are stored in setting /** @inheritdoc */ - public function html(\admin_plugin_config $plugin, $echo = false) { + public function html(\admin_plugin_config $plugin, $echo = false) + { $disable = ''; $nochoice = ''; - if($this->isProtected()) { + if ($this->isProtected()) { $value = $this->protected; $disable = ' disabled="disabled"'; } else { @@ -22,11 +24,11 @@ class SettingMultichoice extends SettingString { } // ensure current value is included - if(!in_array($value, $this->choices)) { + if (!in_array($value, $this->choices)) { $this->choices[] = $value; } // disable if no other choices - if(!$this->isProtected() && count($this->choices) <= 1) { + if (!$this->isProtected() && count($this->choices) <= 1) { $disable = ' disabled="disabled"'; $nochoice = $plugin->getLang('nochoice'); } @@ -37,13 +39,13 @@ class SettingMultichoice extends SettingString { $input = "<div class=\"input\">\n"; $input .= '<select class="edit" id="config___' . $key . '" name="config[' . $key . ']"' . $disable . '>' . "\n"; - foreach($this->choices as $choice) { + 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])) { + if (!$option && isset($this->lang[$this->key . '_o_' . $choice])) { $option = $this->lang[$this->key . '_o_' . $choice]; } - if(!$option) $option = $choice; + if (!$option) $option = $choice; $choice = htmlspecialchars($choice); $option = htmlspecialchars($option); @@ -52,18 +54,19 @@ class SettingMultichoice extends SettingString { $input .= "</select> $nochoice \n"; $input .= "</div>\n"; - return array($label, $input); + return [$label, $input]; } /** @inheritdoc */ - public function update($input) { - if(is_null($input)) return false; - if($this->isProtected()) return false; + public function update($input) + { + if (is_null($input)) return false; + if ($this->isProtected()) return false; $value = is_null($this->local) ? $this->default : $this->local; - if($value == $input) return false; + if ($value == $input) return false; - if(!in_array($input, $this->choices)) return false; + if (!in_array($input, $this->choices)) return false; $this->local = $input; return true; diff --git a/lib/plugins/config/core/Setting/SettingNoClass.php b/lib/plugins/config/core/Setting/SettingNoClass.php index 8efff216a..805ab11c9 100644 --- a/lib/plugins/config/core/Setting/SettingNoClass.php +++ b/lib/plugins/config/core/Setting/SettingNoClass.php @@ -7,6 +7,7 @@ namespace dokuwiki\plugin\config\core\Setting; * A do-nothing class used to detect settings with a missing setting class. * Used internaly to hide undefined settings, and generate the undefined settings list. */ -class SettingNoClass extends SettingUndefined { +class SettingNoClass extends SettingUndefined +{ protected $errorMessage = '_msg_setting_no_class'; } diff --git a/lib/plugins/config/core/Setting/SettingNoDefault.php b/lib/plugins/config/core/Setting/SettingNoDefault.php index 07b8412dd..2780be095 100644 --- a/lib/plugins/config/core/Setting/SettingNoDefault.php +++ b/lib/plugins/config/core/Setting/SettingNoDefault.php @@ -8,6 +8,7 @@ namespace dokuwiki\plugin\config\core\Setting; * A do-nothing class used to detect settings with no default value. * Used internaly to hide undefined settings, and generate the undefined settings list. */ -class SettingNoDefault extends SettingUndefined { +class SettingNoDefault extends SettingUndefined +{ protected $errorMessage = '_msg_setting_no_default'; } diff --git a/lib/plugins/config/core/Setting/SettingNoKnownClass.php b/lib/plugins/config/core/Setting/SettingNoKnownClass.php index 3c527e1ee..0d5c1c734 100644 --- a/lib/plugins/config/core/Setting/SettingNoKnownClass.php +++ b/lib/plugins/config/core/Setting/SettingNoKnownClass.php @@ -6,6 +6,7 @@ namespace dokuwiki\plugin\config\core\Setting; * A do-nothing class used to detect settings with a missing setting class. * Used internaly to hide undefined settings, and generate the undefined settings list. */ -class SettingNoKnownClass extends SettingUndefined { +class SettingNoKnownClass extends SettingUndefined +{ protected $errorMessage = '_msg_setting_no_known_class'; } diff --git a/lib/plugins/config/core/Setting/SettingNumeric.php b/lib/plugins/config/core/Setting/SettingNumeric.php index 8a6b17956..27ca1945c 100644 --- a/lib/plugins/config/core/Setting/SettingNumeric.php +++ b/lib/plugins/config/core/Setting/SettingNumeric.php @@ -5,22 +5,26 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_numeric */ -class SettingNumeric extends SettingString { +class SettingNumeric extends SettingString +{ // This allows for many PHP syntax errors... // var $_pattern = '/^[-+\/*0-9 ]*$/'; // much more restrictive, but should eliminate syntax errors. - protected $pattern = '/^[-+]? *[0-9]+ *(?:[-+*] *[0-9]+ *)*$/'; - protected $min = null; - protected $max = null; + protected $pattern = '/^[-+]? *\d+ *(?:[-+*] *\d+ *)*$/'; + protected $min; + protected $max; /** @inheritdoc */ - public function update($input) { + public function update($input) + { $local = $this->local; $valid = parent::update($input); - if($valid && !(is_null($this->min) && is_null($this->max))) { + if ($valid && !(is_null($this->min) && is_null($this->max))) { $numeric_local = (int) eval('return ' . $this->local . ';'); - if((!is_null($this->min) && $numeric_local < $this->min) || - (!is_null($this->max) && $numeric_local > $this->max)) { + if ( + (!is_null($this->min) && $numeric_local < $this->min) || + (!is_null($this->max) && $numeric_local > $this->max) + ) { $this->error = true; $this->input = $input; $this->local = $local; @@ -31,8 +35,9 @@ class SettingNumeric extends SettingString { } /** @inheritdoc */ - public function out($var, $fmt = 'php') { - if($fmt != 'php') return ''; + public function out($var, $fmt = 'php') + { + if ($fmt != 'php') return ''; $local = $this->local === '' ? "''" : $this->local; $out = '$' . $var . "['" . $this->getArrayKey() . "'] = " . $local . ";\n"; diff --git a/lib/plugins/config/core/Setting/SettingNumericopt.php b/lib/plugins/config/core/Setting/SettingNumericopt.php index a486e187f..117e3920a 100644 --- a/lib/plugins/config/core/Setting/SettingNumericopt.php +++ b/lib/plugins/config/core/Setting/SettingNumericopt.php @@ -5,17 +5,19 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_numericopt */ -class SettingNumericopt extends SettingNumeric { +class SettingNumericopt extends SettingNumeric +{ // just allow an empty config - protected $pattern = '/^(|[-]?[0-9]+(?:[-+*][0-9]+)*)$/'; + protected $pattern = '/^(|[-]?\d+(?:[-+*]\d+)*)$/'; /** * @inheritdoc * Empty string is valid for numericopt */ - public function update($input) { - if($input === '') { - if($input == $this->local) return false; + public function update($input) + { + if ($input === '') { + if ($input == $this->local) return false; $this->local = $input; return true; } diff --git a/lib/plugins/config/core/Setting/SettingOnoff.php b/lib/plugins/config/core/Setting/SettingOnoff.php index 780778b48..69a74aa9f 100644 --- a/lib/plugins/config/core/Setting/SettingOnoff.php +++ b/lib/plugins/config/core/Setting/SettingOnoff.php @@ -5,29 +5,31 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_onoff */ -class SettingOnoff extends SettingNumeric { - +class SettingOnoff extends SettingNumeric +{ /** * We treat the strings 'false' and 'off' as false * @inheritdoc */ - protected function cleanValue($value) { - if($value === null) return null; - - if(is_string($value)) { - if(strtolower($value) === 'false') return 0; - if(strtolower($value) === 'off') return 0; - if(trim($value) === '') return 0; + protected function cleanValue($value) + { + if ($value === null) return null; + + if (is_string($value)) { + if (strtolower($value) === 'false') return 0; + if (strtolower($value) === 'off') return 0; + if (trim($value) === '') return 0; } return (int) (bool) $value; } /** @inheritdoc */ - public function html(\admin_plugin_config $plugin, $echo = false) { + public function html(\admin_plugin_config $plugin, $echo = false) + { $disable = ''; - if($this->isProtected()) { + if ($this->isProtected()) { $value = $this->protected; $disable = ' disabled="disabled"'; } else { @@ -40,16 +42,17 @@ class SettingOnoff extends SettingNumeric { $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>'; - return array($label, $input); + return [$label, $input]; } /** @inheritdoc */ - public function update($input) { - if($this->isProtected()) return false; + public function update($input) + { + if ($this->isProtected()) return false; $input = ($input) ? 1 : 0; $value = is_null($this->local) ? $this->default : $this->local; - if($value == $input) return false; + if ($value == $input) return false; $this->local = $input; return true; diff --git a/lib/plugins/config/core/Setting/SettingPassword.php b/lib/plugins/config/core/Setting/SettingPassword.php index 9d9c53377..e56a1338f 100644 --- a/lib/plugins/config/core/Setting/SettingPassword.php +++ b/lib/plugins/config/core/Setting/SettingPassword.php @@ -5,16 +5,17 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_password */ -class SettingPassword extends SettingString { - +class SettingPassword extends SettingString +{ protected $code = 'plain'; // mechanism to be used to obscure passwords /** @inheritdoc */ - public function update($input) { - if($this->isProtected()) return false; - if(!$input) return false; + public function update($input) + { + if ($this->isProtected()) return false; + if (!$input) return false; - if($this->pattern && !preg_match($this->pattern, $input)) { + if ($this->pattern && !preg_match($this->pattern, $input)) { $this->error = true; $this->input = $input; return false; @@ -25,7 +26,8 @@ class SettingPassword extends SettingString { } /** @inheritdoc */ - public function html(\admin_plugin_config $plugin, $echo = false) { + public function html(\admin_plugin_config $plugin, $echo = false) + { $disable = $this->isProtected() ? 'disabled="disabled"' : ''; @@ -34,6 +36,6 @@ class SettingPassword extends SettingString { $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 . ' />'; - return array($label, $input); + return [$label, $input]; } } diff --git a/lib/plugins/config/core/Setting/SettingRegex.php b/lib/plugins/config/core/Setting/SettingRegex.php index b38f0a560..7ec3a4d81 100644 --- a/lib/plugins/config/core/Setting/SettingRegex.php +++ b/lib/plugins/config/core/Setting/SettingRegex.php @@ -5,24 +5,25 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_regex */ -class SettingRegex extends SettingString { - +class SettingRegex extends SettingString +{ protected $delimiter = '/'; // regex delimiter to be used in testing input protected $pregflags = 'ui'; // regex pattern modifiers to be used in testing input /** @inheritdoc */ - public function update($input) { + public function update($input) + { // let parent do basic checks, value, not changed, etc. $local = $this->local; - if(!parent::update($input)) return false; + if (!parent::update($input)) return false; $this->local = $local; // see if the regex compiles and runs (we don't check for effectiveness) $regex = $this->delimiter . $input . $this->delimiter . $this->pregflags; $lastError = error_get_last(); @preg_match($regex, 'testdata'); - if(preg_last_error() != PREG_NO_ERROR || error_get_last() != $lastError) { + if (preg_last_error() != PREG_NO_ERROR || error_get_last() !== $lastError) { $this->input = $input; $this->error = true; return false; diff --git a/lib/plugins/config/core/Setting/SettingRenderer.php b/lib/plugins/config/core/Setting/SettingRenderer.php index 37ba9c70a..10b3e33f8 100644 --- a/lib/plugins/config/core/Setting/SettingRenderer.php +++ b/lib/plugins/config/core/Setting/SettingRenderer.php @@ -1,4 +1,5 @@ <?php + /** * additional setting classes specific to these settings * @@ -10,17 +11,19 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_renderer */ -class SettingRenderer extends SettingMultichoice { - protected $prompts = array(); - protected $format = null; +class SettingRenderer extends SettingMultichoice +{ + protected $prompts = []; + protected $format; /** @inheritdoc */ - public function initialize($default = null, $local = null, $protected = null) { + public function initialize($default = null, $local = null, $protected = null) + { $format = $this->format; - foreach(plugin_list('renderer') as $plugin) { + foreach (plugin_list('renderer') as $plugin) { $renderer = plugin_load('renderer', $plugin); - if(method_exists($renderer, 'canRender') && $renderer->canRender($format)) { + if (method_exists($renderer, 'canRender') && $renderer->canRender($format)) { $this->choices[] = $plugin; $info = $renderer->getInfo(); @@ -32,13 +35,14 @@ class SettingRenderer extends SettingMultichoice { } /** @inheritdoc */ - public 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 - foreach($this->choices as $choice) { - if(!$plugin->getLang($this->key . '_o_' . $choice)) { - if(!isset($this->prompts[$choice])) { + foreach ($this->choices as $choice) { + if (!$plugin->getLang($this->key . '_o_' . $choice)) { + if (!isset($this->prompts[$choice])) { $plugin->addLang( $this->key . '_o_' . $choice, sprintf($plugin->getLang('renderer__core'), $choice) diff --git a/lib/plugins/config/core/Setting/SettingSavedir.php b/lib/plugins/config/core/Setting/SettingSavedir.php index 43e428dd3..a429b7a38 100644 --- a/lib/plugins/config/core/Setting/SettingSavedir.php +++ b/lib/plugins/config/core/Setting/SettingSavedir.php @@ -5,16 +5,17 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_savedir */ -class SettingSavedir extends SettingString { - +class SettingSavedir extends SettingString +{ /** @inheritdoc */ - public function update($input) { - if($this->isProtected()) return false; + public function update($input) + { + if ($this->isProtected()) return false; $value = is_null($this->local) ? $this->default : $this->local; - if($value == $input) return false; + if ($value == $input) return false; - if(!init_path($input)) { + if (!init_path($input)) { $this->error = true; $this->input = $input; return false; diff --git a/lib/plugins/config/core/Setting/SettingSepchar.php b/lib/plugins/config/core/Setting/SettingSepchar.php index 57cd0ae92..db9e9d694 100644 --- a/lib/plugins/config/core/Setting/SettingSepchar.php +++ b/lib/plugins/config/core/Setting/SettingSepchar.php @@ -5,12 +5,13 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_sepchar */ -class SettingSepchar extends SettingMultichoice { - +class SettingSepchar extends SettingMultichoice +{ /** @inheritdoc */ - public function __construct($key, $param = null) { + public function __construct($key, $param = null) + { $str = '_-.'; - for($i = 0; $i < strlen($str); $i++) $this->choices[] = $str[$i]; + for ($i = 0; $i < strlen($str); $i++) $this->choices[] = $str[$i]; // call foundation class constructor parent::__construct($key, $param); diff --git a/lib/plugins/config/core/Setting/SettingString.php b/lib/plugins/config/core/Setting/SettingString.php index b819407b7..090108501 100644 --- a/lib/plugins/config/core/Setting/SettingString.php +++ b/lib/plugins/config/core/Setting/SettingString.php @@ -5,20 +5,20 @@ namespace dokuwiki\plugin\config\core\Setting; /** * Class setting_string */ -class SettingString extends Setting { +class SettingString extends Setting +{ /** @inheritdoc */ - public function html(\admin_plugin_config $plugin, $echo = false) { + public function html(\admin_plugin_config $plugin, $echo = false) + { $disable = ''; - if($this->isProtected()) { + if ($this->isProtected()) { $value = $this->protected; $disable = 'disabled="disabled"'; + } elseif ($echo && $this->error) { + $value = $this->input; } else { - if($echo && $this->error) { - $value = $this->input; - } else { - $value = is_null($this->local) ? $this->default : $this->local; - } + $value = is_null($this->local) ? $this->default : $this->local; } $key = htmlspecialchars($this->key); @@ -27,6 +27,6 @@ class SettingString extends Setting { $label = '<label for="config___' . $key . '">' . $this->prompt($plugin) . '</label>'; $input = '<input id="config___' . $key . '" name="config[' . $key . ']" type="text" class="edit" value="' . $value . '" ' . $disable . '/>'; - return array($label, $input); + return [$label, $input]; } } diff --git a/lib/plugins/config/core/Setting/SettingUndefined.php b/lib/plugins/config/core/Setting/SettingUndefined.php index fa46a9f1d..e70c90cd7 100644 --- a/lib/plugins/config/core/Setting/SettingUndefined.php +++ b/lib/plugins/config/core/Setting/SettingUndefined.php @@ -8,23 +8,27 @@ use dokuwiki\plugin\config\core\Configuration; * A do-nothing class used to detect settings with no metadata entry. * Used internaly to hide undefined settings, and generate the undefined settings list. */ -class SettingUndefined extends SettingHidden { - +class SettingUndefined extends SettingHidden +{ protected $errorMessage = '_msg_setting_undefined'; /** @inheritdoc */ - public function shouldHaveDefault() { + public function shouldHaveDefault() + { return false; } /** @inheritdoc */ - public function html(\admin_plugin_config $plugin, $echo = false) { + public function html(\admin_plugin_config $plugin, $echo = false) + { // determine the name the meta key would be called - if(preg_match( - '/^(?:plugin|tpl)' . Configuration::KEYMARKER . '.*?' . Configuration::KEYMARKER . '(.*)$/', - $this->getKey(), - $undefined_setting_match - )) { + if ( + preg_match( + '/^(?:plugin|tpl)' . Configuration::KEYMARKER . '.*?' . Configuration::KEYMARKER . '(.*)$/', + $this->getKey(), + $undefined_setting_match + ) + ) { $undefined_setting_key = $undefined_setting_match[1]; } else { $undefined_setting_key = $this->getKey(); @@ -34,7 +38,6 @@ class SettingUndefined extends SettingHidden { 'conf' . '[\'' . $this->getArrayKey() . '\']</span>'; $input = $plugin->getLang($this->errorMessage); - return array($label, $input); + return [$label, $input]; } - } diff --git a/lib/plugins/config/core/Writer.php b/lib/plugins/config/core/Writer.php index 18aa9ee02..6751b88ba 100644 --- a/lib/plugins/config/core/Writer.php +++ b/lib/plugins/config/core/Writer.php @@ -1,13 +1,15 @@ <?php namespace dokuwiki\plugin\config\core; + use dokuwiki\plugin\config\core\Setting\Setting; use dokuwiki\Logger; /** * Writes the settings to the correct local file */ -class Writer { +class Writer +{ /** @var string header info */ protected $header = 'Dokuwiki\'s Main Configuration File - Local Settings'; @@ -17,7 +19,8 @@ class Writer { /** * Writer constructor. */ - public function __construct() { + public function __construct() + { global $config_cascade; $this->savefile = end($config_cascade['main']['local']); } @@ -28,36 +31,37 @@ class Writer { * @param Setting[] $settings * @throws \Exception */ - public function save($settings) { + public function save($settings) + { global $conf; - if($this->isLocked()) throw new \Exception('no save'); + if ($this->isLocked()) throw new \Exception('no save'); // backup current file (remove any existing backup) - if(file_exists($this->savefile)) { - if(file_exists($this->savefile . '.bak.php')) @unlink($this->savefile . '.bak.php'); - if(!io_rename($this->savefile, $this->savefile . '.bak.php')) throw new \Exception('no backup'); + if (file_exists($this->savefile)) { + if (file_exists($this->savefile . '.bak.php')) @unlink($this->savefile . '.bak.php'); + if (!io_rename($this->savefile, $this->savefile . '.bak.php')) throw new \Exception('no backup'); } - if(!$fh = @fopen($this->savefile, 'wb')) { + if (!$fh = @fopen($this->savefile, 'wb')) { io_rename($this->savefile . '.bak.php', $this->savefile); // problem opening, restore the backup throw new \Exception('no save'); } $out = ''; - foreach($settings as $setting) { - if($setting->shouldBeSaved()) { + foreach ($settings as $setting) { + if ($setting->shouldBeSaved()) { $out .= $setting->out('conf', 'php'); } } - if($out === '') { + if ($out === '') { throw new \Exception('empty config'); } $out = $this->getHeader() . $out; fwrite($fh, $out); fclose($fh); - if($conf['fperm']) chmod($this->savefile, $conf['fperm']); + if ($conf['fperm']) chmod($this->savefile, $conf['fperm']); $this->opcacheUpdate($this->savefile); } @@ -68,8 +72,9 @@ class Writer { * * @throws \Exception when the config isn't writable */ - public function touch() { - if($this->isLocked()) throw new \Exception('no save'); + public function touch() + { + if ($this->isLocked()) throw new \Exception('no save'); @touch($this->savefile); $this->opcacheUpdate($this->savefile); } @@ -80,11 +85,12 @@ class Writer { * @todo this should probably be moved to core * @param string $file */ - protected function opcacheUpdate($file) { - if(!function_exists('opcache_invalidate')) return; + protected function opcacheUpdate($file) + { + if (!function_exists('opcache_invalidate')) return; set_error_handler(function ($errNo, $errMsg) { - Logger::debug('Unable to invalidate opcache: ' . $errMsg); } - ); + Logger::debug('Unable to invalidate opcache: ' . $errMsg); + }); opcache_invalidate($file); restore_error_handler(); } @@ -95,10 +101,11 @@ class Writer { * * @return bool true: locked, false: writable */ - public function isLocked() { - if(!$this->savefile) return true; - if(!is_writable(dirname($this->savefile))) return true; - if(file_exists($this->savefile) && !is_writable($this->savefile)) return true; + public function isLocked() + { + if (!$this->savefile) return true; + if (!is_writable(dirname($this->savefile))) return true; + if (file_exists($this->savefile) && !is_writable($this->savefile)) return true; return false; } @@ -107,20 +114,21 @@ class Writer { * * @return string */ - protected function getHeader() { - return join( + protected function getHeader() + { + return implode( "\n", - array( + [ '<?php', '/*', ' * ' . $this->header, ' * Auto-generated by config plugin', - ' * Run for user: ' . (isset($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'] : 'Unknown'), + ' * Run for user: ' . ($_SERVER['REMOTE_USER'] ?? 'Unknown'), ' * Date: ' . date('r'), ' */', '', '' - ) + ] ); } } diff --git a/lib/plugins/config/settings/config.metadata.php b/lib/plugins/config/settings/config.metadata.php index 5774f13bb..59c3b8853 100644 --- a/lib/plugins/config/settings/config.metadata.php +++ b/lib/plugins/config/settings/config.metadata.php @@ -1,4 +1,5 @@ <?php + /** * Metadata for configuration manager plugin * @@ -80,62 +81,77 @@ * @author Chris Smith <chris@jalakai.co.uk> */ -$meta['_basic'] = array('fieldset'); -$meta['title'] = array('string'); -$meta['start'] = array('string','_caution' => 'warning','_pattern' => '!^[^:;/]+$!'); // don't accept namespaces -$meta['lang'] = array('dirchoice','_dir' => DOKU_INC.'inc/lang/'); -$meta['template'] = array('dirchoice','_dir' => DOKU_INC.'lib/tpl/','_pattern' => '/^[\w-]+$/'); -$meta['tagline'] = array('string'); -$meta['sidebar'] = array('string'); -$meta['license'] = array('license'); -$meta['savedir'] = array('savedir','_caution' => 'danger'); -$meta['basedir'] = array('string','_caution' => 'danger'); -$meta['baseurl'] = array('string','_caution' => 'danger'); -$meta['cookiedir'] = array('string','_caution' => 'danger'); -$meta['dmode'] = array('numeric','_pattern' => '/0[0-7]{3,4}/'); // only accept octal representation -$meta['fmode'] = array('numeric','_pattern' => '/0[0-7]{3,4}/'); // only accept octal representation -$meta['allowdebug'] = array('onoff','_caution' => 'security'); +$meta['_basic'] = ['fieldset']; +$meta['title'] = ['string']; +$meta['start'] = ['string', '_caution' => 'warning', '_pattern' => '!^[^:;/]+$!']; // don't accept namespaces +$meta['lang'] = ['dirchoice', '_dir' => DOKU_INC . 'inc/lang/']; +$meta['template'] = ['dirchoice', '_dir' => DOKU_INC . 'lib/tpl/', '_pattern' => '/^[\w-]+$/']; +$meta['tagline'] = ['string']; +$meta['sidebar'] = ['string']; +$meta['license'] = ['license']; +$meta['savedir'] = ['savedir', '_caution' => 'danger']; +$meta['basedir'] = ['string', '_caution' => 'danger']; +$meta['baseurl'] = ['string', '_caution' => 'danger']; +$meta['cookiedir'] = ['string', '_caution' => 'danger']; +$meta['dmode'] = ['numeric', '_pattern' => '/0[0-7]{3,4}/']; // only accept octal representation +$meta['fmode'] = ['numeric', '_pattern' => '/0[0-7]{3,4}/']; // only accept octal representation +$meta['allowdebug'] = ['onoff', '_caution' => 'security']; -$meta['_display'] = array('fieldset'); -$meta['recent'] = array('numeric'); -$meta['recent_days'] = array('numeric'); -$meta['breadcrumbs'] = array('numeric','_min' => 0); -$meta['youarehere'] = array('onoff'); -$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['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)); -$meta['maxseclevel'] = array('multichoice','_choices' => array(0,1,2,3,4,5)); // 0 for no sec edit buttons -$meta['camelcase'] = array('onoff','_caution' => 'warning'); -$meta['deaccent'] = array('multichoice','_choices' => array(0,1,2),'_caution' => 'warning'); -$meta['useheading'] = array('multichoice','_choices' => array(0,'navigation','content',1)); -$meta['sneaky_index'] = array('onoff'); -$meta['hidepages'] = array('regex'); +$meta['_display'] = ['fieldset']; +$meta['recent'] = ['numeric']; +$meta['recent_days'] = ['numeric']; +$meta['breadcrumbs'] = ['numeric', '_min' => 0]; +$meta['youarehere'] = ['onoff']; +$meta['fullpath'] = ['onoff', '_caution' => 'security']; +$meta['typography'] = ['multichoice', '_choices' => [0, 1, 2]]; +$meta['dformat'] = ['string']; +$meta['signature'] = ['string']; +$meta['showuseras'] = ['multichoice', '_choices' => ['loginname', 'username', 'username_link', 'email', 'email_link']]; +$meta['toptoclevel'] = ['multichoice', '_choices' => [1, 2, 3, 4, 5]]; // 5 toc levels +$meta['tocminheads'] = ['multichoice', '_choices' => [0, 1, 2, 3, 4, 5, 10, 15, 20]]; +$meta['maxtoclevel'] = ['multichoice', '_choices' => [0, 1, 2, 3, 4, 5]]; +$meta['maxseclevel'] = ['multichoice', '_choices' => [0, 1, 2, 3, 4, 5]]; // 0 for no sec edit buttons +$meta['camelcase'] = ['onoff', '_caution' => 'warning']; +$meta['deaccent'] = ['multichoice', '_choices' => [0, 1, 2], '_caution' => 'warning']; +$meta['useheading'] = ['multichoice', '_choices' => [0, 'navigation', 'content', 1]]; +$meta['sneaky_index'] = ['onoff']; +$meta['hidepages'] = ['regex']; -$meta['_authentication'] = array('fieldset'); -$meta['useacl'] = array('onoff','_caution' => 'danger'); -$meta['autopasswd'] = array('onoff'); -$meta['authtype'] = array('authtype','_caution' => 'danger'); -$meta['passcrypt'] = array('multichoice','_choices' => array( - 'smd5','md5','apr1','sha1','ssha','lsmd5','crypt','mysql','my411','kmd5','pmd5','hmd5', - 'mediawiki','bcrypt','djangomd5','djangosha1','djangopbkdf2_sha1','djangopbkdf2_sha256', - 'sha512','argon2i','argon2id' -)); -$meta['defaultgroup']= array('string'); -$meta['superuser'] = array('string','_caution' => 'danger'); -$meta['manager'] = array('string'); -$meta['profileconfirm'] = array('onoff'); -$meta['rememberme'] = array('onoff'); -$meta['disableactions'] = array( - 'disableactions', - '_choices' => array( +$meta['_authentication'] = ['fieldset']; +$meta['useacl'] = ['onoff', '_caution' => 'danger']; +$meta['autopasswd'] = ['onoff']; +$meta['authtype'] = ['authtype', '_caution' => 'danger']; +$meta['passcrypt'] = ['multichoice', + '_choices' => [ + 'smd5', + 'md5', + 'apr1', + 'sha1', + 'ssha', + 'lsmd5', + 'crypt', + 'mysql', + 'my411', + 'kmd5', + 'pmd5', + 'hmd5', + 'mediawiki', + 'bcrypt', + 'djangomd5', + 'djangosha1', + 'djangopbkdf2_sha1', + 'djangopbkdf2_sha256', + 'sha512', + 'argon2i', + 'argon2id'] +]; +$meta['defaultgroup'] = ['string']; +$meta['superuser'] = ['string', '_caution' => 'danger']; +$meta['manager'] = ['string']; +$meta['profileconfirm'] = ['onoff']; +$meta['rememberme'] = ['onoff']; +$meta['disableactions'] = ['disableactions', + '_choices' => [ 'backlink', 'index', 'recent', @@ -150,105 +166,98 @@ $meta['disableactions'] = array( '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['samesitecookie'] = array('multichoice','_choices' => array('','Lax','Strict','None')); -$meta['remote'] = array('onoff','_caution' => 'security'); -$meta['remoteuser'] = array('string'); -$meta['remotecors'] = array('string', '_caution' => 'security'); + ], + '_combine' => [ + 'subscription' => ['subscribe', 'unsubscribe'], + 'wikicode' => ['source', 'export_raw'] + ] +]; +$meta['auth_security_timeout'] = ['numeric']; +$meta['securecookie'] = ['onoff']; +$meta['samesitecookie'] = ['multichoice', '_choices' => ['', 'Lax', 'Strict', 'None']]; +$meta['remote'] = ['onoff', '_caution' => 'security']; +$meta['remoteuser'] = ['string']; +$meta['remotecors'] = ['string', '_caution' => 'security']; -$meta['_anti_spam'] = array('fieldset'); -$meta['usewordblock']= array('onoff'); -$meta['relnofollow'] = array('onoff'); -$meta['indexdelay'] = array('numeric'); -$meta['mailguard'] = array('multichoice','_choices' => array('visible','hex','none')); -$meta['iexssprotect']= array('onoff','_caution' => 'security'); +$meta['_anti_spam'] = ['fieldset']; +$meta['usewordblock'] = ['onoff']; +$meta['relnofollow'] = ['onoff']; +$meta['indexdelay'] = ['numeric']; +$meta['mailguard'] = ['multichoice', '_choices' => ['visible', 'hex', 'none']]; +$meta['iexssprotect'] = ['onoff', '_caution' => 'security']; -$meta['_editing'] = array('fieldset'); -$meta['usedraft'] = array('onoff'); -$meta['locktime'] = array('numeric'); -$meta['cachetime'] = array('numeric'); +$meta['_editing'] = ['fieldset']; +$meta['usedraft'] = ['onoff']; +$meta['locktime'] = ['numeric']; +$meta['cachetime'] = ['numeric']; -$meta['_links'] = array('fieldset'); -$meta['target____wiki'] = array('string'); -$meta['target____interwiki'] = array('string'); -$meta['target____extern'] = array('string'); -$meta['target____media'] = array('string'); -$meta['target____windows'] = array('string'); +$meta['_links'] = ['fieldset']; +$meta['target____wiki'] = ['string']; +$meta['target____interwiki'] = ['string']; +$meta['target____extern'] = ['string']; +$meta['target____media'] = ['string']; +$meta['target____windows'] = ['string']; -$meta['_media'] = array('fieldset'); -$meta['mediarevisions'] = array('onoff'); -$meta['gdlib'] = array('multichoice','_choices' => array(0,1,2)); -$meta['im_convert'] = array('im_convert'); -$meta['jpg_quality'] = array('numeric','_pattern' => '/^100$|^[1-9]?[0-9]$/'); //(0-100) -$meta['fetchsize'] = array('numeric'); -$meta['refcheck'] = array('onoff'); +$meta['_media'] = ['fieldset']; +$meta['mediarevisions'] = ['onoff']; +$meta['gdlib'] = ['multichoice', '_choices' => [0, 1, 2]]; +$meta['im_convert'] = ['im_convert']; +$meta['jpg_quality'] = ['numeric', '_pattern' => '/^100$|^[1-9]?\d$/']; //(0-100) +$meta['fetchsize'] = ['numeric']; +$meta['refcheck'] = ['onoff']; -$meta['_notifications'] = array('fieldset'); -$meta['subscribers'] = array('onoff'); -$meta['subscribe_time'] = array('numeric'); -$meta['notify'] = array('email', '_multiple' => true); -$meta['registernotify'] = array('email', '_multiple' => true); -$meta['mailfrom'] = array('email', '_placeholders' => true); -$meta['mailreturnpath'] = array('email', '_placeholders' => true); -$meta['mailprefix'] = array('string'); -$meta['htmlmail'] = array('onoff'); -$meta['dontlog'] = array( - 'disableactions', - '_choices' => array( - 'error', - 'debug', - 'deprecated', - ), -); +$meta['_notifications'] = ['fieldset']; +$meta['subscribers'] = ['onoff']; +$meta['subscribe_time'] = ['numeric']; +$meta['notify'] = ['email', '_multiple' => true]; +$meta['registernotify'] = ['email', '_multiple' => true]; +$meta['mailfrom'] = ['email', '_placeholders' => true]; +$meta['mailreturnpath'] = ['email', '_placeholders' => true]; +$meta['mailprefix'] = ['string']; +$meta['htmlmail'] = ['onoff']; +$meta['dontlog'] = ['disableactions', '_choices' => ['error', 'debug', 'deprecated']]; -$meta['_syndication'] = array('fieldset'); -$meta['sitemap'] = array('numeric'); -$meta['rss_type'] = array('multichoice','_choices' => array('rss','rss1','rss2','atom','atom1')); -$meta['rss_linkto'] = array('multichoice','_choices' => array('diff','page','rev','current')); -$meta['rss_content'] = array('multichoice','_choices' => array('abstract','diff','htmldiff','html')); -$meta['rss_media'] = array('multichoice','_choices' => array('both','pages','media')); -$meta['rss_update'] = array('numeric'); -$meta['rss_show_summary'] = array('onoff'); -$meta['rss_show_deleted'] = array('onoff'); +$meta['_syndication'] = ['fieldset']; +$meta['sitemap'] = ['numeric']; +$meta['rss_type'] = ['multichoice', '_choices' => ['rss', 'rss1', 'rss2', 'atom', 'atom1']]; +$meta['rss_linkto'] = ['multichoice', '_choices' => ['diff', 'page', 'rev', 'current']]; +$meta['rss_content'] = ['multichoice', '_choices' => ['abstract', 'diff', 'htmldiff', 'html']]; +$meta['rss_media'] = ['multichoice', '_choices' => ['both', 'pages', 'media']]; +$meta['rss_update'] = ['numeric']; +$meta['rss_show_summary'] = ['onoff']; +$meta['rss_show_deleted'] = ['onoff']; -$meta['_advanced'] = array('fieldset'); -$meta['updatecheck'] = array('onoff'); -$meta['userewrite'] = array('multichoice','_choices' => array(0,1,2),'_caution' => 'danger'); -$meta['useslash'] = array('onoff'); -$meta['sepchar'] = array('sepchar','_caution' => 'warning'); -$meta['canonical'] = array('onoff'); -$meta['fnencode'] = array('multichoice','_choices' => array('url','safe','utf-8'),'_caution' => 'warning'); -$meta['autoplural'] = array('onoff'); -$meta['compress'] = array('onoff'); -$meta['cssdatauri'] = array('numeric','_pattern' => '/^\d+$/'); -$meta['gzip_output'] = array('onoff'); -$meta['send404'] = array('onoff'); -$meta['compression'] = array('compression','_caution' => 'warning'); -$meta['broken_iua'] = array('onoff'); -$meta['xsendfile'] = array('multichoice','_choices' => array(0,1,2,3),'_caution' => 'warning'); -$meta['renderer_xhtml'] = array('renderer','_format' => 'xhtml','_choices' => array('xhtml'),'_caution' => 'warning'); -$meta['readdircache'] = array('numeric'); -$meta['search_nslimit'] = array('numeric', '_min' => 0); -$meta['search_fragment'] = array('multichoice','_choices' => array('exact', 'starts_with', 'ends_with', 'contains'),); -$meta['trustedproxy'] = array('regex'); +$meta['_advanced'] = ['fieldset']; +$meta['updatecheck'] = ['onoff']; +$meta['userewrite'] = ['multichoice', '_choices' => [0, 1, 2], '_caution' => 'danger']; +$meta['useslash'] = ['onoff']; +$meta['sepchar'] = ['sepchar', '_caution' => 'warning']; +$meta['canonical'] = ['onoff']; +$meta['fnencode'] = ['multichoice', '_choices' => ['url', 'safe', 'utf-8'], '_caution' => 'warning']; +$meta['autoplural'] = ['onoff']; +$meta['compress'] = ['onoff']; +$meta['cssdatauri'] = ['numeric', '_pattern' => '/^\d+$/']; +$meta['gzip_output'] = ['onoff']; +$meta['send404'] = ['onoff']; +$meta['compression'] = ['compression', '_caution' => 'warning']; +$meta['broken_iua'] = ['onoff']; +$meta['xsendfile'] = ['multichoice', '_choices' => [0, 1, 2, 3], '_caution' => 'warning']; +$meta['renderer_xhtml'] = ['renderer', '_format' => 'xhtml', '_choices' => ['xhtml'], '_caution' => 'warning']; +$meta['readdircache'] = ['numeric']; +$meta['search_nslimit'] = ['numeric', '_min' => 0]; +$meta['search_fragment'] = ['multichoice', '_choices' => ['exact', 'starts_with', 'ends_with', 'contains']]; +$meta['trustedproxy'] = ['regex']; $meta['_feature_flags'] = ['fieldset']; -$meta['defer_js'] = ['onoff']; -$meta['hidewarnings'] = ['onoff']; +$meta['defer_js'] = ['onoff']; +$meta['hidewarnings'] = ['onoff']; -$meta['_network'] = array('fieldset'); -$meta['dnslookups'] = array('onoff'); -$meta['jquerycdn'] = array('multichoice', '_choices' => array(0,'jquery', 'cdnjs')); -$meta['proxy____host'] = array('string','_pattern' => '#^(|[a-z0-9\-\.+]+)$#i'); -$meta['proxy____port'] = array('numericopt'); -$meta['proxy____user'] = array('string'); -$meta['proxy____pass'] = array('password','_code' => 'base64'); -$meta['proxy____ssl'] = array('onoff'); -$meta['proxy____except'] = array('string'); +$meta['_network'] = ['fieldset']; +$meta['dnslookups'] = ['onoff']; +$meta['jquerycdn'] = ['multichoice', '_choices' => [0, 'jquery', 'cdnjs']]; +$meta['proxy____host'] = ['string', '_pattern' => '#^(|[a-z0-9\-\.+]+)$#i']; +$meta['proxy____port'] = ['numericopt']; +$meta['proxy____user'] = ['string']; +$meta['proxy____pass'] = ['password', '_code' => 'base64']; +$meta['proxy____ssl'] = ['onoff']; +$meta['proxy____except'] = ['string']; diff --git a/lib/plugins/extension/action.php b/lib/plugins/extension/action.php index b57fe558e..116208a40 100644 --- a/lib/plugins/extension/action.php +++ b/lib/plugins/extension/action.php @@ -1,20 +1,23 @@ <?php + +use dokuwiki\Extension\ActionPlugin; +use dokuwiki\Extension\EventHandler; +use dokuwiki\Extension\Event; + /** DokuWiki Plugin extension (Action Component) * * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Andreas Gohr <andi@splitbrain.org> */ - -class action_plugin_extension extends DokuWiki_Action_Plugin +class action_plugin_extension extends ActionPlugin { - /** * Registers a callback function for a given event * - * @param Doku_Event_Handler $controller DokuWiki's event controller object + * @param EventHandler $controller DokuWiki's event controller object * @return void */ - public function register(Doku_Event_Handler $controller) + public function register(EventHandler $controller) { $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'info'); } @@ -22,10 +25,10 @@ class action_plugin_extension extends DokuWiki_Action_Plugin /** * Create the detail info for a single plugin * - * @param Doku_Event $event - * @param $param + * @param Event $event + * @param $param */ - public function info(Doku_Event $event, $param) + public function info(Event $event, $param) { global $USERINFO; global $INPUT; @@ -57,7 +60,7 @@ class action_plugin_extension extends DokuWiki_Action_Plugin switch ($act) { case 'enable': case 'disable': - if(getSecurityToken() != $INPUT->str('sectok')) { + if (getSecurityToken() != $INPUT->str('sectok')) { http_status(403); echo 'Security Token did not match. Possible CSRF attack.'; return; @@ -66,14 +69,14 @@ class action_plugin_extension extends DokuWiki_Action_Plugin $extension->$act(); //enables/disables $reverse = ($act == 'disable') ? 'enable' : 'disable'; - $return = array( - 'state' => $act.'d', // isn't English wonderful? :-) + $return = [ + 'state' => $act . 'd', // isn't English wonderful? :-) 'reverse' => $reverse, - 'label' => $extension->getLang('btn_'.$reverse) - ); + 'label' => $extension->getLang('btn_' . $reverse), + ]; header('Content-Type: application/json'); - echo json_encode($return); + echo json_encode($return, JSON_THROW_ON_ERROR); break; case 'info': diff --git a/lib/plugins/extension/admin.php b/lib/plugins/extension/admin.php index 7e7eb60d4..edced2134 100644 --- a/lib/plugins/extension/admin.php +++ b/lib/plugins/extension/admin.php @@ -1,4 +1,7 @@ <?php + +use dokuwiki\Extension\AdminPlugin; + /** * DokuWiki Plugin extension (Admin Component) * @@ -9,9 +12,9 @@ /** * Admin part of the extension manager */ -class admin_plugin_extension extends DokuWiki_Admin_Plugin +class admin_plugin_extension extends AdminPlugin { - protected $infoFor = null; + protected $infoFor; /** @var helper_plugin_extension_gui */ protected $gui; @@ -53,9 +56,8 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin if (!$repository->hasAccess(!$INPUT->bool('purge'))) { $url = $this->gui->tabURL('', ['purge' => 1], '&'); - msg($this->getLang('repo_error'). - ' [<a href="'.$url.'">'.$this->getLang('repo_retry').'</a>]', -1 - ); + msg($this->getLang('repo_error') . + ' [<a href="' . $url . '">' . $this->getLang('repo_retry') . '</a>]', -1); } if (!in_array('ssl', stream_get_transports())) { @@ -76,11 +78,11 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin case 'update': $extension->setExtension($extname); $installed = $extension->installOrUpdate(); - foreach ($installed as $ext => $info) { + foreach ($installed as $info) { msg(sprintf( - $this->getLang('msg_'.$info['type'].'_'.$info['action'].'_success'), - $info['base']), 1 - ); + $this->getLang('msg_' . $info['type'] . '_' . $info['action'] . '_success'), + $info['base'] + ), 1); } break; case 'uninstall': @@ -89,13 +91,13 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin if ($status) { msg(sprintf( $this->getLang('msg_delete_success'), - hsc($extension->getDisplayName())), 1 - ); + hsc($extension->getDisplayName()) + ), 1); } else { msg(sprintf( $this->getLang('msg_delete_failed'), - hsc($extension->getDisplayName())), -1 - ); + hsc($extension->getDisplayName()) + ), -1); } break; case 'enable': @@ -106,8 +108,8 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin } else { msg(sprintf( $this->getLang('msg_enabled'), - hsc($extension->getDisplayName())), 1 - ); + hsc($extension->getDisplayName()) + ), 1); } break; case 'disable': @@ -118,8 +120,8 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin } else { msg(sprintf( $this->getLang('msg_disabled'), - hsc($extension->getDisplayName())), 1 - ); + hsc($extension->getDisplayName()) + ), 1); } break; } @@ -129,21 +131,22 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin } elseif ($INPUT->post->str('installurl') && checkSecurityToken()) { $installed = $extension->installFromURL( $INPUT->post->str('installurl'), - $INPUT->post->bool('overwrite')); - foreach ($installed as $ext => $info) { + $INPUT->post->bool('overwrite') + ); + foreach ($installed as $info) { msg(sprintf( - $this->getLang('msg_'.$info['type'].'_'.$info['action'].'_success'), - $info['base']), 1 - ); + $this->getLang('msg_' . $info['type'] . '_' . $info['action'] . '_success'), + $info['base'] + ), 1); } send_redirect($this->gui->tabURL('', [], '&', true)); } elseif (isset($_FILES['installfile']) && checkSecurityToken()) { $installed = $extension->installFromUpload('installfile', $INPUT->post->bool('overwrite')); - foreach ($installed as $ext => $info) { + foreach ($installed as $info) { msg(sprintf( - $this->getLang('msg_'.$info['type'].'_'.$info['action'].'_success'), - $info['base']), 1 - ); + $this->getLang('msg_' . $info['type'] . '_' . $info['action'] . '_success'), + $info['base'] + ), 1); } send_redirect($this->gui->tabURL('', [], '&', true)); } @@ -158,8 +161,8 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin */ public function html() { - echo '<h1>'.$this->getLang('menu').'</h1>'.DOKU_LF; - echo '<div id="extension__manager">'.DOKU_LF; + echo '<h1>' . $this->getLang('menu') . '</h1>' . DOKU_LF; + echo '<div id="extension__manager">' . DOKU_LF; $this->gui->tabNavigation(); @@ -178,7 +181,7 @@ class admin_plugin_extension extends DokuWiki_Admin_Plugin $this->gui->tabPlugins(); } - echo '</div>'.DOKU_LF; + echo '</div>' . DOKU_LF; } } diff --git a/lib/plugins/extension/cli.php b/lib/plugins/extension/cli.php index 0e1bf83d5..4e6200ba2 100644 --- a/lib/plugins/extension/cli.php +++ b/lib/plugins/extension/cli.php @@ -1,5 +1,8 @@ <?php +use dokuwiki\Extension\CLIPlugin; +use splitbrain\phpcli\Options; +use splitbrain\phpcli\TableFormatter; use splitbrain\phpcli\Colors; /** @@ -10,10 +13,10 @@ use splitbrain\phpcli\Colors; * @license GPL2 * @author Andreas Gohr <andi@splitbrain.org> */ -class cli_plugin_extension extends DokuWiki_CLI_Plugin +class cli_plugin_extension extends CLIPlugin { /** @inheritdoc */ - protected function setup(\splitbrain\phpcli\Options $options) + protected function setup(Options $options) { // general setup $options->setHelp( @@ -42,8 +45,11 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin // install $options->registerCommand('install', 'Install or upgrade extensions'); - $options->registerArgument('extensions...', - 'One or more extensions to install. Either by name or download URL', true, 'install' + $options->registerArgument( + 'extensions...', + 'One or more extensions to install. Either by name or download URL', + true, + 'install' ); // uninstall @@ -57,12 +63,10 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin // disable $options->registerCommand('disable', 'Disable installed extensions'); $options->registerArgument('extensions...', 'One or more extensions to disable', true, 'disable'); - - } /** @inheritdoc */ - protected function main(\splitbrain\phpcli\Options $options) + protected function main(Options $options) { /** @var helper_plugin_extension_repository $repo */ $repo = plugin_load('helper', 'extension_repository'); @@ -145,7 +149,7 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin $ext->setExtension($extname); if (!$ext->isInstalled()) { $this->error(sprintf('Extension %s is not installed', $ext->getID())); - $ok += 1; + ++$ok; continue; } @@ -159,7 +163,7 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin if ($status !== true) { $this->error($status); - $ok += 1; + ++$ok; continue; } else { $this->success(sprintf($this->getLang($msg), $ext->getID())); @@ -185,7 +189,7 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin $ext->setExtension($extname); if (!$ext->isInstalled()) { $this->error(sprintf('Extension %s is not installed', $ext->getID())); - $ok += 1; + ++$ok; continue; } @@ -221,13 +225,13 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin $installed = $ext->installFromURL($extname, true); } catch (Exception $e) { $this->error($e->getMessage()); - $ok += 1; + ++$ok; } } else { $ext->setExtension($extname); if (!$ext->getDownloadURL()) { - $ok += 1; + ++$ok; $this->error( sprintf('Could not find download for %s', $ext->getID()) ); @@ -238,11 +242,11 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin $installed = $ext->installOrUpdate(); } catch (Exception $e) { $this->error($e->getMessage()); - $ok += 1; + ++$ok; } } - foreach ($installed as $name => $info) { + foreach ($installed as $info) { $this->success( sprintf( $this->getLang('msg_' . $info['type'] . '_' . $info['action'] . '_success'), @@ -301,9 +305,8 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin global $plugin_controller; $pluginlist = $plugin_controller->getList('', true); $tpllist = glob(DOKU_INC . 'lib/tpl/*', GLOB_ONLYDIR); - $tpllist = array_map(function ($path) { - return 'template:' . basename($path); - }, $tpllist); + $tpllist = array_map(static fn($path) => 'template:' . basename($path), $tpllist); + $list = array_merge($pluginlist, $tpllist); sort($list); return $list; @@ -321,7 +324,7 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin { /** @var helper_plugin_extension_extension $ext */ $ext = $this->loadHelper('extension_extension'); - $tr = new \splitbrain\phpcli\TableFormatter($this->colors); + $tr = new TableFormatter($this->colors); foreach ($list as $name) { @@ -363,10 +366,10 @@ class cli_plugin_extension extends DokuWiki_CLI_Plugin $status, $date, strip_tags(sprintf( - $this->getLang('extensionby'), - $ext->getDisplayName(), - $this->colors->wrap($ext->getAuthor(), Colors::C_PURPLE)) - ) + $this->getLang('extensionby'), + $ext->getDisplayName(), + $this->colors->wrap($ext->getAuthor(), Colors::C_PURPLE) + )) ], [ $ecolor, diff --git a/lib/plugins/extension/helper/extension.php b/lib/plugins/extension/helper/extension.php index 1d06f0482..84c731fcc 100644 --- a/lib/plugins/extension/helper/extension.php +++ b/lib/plugins/extension/helper/extension.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki Plugin extension (Helper Component) * @@ -6,13 +7,19 @@ * @author Michael Hamann <michael@content-space.de> */ +use dokuwiki\Extension\Plugin; +use dokuwiki\Extension\PluginInterface; +use dokuwiki\Utf8\PhpString; +use splitbrain\PHPArchive\Tar; +use splitbrain\PHPArchive\ArchiveIOException; +use splitbrain\PHPArchive\Zip; use dokuwiki\HTTP\DokuHTTPClient; use dokuwiki\Extension\PluginController; /** * 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 Plugin { private $id; private $base; @@ -21,10 +28,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin private $remoteInfo; private $managerData; /** @var helper_plugin_extension_repository $repository */ - private $repository = null; + private $repository; /** @var array list of temporary directories */ - private $temporary = array(); + private $temporary = []; /** @var string where templates are installed to */ private $tpllib = ''; @@ -34,7 +41,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin */ public function __construct() { - $this->tpllib = dirname(tpl_incdir()).'/'; + $this->tpllib = dirname(tpl_incdir()) . '/'; } /** @@ -67,6 +74,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { $id = cleanID($id); $this->id = $id; + $this->base = $id; if (substr($id, 0, 9) == 'template:') { @@ -76,9 +84,9 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin $this->is_template = false; } - $this->localInfo = array(); - $this->managerData = array(); - $this->remoteInfo = array(); + $this->localInfo = []; + $this->managerData = []; + $this->remoteInfo = []; if ($this->isInstalled()) { $this->readLocalData(); @@ -112,7 +120,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function isGitControlled() { if (!$this->isInstalled()) return false; - return file_exists($this->getInstallDir().'/.git'); + return file_exists($this->getInstallDir() . '/.git'); } /** @@ -125,12 +133,24 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin if (!empty($this->remoteInfo['bundled'])) return $this->remoteInfo['bundled']; return in_array( $this->id, - array( - 'authad', 'authldap', 'authpdo', 'authplain', - 'acl', 'config', 'extension', 'info', 'popularity', 'revert', - 'safefnrecode', 'styling', 'testing', 'usermanager', 'logviewer', - 'template:dokuwiki', - ) + [ + 'authad', + 'authldap', + 'authpdo', + 'authplain', + 'acl', + 'config', + 'extension', + 'info', + 'popularity', + 'revert', + 'safefnrecode', + 'styling', + 'testing', + 'usermanager', + 'logviewer', + 'template:dokuwiki' + ] ); } @@ -306,8 +326,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function getURL() { if (!empty($this->localInfo['url'])) return $this->localInfo['url']; - return 'https://www.dokuwiki.org/'. - ($this->isTemplate() ? 'template' : 'plugin').':'.$this->getBase(); + return 'https://www.dokuwiki.org/' . + ($this->isTemplate() ? 'template' : 'plugin') . ':' . $this->getBase(); } /** @@ -352,7 +372,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function getDependencies() { if (!empty($this->remoteInfo['dependencies'])) return $this->remoteInfo['dependencies']; - return array(); + return []; } /** @@ -365,7 +385,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin /* @var PluginController $plugin_controller */ global $plugin_controller; $dependencies = $this->getDependencies(); - $missing_dependencies = array(); + $missing_dependencies = []; foreach ($dependencies as $dependency) { if (!$plugin_controller->isEnabled($dependency)) { $missing_dependencies[] = $dependency; @@ -382,7 +402,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function getConflicts() { if (!empty($this->remoteInfo['conflicts'])) return $this->remoteInfo['conflicts']; - return array(); + return []; } /** @@ -393,7 +413,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function getSimilarExtensions() { if (!empty($this->remoteInfo['similar'])) return $this->remoteInfo['similar']; - return array(); + return []; } /** @@ -404,7 +424,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function getTags() { if (!empty($this->remoteInfo['tags'])) return $this->remoteInfo['tags']; - return array(); + return []; } /** @@ -537,8 +557,8 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function getTypes() { if (!empty($this->remoteInfo['types'])) return $this->remoteInfo['types']; - if ($this->isTemplate()) return array(32 => 'template'); - return array(); + if ($this->isTemplate()) return [32 => 'template']; + return []; } /** @@ -549,7 +569,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function getCompatibleVersions() { if (!empty($this->remoteInfo['compatible'])) return $this->remoteInfo['compatible']; - return array(); + return []; } /** @@ -571,9 +591,9 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function getInstallDir() { if ($this->isTemplate()) { - return $this->tpllib.$this->base; + return $this->tpllib . $this->base; } else { - return DOKU_PLUGIN.$this->base; + return DOKU_PLUGIN . $this->base; } } @@ -586,7 +606,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin { if (!$this->isInstalled()) return 'none'; if (!empty($this->managerData)) return 'automatic'; - if (is_dir($this->getInstallDir().'/.git')) return 'git'; + if (is_dir($this->getInstallDir() . '/.git')) return 'git'; return 'manual'; } @@ -622,7 +642,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin public function installFromUpload($field, $overwrite = true) { if ($_FILES[$field]['error']) { - throw new Exception($this->getLang('msg_upload_failed').' ('.$_FILES[$field]['error'].')'); + throw new Exception($this->getLang('msg_upload_failed') . ' (' . $_FILES[$field]['error'] . ')'); } $tmp = $this->mkTmpDir(); @@ -636,16 +656,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin if (!move_uploaded_file($_FILES[$field]['tmp_name'], "$tmp/upload.archive")) { throw new Exception($this->getLang('msg_upload_failed')); } - - try { - $installed = $this->installArchive("$tmp/upload.archive", $overwrite, $basename); - $this->updateManagerData('', $installed); - $this->removeDeletedfiles($installed); - // purge cache - $this->purgeCache(); - } catch (Exception $e) { - throw $e; - } + $installed = $this->installArchive("$tmp/upload.archive", $overwrite, $basename); + $this->updateManagerData('', $installed); + $this->removeDeletedfiles($installed); + $this->purgeCache(); return $installed; } @@ -659,17 +673,11 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin */ public function installFromURL($url, $overwrite = true) { - try { - $path = $this->download($url); - $installed = $this->installArchive($path, $overwrite); - $this->updateManagerData($url, $installed); - $this->removeDeletedfiles($installed); - - // purge cache - $this->purgeCache(); - } catch (Exception $e) { - throw $e; - } + $path = $this->download($url); + $installed = $this->installArchive($path, $overwrite); + $this->updateManagerData($url, $installed); + $this->removeDeletedfiles($installed); + $this->purgeCache(); return $installed; } @@ -767,37 +775,36 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin protected function readLocalData() { if ($this->isTemplate()) { - $infopath = $this->getInstallDir().'/template.info.txt'; + $infopath = $this->getInstallDir() . '/template.info.txt'; } else { - $infopath = $this->getInstallDir().'/plugin.info.txt'; + $infopath = $this->getInstallDir() . '/plugin.info.txt'; } if (is_readable($infopath)) { $this->localInfo = confToHash($infopath); } elseif (!$this->isTemplate() && $this->isEnabled()) { - $path = $this->getInstallDir().'/'; + $path = $this->getInstallDir() . '/'; $plugin = null; foreach (PluginController::PLUGIN_TYPES as $type) { - if (file_exists($path.$type.'.php')) { + if (file_exists($path . $type . '.php')) { $plugin = plugin_load($type, $this->base); - if ($plugin) break; + if ($plugin instanceof PluginInterface) break; } - if ($dh = @opendir($path.$type.'/')) { + 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; + $plugin = plugin_load($type, $this->base . '_' . substr($cp, 0, -4)); + if ($plugin instanceof PluginInterface) break; } - if ($plugin) break; + if ($plugin instanceof PluginInterface) break; closedir($dh); } } - if ($plugin) { - /* @var DokuWiki_Plugin $plugin */ + if ($plugin instanceof PluginInterface) { $this->localInfo = $plugin->getInfo(); } } @@ -814,10 +821,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin $origID = $this->getID(); if (is_null($installed)) { - $installed = array($origID); + $installed = [$origID]; } - foreach ($installed as $ext => $info) { + foreach (array_keys($installed) as $ext) { if ($this->getID() != $ext) $this->setExtension($ext); if ($url) { $this->managerData['downloadurl'] = $url; @@ -840,12 +847,12 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin */ protected function readManagerData() { - $managerpath = $this->getInstallDir().'/manager.dat'; + $managerpath = $this->getInstallDir() . '/manager.dat'; if (is_readable($managerpath)) { $file = @file($managerpath); if (!empty($file)) { foreach ($file as $line) { - list($key, $value) = sexplode('=', trim($line, DOKU_LF), 2, ''); + [$key, $value] = sexplode('=', trim($line, DOKU_LF), 2, ''); $key = trim($key); $value = trim($value); // backwards compatible with old plugin manager @@ -861,10 +868,10 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin */ protected function writeManagerData() { - $managerpath = $this->getInstallDir().'/manager.dat'; + $managerpath = $this->getInstallDir() . '/manager.dat'; $data = ''; foreach ($this->managerData as $k => $v) { - $data .= $k.'='.$v.DOKU_LF; + $data .= $k . '=' . $v . DOKU_LF; } io_saveFile($managerpath, $data); } @@ -913,13 +920,13 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin $name = ''; if (isset($http->resp_headers['content-disposition'])) { $content_disposition = $http->resp_headers['content-disposition']; - $match = array(); - if (is_string($content_disposition) && + $match = []; + if ( + is_string($content_disposition) && preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match) ) { - $name = \dokuwiki\Utf8\PhpString::basename($match[1]); + $name = PhpString::basename($match[1]); } - } if (!$name) { @@ -927,14 +934,14 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin $name = $defaultName; } - $file = $file.$name; + $file .= $name; $fileexists = file_exists($file); - $fp = @fopen($file,"w"); + $fp = @fopen($file, "w"); if (!$fp) return false; fwrite($fp, $data); fclose($fp); - if (!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']); + if (!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']); return $name; } @@ -957,7 +964,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin if (is_null($file)) { $file = md5($url); } else { - $file = \dokuwiki\Utf8\PhpString::basename($file); + $file = PhpString::basename($file); } // create tmp directory for download @@ -966,14 +973,15 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin } // download - if (!$file = $this->downloadToFile($url, $tmp.'/', $file)) { + if (!$file = $this->downloadToFile($url, $tmp . '/', $file)) { io_rmdir($tmp, true); - throw new Exception(sprintf($this->getLang('error_download'), - '<bdi>'.hsc($url).'</bdi>') - ); + throw new Exception(sprintf( + $this->getLang('error_download'), + '<bdi>' . hsc($url) . '</bdi>' + )); } - return $tmp.'/'.$file; + return $tmp . '/' . $file; } /** @@ -985,7 +993,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin */ public function installArchive($file, $overwrite = false, $base = '') { - $installed_extensions = array(); + $installed_extensions = []; // create tmp directory for decompression if (!($tmp = $this->mkTmpDir())) { @@ -993,18 +1001,18 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin } // 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')); } // decompress - $this->decompress($file, "$tmp/".$base); + $this->decompress($file, "$tmp/" . $base); // search $tmp/$base for the folder(s) that has been created // move the folder(s) to lib/.. - $result = array('old'=>array(), 'new'=>array()); + $result = ['old' => [], 'new' => []]; $default = ($this->isTemplate() ? 'template' : 'plugin'); - if (!$this->findFolders($result, $tmp.'/'.$base, $default)) { + if (!$this->findFolders($result, $tmp . '/' . $base, $default)) { throw new Exception($this->getLang('error_findfolder')); } @@ -1040,7 +1048,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin } // check to make sure we aren't overwriting anything - $target = $target_base_dir.$item['base']; + $target = $target_base_dir . $item['base']; if (!$overwrite && file_exists($target)) { // this info message is not being exposed via exception, // so that it's not interrupting the installation @@ -1055,17 +1063,18 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin // return info $id = $item['base']; if ($item['type'] == 'template') { - $id = 'template:'.$id; + $id = 'template:' . $id; } - $installed_extensions[$id] = array( + $installed_extensions[$id] = [ 'base' => $item['base'], 'type' => $item['type'], 'action' => $action - ); + ]; } else { - throw new Exception(sprintf($this->getLang('error_copy').DOKU_LF, - '<bdi>'.$item['base'].'</bdi>') - ); + throw new Exception(sprintf( + $this->getLang('error_copy') . DOKU_LF, + '<bdi>' . $item['base'] . '</bdi>' + )); } } @@ -1105,7 +1114,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin $dh = @opendir($this_dir); if (!$dh) return false; - $found_dirs = array(); + $found_dirs = []; $found_files = 0; $found_template_parts = 0; while (false !== ($f = readdir($dh))) { @@ -1120,7 +1129,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin case 'plugin.info.txt': case 'template.info.txt': // we have found a clear marker, save and return - $info = array(); + $info = []; $type = explode('.', $f, 2); $info['type'] = $type[0]; $info['tmp'] = $this_dir; @@ -1142,7 +1151,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin // files where found but no info.txt - use old method if ($found_files) { - $info = array(); + $info = []; $info['tmp'] = $this_dir; // does this look like a template or should we use the default type? if ($found_template_parts >= 2) { @@ -1178,23 +1187,23 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin if (substr($target, -1) == "/") $target = substr($target, 0, -1); $ext = $this->guessArchiveType($file); - if (in_array($ext, array('tar', 'bz', 'gz'))) { + if (in_array($ext, ['tar', 'bz', 'gz'])) { try { - $tar = new \splitbrain\PHPArchive\Tar(); + $tar = new Tar(); $tar->open($file); $tar->extract($target); - } catch (\splitbrain\PHPArchive\ArchiveIOException $e) { - throw new Exception($this->getLang('error_decompress').' '.$e->getMessage()); + } catch (ArchiveIOException $e) { + throw new Exception($this->getLang('error_decompress') . ' ' . $e->getMessage(), $e->getCode(), $e); } return true; } elseif ($ext == 'zip') { try { - $zip = new \splitbrain\PHPArchive\Zip(); + $zip = new Zip(); $zip->open($file); $zip->extract($target); - } catch (\splitbrain\PHPArchive\ArchiveIOException $e) { - throw new Exception($this->getLang('error_decompress').' '.$e->getMessage()); + } catch (ArchiveIOException $e) { + throw new Exception($this->getLang('error_decompress') . ' ' . $e->getMessage(), $e->getCode(), $e); } return true; @@ -1202,7 +1211,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin // the only case when we don't get one of the recognized archive types is // when the archive file can't be read - throw new Exception($this->getLang('error_decompress').' Couldn\'t read archive file'); + throw new Exception($this->getLang('error_decompress') . ' Couldn\'t read archive file'); } /** @@ -1269,7 +1278,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin */ private function removeDeletedfiles($installed) { - foreach ($installed as $id => $extension) { + foreach ($installed as $extension) { // only on update if ($extension['action'] == 'install') continue; @@ -1279,7 +1288,7 @@ class helper_plugin_extension_extension extends DokuWiki_Plugin } else { $extensiondir = DOKU_PLUGIN; } - $extensiondir = $extensiondir . $extension['base'] .'/'; + $extensiondir = $extensiondir . $extension['base'] . '/'; $definitionfile = $extensiondir . 'deleted.files'; if (!file_exists($definitionfile)) continue; diff --git a/lib/plugins/extension/helper/gui.php b/lib/plugins/extension/helper/gui.php index 919eb2c0b..4495af1e5 100644 --- a/lib/plugins/extension/helper/gui.php +++ b/lib/plugins/extension/helper/gui.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki Plugin extension (Helper Component) * @@ -6,14 +7,15 @@ * @author Andreas Gohr <andi@splitbrain.org> */ +use dokuwiki\Extension\Plugin; use dokuwiki\Form\Form; /** * 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 Plugin { - protected $tabs = array('plugins', 'templates', 'search', 'install'); + protected $tabs = ['plugins', 'templates', 'search', 'install']; /** @var string the extension that should have an open info window FIXME currently broken */ protected $infoFor = ''; @@ -45,8 +47,8 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin $list = $this->loadHelper('extension_list'); $form = new Form([ - 'action' => $this->tabURL('', [], '&'), - 'id' => 'extension__list', + 'action' => $this->tabURL('', [], '&'), + 'id' => 'extension__list', ]); $list->startForm(); foreach ($pluginlist as $name) { @@ -68,7 +70,7 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin echo '</div>'; // FIXME do we have a real way? - $tpllist = glob(DOKU_INC.'lib/tpl/*', GLOB_ONLYDIR); + $tpllist = glob(DOKU_INC . 'lib/tpl/*', GLOB_ONLYDIR); $tpllist = array_map('basename', $tpllist); sort($tpllist); @@ -78,8 +80,8 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin $list = $this->loadHelper('extension_list'); $form = new Form([ - 'action' => $this->tabURL('', [], '&'), - 'id' => 'extension__list', + 'action' => $this->tabURL('', [], '&'), + 'id' => 'extension__list', ]); $list->startForm(); foreach ($tpllist as $name) { @@ -102,8 +104,8 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin echo '</div>'; $form = new Form([ - 'action' => $this->tabURL('', [], '&'), - 'class' => 'search', + 'action' => $this->tabURL('', [], '&'), + 'class' => 'search', ]); $form->addTagOpen('div')->addClass('no'); $form->addTextInput('q', $this->getLang('search_for')) @@ -118,7 +120,7 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin /* @var helper_plugin_extension_repository $repository FIXME should we use some gloabl instance? */ $repository = $this->loadHelper('extension_repository'); - $result = $repository->search($INPUT->str('q')); + $result = $repository->search($INPUT->str('q')); /* @var helper_plugin_extension_extension $extension */ $extension = $this->loadHelper('extension_extension'); @@ -126,8 +128,8 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin $list = $this->loadHelper('extension_list'); $form = new Form([ - 'action' => $this->tabURL('', [], '&'), - 'id' => 'extension__list', + 'action' => $this->tabURL('', [], '&'), + 'id' => 'extension__list', ]); $list->startForm(); if ($result) { @@ -154,9 +156,9 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin echo '</div>'; $form = new Form([ - 'action' => $this->tabURL('', [], '&'), - 'enctype' => 'multipart/form-data', - 'class' => 'install', + 'action' => $this->tabURL('', [], '&'), + 'enctype' => 'multipart/form-data', + 'class' => 'install', ]); $form->addTagOpen('div')->addClass('no'); $form->addTextInput('installurl', $this->getLang('install_url')) @@ -191,7 +193,8 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin } else { $class = ''; } - echo '<li class="'.$tab.$class.'"><a href="'.$url.'">'.$this->getLang('tab_'.$tab).'</a></li>'; + echo '<li class="' . $tab . $class . '"><a href="' . $url . '">' . + $this->getLang('tab_' . $tab) . '</a></li>'; } echo '</ul>'; } @@ -213,10 +216,10 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin /** * Create an URL inside the extension manager * - * @param string $tab tab to load, empty for current tab - * @param array $params associative array of parameter to set - * @param string $sep seperator to build the URL - * @param bool $absolute create absolute URLs? + * @param string $tab tab to load, empty for current tab + * @param array $params associative array of parameter to set + * @param string $sep seperator to build the URL + * @param bool $absolute create absolute URLs? * @return string */ public function tabURL($tab = '', $params = [], $sep = '&', $absolute = false) @@ -225,11 +228,11 @@ class helper_plugin_extension_gui extends DokuWiki_Plugin global $INPUT; if (!$tab) $tab = $this->currentTab(); - $defaults = array( - 'do' => 'admin', + $defaults = [ + 'do' => 'admin', 'page' => 'extension', - 'tab' => $tab, - ); + 'tab' => $tab + ]; 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 647575b10..ec5db0e1d 100644 --- a/lib/plugins/extension/helper/list.php +++ b/lib/plugins/extension/helper/list.php @@ -1,15 +1,17 @@ <?php + +use dokuwiki\Extension\Plugin; + /** * DokuWiki Plugin extension (Helper Component) * * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Michael Hamann <michael@content-space.de> */ - /** * 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 Plugin { protected $form = ''; /** @var helper_plugin_extension_gui */ @@ -56,7 +58,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin */ public function addHeader($id, $header, $level = 2) { - $this->form .='<h'.$level.' id="'.$id.'">'.hsc($header).'</h'.$level.'>'.DOKU_LF; + $this->form .= '<h' . $level . ' id="' . $id . '">' . hsc($header) . '</h' . $level . '>' . DOKU_LF; } /** @@ -66,7 +68,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin */ public function addParagraph($data) { - $this->form .= '<p>'.hsc($data).'</p>'.DOKU_LF; + $this->form .= '<p>' . hsc($data) . '</p>' . DOKU_LF; } /** @@ -78,9 +80,9 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { $this->form .= '<div class="no">'; foreach ($data as $key => $value) { - $this->form .= '<input type="hidden" name="'.hsc($key).'" value="'.hsc($value).'" />'; + $this->form .= '<input type="hidden" name="' . hsc($key) . '" value="' . hsc($value) . '" />'; } - $this->form .= '</div>'.DOKU_LF; + $this->form .= '</div>' . DOKU_LF; } /** @@ -97,7 +99,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin public function nothingFound() { global $lang; - $this->form .= '<li class="notfound">'.$lang['nothingfound'].'</li>'; + $this->form .= '<li class="notfound">' . $lang['nothingfound'] . '</li>'; } /** @@ -118,8 +120,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin */ private function startRow(helper_plugin_extension_extension $extension) { - $this->form .= '<li id="extensionplugin__'.hsc($extension->getID()). - '" class="'.$this->makeClass($extension).'">'; + $this->form .= '<li id="extensionplugin__' . hsc($extension->getID()) . + '" class="' . $this->makeClass($extension) . '">'; } /** @@ -129,7 +131,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin */ private function populateColumn($class, $html) { - $this->form .= '<div class="'.$class.' col">'.$html.'</div>'.DOKU_LF; + $this->form .= '<div class="' . $class . ' col">' . $html . '</div>' . DOKU_LF; } /** @@ -137,7 +139,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin */ private function endRow() { - $this->form .= '</li>'.DOKU_LF; + $this->form .= '</li>' . DOKU_LF; } /** @@ -155,18 +157,18 @@ class helper_plugin_extension_list extends DokuWiki_Plugin } else { $linktype = 'extern'; } - $param = array( + $param = [ 'href' => $url, 'title' => $url, 'class' => ($linktype == 'extern') ? 'urlextern' : 'interwiki iw_doku', 'target' => $conf['target'][$linktype], - 'rel' => ($linktype == 'extern') ? 'noopener' : '', - ); + 'rel' => ($linktype == 'extern') ? 'noopener' : '' + ]; if ($linktype == 'extern' && $conf['relnofollow']) { $param['rel'] = implode(' ', [$param['rel'], 'ugc nofollow']); } - $html = ' <a '. buildAttributes($param, true).'>'. - $this->getLang('homepage_link').'</a>'; + $html = ' <a ' . buildAttributes($param, true) . '>' . + $this->getLang('homepage_link') . '</a>'; return $html; } @@ -180,12 +182,12 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { $class = ($extension->isTemplate()) ? 'template' : 'plugin'; if ($extension->isInstalled()) { - $class.=' installed'; - $class.= ($extension->isEnabled()) ? ' enabled':' disabled'; + $class .= ' installed'; + $class .= ($extension->isEnabled()) ? ' enabled' : ' disabled'; 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; } @@ -201,17 +203,17 @@ class helper_plugin_extension_list extends DokuWiki_Plugin if ($extension->getAuthor()) { $mailid = $extension->getEmailID(); if ($mailid) { - $url = $this->gui->tabURL('search', array('q' => 'authorid:'.$mailid)); - $html = '<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>'; + $url = $this->gui->tabURL('search', ['q' => 'authorid:' . $mailid]); + $html = '<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>'; } else { - $html = '<span class="author">'.hsc($extension->getAuthor()).'</span>'; + $html = '<span class="author">' . hsc($extension->getAuthor()) . '</span>'; } - $html = '<bdi>'.$html.'</bdi>'; + $html = '<bdi>' . $html . '</bdi>'; } else { - $html = '<em class="author">'.$this->getLang('unknown_author').'</em>'.DOKU_LF; + $html = '<em class="author">' . $this->getLang('unknown_author') . '</em>' . DOKU_LF; } return $html; } @@ -233,17 +235,17 @@ class helper_plugin_extension_list extends DokuWiki_Plugin $thumb = str_replace('http://www.dokuwiki.org', '//www.dokuwiki.org', $thumb); $title = sprintf($this->getLang('screenshot'), hsc($extension->getDisplayName())); - $img = '<a href="'.hsc($screen).'" target="_blank" class="extension_screenshot">'. - '<img alt="'.$title.'" width="120" height="70" src="'.hsc($thumb).'" />'. + $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. + $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. + $img = '<img alt="" width="120" height="70" src="' . DOKU_BASE . 'lib/plugins/extension/images/plugin.png" />'; } - $html = '<div class="screenshot" >'.$img.'<span></span></div>'.DOKU_LF; + $html = '<div class="screenshot" >' . $img . '<span></span></div>' . DOKU_LF; return $html; } @@ -260,26 +262,26 @@ class helper_plugin_extension_list extends DokuWiki_Plugin $html .= '<h2>'; $html .= sprintf( $this->getLang('extensionby'), - '<bdi>'.hsc($extension->getDisplayName()).'</bdi>', + '<bdi>' . hsc($extension->getDisplayName()) . '</bdi>', $this->makeAuthor($extension) ); - $html .= '</h2>'.DOKU_LF; + $html .= '</h2>' . DOKU_LF; $html .= $this->makeScreenshot($extension); $popularity = $extension->getPopularity(); if ($popularity !== false && !$extension->isBundled()) { - $popularityText = sprintf($this->getLang('popularity'), round($popularity*100, 2)); - $html .= '<div class="popularity" title="'.$popularityText.'">'. - '<div style="width: '.($popularity * 100).'%;">'. - '<span class="a11y">'.$popularityText.'</span>'. - '</div></div>'.DOKU_LF; + $popularityText = sprintf($this->getLang('popularity'), round($popularity * 100, 2)); + $html .= '<div class="popularity" title="' . $popularityText . '">' . + '<div style="width: ' . ($popularity * 100) . '%;">' . + '<span class="a11y">' . $popularityText . '</span>' . + '</div></div>' . DOKU_LF; } if ($extension->getDescription()) { $html .= '<p><bdi>'; - $html .= hsc($extension->getDescription()).' '; - $html .= '</bdi></p>'.DOKU_LF; + $html .= hsc($extension->getDescription()) . ' '; + $html .= '</bdi></p>' . DOKU_LF; } $html .= $this->makeLinkbar($extension); @@ -288,18 +290,18 @@ class helper_plugin_extension_list extends DokuWiki_Plugin $url = $this->gui->tabURL(''); $class = 'close'; } else { - $url = $this->gui->tabURL('', array('info' => $extension->getID())); + $url = $this->gui->tabURL('', ['info' => $extension->getID()]); $class = ''; } - $html .= ' <a href="'.$url.'#extensionplugin__'.$extension->getID(). - '" class="info '.$class.'" title="'.$this->getLang('btn_info'). - '" data-extid="'.$extension->getID().'">'.$this->getLang('btn_info').'</a>'; + $html .= ' <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) { $html .= $this->makeInfo($extension); } $html .= $this->makeNoticeArea($extension); - $html .= '</div>'.DOKU_LF; + $html .= '</div>' . DOKU_LF; return $html; } @@ -322,34 +324,34 @@ class helper_plugin_extension_list extends DokuWiki_Plugin } else { $linktype = 'extern'; } - $param = array( + $param = [ 'href' => $bugtrackerURL, 'title' => $bugtrackerURL, 'class' => 'bugs', 'target' => $conf['target'][$linktype], - 'rel' => ($linktype == 'extern') ? 'noopener' : '', - ); + 'rel' => ($linktype == 'extern') ? 'noopener' : '' + ]; if ($conf['relnofollow']) { $param['rel'] = implode(' ', [$param['rel'], 'ugc nofollow']); } - $html .= ' <a '.buildAttributes($param, true).'>'. - $this->getLang('bugs_features').'</a>'; + $html .= ' <a ' . buildAttributes($param, true) . '>' . + $this->getLang('bugs_features') . '</a>'; } if ($extension->getTags()) { $first = true; - $html .= ' <span class="tags">'.$this->getLang('tags').' '; + $html .= ' <span class="tags">' . $this->getLang('tags') . ' '; foreach ($extension->getTags() as $tag) { if (!$first) { $html .= ', '; } else { $first = false; } - $url = $this->gui->tabURL('search', ['q' => 'tag:'.$tag]); - $html .= '<bdi><a href="'.$url.'">'.hsc($tag).'</a></bdi>'; + $url = $this->gui->tabURL('search', ['q' => 'tag:' . $tag]); + $html .= '<bdi><a href="' . $url . '">' . hsc($tag) . '</a></bdi>'; } $html .= '</span>'; } - $html .= '</div>'.DOKU_LF; + $html .= '</div>' . DOKU_LF; return $html; } @@ -381,18 +383,18 @@ class helper_plugin_extension_list extends DokuWiki_Plugin '</div>'; } if (($securityissue = $extension->getSecurityIssue()) !== false) { - $html .= '<div class="msg error">'. - sprintf($this->getLang('security_issue'), '<bdi>'.hsc($securityissue).'</bdi>'). + $html .= '<div class="msg error">' . + sprintf($this->getLang('security_issue'), '<bdi>' . hsc($securityissue) . '</bdi>') . '</div>'; } if (($securitywarning = $extension->getSecurityWarning()) !== false) { - $html .= '<div class="msg notify">'. - sprintf($this->getLang('security_warning'), '<bdi>'.hsc($securitywarning).'</bdi>'). + $html .= '<div class="msg notify">' . + sprintf($this->getLang('security_warning'), '<bdi>' . hsc($securitywarning) . '</bdi>') . '</div>'; } if ($extension->updateAvailable()) { - $html .= '<div class="msg notify">'. - sprintf($this->getLang('update_available'), hsc($extension->getLastUpdate())). + $html .= '<div class="msg notify">' . + sprintf($this->getLang('update_available'), hsc($extension->getLastUpdate())) . '</div>'; } if ($extension->hasDownloadURLChanged()) { @@ -404,7 +406,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin ) . '</div>'; } - return $html.DOKU_LF; + return $html . DOKU_LF; } /** @@ -420,13 +422,13 @@ class helper_plugin_extension_list extends DokuWiki_Plugin $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']; $name = shorten($base, $long, 55); - $html = '<a href="'.hsc($url).'" class="urlextern">'.hsc($name).'</a>'; + $html = '<a href="' . hsc($url) . '" class="urlextern">' . hsc($name) . '</a>'; return $html; } @@ -441,26 +443,26 @@ class helper_plugin_extension_list extends DokuWiki_Plugin $default = $this->getLang('unknown'); $html = '<dl class="details">'; - $html .= '<dt>'.$this->getLang('status').'</dt>'; - $html .= '<dd>'.$this->makeStatus($extension).'</dd>'; + $html .= '<dt>' . $this->getLang('status') . '</dt>'; + $html .= '<dd>' . $this->makeStatus($extension) . '</dd>'; if ($extension->getDonationURL()) { - $html .= '<dt>'.$this->getLang('donate').'</dt>'; + $html .= '<dt>' . $this->getLang('donate') . '</dt>'; $html .= '<dd>'; - $html .= '<a href="'.$extension->getDonationURL().'" class="donate">'. - $this->getLang('donate_action').'</a>'; + $html .= '<a href="' . $extension->getDonationURL() . '" class="donate">' . + $this->getLang('donate_action') . '</a>'; $html .= '</dd>'; } if (!$extension->isBundled()) { - $html .= '<dt>'.$this->getLang('downloadurl').'</dt>'; + $html .= '<dt>' . $this->getLang('downloadurl') . '</dt>'; $html .= '<dd><bdi>'; $html .= ($extension->getDownloadURL() ? $this->shortlink($extension->getDownloadURL()) : $default); $html .= '</bdi></dd>'; - $html .= '<dt>'.$this->getLang('repository').'</dt>'; + $html .= '<dt>' . $this->getLang('repository') . '</dt>'; $html .= '<dd><bdi>'; $html .= ($extension->getSourcerepoURL() ? $this->shortlink($extension->getSourcerepoURL()) @@ -470,13 +472,13 @@ class helper_plugin_extension_list extends DokuWiki_Plugin if ($extension->isInstalled()) { if ($extension->getInstalledVersion()) { - $html .= '<dt>'.$this->getLang('installed_version').'</dt>'; + $html .= '<dt>' . $this->getLang('installed_version') . '</dt>'; $html .= '<dd>'; $html .= hsc($extension->getInstalledVersion()); $html .= '</dd>'; } if (!$extension->isBundled()) { - $html .= '<dt>'.$this->getLang('install_date').'</dt>'; + $html .= '<dt>' . $this->getLang('install_date') . '</dt>'; $html .= '<dd>'; $html .= ($extension->getUpdateDate() ? hsc($extension->getUpdateDate()) @@ -485,7 +487,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin } } if (!$extension->isInstalled() || $extension->updateAvailable()) { - $html .= '<dt>'.$this->getLang('available_version').'</dt>'; + $html .= '<dt>' . $this->getLang('available_version') . '</dt>'; $html .= '<dd>'; $html .= ($extension->getLastUpdate() ? hsc($extension->getLastUpdate()) @@ -493,7 +495,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin $html .= '</dd>'; } - $html .= '<dt>'.$this->getLang('provides').'</dt>'; + $html .= '<dt>' . $this->getLang('provides') . '</dt>'; $html .= '<dd><bdi>'; $html .= ($extension->getTypes() ? hsc(implode(', ', $extension->getTypes())) @@ -501,35 +503,35 @@ class helper_plugin_extension_list extends DokuWiki_Plugin $html .= '</bdi></dd>'; if (!$extension->isBundled() && $extension->getCompatibleVersions()) { - $html .= '<dt>'.$this->getLang('compatible').'</dt>'; + $html .= '<dt>' . $this->getLang('compatible') . '</dt>'; $html .= '<dd>'; foreach ($extension->getCompatibleVersions() as $date => $version) { - $html .= '<bdi>'.$version['label'].' ('.$date.')</bdi>, '; + $html .= '<bdi>' . $version['label'] . ' (' . $date . ')</bdi>, '; } $html = rtrim($html, ', '); $html .= '</dd>'; } if ($extension->getDependencies()) { - $html .= '<dt>'.$this->getLang('depends').'</dt>'; + $html .= '<dt>' . $this->getLang('depends') . '</dt>'; $html .= '<dd>'; $html .= $this->makeLinkList($extension->getDependencies()); $html .= '</dd>'; } if ($extension->getSimilarExtensions()) { - $html .= '<dt>'.$this->getLang('similar').'</dt>'; + $html .= '<dt>' . $this->getLang('similar') . '</dt>'; $html .= '<dd>'; $html .= $this->makeLinkList($extension->getSimilarExtensions()); $html .= '</dd>'; } if ($extension->getConflicts()) { - $html .= '<dt>'.$this->getLang('conflicts').'</dt>'; + $html .= '<dt>' . $this->getLang('conflicts') . '</dt>'; $html .= '<dd>'; $html .= $this->makeLinkList($extension->getConflicts()); $html .= '</dd>'; } - $html .= '</dl>'.DOKU_LF; + $html .= '</dl>' . DOKU_LF; return $html; } @@ -543,9 +545,9 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { $html = ''; foreach ($ext as $link) { - $html .= '<bdi><a href="'. - $this->gui->tabURL('search', array('q'=>'ext:'.$link)).'">'. - hsc($link).'</a></bdi>, '; + $html .= '<bdi><a href="' . + $this->gui->tabURL('search', ['q' => 'ext:' . $link]) . '">' . + hsc($link) . '</a></bdi>, '; } return rtrim($html, ', '); } @@ -575,9 +577,8 @@ class helper_plugin_extension_list extends DokuWiki_Plugin } } } else { - $errors .= '<p class="permerror">'.$this->getLang($canmod).'</p>'; + $errors .= '<p class="permerror">' . $this->getLang($canmod) . '</p>'; } - if (!$extension->isProtected() && !$extension->isTemplate()) { // no enable/disable for templates if ($extension->isEnabled()) { $html .= $this->makeAction('disable', $extension); @@ -585,35 +586,32 @@ class helper_plugin_extension_list extends DokuWiki_Plugin $html .= $this->makeAction('enable', $extension); } } - if ($extension->isGitControlled()) { - $errors .= '<p class="permerror">'.$this->getLang('git').'</p>'; + $errors .= '<p class="permerror">' . $this->getLang('git') . '</p>'; } - - if ($extension->isEnabled() && + if ( + $extension->isEnabled() && in_array('Auth', $extension->getTypes()) && $conf['authtype'] != $extension->getID() ) { - $errors .= '<p class="permerror">'.$this->getLang('auth').'</p>'; + $errors .= '<p class="permerror">' . $this->getLang('auth') . '</p>'; } - } else { - if (($canmod = $extension->canModify()) === true) { - if ($extension->getDownloadURL()) { - $html .= $this->makeAction('install', $extension); - } - } else { - $errors .= '<div class="permerror">'.$this->getLang($canmod).'</div>'; + } elseif (($canmod = $extension->canModify()) === true) { + if ($extension->getDownloadURL()) { + $html .= $this->makeAction('install', $extension); } + } else { + $errors .= '<div class="permerror">' . $this->getLang($canmod) . '</div>'; } if (!$extension->isInstalled() && $extension->getDownloadURL()) { - $html .= ' <span class="version">'.$this->getLang('available_version').' '; + $html .= ' <span class="version">' . $this->getLang('available_version') . ' '; $html .= ($extension->getLastUpdate() ? hsc($extension->getLastUpdate()) - : $this->getLang('unknown')).'</span>'; + : $this->getLang('unknown')) . '</span>'; } - return $html.' '.$errors.DOKU_LF; + return $html . ' ' . $errors . DOKU_LF; } /** @@ -627,18 +625,15 @@ class helper_plugin_extension_list extends DokuWiki_Plugin { $title = ''; - switch ($action) { - case 'install': - case 'reinstall': - $title = 'title="'.hsc($extension->getDownloadURL()).'"'; - break; + if ($action == 'install' || $action == 'reinstall') { + $title = 'title="' . hsc($extension->getDownloadURL()) . '"'; } - $classes = 'button '.$action; - $name = 'fn['.$action.']['.hsc($extension->getID()).']'; + $classes = 'button ' . $action; + $name = 'fn[' . $action . '][' . hsc($extension->getID()) . ']'; - $html = '<button class="'.$classes.'" name="'.$name.'" type="submit" '.$title.'>'. - $this->getLang('btn_'.$action).'</button> '; + $html = '<button class="' . $classes . '" name="' . $name . '" type="submit" ' . $title . '>' . + $this->getLang('btn_' . $action) . '</button> '; return $html; } @@ -650,7 +645,7 @@ class helper_plugin_extension_list extends DokuWiki_Plugin */ public function makeStatus(helper_plugin_extension_extension $extension) { - $status = array(); + $status = []; if ($extension->isInstalled()) { $status[] = $this->getLang('status_installed'); diff --git a/lib/plugins/extension/helper/repository.php b/lib/plugins/extension/helper/repository.php index 0bca6c975..9d7f61f3e 100644 --- a/lib/plugins/extension/helper/repository.php +++ b/lib/plugins/extension/helper/repository.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki Plugin extension (Helper Component) * @@ -6,6 +7,7 @@ * @author Michael Hamann <michael@content-space.de> */ +use dokuwiki\Extension\Plugin; use dokuwiki\Cache\Cache; use dokuwiki\HTTP\DokuHTTPClient; use dokuwiki\Extension\PluginController; @@ -13,13 +15,12 @@ use dokuwiki\Extension\PluginController; /** * 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 Plugin { + public const EXTENSION_REPOSITORY_API = 'https://www.dokuwiki.org/lib/plugins/pluginrepo/api.php'; - const EXTENSION_REPOSITORY_API = 'https://www.dokuwiki.org/lib/plugins/pluginrepo/api.php'; - - private $loaded_extensions = array(); - private $has_access = null; + private $loaded_extensions = []; + private $has_access; /** * Initialize the repository (cache), fetches data for all installed plugins @@ -30,14 +31,15 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin global $plugin_controller; if ($this->hasAccess()) { $list = $plugin_controller->getList('', true); - $request_data = array('fmt' => 'php'); + $request_data = ['fmt' => 'php']; $request_needed = false; foreach ($list as $name) { - $cache = new Cache('##extension_manager##'.$name, '.repo'); + $cache = new Cache('##extension_manager##' . $name, '.repo'); - if (!isset($this->loaded_extensions[$name]) && + if ( + !isset($this->loaded_extensions[$name]) && $this->hasAccess() && - !$cache->useCache(array('age' => 3600 * 24)) + !$cache->useCache(['age' => 3600 * 24]) ) { $this->loaded_extensions[$name] = true; $request_data['ext'][] = $name; @@ -51,7 +53,7 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin if ($data !== false) { $extensions = unserialize($data); foreach ($extensions as $extension) { - $cache = new Cache('##extension_manager##'.$extension['plugin'], '.repo'); + $cache = new Cache('##extension_manager##' . $extension['plugin'], '.repo'); $cache->storeCache(serialize($extension)); } } else { @@ -67,14 +69,15 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin * @param bool $usecache use cached result if still valid * @return bool If repository access is available */ - public function hasAccess($usecache = true) { + public function hasAccess($usecache = true) + { if ($this->has_access === null) { $cache = new Cache('##extension_manager###hasAccess', '.repo'); - if (!$cache->useCache(array('age' => 60*10, 'purge' => !$usecache))) { + if (!$cache->useCache(['age' => 60 * 10, 'purge' => !$usecache])) { $httpclient = new DokuHTTPClient(); $httpclient->timeout = 5; - $data = $httpclient->get(self::EXTENSION_REPOSITORY_API.'?cmd=ping'); + $data = $httpclient->get(self::EXTENSION_REPOSITORY_API . '?cmd=ping'); if ($data !== false) { $this->has_access = true; $cache->storeCache(1); @@ -97,22 +100,23 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin */ public function getData($name) { - $cache = new Cache('##extension_manager##'.$name, '.repo'); + $cache = new Cache('##extension_manager##' . $name, '.repo'); - if (!isset($this->loaded_extensions[$name]) && + if ( + !isset($this->loaded_extensions[$name]) && $this->hasAccess() && - !$cache->useCache(array('age' => 3600 * 24)) + !$cache->useCache(['age' => 3600 * 24]) ) { $this->loaded_extensions[$name] = true; $httpclient = new DokuHTTPClient(); - $data = $httpclient->get(self::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); - if(count($result)) { + if (count($result)) { $cache->storeCache(serialize($result[0])); return $result[0]; } - return array(); + return []; } else { $this->has_access = false; } @@ -120,7 +124,7 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin if (file_exists($cache->cache)) { return unserialize($cache->retrieveCache(false)); } - return array(); + return []; } /** @@ -136,15 +140,15 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin $httpclient = new DokuHTTPClient(); $data = $httpclient->post(self::EXTENSION_REPOSITORY_API, $query); - if ($data === false) return array(); + if ($data === false) return []; $result = unserialize($data); - $ids = array(); + $ids = []; // store cache info for each extension foreach ($result as $ext) { $name = $ext['plugin']; - $cache = new Cache('##extension_manager##'.$name, '.repo'); + $cache = new Cache('##extension_manager##' . $name, '.repo'); $cache->storeCache(serialize($ext)); $ids[] = $name; } @@ -160,12 +164,7 @@ class helper_plugin_extension_repository extends DokuWiki_Plugin */ protected function parseQuery($q) { - $parameters = array( - 'tag' => array(), - 'mail' => array(), - 'type' => array(), - 'ext' => array() - ); + $parameters = ['tag' => [], 'mail' => [], 'type' => [], 'ext' => []]; // extract tags if (preg_match_all('/(^|\s)(tag:([\S]+))/', $q, $matches, PREG_SET_ORDER)) { diff --git a/lib/plugins/info/syntax.php b/lib/plugins/info/syntax.php index 8d86c220a..9027653b6 100644 --- a/lib/plugins/info/syntax.php +++ b/lib/plugins/info/syntax.php @@ -1,5 +1,8 @@ <?php +use dokuwiki\Extension\SyntaxPlugin; +use dokuwiki\Extension\PluginInterface; + /** * Info Plugin: Displays information about various DokuWiki internals * @@ -7,9 +10,8 @@ * @author Andreas Gohr <andi@splitbrain.org> * @author Esther Brunner <wikidesign@gmail.com> */ -class syntax_plugin_info extends DokuWiki_Syntax_Plugin +class syntax_plugin_info extends SyntaxPlugin { - /** * What kind of syntax are we? */ @@ -54,7 +56,7 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin 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)); + return [strtolower($match)]; } /** @@ -127,12 +129,13 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { global $lang; $plugins = plugin_list($type); - $plginfo = array(); + $plginfo = []; // remove subparts foreach ($plugins as $p) { - if (!$po = plugin_load($type, $p)) continue; - list($name,/* $part */) = explode('_', $p, 2); + $po = plugin_load($type, $p); + if (! $po instanceof PluginInterface) continue; + [$name, /* part */] = explode('_', $p, 2); $plginfo[$name] = $po->getInfo(); } @@ -167,7 +170,8 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { $plugins = plugin_list('helper'); foreach ($plugins as $p) { - if (!$po = plugin_load('helper', $p)) continue; + $po = plugin_load('helper', $p); + if (!$po instanceof PluginInterface) continue; if (!method_exists($po, 'getMethods')) continue; $methods = $po->getMethods(); @@ -176,7 +180,7 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin $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 .= '<p>' . strtr(hsc($info['desc']), ["\n" => "<br />"]) . '</p>'; $doc .= '<pre class="code">$' . $p . " = plugin_load('helper', '" . $p . "');</pre>"; $doc .= '</div>'; foreach ($methods as $method) { @@ -190,11 +194,11 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin if ($method['params']) { $c = count($method['params']); $doc .= '<tr><th rowspan="' . $c . '">Parameters</th><td>'; - $params = array(); + $params = []; foreach ($method['params'] as $desc => $type) { $params[] = hsc($desc) . '</td><td>' . hsc($type); } - $doc .= join('</td></tr><tr><td>', $params) . '</td></tr>'; + $doc .= implode('</td></tr><tr><td>', $params) . '</td></tr>'; } if ($method['return']) { $doc .= '<tr><th>Return value</th><td>' . hsc(key($method['return'])) . @@ -226,7 +230,7 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin $doc .= $mode; $doc .= '</td>'; $doc .= '<td class="leftalign">'; - $doc .= join(', ', $modes); + $doc .= implode(', ', $modes); $doc .= '</td>'; $doc .= '</tr>'; } @@ -243,7 +247,7 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin { $modes = p_get_parsermodes(); - $compactmodes = array(); + $compactmodes = []; foreach ($modes as $mode) { $compactmodes[$mode['sort']][] = $mode['mode']; } @@ -325,12 +329,12 @@ class syntax_plugin_info extends DokuWiki_Syntax_Plugin $hid = ''; if (($level >= $conf['toptoclevel']) && ($level <= $conf['maxtoclevel'])) { $hid = $renderer->_headerToLink($text, true); - $renderer->toc[] = array( + $renderer->toc[] = [ 'hid' => $hid, 'title' => $text, 'type' => 'ul', - 'level' => $level - $conf['toptoclevel'] + 1, - ); + 'level' => $level - $conf['toptoclevel'] + 1 + ]; } return $hid; } diff --git a/lib/plugins/logviewer/admin.php b/lib/plugins/logviewer/admin.php index 335af4c78..a747686af 100644 --- a/lib/plugins/logviewer/admin.php +++ b/lib/plugins/logviewer/admin.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\Extension\AdminPlugin; +use dokuwiki\Form\Form; use dokuwiki\Logger; /** @@ -8,9 +10,9 @@ use dokuwiki\Logger; * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Andreas Gohr <andi@splitbrain.org> */ -class admin_plugin_logviewer extends DokuWiki_Admin_Plugin +class admin_plugin_logviewer extends AdminPlugin { - const MAX_READ_SIZE = 1048576; // 1 MB + protected const MAX_READ_SIZE = 1_048_576; // 1 MB protected $facilities; protected $facility; @@ -56,7 +58,7 @@ class admin_plugin_logviewer extends DokuWiki_Admin_Plugin { global $ID; - $form = new dokuwiki\Form\Form(['method' => 'GET']); + $form = new Form(['method' => 'GET']); $form->setHiddenField('do', 'admin'); $form->setHiddenField('page', 'logviewer'); $form->setHiddenField('facility', $this->facility); @@ -71,8 +73,10 @@ class admin_plugin_logviewer extends DokuWiki_Admin_Plugin if ($facility == $this->facility) { echo '<strong>' . hsc($facility) . '</strong>'; } else { - $link = wl($ID, - ['do' => 'admin', 'page' => 'logviewer', 'date' => $this->date, 'facility' => $facility]); + $link = wl( + $ID, + ['do' => 'admin', 'page' => 'logviewer', 'date' => $this->date, 'facility' => $facility] + ); echo '<a href="' . $link . '">' . hsc($facility) . '</a>'; } echo '</li>'; @@ -156,7 +160,7 @@ class admin_plugin_logviewer extends DokuWiki_Admin_Plugin if ($size >= self::MAX_READ_SIZE) { array_shift($lines); // Discard the first line - while (!empty($lines) && (substr($lines[0], 0, 2) === ' ')) { + while ($lines !== [] && (substr($lines[0], 0, 2) === ' ')) { array_shift($lines); // Discard indented lines } @@ -191,10 +195,10 @@ class admin_plugin_logviewer extends DokuWiki_Admin_Plugin $line = $lines[$i] ?? ''; } echo '</dd>'; - $i -= 1; // rewind the counter + --$i; // rewind the counter } else { // other lines are actual log lines in three parts - list($dt, $file, $msg) = sexplode("\t", $line, 3, ''); + [$dt, $file, $msg] = sexplode("\t", $line, 3, ''); echo '<dt>'; echo '<span class="datetime">' . hsc($dt) . '</span>'; echo '<span class="log">'; diff --git a/lib/plugins/popularity/action.php b/lib/plugins/popularity/action.php index fac610735..16b1a21cc 100644 --- a/lib/plugins/popularity/action.php +++ b/lib/plugins/popularity/action.php @@ -1,13 +1,16 @@ <?php + +use dokuwiki\Extension\ActionPlugin; +use dokuwiki\Extension\EventHandler; +use dokuwiki\Extension\Event; + /** * Popularity Feedback Plugin * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) */ - -class action_plugin_popularity extends DokuWiki_Action_Plugin +class action_plugin_popularity extends ActionPlugin { - /** * @var helper_plugin_popularity */ @@ -19,18 +22,18 @@ class action_plugin_popularity extends DokuWiki_Action_Plugin } /** @inheritdoc */ - public function register(Doku_Event_Handler $controller) + public function register(EventHandler $controller) { - $controller->register_hook('INDEXER_TASKS_RUN', 'AFTER', $this, 'autosubmit', array()); + $controller->register_hook('INDEXER_TASKS_RUN', 'AFTER', $this, 'autosubmit', []); } /** * Event handler * - * @param Doku_Event $event + * @param Event $event * @param $param */ - public function autosubmit(Doku_Event &$event, $param) + public function autosubmit(Event $event, $param) { //Do we have to send the data now if (!$this->helper->isAutosubmitEnabled() || $this->isTooEarlyToSubmit()) { @@ -61,6 +64,6 @@ class action_plugin_popularity extends DokuWiki_Action_Plugin protected function isTooEarlyToSubmit() { $lastSubmit = $this->helper->lastSentTime(); - return $lastSubmit + 24*60*60*30 > time(); + return $lastSubmit + 24 * 60 * 60 * 30 > time(); } } diff --git a/lib/plugins/popularity/admin.php b/lib/plugins/popularity/admin.php index 61d8cc3bf..f9adcf045 100644 --- a/lib/plugins/popularity/admin.php +++ b/lib/plugins/popularity/admin.php @@ -1,16 +1,18 @@ <?php + +use dokuwiki\Extension\AdminPlugin; + /** * Popularity Feedback Plugin * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Andreas Gohr <andi@splitbrain.org> */ -class admin_plugin_popularity extends DokuWiki_Admin_Plugin +class admin_plugin_popularity extends AdminPlugin { - /** @var helper_plugin_popularity */ protected $helper; - protected $sentStatus = null; + protected $sentStatus; /** * admin_plugin_popularity constructor. @@ -88,7 +90,6 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin 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)) { @@ -96,26 +97,21 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin echo io_readFile($this->helper->autosubmitErrorFile); } } - flush(); echo $this->buildForm('server'); - //Print the last time the data was sent $lastSent = $this->helper->lastSentTime(); if ($lastSent !== 0) { echo $this->getLang('lastSent') . ' ' . datetime_h($lastSent); } + } elseif ($this->sentStatus === '') { + //If we successfully send the data + echo $this->locale_xhtml('submitted'); } else { - //If we just submitted the form - if ($this->sentStatus === '') { - //If we successfully sent the data - echo $this->locale_xhtml('submitted'); - } else { - //If we failed to submit the data, try directly with the browser - echo $this->getLang('submissionFailed') . $this->sentStatus . '<br />'; - echo $this->getLang('submitDirectly'); - echo $this->buildForm('browser', $INPUT->str('data')); - } + //If we failed to submit the data, try directly with the browser + echo $this->getLang('submissionFailed') . $this->sentStatus . '<br />'; + echo $this->getLang('submitDirectly'); + echo $this->buildForm('browser', $INPUT->str('data')); } } @@ -133,25 +129,25 @@ class admin_plugin_popularity extends DokuWiki_Admin_Plugin $data = $this->helper->gatherAsString(); } - $form = '<form method="post" action="'. $url .'" accept-charset="utf-8">' - .'<fieldset style="width: 60%;">' - .'<textarea class="edit" rows="10" cols="80" readonly="readonly" name="data">' - .$data - .'</textarea><br />'; + $form = '<form method="post" action="' . $url . '" accept-charset="utf-8">' + . '<fieldset style="width: 60%;">' + . '<textarea class="edit" rows="10" cols="80" readonly="readonly" name="data">' + . $data + . '</textarea><br />'; //If we submit via the server, we give the opportunity to suscribe to the autosubmission option if ($submissionMode !== 'browser') { $form .= '<label for="autosubmit">' - .'<input type="checkbox" name="autosubmit" id="autosubmit" ' - .($this->helper->isAutosubmitEnabled() ? 'checked' : '' ) - .'/> ' . $this->getLang('autosubmit') .'<br />' - .'</label>' - .'<input type="hidden" name="do" value="admin" />' - .'<input type="hidden" name="page" value="popularity" />'; + . '<input type="checkbox" name="autosubmit" id="autosubmit" ' + . ($this->helper->isAutosubmitEnabled() ? 'checked' : '' ) + . '/> ' . $this->getLang('autosubmit') . '<br />' + . '</label>' + . '<input type="hidden" name="do" value="admin" />' + . '<input type="hidden" name="page" value="popularity" />'; } - $form .= '<button type="submit">'.$this->getLang('submit').'</button>' - .'</fieldset>' - .'</form>'; + $form .= '<button type="submit">' . $this->getLang('submit') . '</button>' + . '</fieldset>' + . '</form>'; return $form; } } diff --git a/lib/plugins/popularity/helper.php b/lib/plugins/popularity/helper.php index 506126a35..b3393d24b 100644 --- a/lib/plugins/popularity/helper.php +++ b/lib/plugins/popularity/helper.php @@ -1,5 +1,6 @@ <?php +use dokuwiki\Extension\AuthPlugin; use dokuwiki\HTTP\DokuHTTPClient; use dokuwiki\Extension\Event; @@ -39,9 +40,9 @@ class helper_plugin_popularity extends Dokuwiki_Plugin public function __construct() { global $conf; - $this->autosubmitFile = $conf['cachedir'].'/autosubmit.txt'; - $this->autosubmitErrorFile = $conf['cachedir'].'/autosubmitError.txt'; - $this->popularityLastSubmitFile = $conf['cachedir'].'/lastSubmitTime.txt'; + $this->autosubmitFile = $conf['cachedir'] . '/autosubmit.txt'; + $this->autosubmitErrorFile = $conf['cachedir'] . '/autosubmitError.txt'; + $this->popularityLastSubmitFile = $conf['cachedir'] . '/lastSubmitTime.txt'; } /** @@ -64,7 +65,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin { $error = ''; $httpClient = new DokuHTTPClient(); - $status = $httpClient->sendRequest($this->submitUrl, array('data' => $data), 'POST'); + $status = $httpClient->sendRequest($this->submitUrl, ['data' => $data], 'POST'); if (! $status) { $error = $httpClient->error; } @@ -95,9 +96,9 @@ class helper_plugin_popularity extends Dokuwiki_Plugin $string = ''; foreach ($data as $key => $val) { if (is_array($val)) foreach ($val as $v) { - $string .= hsc($key)."\t".hsc($v)."\n"; + $string .= hsc($key) . "\t" . hsc($v) . "\n"; } else { - $string .= hsc($key)."\t".hsc($val)."\n"; + $string .= hsc($key) . "\t" . hsc($val) . "\n"; } } return $string; @@ -132,7 +133,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin global $conf; /** @var $auth DokuWiki_Auth_Plugin */ global $auth; - $data = array(); + $data = []; $phptime = ini_get('max_execution_time'); @set_time_limit(0); $pluginInfo = $this->getInfo(); @@ -152,7 +153,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin // number and size of pages $list = $this->initEmptySearchList(); - search($list, $conf['datadir'], array($this, 'searchCountCallback'), array('all'=>false), ''); + search($list, $conf['datadir'], [$this, 'searchCountCallback'], ['all' => false], ''); $data['page_count'] = $list['file_count']; $data['page_size'] = $list['file_size']; $data['page_biggest'] = $list['file_max']; @@ -165,7 +166,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin // number and size of media $list = $this->initEmptySearchList(); - search($list, $conf['mediadir'], array($this, 'searchCountCallback'), array('all'=>true)); + search($list, $conf['mediadir'], [$this, 'searchCountCallback'], ['all' => true]); $data['media_count'] = $list['file_count']; $data['media_size'] = $list['file_size']; $data['media_biggest'] = $list['file_max']; @@ -177,7 +178,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin // number and size of cache $list = $this->initEmptySearchList(); - search($list, $conf['cachedir'], array($this, 'searchCountCallback'), array('all'=>true)); + search($list, $conf['cachedir'], [$this, 'searchCountCallback'], ['all' => true]); $data['cache_count'] = $list['file_count']; $data['cache_size'] = $list['file_size']; $data['cache_biggest'] = $list['file_max']; @@ -187,7 +188,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin // number and size of index $list = $this->initEmptySearchList(); - search($list, $conf['indexdir'], array($this, 'searchCountCallback'), array('all'=>true)); + search($list, $conf['indexdir'], [$this, 'searchCountCallback'], ['all' => true]); $data['index_count'] = $list['file_count']; $data['index_size'] = $list['file_size']; $data['index_biggest'] = $list['file_max']; @@ -197,7 +198,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin // number and size of meta $list = $this->initEmptySearchList(); - search($list, $conf['metadir'], array($this, 'searchCountCallback'), array('all'=>true)); + search($list, $conf['metadir'], [$this, 'searchCountCallback'], ['all' => true]); $data['meta_count'] = $list['file_count']; $data['meta_size'] = $list['file_size']; $data['meta_biggest'] = $list['file_max']; @@ -207,7 +208,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin // number and size of attic $list = $this->initEmptySearchList(); - search($list, $conf['olddir'], array($this, 'searchCountCallback'), array('all'=>true)); + search($list, $conf['olddir'], [$this, 'searchCountCallback'], ['all' => true]); $data['attic_count'] = $list['file_count']; $data['attic_size'] = $list['file_size']; $data['attic_biggest'] = $list['file_max']; @@ -217,18 +218,18 @@ class helper_plugin_popularity extends Dokuwiki_Plugin unset($list); // user count - if ($auth && $auth->canDo('getUserCount')) { + if ($auth instanceof AuthPlugin && $auth->canDo('getUserCount')) { $data['user_count'] = $auth->getUserCount(); } // calculate edits per day - $list = (array) @file($conf['metadir'].'/_dokuwiki.changes'); + $list = (array) @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); - $dur = ($last - $first)/(60*60*24); // number of days in the changelog - $data['edits_per_day'] = $count/$dur; + $dur = ($last - $first) / (60 * 60 * 24); // number of days in the changelog + $data['edits_per_day'] = $count / $dur; } unset($list); @@ -244,7 +245,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin $data['os'] = PHP_OS; $data['webserver'] = $_SERVER['SERVER_SOFTWARE']; $data['php_version'] = phpversion(); - $data['php_sapi'] = php_sapi_name(); + $data['php_sapi'] = PHP_SAPI; $data['php_memory'] = php_to_byte(ini_get('memory_limit')); $data['php_exectime'] = $phptime; $data['php_extension'] = get_loaded_extensions(); @@ -262,7 +263,7 @@ class helper_plugin_popularity extends Dokuwiki_Plugin */ protected function addPluginUsageData(&$data) { - $pluginsData = array(); + $pluginsData = []; Event::createAndTrigger('PLUGIN_POPULARITY_DATA_SETUP', $pluginsData); foreach ($pluginsData as $plugin => $d) { if (is_array($d)) { @@ -297,8 +298,8 @@ class helper_plugin_popularity extends Dokuwiki_Plugin //only search txt files if 'all' option not set if ($opts['all'] || substr($file, -4) == '.txt') { - $size = filesize($base.'/'.$file); - $date = filemtime($base.'/'.$file); + $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; diff --git a/lib/plugins/remote.php b/lib/plugins/remote.php index 5bf8da91e..e75f700a0 100644 --- a/lib/plugins/remote.php +++ b/lib/plugins/remote.php @@ -1,4 +1,9 @@ <?php -\dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction( - 'Autoloading', 1, 'require(' . basename(__FILE__) . ')' + +use dokuwiki\Debug\DebugHelper; + +DebugHelper::dbgDeprecatedFunction( + 'Autoloading', + 1, + 'require(' . basename(__FILE__) . ')' ); diff --git a/lib/plugins/revert/admin.php b/lib/plugins/revert/admin.php index 2d11dc05a..4b9fe8584 100644 --- a/lib/plugins/revert/admin.php +++ b/lib/plugins/revert/admin.php @@ -1,12 +1,13 @@ <?php +use dokuwiki\Extension\AdminPlugin; use dokuwiki\ChangeLog\PageChangeLog; /** * All DokuWiki plugins to extend the admin function * need to inherit from this class */ -class admin_plugin_revert extends DokuWiki_Admin_Plugin +class admin_plugin_revert extends AdminPlugin { protected $cmd; // some vars which might need tuning later @@ -70,10 +71,10 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin { global $lang, $INPUT; echo '<form action="" method="post"><div class="no">'; - echo '<label>'.$this->getLang('filter').': </label>'; - echo '<input type="text" name="filter" class="edit" value="'.hsc($INPUT->str('filter')).'" /> '; - echo '<button type="submit">'.$lang['btn_search'].'</button> '; - echo '<span>'.$this->getLang('note1').'</span>'; + echo '<label>' . $this->getLang('filter') . ': </label>'; + echo '<input type="text" name="filter" class="edit" value="' . hsc($INPUT->str('filter')) . '" /> '; + echo '<button type="submit">' . $lang['btn_search'] . '</button> '; + echo '<span>' . $this->getLang('note1') . '</span>'; echo '</div></form><br /><br />'; } @@ -83,7 +84,7 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin protected function revertEdits($revert, $filter) { echo '<hr /><br />'; - echo '<p>'.$this->getLang('revstart').'</p>'; + echo '<p>' . $this->getLang('revstart') . '</p>'; echo '<ul>'; foreach ($revert as $id) { @@ -93,26 +94,26 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin $data = ''; $pagelog = new PageChangeLog($id); $old = $pagelog->getRevisions(0, $this->max_revs); - if (count($old)) { + if ($old !== []) { foreach ($old as $REV) { $data = rawWiki($id, $REV); - if (strpos($data, $filter) === false) break; + if (strpos($data, (string) $filter) === false) break; } } if ($data) { saveWikiText($id, $data, 'old revision restored', false); - printf('<li><div class="li">'.$this->getLang('reverted').'</div></li>', $id, $REV); + 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); + printf('<li><div class="li">' . $this->getLang('removed') . '</div></li>', $id); } @set_time_limit(10); flush(); } echo '</ul>'; - echo '<p>'.$this->getLang('revstop').'</p>'; + echo '<p>' . $this->getLang('revstop') . '</p>'; } /** @@ -124,7 +125,7 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin global $lang; echo '<hr /><br />'; echo '<form action="" method="post"><div class="no">'; - echo '<input type="hidden" name="filter" value="'.hsc($filter).'" />'; + echo '<input type="hidden" name="filter" value="' . hsc($filter) . '" />'; formSecurityToken(); $recents = getRecents(0, $this->max_lines); @@ -133,21 +134,21 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin $cnt = 0; foreach ($recents as $recent) { if ($filter) { - if (strpos(rawWiki($recent['id']), $filter) === false) continue; + if (strpos(rawWiki($recent['id']), (string) $filter) === false) continue; } $cnt++; $date = dformat($recent['date']); - echo ($recent['type']===DOKU_CHANGE_TYPE_MINOR_EDIT) ? '<li class="minor">' : '<li>'; + 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 ' <label for="revert__'.$cnt.'">'.$date.'</label> '; + 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").'">'; - $p = array(); - $p['src'] = DOKU_BASE.'lib/images/diff.png'; + echo '<a href="' . wl($recent['id'], "do=diff") . '">'; + $p = []; + $p['src'] = DOKU_BASE . 'lib/images/diff.png'; $p['width'] = 15; $p['height'] = 11; $p['title'] = $lang['diff']; @@ -156,9 +157,9 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin echo "<img $att />"; echo '</a> '; - echo '<a href="'.wl($recent['id'], "do=revisions").'">'; - $p = array(); - $p['src'] = DOKU_BASE.'lib/images/history.png'; + echo '<a href="' . wl($recent['id'], "do=revisions") . '">'; + $p = []; + $p['src'] = DOKU_BASE . 'lib/images/history.png'; $p['width'] = 12; $p['height'] = 14; $p['title'] = $lang['btn_revs']; @@ -167,11 +168,11 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin echo "<img $att />"; echo '</a> '; - echo html_wikilink(':'.$recent['id'], (useHeading('navigation'))?null:$recent['id']); - echo ' – '.htmlspecialchars($recent['sum']); + echo html_wikilink(':' . $recent['id'], (useHeading('navigation')) ? null : $recent['id']); + echo ' – ' . htmlspecialchars($recent['sum']); echo ' <span class="user">'; - echo $recent['user'].' '.$recent['ip']; + echo $recent['user'] . ' ' . $recent['ip']; echo '</span>'; echo '</div>'; @@ -183,7 +184,7 @@ class admin_plugin_revert extends DokuWiki_Admin_Plugin echo '</ul>'; echo '<p>'; - echo '<button type="submit">'.$this->getLang('revert').'</button> '; + echo '<button type="submit">' . $this->getLang('revert') . '</button> '; printf($this->getLang('note2'), hsc($filter)); echo '</p>'; diff --git a/lib/plugins/safefnrecode/action.php b/lib/plugins/safefnrecode/action.php index 952d95c90..b3e14fffe 100644 --- a/lib/plugins/safefnrecode/action.php +++ b/lib/plugins/safefnrecode/action.php @@ -1,16 +1,19 @@ <?php + +use dokuwiki\Extension\ActionPlugin; +use dokuwiki\Extension\EventHandler; +use dokuwiki\Extension\Event; + /** * DokuWiki Plugin safefnrecode (Action Component) * * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Andreas Gohr <andi@splitbrain.org> */ - -class action_plugin_safefnrecode extends DokuWiki_Action_Plugin +class action_plugin_safefnrecode extends ActionPlugin { - /** @inheritdoc */ - public function register(Doku_Event_Handler $controller) + public function register(EventHandler $controller) { $controller->register_hook('INDEXER_TASKS_RUN', 'BEFORE', $this, 'handleIndexerTasksRun'); } @@ -18,32 +21,32 @@ class action_plugin_safefnrecode extends DokuWiki_Action_Plugin /** * Handle indexer event * - * @param Doku_Event $event + * @param Event $event * @param $param */ - public function handleIndexerTasksRun(Doku_Event $event, $param) + public function handleIndexerTasksRun(Event $event, $param) { global $conf; 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'); + 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'); + 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'); + 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'); + touch($conf['mediadir'] . '_safefn.recoded'); } } diff --git a/lib/plugins/styling/action.php b/lib/plugins/styling/action.php index 46245ca75..39da86028 100644 --- a/lib/plugins/styling/action.php +++ b/lib/plugins/styling/action.php @@ -1,20 +1,24 @@ <?php + +use dokuwiki\Extension\ActionPlugin; +use dokuwiki\Extension\EventHandler; +use dokuwiki\Extension\Event; + /** * DokuWiki Plugin styling (Action Component) * * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Andreas Gohr <andi@splitbrain.org> */ -class action_plugin_styling extends DokuWiki_Action_Plugin +class action_plugin_styling extends ActionPlugin { - /** * Registers a callback functions * - * @param Doku_Event_Handler $controller DokuWiki's event controller object + * @param EventHandler $controller DokuWiki's event controller object * @return void */ - public function register(Doku_Event_Handler $controller) + public function register(EventHandler $controller) { $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleHeader'); } @@ -22,12 +26,12 @@ class action_plugin_styling extends DokuWiki_Action_Plugin /** * Adds the preview parameter to the stylesheet loading in non-js mode * - * @param Doku_Event $event event object by reference - * @param mixed $param [the parameters passed as fifth argument to register_hook() when this - * handler was registered] + * @param Event $event event object by reference + * @param mixed $param [the parameters passed as fifth argument to register_hook() when this + * handler was registered] * @return void */ - public function handleHeader(Doku_Event &$event, $param) + public function handleHeader(Event &$event, $param) { global $ACT; global $INPUT; @@ -39,10 +43,11 @@ class action_plugin_styling extends DokuWiki_Action_Plugin // set preview $len = count($event->data['link']); for ($i = 0; $i < $len; $i++) { - if ($event->data['link'][$i]['rel'] == 'stylesheet' && + 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(); + $event->data['link'][$i]['href'] .= '&preview=1&tseed=' . time(); } } } diff --git a/lib/plugins/styling/admin.php b/lib/plugins/styling/admin.php index 08c9afdc2..9fe4ebdba 100644 --- a/lib/plugins/styling/admin.php +++ b/lib/plugins/styling/admin.php @@ -1,13 +1,16 @@ <?php + +use dokuwiki\Extension\AdminPlugin; +use dokuwiki\StyleUtils; + /** * DokuWiki Plugin styling (Admin Component) * * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Andreas Gohr <andi@splitbrain.org> */ -class admin_plugin_styling extends DokuWiki_Admin_Plugin +class admin_plugin_styling extends AdminPlugin { - public $ispopup = false; /** @@ -34,8 +37,8 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin global $INPUT; $run = $INPUT->extract('run')->str('run'); if (!$run) return; - if(!checkSecurityToken()) return; - $run = 'run'.ucfirst($run); + if (!checkSecurityToken()) return; + $run = 'run' . ucfirst($run); $this->$run(); } @@ -47,8 +50,8 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin $class = 'nopopup'; if ($this->ispopup) $class = 'ispopup page'; - echo '<div id="plugin__styling" class="'.$class.'">'; - ptln('<h1>'.$this->getLang('menu').'</h1>'); + echo '<div id="plugin__styling" class="' . $class . '">'; + echo '<h1>' . $this->getLang('menu') . '</h1>'; $this->form(); echo '</div>'; } @@ -61,22 +64,22 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin global $conf; global $ID; - $styleUtil = new \dokuwiki\StyleUtils($conf['template'], true, true); - $styleini = $styleUtil->cssStyleini(); + $styleUtil = new StyleUtils($conf['template'], true, true); + $styleini = $styleUtil->cssStyleini(); $replacements = $styleini['replacements']; if ($this->ispopup) { - $target = DOKU_BASE.'lib/plugins/styling/popup.php'; + $target = DOKU_BASE . 'lib/plugins/styling/popup.php'; } else { - $target = wl($ID, array('do' => 'admin', 'page' => 'styling')); + $target = wl($ID, ['do' => 'admin', 'page' => 'styling']); } if (empty($replacements)) { - echo '<p class="error">'.$this->getLang('error').'</p>'; + echo '<p class="error">' . $this->getLang('error') . '</p>'; } else { echo $this->locale_xhtml('intro'); - echo '<form class="styling" method="post" action="'.$target.'">'; + echo '<form class="styling" method="post" action="' . $target . '">'; formSecurityToken(); echo '<table><tbody>'; @@ -86,27 +89,28 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin if (empty($name)) $name = $key; echo '<tr>'; - echo '<td><label for="tpl__'.hsc($key).'">'.$name.'</label></td>'; - echo '<td><input type="'.$this->colorType($value).'" name="tpl['.hsc($key).']" id="tpl__'.hsc($key).'" - value="'.hsc($this->colorValue($value)).'" dir="ltr" required="required"/></td>'; + echo '<td><label for="tpl__' . hsc($key) . '">' . $name . '</label></td>'; + echo '<td><input type="' . $this->colorType($value) . '" name="tpl[' . hsc($key) . ']" ' . + 'id="tpl__' . hsc($key) . '" value="' . hsc($this->colorValue($value)) . '" ' . + 'dir="ltr" required="required"/></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[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 '<button type="submit" name="run[reset]">' . $this->getLang('btn_reset') . '</button>'; echo '</p>'; echo '<p>'; - echo '<button type="submit" name="run[save]" class="primary">'.$this->getLang('btn_save').'</button>'; + echo '<button type="submit" name="run[save]" class="primary">' . $this->getLang('btn_save') . '</button>'; echo '</p>'; echo '<p>'; #FIXME only if local.ini exists: - echo '<button type="submit" name="run[revert]">'.$this->getLang('btn_revert').'</button>'; + echo '<button type="submit" name="run[revert]">' . $this->getLang('btn_revert') . '</button>'; echo '</p>'; echo '</form>'; @@ -150,7 +154,7 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin public function runPreview() { global $conf; - $ini = $conf['cachedir'].'/preview.ini'; + $ini = $conf['cachedir'] . '/preview.ini'; io_saveFile($ini, $this->makeini()); } @@ -160,7 +164,7 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin protected function runReset() { global $conf; - $ini = $conf['cachedir'].'/preview.ini'; + $ini = $conf['cachedir'] . '/preview.ini'; io_saveFile($ini, ''); } @@ -195,7 +199,7 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin $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) { - $ini .= $key.' = "'.addslashes($val).'"'."\n"; + $ini .= $key . ' = "' . addslashes($val) . '"' . "\n"; } return $ini; @@ -209,7 +213,7 @@ class admin_plugin_styling extends DokuWiki_Admin_Plugin protected function replaceIni($new) { global $conf; - $ini = DOKU_CONF."tpl/".$conf['template']."/style.ini"; + $ini = DOKU_CONF . "tpl/" . $conf['template'] . "/style.ini"; if (file_exists($ini)) { $old = io_readFile($ini); $old = preg_replace('/\[replacements\]\n.*?(\n\[.*]|$)/s', '\\1', $old); diff --git a/lib/plugins/styling/popup.php b/lib/plugins/styling/popup.php index 079062e43..0fef79ce3 100644 --- a/lib/plugins/styling/popup.php +++ b/lib/plugins/styling/popup.php @@ -1,6 +1,6 @@ <?php // phpcs:disable PSR1.Files.SideEffects -if (!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__) . '/../../../'); +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../../'); require_once(DOKU_INC . 'inc/init.php'); //close session session_write_close(); @@ -23,7 +23,7 @@ $plugin->handle(); <title><?php echo $plugin->getLang('menu') ?></title> <?php tpl_metaheaders(false) ?> <meta name="viewport" content="width=device-width,initial-scale=1" /> - <?php echo tpl_favicon(array('favicon')) ?> + <?php echo tpl_favicon(['favicon']) ?> </head> <body class="dokuwiki"> <?php $plugin->html() ?> diff --git a/lib/plugins/syntax.php b/lib/plugins/syntax.php index 5bf8da91e..e75f700a0 100644 --- a/lib/plugins/syntax.php +++ b/lib/plugins/syntax.php @@ -1,4 +1,9 @@ <?php -\dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction( - 'Autoloading', 1, 'require(' . basename(__FILE__) . ')' + +use dokuwiki\Debug\DebugHelper; + +DebugHelper::dbgDeprecatedFunction( + 'Autoloading', + 1, + 'require(' . basename(__FILE__) . ')' ); diff --git a/lib/plugins/testing/action.php b/lib/plugins/testing/action.php index 09b84262e..48945c337 100644 --- a/lib/plugins/testing/action.php +++ b/lib/plugins/testing/action.php @@ -1,5 +1,7 @@ <?php +use dokuwiki\Extension\ActionPlugin; +use dokuwiki\Extension\EventHandler; use dokuwiki\Extension\Event; /** @@ -9,16 +11,18 @@ use dokuwiki\Extension\Event; * * @author Tobias Sarnowski <tobias@trustedco.de> */ -class action_plugin_testing extends DokuWiki_Action_Plugin { - +class action_plugin_testing extends ActionPlugin +{ /** @inheritdoc */ - public function register(Doku_Event_Handler $controller) { + public function register(EventHandler $controller) + { $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'dokuwikiStarted'); } - public function dokuwikiStarted() { - $param = array(); + public function dokuwikiStarted() + { + $param = []; Event::createAndTrigger('TESTING_PLUGIN_INSTALLED', $param); - msg('The testing plugin is enabled and should be disabled.',-1); + msg('The testing plugin is enabled and should be disabled.', -1); } } diff --git a/lib/plugins/testing/conf/default.php b/lib/plugins/testing/conf/default.php index 28aef9b7e..8ce3ce83b 100644 --- a/lib/plugins/testing/conf/default.php +++ b/lib/plugins/testing/conf/default.php @@ -1,9 +1,10 @@ <?php + /** * Default options * * They don't do anything and are just there for testing config reading */ + $conf['schnibble'] = 0; $conf['second'] = 'Default value'; - diff --git a/lib/plugins/testing/conf/metadata.php b/lib/plugins/testing/conf/metadata.php index 3ea183cfa..09b6f143a 100644 --- a/lib/plugins/testing/conf/metadata.php +++ b/lib/plugins/testing/conf/metadata.php @@ -1,8 +1,10 @@ <?php + /** * Option Metadata * * They don't do anything and are just there for testing config reading */ + $meta['schnibble'] = array('onoff'); $meta['second'] = array('string'); diff --git a/lib/plugins/usermanager/admin.php b/lib/plugins/usermanager/admin.php index 423467133..2314a70a9 100644 --- a/lib/plugins/usermanager/admin.php +++ b/lib/plugins/usermanager/admin.php @@ -1,4 +1,9 @@ <?php + +use dokuwiki\Extension\AdminPlugin; +use dokuwiki\Extension\AuthPlugin; +use dokuwiki\Utf8\Clean; + /* * User Manager * @@ -15,20 +20,20 @@ * All DokuWiki plugins to extend the admin function * need to inherit from this class */ -class admin_plugin_usermanager extends DokuWiki_Admin_Plugin +class admin_plugin_usermanager extends AdminPlugin { - const IMAGE_DIR = DOKU_BASE.'lib/plugins/usermanager/images/'; + protected const IMAGE_DIR = DOKU_BASE . 'lib/plugins/usermanager/images/'; - protected $auth = null; // auth object + protected $auth; // auth object protected $users_total = 0; // number of registered users - protected $filter = array(); // user selection filter(s) + protected $filter = []; // 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 $edit_userdata = []; protected $disabled = ''; // if disabled set to explanatory string - protected $import_failures = array(); + protected $import_failures = []; protected $lastdisabled = false; // set to true if last user is unknown and last button is hence buggy /** @@ -36,18 +41,18 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin */ public function __construct() { - /** @var DokuWiki_Auth_Plugin $auth */ + /** @var AuthPlugin $auth */ global $auth; $this->setupLocale(); - if (!isset($auth)) { + if (!$auth instanceof AuthPlugin) { $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 @@ -66,9 +71,9 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { if (!is_null($this->auth)) - return parent::getMenuText($language); + return parent::getMenuText($language); - return $this->getLang('menu').' '.$this->disabled; + return $this->getLang('menu') . ' ' . $this->disabled; } /** @@ -117,7 +122,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin // extract the command and any specific parameters // submit button name is of the form - fn[cmd][param(s)] - $fn = $INPUT->param('fn'); + $fn = $INPUT->param('fn'); if (is_array($fn)) { $cmd = key($fn); @@ -147,7 +152,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin break; case "search": $this->setFilter($param); - $this->start = 0; + $this->start = 0; break; case "export": $this->exportCSV(); @@ -185,13 +190,14 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin * Output appropriate html * * @return bool + * @todo split into smaller functions, use Form class */ public function html() { global $ID; if (is_null($this->auth)) { - print $this->lang['badauth']; + echo $this->lang['badauth']; return false; } @@ -203,21 +209,19 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin $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'); + echo $this->locale_xhtml('intro'); + echo $this->locale_xhtml('list'); - ptln("<div id=\"user__manager\">"); - ptln("<div class=\"level2\">"); + echo '<div id="user__manager">'; + echo '<div class="level2">'; if ($this->users_total > 0) { - ptln( - "<p>" . sprintf( - $this->lang['summary'], - $this->start + 1, - $this->last, - $this->users_total, - $this->auth->getUserCount() - ) . "</p>" + printf( + '<p>' . $this->lang['summary'] . '</p>', + $this->start + 1, + $this->last, + $this->users_total, + $this->auth->getUserCount() ); } else { if ($this->users_total < 0) { @@ -225,126 +229,122 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin } else { $allUserTotal = $this->auth->getUserCount(); } - ptln("<p>".sprintf($this->lang['nonefound'], $allUserTotal)."</p>"); + printf('<p>%s</p>', sprintf($this->lang['nonefound'], $allUserTotal)); } - ptln("<form action=\"".wl($ID)."\" method=\"post\">"); + printf('<form action="%s" method="post">', wl($ID)); formSecurityToken(); - ptln(" <div class=\"table\">"); - 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(" </tr>"); - - ptln(" <tr>"); - 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>"); + echo '<div class="table">'; + echo '<table class="inline">'; + echo '<thead>'; + echo '<tr>'; + echo '<th> </th>'; + echo '<th>' . $this->lang["user_id"] . '</th>'; + echo '<th>' . $this->lang["user_name"] . '</th>'; + echo '<th>' . $this->lang["user_mail"] . '</th>'; + echo '<th>' . $this->lang["user_groups"] . '</th>'; + echo '</tr>'; + + echo '<tr>'; + echo '<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>'; + echo '<td><input type="text" name="userid" class="edit" value="' . $this->htmlFilter('user') . '" /></td>'; + echo '<td><input type="text" name="username" class="edit" value="' . $this->htmlFilter('name') . '" /></td>'; + echo '<td><input type="text" name="usermail" class="edit" value="' . $this->htmlFilter('mail') . '" /></td>'; + echo '<td><input type="text" name="usergroups" class="edit" value="' . $this->htmlFilter('grps') . '" /></td>'; + echo '</tr>'; + echo '</thead>'; if ($this->users_total) { - ptln(" <tbody>"); + echo '<tbody>'; foreach ($user_list as $user => $userinfo) { extract($userinfo); /** * @var string $name * @var string $pass * @var string $mail - * @var array $grps + * @var array $grps */ - $groups = join(', ', $grps); - ptln(" <tr class=\"user_info\">"); - ptln(" <td class=\"centeralign\"><input type=\"checkbox\" name=\"delete[".hsc($user). - "]\" ".$delete_disable." /></td>"); + $groups = implode(', ', $grps); + echo '<tr class="user_info">'; + echo '<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, - 'do' => 'admin', - 'page' => 'usermanager', - 'sectok' => getSecurityToken())). - "\" title=\"".$this->lang['edit_prompt']."\">".hsc($user)."</a></td>"); + echo '<td><a href="' . wl($ID, ['fn[edit][' . $user . ']' => 1, + 'do' => 'admin', + 'page' => 'usermanager', + 'sectok' => getSecurityToken()]) . + '" title="' . $this->lang['edit_prompt'] . '">' . hsc($user) . '</a></td>'; } else { - ptln(" <td>".hsc($user)."</td>"); + echo '<td>' . hsc($user) . '</td>'; } - ptln(" <td>".hsc($name)."</td><td>".hsc($mail)."</td><td>".hsc($groups)."</td>"); - ptln(" </tr>"); + echo '<td>' . hsc($name) . '</td><td>' . hsc($mail) . '</td><td>' . hsc($groups) . '</td>'; + echo '</tr>'; } - ptln(" </tbody>"); + echo '</tbody>'; } - 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(" </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(" </span>"); + echo '<tbody>'; + echo '<tr><td colspan="5" class="centeralign">'; + echo '<span class="medialeft">'; + echo '<button type="submit" name="fn[delete]" id="usrmgr__del" ' . $delete_disable . '>' . + $this->lang['delete_selected'] . '</button>'; + echo '</span>'; + echo '<span class="mediaright">'; + echo '<button type="submit" name="fn[start]" ' . $page_buttons['start'] . '>' . + $this->lang['start'] . '</button>'; + echo '<button type="submit" name="fn[prev]" ' . $page_buttons['prev'] . '>' . + $this->lang['prev'] . "</button>"; + echo '<button type="submit" name="fn[next]" ' . $page_buttons['next'] . '>' . + $this->lang['next'] . '</button>'; + echo '<button type="submit" name="fn[last]" ' . $page_buttons['last'] . '>' . + $this->lang['last'] . '</button>'; + echo '</span>'; if (!empty($this->filter)) { - ptln(" <button type=\"submit\" name=\"fn[search][clear]\">".$this->lang['clear']."</button>"); + echo '<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\" />"); + echo '<button type="submit" name="fn[export]">' . $export_label . '</button>'; + echo '<input type="hidden" name="do" value="admin" />'; + echo '<input type="hidden" name="page" value="usermanager" />'; $this->htmlFilterSettings(2); - ptln(" </td></tr>"); - ptln(" </tbody>"); - ptln(" </table>"); - ptln(" </div>"); + echo '</td></tr>'; + echo '</tbody>'; + echo '</table>'; + echo '</div>'; - ptln("</form>"); - ptln("</div>"); + echo '</form>'; + echo '</div>'; - $style = $this->edit_user ? " class=\"edit_user\"" : ""; + $style = $this->edit_user ? ' class="edit_user"' : ''; if ($this->auth->canDo('addUser')) { - ptln("<div".$style.">"); - print $this->locale_xhtml('add'); - ptln(" <div class=\"level2\">"); + echo '<div' . $style . '>'; + echo $this->locale_xhtml('add'); + echo '<div class="level2">'; - $this->htmlUserForm('add', null, array(), 4); + $this->htmlUserForm('add', null, [], 4); - ptln(" </div>"); - ptln("</div>"); + echo '</div>'; + echo '</div>'; } - if ($this->edit_user && $this->auth->canDo('UserMod')) { - ptln("<div".$style." id=\"scroll__here\">"); - print $this->locale_xhtml('edit'); - ptln(" <div class=\"level2\">"); + if ($this->edit_user && $this->auth->canDo('UserMod')) { + echo '<div' . $style . ' id="scroll__here">'; + echo $this->locale_xhtml('edit'); + echo '<div class="level2">'; $this->htmlUserForm('modify', $this->edit_user, $this->edit_userdata, 4); - ptln(" </div>"); - ptln("</div>"); + echo '</div>'; + echo '</div>'; } if ($this->auth->canDo('addUser')) { $this->htmlImportForm(); } - ptln("</div>"); + echo '</div>'; return true; } @@ -356,9 +356,9 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin */ public function isAccessibleByCurrentUser() { - /** @var DokuWiki_Auth_Plugin $auth */ + /** @var AuthPlugin $auth */ global $auth; - if(!$auth || !$auth->canDo('getUsers') ) { + if (!$auth instanceof AuthPlugin || !$auth->canDo('getUsers')) { return false; } @@ -371,33 +371,35 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin * * @param string $cmd 'add' or 'modify' * @param string $user id of user - * @param array $userdata array with name, mail, pass and grps - * @param int $indent + * @param array $userdata array with name, mail, pass and grps + * @param int $indent + * @todo use Form class */ - protected function htmlUserForm($cmd, $user = '', $userdata = array(), $indent = 0) + protected function htmlUserForm($cmd, $user = '', $userdata = [], $indent = 0) { global $conf; global $ID; global $lang; - - $name = $mail = $groups = ''; - $notes = array(); + $name = ''; + $mail = ''; + $groups = ''; + $notes = []; if ($user) { extract($userdata); - if (!empty($grps)) $groups = join(',', $grps); + if (!empty($grps)) $groups = implode(',', $grps); } else { $notes[] = sprintf($this->lang['note_group'], $conf['defaultgroup']); } - ptln("<form action=\"".wl($ID)."\" method=\"post\">", $indent); + printf('<form action="%s" method="post">', wl($ID)); 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); + echo '<div class="table">'; + echo '<table class="inline">'; + echo '<thead>'; + echo '<tr><th>' . $this->lang["field"] . "</th><th>" . $this->lang["value"] . "</th></tr>"; + echo '</thead>'; + echo '<tbody>'; $this->htmlInputField( $cmd . "_userid", @@ -462,40 +464,41 @@ 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); + echo '<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>'; } - 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); + echo '</tbody>'; + echo '<tbody>'; + echo '<tr>'; + echo '<td colspan="2">'; + echo '<input type="hidden" name="do" value="admin" />'; + echo '<input type="hidden" name="page" value="usermanager" />'; // 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); + if ($user) { + echo '<input type="hidden" name="userid_old" value="' . hsc($user) . "\" />"; + } - $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); + echo '<button type="submit" name="fn[' . $cmd . ']">' . $this->lang[$cmd] . '</button>'; + echo '</td>'; + echo '</tr>'; + echo '</tbody>'; + echo '</table>'; if ($notes) { - ptln(" <ul class=\"notes\">"); + echo '<ul class="notes">'; foreach ($notes as $note) { - ptln(" <li><span class=\"li\">".$note."</li>", $indent); + echo '<li><span class="li">' . $note . '</li>'; } - ptln(" </ul>"); + echo '</ul>'; } - ptln(" </div>", $indent); - ptln("</form>", $indent); + echo '</div>'; + echo '</form>'; } /** @@ -505,9 +508,10 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin * @param string $name * @param string $label * @param string $value - * @param bool $cando whether auth backend is capable to do this action - * @param bool $required is this field required? + * @param bool $cando whether auth backend is capable to do this action + * @param bool $required is this field required? * @param int $indent + * @todo obsolete when Form class is used */ protected function htmlInputField($id, $name, $label, $value, $cando, $required, $indent = 0) { @@ -516,19 +520,19 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin if ($name == 'userpass' || $name == 'userpass2') { $fieldtype = 'password'; - $autocomp = 'autocomplete="off"'; + $autocomp = 'autocomplete="off"'; } elseif ($name == 'usermail') { $fieldtype = 'email'; - $autocomp = ''; + $autocomp = ''; } else { $fieldtype = 'text'; - $autocomp = ''; + $autocomp = ''; } $value = hsc($value); echo "<tr $class>"; echo "<td><label for=\"$id\" >$label: </label></td>"; - echo "<td>"; + echo '<td>'; if ($cando) { $req = ''; if ($required) $req = 'required="required"'; @@ -539,8 +543,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin echo "<input type=\"$fieldtype\" id=\"$id\" name=\"$name\" value=\"$value\" class=\"edit disabled\" disabled=\"disabled\" />"; } - echo "</td>"; - echo "</tr>"; + echo '</td>'; + echo '</tr>'; } /** @@ -563,10 +567,10 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin protected function htmlFilterSettings($indent = 0) { - ptln("<input type=\"hidden\" name=\"start\" value=\"".$this->start."\" />", $indent); + echo '<input type="hidden" name="start" value="' . $this->start . '" />'; foreach ($this->filter as $key => $filter) { - ptln("<input type=\"hidden\" name=\"filter[".$key."]\" value=\"".hsc($filter)."\" />", $indent); + echo '<input type="hidden" name="filter[' . $key . ']" value="' . hsc($filter) . '" />'; } } @@ -579,52 +583,52 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { global $ID; - $failure_download_link = wl($ID, array('do'=>'admin','page'=>'usermanager','fn[importfails]'=>1)); + $failure_download_link = wl($ID, ['do' => 'admin', 'page' => 'usermanager', 'fn[importfails]' => 1]); - ptln('<div class="level2 import_users">', $indent); - print $this->locale_xhtml('import'); - ptln(' <form action="'.wl($ID).'" method="post" enctype="multipart/form-data">', $indent); + echo '<div class="level2 import_users">'; + echo $this->locale_xhtml('import'); + echo '<form action="' . wl($ID) . '" method="post" enctype="multipart/form-data">'; 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); + echo '<label>' . $this->lang['import_userlistcsv'] . '<input type="file" name="import" /></label>'; + echo '<button type="submit" name="fn[import]">' . $this->lang['import'] . '</button>'; + echo '<input type="hidden" name="do" value="admin" />'; + echo '<input type="hidden" name="page" value="usermanager" />'; - $this->htmlFilterSettings($indent+4); - ptln(' </form>', $indent); - ptln('</div>'); + $this->htmlFilterSettings($indent + 4); + echo '</form>'; + echo '</div>'; // list failures from the previous import 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); + echo '<div class="level3 import_failures">'; + echo '<h3>' . $this->lang['import_header'] . '</h3>'; + echo '<table class="import_failures">'; + echo '<thead>'; + echo '<tr>'; + echo '<th class="line">' . $this->lang['line'] . '</th>'; + echo '<th class="error">' . $this->lang['error'] . '</th>'; + echo '<th class="userid">' . $this->lang['user_id'] . '</th>'; + echo '<th class="username">' . $this->lang['user_name'] . '</th>'; + echo '<th class="usermail">' . $this->lang['user_mail'] . '</th>'; + echo '<th class="usergroups">' . $this->lang['user_groups'] . '</th>'; + echo '</tr>'; + echo '</thead>'; + echo '<tbody>'; 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); + echo '<tr>'; + echo '<td class="lineno"> ' . sprintf('%0' . $digits . 'd', $line) . ' </td>'; + echo '<td class="error">' . $failure['error'] . ' </td>'; + echo '<td class="field userid"> ' . hsc($failure['user'][0]) . ' </td>'; + echo '<td class="field username"> ' . hsc($failure['user'][2]) . ' </td>'; + echo '<td class="field usermail"> ' . hsc($failure['user'][3]) . ' </td>'; + echo '<td class="field usergroups"> ' . hsc($failure['user'][4]) . ' </td>'; + echo '</tr>'; } - ptln(' </tbody>', $indent); - ptln(' </table>', $indent); - ptln(' <p><a href="'.$failure_download_link.'">'.$this->lang['import_downloadfailures'].'</a></p>'); - ptln('</div>'); + echo '</tbody>'; + echo '</table>'; + echo '<p><a href="' . $failure_download_link . '">' . $this->lang['import_downloadfailures'] . '</a></p>'; + echo '</div>'; } } @@ -639,7 +643,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin if (!checkSecurityToken()) return false; if (!$this->auth->canDo('addUser')) return false; - list($user,$pass,$name,$mail,$grps,$passconfirm) = $this->retrieveUser(); + [$user, $pass, $name, $mail, $grps, $passconfirm] = $this->retrieveUser(); if (empty($user)) return false; if ($this->auth->canDo('modPass')) { @@ -651,19 +655,15 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin msg($this->lang['addUser_error_missing_pass'], -1); return false; } - } else { - 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)) { + } elseif (!$this->verifyPassword($pass, $passconfirm)) { msg($this->lang['add_fail'], -1); - msg($this->lang['addUser_error_modPass_disabled'], -1); + msg($this->lang['addUser_error_pass_not_identical'], -1); return false; } + } elseif (!empty($pass)) { + msg($this->lang['add_fail'], -1); + msg($this->lang['addUser_error_modPass_disabled'], -1); + return false; } if ($this->auth->canDo('modName')) { @@ -672,12 +672,10 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin msg($this->lang['addUser_error_name_missing'], -1); return false; } - } else { - if (!empty($name)) { - msg($this->lang['add_fail'], -1); - msg($this->lang['addUser_error_modName_disabled'], -1); - return false; - } + } elseif (!empty($name)) { + msg($this->lang['add_fail'], -1); + msg($this->lang['addUser_error_modName_disabled'], -1); + return false; } if ($this->auth->canDo('modMail')) { @@ -686,15 +684,13 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin msg($this->lang['addUser_error_mail_missing'], -1); return false; } - } else { - if (!empty($mail)) { - msg($this->lang['add_fail'], -1); - msg($this->lang['addUser_error_modMail_disabled'], -1); - return false; - } + } elseif (!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', [$user, $pass, $name, $mail, $grps])) { msg($this->lang['add_ok'], 1); if ($INPUT->has('usernotify') && $pass) { @@ -729,18 +725,18 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin return false; } - $count = $this->auth->triggerUserMod('delete', array($selected)); + $count = $this->auth->triggerUserMod('delete', [$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']); + $part2 = str_replace('%d', (count($selected) - $count), $this->lang['delete_fail']); msg("$part1, $part2", -1); } // invalidate all sessions - io_saveFile($conf['cachedir'].'/sessionpurge', time()); + io_saveFile($conf['cachedir'] . '/sessionpurge', time()); return true; } @@ -787,10 +783,10 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin $oldinfo = $this->auth->getUserData($olduser); // get new user data subject to change - list($newuser,$newpass,$newname,$newmail,$newgrps,$passconfirm) = $this->retrieveUser(); + [$newuser, $newpass, $newname, $newmail, $newgrps, $passconfirm] = $this->retrieveUser(); if (empty($newuser)) return false; - $changes = array(); + $changes = []; if ($newuser != $olduser) { if (!$this->auth->canDo('modLogin')) { // sanity check, shouldn't be possible msg($this->lang['update_fail'], -1); @@ -812,11 +808,9 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin } else { return false; } - } else { + } elseif ($INPUT->has('usernotify')) { // no new password supplied, check if we need to generate one (or it stays unchanged) - if ($INPUT->has('usernotify')) { - $changes['pass'] = auth_pwgen($olduser); - } + $changes['pass'] = auth_pwgen($olduser); } } @@ -830,7 +824,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin $changes['grps'] = $newgrps; } - if ($ok = $this->auth->triggerUserMod('modify', array($olduser, $changes))) { + if ($ok = $this->auth->triggerUserMod('modify', [$olduser, $changes])) { msg($this->lang['update_ok'], 1); if ($INPUT->has('usernotify') && !empty($changes['pass'])) { @@ -839,7 +833,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin } // invalidate all sessions - io_saveFile($conf['cachedir'].'/sessionpurge', time()); + io_saveFile($conf['cachedir'] . '/sessionpurge', time()); } else { msg($this->lang['update_fail'], -1); } @@ -854,9 +848,9 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin /** * Send password change notification email * - * @param string $user id of user - * @param string $password plain text - * @param bool $status_alert whether status alert should be shown + * @param string $user id of user + * @param string $password plain text + * @param bool $status_alert whether status alert should be shown * @return bool whether succesful */ protected function notifyUser($user, $password, $status_alert = true) @@ -866,10 +860,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin if ($status_alert) { msg($this->lang['notify_ok'], 1); } - } else { - if ($status_alert) { - msg($this->lang['notify_fail'], -1); - } + } elseif ($status_alert) { + msg($this->lang['notify_fail'], -1); } return $sent; @@ -879,8 +871,8 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin * Verify password meets minimum requirements * :TODO: extend to support password strength * - * @param string $password candidate string for new password - * @param string $confirm repeated password for confirmation + * @param string $password candidate string for new password + * @param string $confirm repeated password for confirmation * @return bool true if meets requirements, false otherwise */ protected function verifyPassword($password, $confirm) @@ -910,23 +902,27 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin */ protected function retrieveUser($clean = true) { - /** @var DokuWiki_Auth_Plugin $auth */ + /** @var AuthPlugin $auth */ global $auth; global $INPUT; - $user = array(); + $user = []; $user[0] = ($clean) ? $auth->cleanUser($INPUT->str('userid')) : $INPUT->str('userid'); $user[1] = $INPUT->str('userpass'); $user[2] = $INPUT->str('username'); $user[3] = $INPUT->str('usermail'); $user[4] = explode(',', $INPUT->str('usergroups')); - $user[5] = $INPUT->str('userpass2'); // repeated password for confirmation + $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]); + if ($clean) { + $user[4] = array_map([$auth, 'cleanGroup'], $user[4]); + } $user[4] = array_filter($user[4]); $user[4] = array_unique($user[4]); - if (!count($user[4])) $user[4] = null; + if ($user[4] === []) { + $user[4] = null; + } return $user; } @@ -939,15 +935,15 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin protected function setFilter($op) { - $this->filter = array(); + $this->filter = []; if ($op == 'new') { - list($user,/* $pass */,$name,$mail,$grps) = $this->retrieveUser(false); + [$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($grps)) $this->filter['grps'] = implode('|', $grps); } } @@ -963,7 +959,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin $t_filter = $INPUT->arr('filter'); // messy, but this way we ensure we aren't getting any additional crap from malicious users - $filter = array(); + $filter = []; if (isset($t_filter['user'])) $filter['user'] = $t_filter['user']; if (isset($t_filter['name'])) $filter['name'] = $t_filter['name']; @@ -997,7 +993,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin $disabled = 'disabled="disabled"'; - $buttons = array(); + $buttons = []; $buttons['start'] = $buttons['prev'] = ($this->start == 0) ? $disabled : ''; if ($this->users_total == -1) { @@ -1022,12 +1018,12 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin { // list of users for export - based on current filter criteria $user_list = $this->auth->retrieveUsers(0, 0, $this->filter); - $column_headings = array( + $column_headings = [ $this->lang["user_id"], $this->lang["user_name"], $this->lang["user_mail"], $this->lang["user_groups"] - ); + ]; // ============================================================================================== // GENERATE OUTPUT @@ -1041,7 +1037,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin $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 = [$user, $info['name'], $info['mail'], implode(',', $info['grps'])]; fputcsv($fd, $line); } fclose($fd); @@ -1066,21 +1062,22 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin if (!$this->auth->canDo('addUser')) return false; // check file uploaded ok. - if (empty($_FILES['import']['size']) || + 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 = []; $import_success_count = 0; $import_fail_count = 0; $line = 0; $fd = fopen($_FILES['import']['tmp_name'], 'r'); if ($fd) { while ($csv = fgets($fd)) { - if (!\dokuwiki\Utf8\Clean::isUtf8($csv)) { + if (!Clean::isUtf8($csv)) { $csv = utf8_encode($csv); } $raw = str_getcsv($csv); @@ -1092,7 +1089,7 @@ 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] = ['error' => $error, 'user' => $raw, 'orig' => $csv]; continue; } array_splice($raw, 1, 0, auth_pwgen()); // splice in a generated password @@ -1106,7 +1103,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin } 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] = ['error' => $error, 'user' => $raw, 'orig' => $csv]; } } msg( @@ -1140,7 +1137,7 @@ 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; @@ -1152,7 +1149,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin $INPUT->set('usergroups', $candidate[4]); $cleaned = $this->retrieveUser(); - list($user,/* $pass */,$name,$mail,/* $grps */) = $cleaned; + [$user, /* pass */, $name, $mail, /* grps */] = $cleaned; if (empty($user)) { $error = $this->lang['import_error_baduserid']; return false; @@ -1170,11 +1167,9 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin $error = $this->lang['import_error_badmail']; return false; } - } else { - if (!empty($mail)) { - $error = $this->lang['import_error_badmail']; - return false; - } + } elseif (!empty($mail)) { + $error = $this->lang['import_error_badmail']; + return false; } return $cleaned; @@ -1185,7 +1180,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin * * Required a check of canDo('addUser') before * - * @param array $user data of user + * @param array $user data of user * @param string &$error reference catched error message * @return bool whether successful */ @@ -1216,7 +1211,7 @@ class admin_plugin_usermanager extends DokuWiki_Admin_Plugin // output the csv $fd = fopen('php://output', 'w'); foreach ($this->import_failures as $fail) { - fputs($fd, $fail['orig']); + fwrite($fd, $fail['orig']); } fclose($fd); die; diff --git a/lib/plugins/usermanager/cli.php b/lib/plugins/usermanager/cli.php index 0efd9ec0d..91cf07561 100644 --- a/lib/plugins/usermanager/cli.php +++ b/lib/plugins/usermanager/cli.php @@ -1,5 +1,6 @@ <?php +use dokuwiki\Extension\CLIPlugin; use dokuwiki\Extension\AuthPlugin; use splitbrain\phpcli\Options; use splitbrain\phpcli\TableFormatter; @@ -12,7 +13,7 @@ use splitbrain\phpcli\TableFormatter; * @license GPL2 * @author Karsten Kosmala <karsten.kosmala@gmail.com> */ -class cli_plugin_usermanager extends DokuWiki_CLI_Plugin +class cli_plugin_usermanager extends CLIPlugin { public function __construct() { @@ -62,7 +63,7 @@ class cli_plugin_usermanager extends DokuWiki_CLI_Plugin /** @var AuthPlugin $auth */ global $auth; - if (!isset($auth)) { + if (!$auth instanceof AuthPlugin) { $this->error($this->getLang('noauth')); return 1; } @@ -127,9 +128,9 @@ class cli_plugin_usermanager extends DokuWiki_CLI_Plugin foreach ($list as $username => $user) { $content = [$username]; if ($details) { - array_push($content, $user['name']); - array_push($content, $user['mail']); - array_push($content, implode(", ", $user['grps'])); + $content[] = $user['name']; + $content[] = $user['mail']; + $content[] = implode(", ", $user['grps']); } echo $tr->format( [15, 25, 25, 15], @@ -155,7 +156,7 @@ class cli_plugin_usermanager extends DokuWiki_CLI_Plugin return 1; } - list($login, $mail, $name, $grps, $pass) = $args; + [$login, $mail, $name, $grps, $pass] = $args; $grps = array_filter(array_map('trim', explode(',', $grps))); if ($auth->canDo('modPass')) { @@ -168,15 +169,13 @@ class cli_plugin_usermanager extends DokuWiki_CLI_Plugin return 1; } } - } else { - if (!empty($pass)) { - $this->error($this->getLang('add_fail')); - $this->error($this->getLang('addUser_error_modPass_disabled')); - return 1; - } + } elseif (!empty($pass)) { + $this->error($this->getLang('add_fail')); + $this->error($this->getLang('addUser_error_modPass_disabled')); + return 1; } - if ($auth->triggerUserMod('create', array($login, $pass, $name, $mail, $grps))) { + if ($auth->triggerUserMod('create', [$login, $pass, $name, $mail, $grps])) { $this->success($this->getLang('add_ok')); } else { $this->printErrorMessages(); @@ -204,9 +203,9 @@ class cli_plugin_usermanager extends DokuWiki_CLI_Plugin } $users = explode(',', $args[0]); - $count = $auth->triggerUserMod('delete', array($users)); + $count = $auth->triggerUserMod('delete', [$users]); - if (!($count == count($users))) { + if ($count != count($users)) { $this->printErrorMessages(); $part1 = str_replace('%d', $count, $this->getLang('delete_ok')); $part2 = str_replace('%d', (count($users) - $count), $this->getLang('delete_fail')); @@ -228,22 +227,22 @@ class cli_plugin_usermanager extends DokuWiki_CLI_Plugin /** @var AuthPlugin $auth */ global $auth; - list($name, $newgrps) = $args; + [$name, $newgrps] = $args; $newgrps = array_filter(array_map('trim', explode(',', $newgrps))); $oldinfo = $auth->getUserData($name); - $changes = array(); + $changes = []; - if (!empty($newgrps) && $auth->canDo('modGroups')) { + if ($newgrps !== [] && $auth->canDo('modGroups')) { $changes['grps'] = $oldinfo['grps']; foreach ($newgrps as $group) { if (!in_array($group, $oldinfo['grps'])) { - array_push($changes['grps'], $group); + $changes['grps'][] = $group; } } } if (!empty(array_diff($changes['grps'], $oldinfo['grps']))) { - if ($auth->triggerUserMod('modify', array($name, $changes))) { + if ($auth->triggerUserMod('modify', [$name, $changes])) { $this->success($this->getLang('update_ok')); } else { $this->printErrorMessages(); @@ -266,12 +265,12 @@ class cli_plugin_usermanager extends DokuWiki_CLI_Plugin /** @var AuthPlugin $auth */ global $auth; - list($name, $grps) = $args; + [$name, $grps] = $args; $grps = array_filter(array_map('trim', explode(',', $grps))); $oldinfo = $auth->getUserData($name); - $changes = array(); + $changes = []; - if (!empty($grps) && $auth->canDo('modGroups')) { + if ($grps !== [] && $auth->canDo('modGroups')) { $changes['grps'] = $oldinfo['grps']; foreach ($grps as $group) { if (($pos = array_search($group, $changes['grps'])) == !false) { @@ -281,7 +280,7 @@ class cli_plugin_usermanager extends DokuWiki_CLI_Plugin } if (!empty(array_diff($oldinfo['grps'], $changes['grps']))) { - if ($auth->triggerUserMod('modify', array($name, $changes))) { + if ($auth->triggerUserMod('modify', [$name, $changes])) { $this->success($this->getLang('update_ok')); } else { $this->printErrorMessages(); diff --git a/lib/tpl/dokuwiki/detail.php b/lib/tpl/dokuwiki/detail.php index b5f0a6361..c47a7549e 100644 --- a/lib/tpl/dokuwiki/detail.php +++ b/lib/tpl/dokuwiki/detail.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki Image Detail Page * @@ -15,20 +16,20 @@ if (!defined('DOKU_INC')) die(); <head> <meta charset="utf-8" /> <title> - <?php echo hsc(tpl_img_getTag('IPTC.Headline',$IMG))?> + <?php echo hsc(tpl_img_getTag('IPTC.Headline', $IMG))?> [<?php echo strip_tags($conf['title'])?>] </title> <script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script> <?php tpl_metaheaders()?> <meta name="viewport" content="width=device-width,initial-scale=1" /> - <?php echo tpl_favicon(array('favicon', 'mobile')) ?> + <?php echo tpl_favicon(['favicon', 'mobile']) ?> <?php tpl_includeFile('meta.html') ?> </head> <body> <div id="dokuwiki__site"><div id="dokuwiki__top" class="site <?php echo tpl_classes(); ?>"> - <?php include('tpl_header.php') ?> + <?php include(__DIR__ . '/tpl_header.php') ?> <div class="wrapper group" id="dokuwiki__detail"> @@ -36,8 +37,8 @@ if (!defined('DOKU_INC')) die(); <main id="dokuwiki__content"><div class="pad group"> <?php html_msgarea() ?> - <?php if(!$ERROR): ?> - <div class="pageId"><span><?php echo hsc(tpl_img_getTag('IPTC.Headline',$IMG)); ?></span></div> + <?php if (!$ERROR) : ?> + <div class="pageId"><span><?php echo hsc(tpl_img_getTag('IPTC.Headline', $IMG)); ?></span></div> <?php endif; ?> <div class="page group"> @@ -45,26 +46,26 @@ if (!defined('DOKU_INC')) die(); <?php tpl_includeFile('pageheader.html') ?> <!-- detail start --> <?php - if($ERROR): - echo '<h1>'.$ERROR.'</h1>'; - else: ?> - <?php if($REV) echo p_locale_xhtml('showrev');?> + if ($ERROR) : + echo '<h1>' . $ERROR . '</h1>'; + else : ?> + <?php if ($REV) echo p_locale_xhtml('showrev');?> <h1><?php echo nl2br(hsc(tpl_img_getTag('simple.title'))); ?></h1> - <?php tpl_img(900,700); /* parameters: maximum width, maximum height (and more) */ ?> + <?php tpl_img(900, 700); /* parameters: maximum width, maximum height (and more) */ ?> <div class="img_detail"> <?php tpl_img_meta(); ?> <dl> <?php - echo '<dt>'.$lang['reference'].':</dt>'; - $media_usage = ft_mediause($IMG,true); - if(count($media_usage) > 0){ - foreach($media_usage as $path){ - echo '<dd>'.html_wikilink($path).'</dd>'; + echo '<dt>' . $lang['reference'] . ':</dt>'; + $media_usage = ft_mediause($IMG, true); + if ($media_usage !== []) { + foreach ($media_usage as $path) { + echo '<dd>' . html_wikilink($path) . '</dd>'; } - }else{ - echo '<dd>'.$lang['nothingfound'].'</dd>'; + } else { + echo '<dd>' . $lang['nothingfound'] . '</dd>'; } ?> </dl> @@ -86,7 +87,7 @@ if (!defined('DOKU_INC')) die(); <hr class="a11y" /> <!-- PAGE ACTIONS --> - <?php if (!$ERROR): ?> + <?php if (!$ERROR) : ?> <nav id="dokuwiki__pagetools" aria-labelledby="dokuwiki__pagetools__heading"> <h3 class="a11y" id="dokuwiki__pagetools__heading"><?php echo $lang['page_tools']; ?></h3> <div class="tools"> @@ -98,7 +99,7 @@ if (!defined('DOKU_INC')) die(); <?php endif; ?> </div><!-- /wrapper --> - <?php include('tpl_footer.php') ?> + <?php include(__DIR__ . '/tpl_footer.php') ?> </div></div><!-- /site --> </body> </html> diff --git a/lib/tpl/dokuwiki/images/pagetools-build.php b/lib/tpl/dokuwiki/images/pagetools-build.php index e19d750c7..42e5bc02c 100644 --- a/lib/tpl/dokuwiki/images/pagetools-build.php +++ b/lib/tpl/dokuwiki/images/pagetools-build.php @@ -17,7 +17,7 @@ $GAMMA = 0.8; $OPTIPNG = '/usr/bin/optipng'; -if('cli' != php_sapi_name()) die('please run from commandline'); +if('cli' != PHP_SAPI) die('please run from commandline'); // load input images $input = glob('pagetools/*.png'); @@ -86,11 +86,7 @@ function hex2rgb($hex) { } // calc rgb - return array( - 'r' => hexdec(substr($hex, 0, 2)), - 'g' => hexdec(substr($hex, 2, 2)), - 'b' => hexdec(substr($hex, 4, 2)) - ); + return ['r' => hexdec(substr($hex, 0, 2)), 'g' => hexdec(substr($hex, 2, 2)), 'b' => hexdec(substr($hex, 4, 2))]; } /** diff --git a/lib/tpl/dokuwiki/main.php b/lib/tpl/dokuwiki/main.php index 014a35c0e..d4b672bd2 100644 --- a/lib/tpl/dokuwiki/main.php +++ b/lib/tpl/dokuwiki/main.php @@ -1,4 +1,5 @@ <?php + /** * DokuWiki Default Template 2012 * @@ -11,7 +12,7 @@ if (!defined('DOKU_INC')) die(); /* must be run from within DokuWiki */ $hasSidebar = page_findnearest($conf['sidebar']); -$showSidebar = $hasSidebar && ($ACT=='show'); +$showSidebar = $hasSidebar && ($ACT == 'show'); ?><!DOCTYPE html> <html lang="<?php echo $conf['lang'] ?>" dir="<?php echo $lang['direction'] ?>" class="no-js"> <head> @@ -20,7 +21,7 @@ $showSidebar = $hasSidebar && ($ACT=='show'); <script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script> <?php tpl_metaheaders() ?> <meta name="viewport" content="width=device-width,initial-scale=1" /> - <?php echo tpl_favicon(array('favicon', 'mobile')) ?> + <?php echo tpl_favicon(['favicon', 'mobile']) ?> <?php tpl_includeFile('meta.html') ?> </head> @@ -28,14 +29,14 @@ $showSidebar = $hasSidebar && ($ACT=='show'); <div id="dokuwiki__site"><div id="dokuwiki__top" class="site <?php echo tpl_classes(); ?> <?php echo ($showSidebar) ? 'showSidebar' : ''; ?> <?php echo ($hasSidebar) ? 'hasSidebar' : ''; ?>"> - <?php include('tpl_header.php') ?> + <?php include(__DIR__ . '/tpl_header.php') ?> <div class="wrapper group"> - <?php if($showSidebar): ?> + <?php if ($showSidebar) : ?> <!-- ********** ASIDE ********** --> <nav id="dokuwiki__aside" aria-label="<?php echo $lang['sidebar'] - ?>"><div class="pad aside include group"> + ?>"><div class="pad aside include group"> <h3 class="toggle"><?php echo $lang['sidebar'] ?></h3> <div class="content"><div class="group"> <?php tpl_flush() ?> @@ -79,7 +80,7 @@ $showSidebar = $hasSidebar && ($ACT=='show'); </nav> </div><!-- /wrapper --> - <?php include('tpl_footer.php') ?> + <?php include(__DIR__ . '/tpl_footer.php') ?> </div></div><!-- /site --> <div class="no"><?php tpl_indexerWebBug() /* provide DokuWiki housekeeping, required in all templates */ ?></div> diff --git a/lib/tpl/dokuwiki/mediamanager.php b/lib/tpl/dokuwiki/mediamanager.php index c859ab627..106a439a4 100644 --- a/lib/tpl/dokuwiki/mediamanager.php +++ b/lib/tpl/dokuwiki/mediamanager.php @@ -1,10 +1,12 @@ <?php + /** * DokuWiki Media Manager Popup * * @author Andreas Gohr <andi@splitbrain.org> * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) */ + // must be run from within DokuWiki if (!defined('DOKU_INC')) die(); @@ -19,7 +21,7 @@ if (!defined('DOKU_INC')) die(); <script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script> <?php tpl_metaheaders()?> <meta name="viewport" content="width=device-width,initial-scale=1" /> - <?php echo tpl_favicon(array('favicon', 'mobile')) ?> + <?php echo tpl_favicon(['favicon', 'mobile']) ?> <?php tpl_includeFile('meta.html') ?> </head> diff --git a/lib/tpl/dokuwiki/tpl_footer.php b/lib/tpl/dokuwiki/tpl_footer.php index 0750c7b58..b892ba848 100644 --- a/lib/tpl/dokuwiki/tpl_footer.php +++ b/lib/tpl/dokuwiki/tpl_footer.php @@ -1,4 +1,5 @@ <?php + /** * Template footer, included in the main and detail files */ @@ -14,7 +15,7 @@ if (!defined('DOKU_INC')) die(); <div class="buttons"> <?php tpl_license('button', true, false, false); // license button, no wrapper - $target = ($conf['target']['extern']) ? 'target="'.$conf['target']['extern'].'"' : ''; + $target = ($conf['target']['extern']) ? 'target="' . $conf['target']['extern'] . '"' : ''; ?> <a href="https://www.dokuwiki.org/donate" title="Donate" <?php echo $target?>><img src="<?php echo tpl_basedir(); ?>images/button-donate.gif" width="80" height="15" alt="Donate" /></a> diff --git a/lib/tpl/dokuwiki/tpl_header.php b/lib/tpl/dokuwiki/tpl_header.php index 75447bb62..9eb608892 100644 --- a/lib/tpl/dokuwiki/tpl_header.php +++ b/lib/tpl/dokuwiki/tpl_header.php @@ -1,4 +1,5 @@ <?php + /** * Template header, included in the main and detail files */ @@ -33,24 +34,24 @@ if (!defined('DOKU_INC')) die(); '<span>' . $conf['title'] . '</span>', 'accesskey="h" title="' . tpl_getLang('home') . ' [h]"' ); - ?></h1> - <?php if ($conf['tagline']): ?> + ?></h1> + <?php if ($conf['tagline']) : ?> <p class="claim"><?php echo $conf['tagline']; ?></p> <?php endif ?> </div> <div class="tools group"> <!-- USER TOOLS --> - <?php if ($conf['useacl']): ?> + <?php if ($conf['useacl']) : ?> <div id="dokuwiki__usertools"> <h3 class="a11y"><?php echo $lang['user_tools']; ?></h3> <ul> <?php - if (!empty($_SERVER['REMOTE_USER'])) { - echo '<li class="user">'; - tpl_userinfo(); /* 'Logged in as ...' */ - echo '</li>'; - } + if (!empty($_SERVER['REMOTE_USER'])) { + echo '<li class="user">'; + tpl_userinfo(); /* 'Logged in as ...' */ + echo '</li>'; + } echo (new \dokuwiki\Menu\UserMenu())->getListItems('action '); ?> </ul> @@ -72,12 +73,12 @@ if (!defined('DOKU_INC')) die(); </div> <!-- BREADCRUMBS --> - <?php if($conf['breadcrumbs'] || $conf['youarehere']): ?> + <?php if ($conf['breadcrumbs'] || $conf['youarehere']) : ?> <div class="breadcrumbs"> - <?php if($conf['youarehere']): ?> + <?php if ($conf['youarehere']) : ?> <div class="youarehere"><?php tpl_youarehere() ?></div> <?php endif ?> - <?php if($conf['breadcrumbs']): ?> + <?php if ($conf['breadcrumbs']) : ?> <div class="trace"><?php tpl_breadcrumbs() ?></div> <?php endif ?> </div> diff --git a/lib/tpl/index.php b/lib/tpl/index.php index 4d48d5127..22a8a8575 100644 --- a/lib/tpl/index.php +++ b/lib/tpl/index.php @@ -1,4 +1,5 @@ <?php + /** * This file reads the style.ini of the used template and displays the * replacements defined in it. Color replacements will be displayed @@ -8,10 +9,11 @@ * @author Andreas Gohr <andi@splitbrain.org> * @author Anika Henke <anika@selfthinker.org> */ + // phpcs:disable PSR1.Files.SideEffects -if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); -if(!defined('NOSESSION')) define('NOSESSION',1); -require_once(DOKU_INC.'inc/init.php'); +if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../'); +if (!defined('NOSESSION')) define('NOSESSION', 1); +require_once(DOKU_INC . 'inc/init.php'); ?> <!DOCTYPE html> <html lang="en" dir="ltr"> @@ -50,21 +52,21 @@ $ini = $styleUtils->cssStyleini(); if (!empty($ini)) { echo '<table>'; - echo "<caption>".hsc($conf['template'])."'s style.ini</caption>"; - foreach($ini['replacements'] as $key => $val){ + echo "<caption>" . hsc($conf['template']) . "'s style.ini</caption>"; + foreach ($ini['replacements'] as $key => $val) { echo '<tr>'; - echo '<td>'.hsc($key).'</td>'; - echo '<td>'.hsc($val).'</td>'; + echo '<td>' . hsc($key) . '</td>'; + echo '<td>' . hsc($val) . '</td>'; echo '<td>'; - if(preg_match('/^#[0-f]{3,6}$/i',$val)){ - echo '<div class="color" style="background-color:'.$val.';"> </div>'; + if (preg_match('/^#[0-f]{3,6}$/i', $val)) { + echo '<div class="color" style="background-color:' . $val . ';"> </div>'; } echo '</td>'; echo '</tr>'; } echo '</table>'; } else { - echo "<p>Non-existent or invalid template or style.ini: <strong>".hsc($conf['template'])."</strong></p>"; + echo "<p>Non-existent or invalid template or style.ini: <strong>" . hsc($conf['template']) . "</strong></p>"; } ?> </body> |