coding style: control flow whitespaces

This commit is contained in:
Andreas Gohr 2023-08-31 14:22:35 +02:00
parent 83bec4752c
commit 177d6836e2
112 changed files with 1541 additions and 1617 deletions

View File

@ -11,12 +11,6 @@
<exclude name="Generic.WhiteSpace.IncrementDecrementSpacing.SpaceAfterDecrement"/>
<exclude name="Generic.WhiteSpace.IncrementDecrementSpacing.SpaceAfterIncrement"/>
<exclude name="Squiz.ControlStructures.ControlSignature.SpaceAfterCloseParenthesis"/>
<exclude name="Squiz.ControlStructures.ControlSignature.SpaceAfterKeyword"/>
<exclude name="Squiz.ControlStructures.ControlSignature.SpaceAfterCloseBrace"/>
<exclude name="Squiz.ControlStructures.ControlSignature.NewlineAfterOpenBrace"/>
<exclude name="Squiz.WhiteSpace.ControlStructureSpacing.SpacingAfterOpen"/>
<exclude name="Squiz.WhiteSpace.ControlStructureSpacing.SpacingBeforeClose"/>
<exclude name="Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore"/>
<exclude name="Squiz.WhiteSpace.ScopeClosingBrace.Indent"/>
<exclude name="Squiz.WhiteSpace.SuperfluousWhitespace.EndLine"/>

View File

@ -5,7 +5,7 @@ use splitbrain\phpcli\CLI;
use splitbrain\phpcli\Options;
use dokuwiki\Utf8\PhpString;
if(!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
define('NOSESSION', 1);
require_once(DOKU_INC . 'inc/init.php');
@ -159,7 +159,7 @@ class PageCLI extends CLI
$command = $options->getCmd();
$args = $options->getArgs();
switch($command) {
switch ($command) {
case 'checkout':
$wiki_id = array_shift($args);
$localfile = array_shift($args);
@ -210,25 +210,25 @@ class PageCLI extends CLI
$wiki_id = cleanID($wiki_id);
$wiki_fn = wikiFN($wiki_id);
if(!file_exists($wiki_fn)) {
if (!file_exists($wiki_fn)) {
$this->fatal("$wiki_id does not yet exist");
}
if(empty($localfile)) {
if (empty($localfile)) {
$localfile = getcwd() . '/' . PhpString::basename($wiki_fn);
}
if(!file_exists(dirname($localfile))) {
if (!file_exists(dirname($localfile))) {
$this->fatal("Directory " . dirname($localfile) . " does not exist");
}
if(stristr(realpath(dirname($localfile)), (string) realpath($conf['datadir'])) !== false) {
if (stristr(realpath(dirname($localfile)), (string) realpath($conf['datadir'])) !== false) {
$this->fatal("Attempt to check out file into data directory - not allowed");
}
$this->obtainLock($wiki_id);
if(!copy($wiki_fn, $localfile)) {
if (!copy($wiki_fn, $localfile)) {
$this->clearLock($wiki_id);
$this->fatal("Unable to copy $wiki_fn to $localfile");
}
@ -249,15 +249,15 @@ class PageCLI extends CLI
$wiki_id = cleanID($wiki_id);
$message = trim($message);
if(!file_exists($localfile)) {
if (!file_exists($localfile)) {
$this->fatal("$localfile does not exist");
}
if(!is_readable($localfile)) {
if (!is_readable($localfile)) {
$this->fatal("Cannot read from $localfile");
}
if(!$message) {
if (!$message) {
$this->fatal("Summary message required");
}
@ -277,18 +277,18 @@ class PageCLI extends CLI
*/
protected function obtainLock($wiki_id)
{
if($this->force) $this->deleteLock($wiki_id);
if ($this->force) $this->deleteLock($wiki_id);
$_SERVER['REMOTE_USER'] = $this->username;
if(checklock($wiki_id)) {
if (checklock($wiki_id)) {
$this->error("Page $wiki_id is already locked by another user");
exit(1);
}
lock($wiki_id);
if(checklock($wiki_id)) {
if (checklock($wiki_id)) {
$this->error("Unable to obtain lock for $wiki_id ");
var_dump(checklock($wiki_id));
exit(1);
@ -302,17 +302,17 @@ class PageCLI extends CLI
*/
protected function clearLock($wiki_id)
{
if($this->force) $this->deleteLock($wiki_id);
if ($this->force) $this->deleteLock($wiki_id);
$_SERVER['REMOTE_USER'] = $this->username;
if(checklock($wiki_id)) {
if (checklock($wiki_id)) {
$this->error("Page $wiki_id is locked by another user");
exit(1);
}
unlock($wiki_id);
if(file_exists(wikiLockFN($wiki_id))) {
if (file_exists(wikiLockFN($wiki_id))) {
$this->error("Unable to clear lock for $wiki_id");
exit(1);
}
@ -327,8 +327,8 @@ class PageCLI extends CLI
{
$wikiLockFN = wikiLockFN($wiki_id);
if(file_exists($wikiLockFN)) {
if(!unlink($wikiLockFN)) {
if (file_exists($wikiLockFN)) {
if (!unlink($wikiLockFN)) {
$this->error("Unable to delete $wikiLockFN");
exit(1);
}
@ -343,12 +343,12 @@ class PageCLI extends CLI
protected function getUser()
{
$user = getenv('USER');
if(empty($user)) {
if (empty($user)) {
$user = getenv('USERNAME');
} else {
return $user;
}
if(empty($user)) {
if (empty($user)) {
$user = 'admin';
}
return $user;

View File

@ -4,7 +4,7 @@
use splitbrain\phpcli\CLI;
use splitbrain\phpcli\Options;
if(!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
define('NOSESSION', 1);
require_once(DOKU_INC . 'inc/init.php');
@ -85,9 +85,9 @@ class GitToolCLI extends CLI
{
$command = $options->getCmd();
$args = $options->getArgs();
if(!$command) $command = array_shift($args);
if (!$command) $command = array_shift($args);
switch($command) {
switch ($command) {
case '':
echo $options->help();
break;
@ -116,7 +116,7 @@ class GitToolCLI extends CLI
$errors = [];
$succeeded = [];
foreach($extensions as $ext) {
foreach ($extensions as $ext) {
$repo = $this->getSourceRepo($ext);
if (!$repo) {
@ -130,8 +130,8 @@ class GitToolCLI extends CLI
}
echo "\n";
if($succeeded) $this->success('successfully cloned the following extensions: ' . implode(', ', $succeeded));
if($errors) $this->error('failed to clone the following extensions: ' . implode(', ', $errors));
if ($succeeded) $this->success('successfully cloned the following extensions: ' . implode(', ', $succeeded));
if ($errors) $this->error('failed to clone the following extensions: ' . implode(', ', $errors));
}
/**
@ -144,12 +144,12 @@ class GitToolCLI extends CLI
$errors = [];
$succeeded = [];
foreach($extensions as $ext) {
foreach ($extensions as $ext) {
$repo = $this->getSourceRepo($ext);
if (!$repo) {
$this->info("could not find a repository for $ext");
if($this->downloadExtension($ext)) {
if ($this->downloadExtension($ext)) {
$succeeded[] = $ext;
} else {
$errors[] = $ext;
@ -162,8 +162,8 @@ class GitToolCLI extends CLI
}
echo "\n";
if($succeeded) $this->success('successfully installed the following extensions: ' . implode(', ', $succeeded));
if($errors) $this->error('failed to install the following extensions: ' . implode(', ', $errors));
if ($succeeded) $this->success('successfully installed the following extensions: ' . implode(', ', $succeeded));
if ($errors) $this->error('failed to install the following extensions: ' . implode(', ', $errors));
}
/**
@ -180,8 +180,8 @@ class GitToolCLI extends CLI
$shell = array_map('escapeshellarg', $shell);
$shell = implode(' ', $shell);
foreach($repos as $repo) {
if(!@chdir($repo)) {
foreach ($repos as $repo) {
if (!@chdir($repo)) {
$this->error("Could not change into $repo");
continue;
}
@ -190,7 +190,7 @@ class GitToolCLI extends CLI
$ret = 0;
system($shell, $ret);
if($ret == 0) {
if ($ret == 0) {
$this->success("git succeeded in $repo");
} else {
$this->error("git failed in $repo");
@ -204,7 +204,7 @@ class GitToolCLI extends CLI
public function cmdRepos()
{
$repos = $this->findRepos();
foreach($repos as $repo) {
foreach ($repos as $repo) {
echo "$repo\n";
}
}
@ -219,12 +219,12 @@ class GitToolCLI extends CLI
{
/** @var helper_plugin_extension_extension $plugin */
$plugin = plugin_load('helper', 'extension_extension');
if(!$ext) die("extension plugin not available, can't continue");
if (!$ext) die("extension plugin not available, can't continue");
$plugin->setExtension($ext);
$url = $plugin->getDownloadURL();
if(!$url) {
if (!$url) {
$this->error("no download URL for $ext");
return false;
}
@ -233,11 +233,11 @@ class GitToolCLI extends CLI
try {
$this->info("installing $ext via download from $url");
$ok = $plugin->installFromURL($url);
} catch(Exception $e) {
} catch (Exception $e) {
$this->error($e->getMessage());
}
if($ok) {
if ($ok) {
$this->success("installed $ext via download");
return true;
} else {
@ -255,7 +255,7 @@ class GitToolCLI extends CLI
*/
private function cloneExtension($ext, $repo)
{
if(substr($ext, 0, 9) == 'template:') {
if (substr($ext, 0, 9) == 'template:') {
$target = fullpath(tpl_incdir() . '../' . substr($ext, 9));
} else {
$target = DOKU_PLUGIN . $ext;
@ -264,7 +264,7 @@ class GitToolCLI extends CLI
$this->info("cloning $ext from $repo to $target");
$ret = 0;
system("git clone $repo $target", $ret);
if($ret === 0) {
if ($ret === 0) {
$this->success("cloning of $ext succeeded");
return true;
} else {
@ -289,7 +289,7 @@ class GitToolCLI extends CLI
glob(fullpath(tpl_incdir() . '../') . '/*/.git', GLOB_ONLYDIR)
);
if(!$data) {
if (!$data) {
$this->error('Found no .git directories');
} else {
$this->success('Found ' . count($data) . ' .git directories');
@ -308,31 +308,31 @@ class GitToolCLI extends CLI
{
/** @var helper_plugin_extension_extension $ext */
$ext = plugin_load('helper', 'extension_extension');
if(!$ext) die("extension plugin not available, can't continue");
if (!$ext) die("extension plugin not available, can't continue");
$ext->setExtension($extension);
$repourl = $ext->getSourcerepoURL();
if(!$repourl) return false;
if (!$repourl) return false;
// match github repos
if(preg_match('/github\.com\/([^\/]+)\/([^\/]+)/i', $repourl, $m)) {
if (preg_match('/github\.com\/([^\/]+)\/([^\/]+)/i', $repourl, $m)) {
$user = $m[1];
$repo = $m[2];
return 'https://github.com/' . $user . '/' . $repo . '.git';
}
// match gitorious repos
if(preg_match('/gitorious.org\/([^\/]+)\/([^\/]+)?/i', $repourl, $m)) {
if (preg_match('/gitorious.org\/([^\/]+)\/([^\/]+)?/i', $repourl, $m)) {
$user = $m[1];
$repo = $m[2];
if(!$repo) $repo = $user;
if (!$repo) $repo = $user;
return 'https://git.gitorious.org/' . $user . '/' . $repo . '.git';
}
// match bitbucket repos - most people seem to use mercurial there though
if(preg_match('/bitbucket\.org\/([^\/]+)\/([^\/]+)/i', $repourl, $m)) {
if (preg_match('/bitbucket\.org\/([^\/]+)\/([^\/]+)/i', $repourl, $m)) {
$user = $m[1];
$repo = $m[2];
return 'https://bitbucket.org/' . $user . '/' . $repo . '.git';

View File

@ -4,7 +4,7 @@
use splitbrain\phpcli\CLI;
use splitbrain\phpcli\Options;
if(!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
define('NOSESSION', 1);
require_once(DOKU_INC . 'inc/init.php');
@ -55,7 +55,7 @@ class IndexerCLI extends CLI
$this->clear = $options->getOpt('clear');
$this->quiet = $options->getOpt('quiet');
if($this->clear) $this->clearindex();
if ($this->clear) $this->clearindex();
$this->update();
}
@ -71,7 +71,7 @@ class IndexerCLI extends CLI
search($data, $conf['datadir'], 'search_allpages', ['skipacl' => true]);
$this->quietecho(count($data) . " pages found.\n");
foreach($data as $val) {
foreach ($data as $val) {
$this->index($val['id']);
}
}
@ -105,7 +105,7 @@ class IndexerCLI extends CLI
*/
protected function quietecho($msg)
{
if(!$this->quiet) echo $msg;
if (!$this->quiet) echo $msg;
}
}

View File

@ -8,7 +8,7 @@ use splitbrain\phpcli\Options;
use dokuwiki\Extension\CLIPlugin;
use splitbrain\phpcli\TableFormatter;
if(!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
define('NOSESSION', 1);
require_once(DOKU_INC . 'inc/init.php');
@ -40,9 +40,9 @@ class PluginCLI extends CLI
global $argv;
$argv = $options->getArgs();
if($argv) {
if ($argv) {
$plugin = $this->loadPlugin($argv[0]);
if($plugin instanceof CLIPlugin) {
if ($plugin instanceof CLIPlugin) {
$plugin->run();
} else {
$this->fatal('Command {cmd} not found.', ['cmd' => $argv[0]]);
@ -68,14 +68,14 @@ class PluginCLI extends CLI
$list = $plugin_controller->getList('cli');
sort($list);
if($list === []) {
if ($list === []) {
echo $this->colors->wrap(" No plugins providing CLI components available\n", Colors::C_RED);
} else {
$tf = new TableFormatter($this->colors);
foreach($list as $name) {
foreach ($list as $name) {
$plugin = $this->loadPlugin($name);
if(!$plugin instanceof CLIPlugin) continue;
if (!$plugin instanceof CLIPlugin) continue;
$info = $plugin->getInfo();
echo $tf->format(
@ -95,11 +95,11 @@ class PluginCLI extends CLI
*/
protected function loadPlugin($name)
{
if(plugin_isdisabled($name)) return null;
if (plugin_isdisabled($name)) return null;
// execute the plugin CLI
$class = "cli_plugin_$name";
if(class_exists($class)) {
if (class_exists($class)) {
return new $class();
}
return null;

View File

@ -4,7 +4,7 @@
use splitbrain\phpcli\CLI;
use splitbrain\phpcli\Options;
if(!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
define('NOSESSION', 1);
require_once(DOKU_INC . 'inc/init.php');
@ -57,7 +57,7 @@ class RenderCLI extends CLI
$source = stream_get_contents(STDIN);
$info = [];
$result = p_render($renderer, p_get_instructions($source), $info);
if(is_null($result)) throw new DokuCLI_Exception("No such renderer $renderer");
if (is_null($result)) throw new DokuCLI_Exception("No such renderer $renderer");
echo $result;
}
}

View File

@ -4,7 +4,7 @@
use splitbrain\phpcli\CLI;
use splitbrain\phpcli\Options;
if(!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
define('NOSESSION', 1);
require_once(DOKU_INC . 'inc/init.php');
@ -51,10 +51,10 @@ class StripLangsCLI extends CLI
*/
protected function main(Options $options)
{
if($options->getOpt('keep')) {
if ($options->getOpt('keep')) {
$keep = explode(',', $options->getOpt('keep'));
if(!in_array('en', $keep)) $keep[] = 'en';
} elseif($options->getOpt('english-only')) {
if (!in_array('en', $keep)) $keep[] = 'en';
} elseif ($options->getOpt('english-only')) {
$keep = ['en'];
} else {
echo $options->help();
@ -75,16 +75,15 @@ class StripLangsCLI extends CLI
*/
protected function processExtensions($path, $keep_langs)
{
if(is_dir($path)) {
if (is_dir($path)) {
$entries = scandir($path);
foreach($entries as $entry) {
if($entry != "." && $entry != "..") {
if(is_dir($path . '/' . $entry)) {
foreach ($entries as $entry) {
if ($entry != "." && $entry != "..") {
if (is_dir($path . '/' . $entry)) {
$plugin_langs = $path . '/' . $entry . '/lang';
if(is_dir($plugin_langs)) {
if (is_dir($plugin_langs)) {
$this->stripDirLangs($plugin_langs, $keep_langs);
}
}
@ -103,10 +102,9 @@ class StripLangsCLI extends CLI
{
$dir = dir($path);
while(($cur_dir = $dir->read()) !== false) {
if($cur_dir != '.' && $cur_dir != '..' && is_dir($path . '/' . $cur_dir)) {
if(!in_array($cur_dir, $keep_langs, true)) {
while (($cur_dir = $dir->read()) !== false) {
if ($cur_dir != '.' && $cur_dir != '..' && is_dir($path . '/' . $cur_dir)) {
if (!in_array($cur_dir, $keep_langs, true)) {
io_rmdir($path . '/' . $cur_dir, true);
}
}

View File

@ -6,7 +6,7 @@ use dokuwiki\File\PageResolver;
use splitbrain\phpcli\CLI;
use splitbrain\phpcli\Options;
if(!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
if (!defined('DOKU_INC')) define('DOKU_INC', realpath(__DIR__ . '/../') . '/');
define('NOSESSION', 1);
require_once(DOKU_INC . 'inc/init.php');
@ -68,7 +68,7 @@ class WantedPagesCLI extends CLI
protected function main(Options $options)
{
$args = $options->getArgs();
if($args) {
if ($args) {
$startdir = dirname(wikiFN($args[0] . ':xxx'));
} else {
$startdir = dirname(wikiFN('xxx'));
@ -79,17 +79,17 @@ class WantedPagesCLI extends CLI
$this->info("searching $startdir");
foreach($this->getPages($startdir) as $page) {
foreach ($this->getPages($startdir) as $page) {
$this->internalLinks($page);
}
Sort::ksort($this->result);
foreach($this->result as $main => $subs) {
if($this->skip) {
foreach ($this->result as $main => $subs) {
if ($this->skip) {
print "$main\n";
} else {
$subs = array_unique($subs);
Sort::sort($subs);
foreach($subs as $sub) {
foreach ($subs as $sub) {
printf("%-40s %s\n", $main, $sub);
}
}
@ -105,16 +105,16 @@ class WantedPagesCLI extends CLI
*/
protected function dirFilter($entry, $basepath)
{
if($entry == '.' || $entry == '..') {
if ($entry == '.' || $entry == '..') {
return WantedPagesCLI::DIR_CONTINUE;
}
if(is_dir($basepath . '/' . $entry)) {
if(strpos($entry, '_') === 0) {
if (is_dir($basepath . '/' . $entry)) {
if (strpos($entry, '_') === 0) {
return WantedPagesCLI::DIR_CONTINUE;
}
return WantedPagesCLI::DIR_NS;
}
if(preg_match('/\.txt$/', $entry)) {
if (preg_match('/\.txt$/', $entry)) {
return WantedPagesCLI::DIR_PAGE;
}
return WantedPagesCLI::DIR_CONTINUE;
@ -130,18 +130,18 @@ class WantedPagesCLI extends CLI
protected function getPages($dir)
{
static $trunclen = null;
if(!$trunclen) {
if (!$trunclen) {
global $conf;
$trunclen = strlen($conf['datadir'] . ':');
}
if(!is_dir($dir)) {
if (!is_dir($dir)) {
throw new DokuCLI_Exception("Unable to read directory $dir");
}
$pages = [];
$dh = opendir($dir);
while(false !== ($entry = readdir($dh))) {
while (false !== ($entry = readdir($dh))) {
$status = $this->dirFilter($entry, $dir);
if ($status == WantedPagesCLI::DIR_CONTINUE) {
continue;
@ -167,13 +167,13 @@ class WantedPagesCLI extends CLI
$instructions = p_get_instructions(file_get_contents($page['file']));
$resolver = new PageResolver($page['id']);
$pid = $page['id'];
foreach($instructions as $ins) {
if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink')) {
foreach ($instructions as $ins) {
if ($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink')) {
$mid = $resolver->resolveId($ins[1][0]);
if(!page_exists($mid)) {
if (!page_exists($mid)) {
[$mid] = explode('#', $mid); //record pages without hashes
if($this->sort == 'origin') {
if ($this->sort == 'origin') {
$this->result[$pid][] = $mid;
} else {
$this->result[$mid][] = $pid;

View File

@ -335,11 +335,11 @@ function rss_buildItems(&$rss, &$data, $opt)
$src_r = ml($id, $more, true, '&amp;', true);
}
if ($rev && $size = media_image_preview_size(
$id,
$rev,
new JpegMeta(mediaFN($id, $rev)),
300
)) {
$id,
$rev,
new JpegMeta(mediaFN($id, $rev)),
300
)) {
$more = 'rev=' . $rev . '&w=' . $size[0] . '&h=' . $size[1];
$src_l = ml($id, $more, true, '&amp;', true);
}

View File

@ -20,7 +20,7 @@ abstract class AbstractAclAction extends AbstractAction
parent::checkPreconditions();
global $conf;
global $auth;
if(!$conf['useacl']) throw new ActionAclRequiredException();
if(!$auth) throw new ActionAclRequiredException();
if (!$conf['useacl']) throw new ActionAclRequiredException();
if (!$auth) throw new ActionAclRequiredException();
}
}

View File

@ -25,7 +25,7 @@ abstract class AbstractAction
*/
public function __construct($actionname = '')
{
if($actionname !== '') {
if ($actionname !== '') {
$this->actionname = $actionname;
} else {
// http://stackoverflow.com/a/27457689/172068

View File

@ -19,7 +19,7 @@ abstract class AbstractUserAction extends AbstractAclAction
{
parent::checkPreconditions();
global $INPUT;
if($INPUT->server->str('REMOTE_USER') === '') {
if ($INPUT->server->str('REMOTE_USER') === '') {
throw new ActionUserRequiredException();
}
}

View File

@ -27,10 +27,10 @@ class Admin extends AbstractUserAction
global $INPUT;
// retrieve admin plugin name from $_REQUEST['page']
if($INPUT->str('page', '', true) != '') {
if ($INPUT->str('page', '', true) != '') {
/** @var AdminPlugin $plugin */
if($plugin = plugin_getRequestAdminPlugin()) { // FIXME this method does also permission checking
if(!$plugin->isAccessibleByCurrentUser()) {
if ($plugin = plugin_getRequestAdminPlugin()) { // FIXME this method does also permission checking
if (!$plugin->isAccessibleByCurrentUser()) {
throw new ActionException('denied');
}
$plugin->handle();

View File

@ -35,8 +35,8 @@ class ActionException extends \Exception
{
global $INPUT;
parent::__construct($message);
if(is_null($newaction)) {
if(strtolower($INPUT->server->str('REQUEST_METHOD')) == 'post') {
if (is_null($newaction)) {
if (strtolower($INPUT->server->str('REQUEST_METHOD')) == 'post') {
$newaction = 'redirect';
} else {
$newaction = 'show';
@ -64,7 +64,7 @@ class ActionException extends \Exception
*/
public function displayToUser($set = null)
{
if(!is_null($set)) $this->displayToUser = $set;
if (!is_null($set)) $this->displayToUser = $set;
return $set;
}
}

View File

@ -51,7 +51,7 @@ class Export extends AbstractAction
$headers['X-Robots-Tag'] = 'noindex';
$mode = substr($this->actionname, 7);
switch($mode) {
switch ($mode) {
case 'raw':
$headers['Content-Type'] = 'text/plain; charset=utf-8';
$headers['Content-Disposition'] = 'attachment; filename=' . noNS($ID) . '.txt';
@ -102,8 +102,8 @@ class Export extends AbstractAction
Event::createAndTrigger('ACTION_EXPORT_POSTPROCESS', $data);
if(!empty($data['output'])) {
if(is_array($data['headers'])) foreach($data['headers'] as $key => $val) {
if (!empty($data['output'])) {
if (is_array($data['headers'])) foreach ($data['headers'] as $key => $val) {
header("$key: $val");
}
print $pre . $data['output'] . $post;

View File

@ -29,7 +29,7 @@ class Logout extends AbstractUserAction
/** @var AuthPlugin $auth */
global $auth;
if(!$auth->canDo('logout')) throw new ActionDisabledException();
if (!$auth->canDo('logout')) throw new ActionDisabledException();
}
/** @inheritdoc */
@ -42,7 +42,7 @@ class Logout extends AbstractUserAction
// when logging out during an edit session, unlock the page
$lockedby = checklock($ID);
if($lockedby == $INPUT->server->str('REMOTE_USER')) {
if ($lockedby == $INPUT->server->str('REMOTE_USER')) {
unlock($ID);
}

View File

@ -29,7 +29,7 @@ class Plugin extends AbstractAction
public function tplContent()
{
$evt = new Event('TPL_ACT_UNKNOWN', $this->actionname);
if($evt->advise_before()) {
if ($evt->advise_before()) {
msg('Failed to handle action: ' . hsc($this->actionname), -1);
}
$evt->advise_after();

View File

@ -30,7 +30,7 @@ class Profile extends AbstractUserAction
/** @var AuthPlugin $auth */
global $auth;
if(!$auth->canDo('Profile')) throw new ActionDisabledException();
if (!$auth->canDo('Profile')) throw new ActionDisabledException();
}
/** @inheritdoc */

View File

@ -29,14 +29,14 @@ class ProfileDelete extends AbstractUserAction
/** @var AuthPlugin $auth */
global $auth;
if(!$auth->canDo('delUser')) throw new ActionDisabledException();
if (!$auth->canDo('delUser')) throw new ActionDisabledException();
}
/** @inheritdoc */
public function preProcess()
{
global $lang;
if(auth_deleteprofile()) {
if (auth_deleteprofile()) {
msg($lang['profdeleted'], 1);
throw new ActionAbort('show');
} else {

View File

@ -57,7 +57,7 @@ class Redirect extends AbstractAliasAction
public function redirect($opts)
{
$go = wl($opts['id'], '', true, '&');
if(isset($opts['fragment'])) $go .= '#' . $opts['fragment'];
if (isset($opts['fragment'])) $go .= '#' . $opts['fragment'];
//show it
send_redirect($go);

View File

@ -118,9 +118,7 @@ class Resendpwd extends AbstractAclAction
msg($lang['proffail'], -1);
return false;
}
} else { // autogenerate the password and send by mail
$pass = auth_pwgen($user);
if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
msg($lang['proffail'], -1);
@ -136,7 +134,6 @@ class Resendpwd extends AbstractAclAction
@unlink($tfile);
return true;
} else {
// we're in request phase

View File

@ -19,7 +19,7 @@ class Save extends AbstractAction
public function minimumPermission()
{
global $INFO;
if($INFO['exists']) {
if ($INFO['exists']) {
return AUTH_EDIT;
} else {
return AUTH_CREATE;
@ -29,7 +29,7 @@ class Save extends AbstractAction
/** @inheritdoc */
public function preProcess()
{
if(!checkSecurityToken()) throw new ActionException('preview');
if (!checkSecurityToken()) throw new ActionException('preview');
global $ID;
global $DATE;
@ -42,12 +42,12 @@ class Save extends AbstractAction
global $INPUT;
//spam check
if(checkwordblock()) {
if (checkwordblock()) {
msg($lang['wordblock'], -1);
throw new ActionException('edit');
}
//conflict check
if($DATE != 0
if ($DATE != 0
&& isset($INFO['meta']['date']['modified'])
&& $INFO['meta']['date']['modified'] > $DATE
) {

View File

@ -33,23 +33,23 @@ class Sitemap extends AbstractAction
{
global $conf;
if($conf['sitemap'] < 1 || !is_numeric($conf['sitemap'])) {
if ($conf['sitemap'] < 1 || !is_numeric($conf['sitemap'])) {
throw new FatalException('Sitemap generation is disabled', 404);
}
$sitemap = Mapper::getFilePath();
if(Mapper::sitemapIsCompressed()) {
if (Mapper::sitemapIsCompressed()) {
$mime = 'application/x-gzip';
} else {
$mime = 'application/xml; charset=utf-8';
}
// Check if sitemap file exists, otherwise create it
if(!is_readable($sitemap)) {
if (!is_readable($sitemap)) {
Mapper::generate();
}
if(is_readable($sitemap)) {
if (is_readable($sitemap)) {
// Send headers
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename=' . PhpString::basename($sitemap));

View File

@ -30,7 +30,7 @@ class Subscribe extends AbstractUserAction
parent::checkPreconditions();
global $conf;
if(isset($conf['subscribers']) && !$conf['subscribers']) throw new ActionDisabledException();
if (isset($conf['subscribers']) && !$conf['subscribers']) throw new ActionDisabledException();
}
/** @inheritdoc */

View File

@ -59,7 +59,7 @@ class ActionRouter
*/
public static function getInstance($reinit = false)
{
if((!self::$instance instanceof \dokuwiki\ActionRouter) || $reinit) {
if ((!self::$instance instanceof \dokuwiki\ActionRouter) || $reinit) {
self::$instance = new ActionRouter();
}
return self::$instance;
@ -90,29 +90,27 @@ class ActionRouter
$this->action = new Plugin($actionname);
}
$evt->advise_after();
} catch(ActionException $e) {
} catch (ActionException $e) {
// we should have gotten a new action
$actionname = $e->getNewAction();
// this one should trigger a user message
if($e instanceof ActionDisabledException) {
if ($e instanceof ActionDisabledException) {
msg('Action disabled: ' . hsc($presetup), -1);
}
// some actions may request the display of a message
if($e->displayToUser()) {
if ($e->displayToUser()) {
msg(hsc($e->getMessage()), -1);
}
// do setup for new action
$this->transitionAction($presetup, $actionname);
} catch(NoActionException $e) {
} catch (NoActionException $e) {
msg('Action unknown: ' . hsc($actionname), -1);
$actionname = 'show';
$this->transitionAction($presetup, $actionname);
} catch(\Exception $e) {
} catch (\Exception $e) {
$this->handleFatalException($e);
}
}
@ -131,12 +129,12 @@ class ActionRouter
$this->transitions++;
// no infinite recursion
if($from == $to) {
if ($from == $to) {
$this->handleFatalException(new FatalException('Infinite loop in actions', 500, $e));
}
// larger loops will be caught here
if($this->transitions >= self::MAX_TRANSITIONS) {
if ($this->transitions >= self::MAX_TRANSITIONS) {
$this->handleFatalException(new FatalException('Maximum action transitions reached', 500, $e));
}
@ -154,12 +152,12 @@ class ActionRouter
*/
protected function handleFatalException(\Throwable $e)
{
if($e instanceof FatalException) {
if ($e instanceof FatalException) {
http_status($e->getCode());
} else {
http_status(500);
}
if(defined('DOKU_UNITTEST')) {
if (defined('DOKU_UNITTEST')) {
throw $e;
}
ErrorHandler::logException($e);
@ -185,10 +183,10 @@ class ActionRouter
{
$actionname = strtolower($actionname); // FIXME is this needed here? should we run a cleanup somewhere else?
$parts = explode('_', $actionname);
while($parts !== []) {
while ($parts !== []) {
$load = implode('_', $parts);
$class = 'dokuwiki\\Action\\' . str_replace('_', '', ucwords($load, '_'));
if(class_exists($class)) {
if (class_exists($class)) {
return new $class($actionname);
}
array_pop($parts);
@ -209,19 +207,19 @@ class ActionRouter
global $INFO;
global $ID;
if(in_array($action->getActionName(), $this->disabled)) {
if (in_array($action->getActionName(), $this->disabled)) {
throw new ActionDisabledException();
}
$action->checkPreconditions();
if(isset($INFO)) {
if (isset($INFO)) {
$perm = $INFO['perm'];
} else {
$perm = auth_quickaclcheck($ID);
}
if($perm < $action->minimumPermission()) {
if ($perm < $action->minimumPermission()) {
throw new ActionException('denied');
}
}

View File

@ -25,11 +25,11 @@ class Ajax
public function __construct($call)
{
$callfn = 'call' . ucfirst($call);
if(method_exists($this, $callfn)) {
if (method_exists($this, $callfn)) {
$this->$callfn();
} else {
$evt = new Event('AJAX_CALL_UNKNOWN', $call);
if($evt->advise_before()) {
if ($evt->advise_before()) {
print "AJAX call '" . hsc($call) . "' unknown!\n";
} else {
$evt->advise_after();
@ -51,24 +51,24 @@ class Ajax
$maxnumbersuggestions = 50;
$query = $INPUT->post->str('q');
if(empty($query)) $query = $INPUT->get->str('q');
if(empty($query)) return;
if (empty($query)) $query = $INPUT->get->str('q');
if (empty($query)) return;
$query = urldecode($query);
$data = ft_pageLookup($query, true, useHeading('navigation'));
if($data === []) return;
if ($data === []) return;
print '<strong>' . $lang['quickhits'] . '</strong>';
print '<ul>';
$counter = 0;
foreach($data as $id => $title) {
if(useHeading('navigation')) {
foreach ($data as $id => $title) {
if (useHeading('navigation')) {
$name = $title;
} else {
$ns = getNS($id);
if($ns) {
if ($ns) {
$name = noNS($id) . ' (' . $ns . ')';
} else {
$name = $id;
@ -77,7 +77,7 @@ class Ajax
echo '<li>' . html_wikilink(':' . $id, $name) . '</li>';
$counter++;
if($counter > $maxnumbersuggestions) {
if ($counter > $maxnumbersuggestions) {
echo '<li>...</li>';
break;
}
@ -96,11 +96,11 @@ class Ajax
global $INPUT;
$query = cleanID($INPUT->post->str('q'));
if(empty($query)) $query = cleanID($INPUT->get->str('q'));
if(empty($query)) return;
if (empty($query)) $query = cleanID($INPUT->get->str('q'));
if (empty($query)) return;
$data = ft_pageLookup($query);
if($data === []) return;
if ($data === []) return;
$data = array_keys($data);
// limit results to 15 hits
@ -134,7 +134,7 @@ class Ajax
global $INPUT;
$ID = cleanID($INPUT->post->str('id'));
if(empty($ID)) return;
if (empty($ID)) return;
$INFO = pageinfo();
@ -143,13 +143,13 @@ class Ajax
'lock' => '0',
'draft' => '',
];
if(!$INFO['writable']) {
if (!$INFO['writable']) {
$response['errors'][] = 'Permission to write this page has been denied.';
echo json_encode($response);
return;
}
if(!checklock($ID)) {
if (!checklock($ID)) {
lock($ID);
$response['lock'] = '1';
}
@ -172,10 +172,10 @@ class Ajax
{
global $INPUT;
$id = cleanID($INPUT->str('id'));
if(empty($id)) return;
if (empty($id)) return;
$client = $INPUT->server->str('REMOTE_USER');
if(!$client) $client = clientIP(true);
if (!$client) $client = clientIP(true);
$draft = new Draft($id, $client);
if ($draft->isDraftAvailable() && checkSecurityToken()) {
@ -201,7 +201,7 @@ class Ajax
$data = [];
search($data, $conf['mediadir'], 'search_index', ['nofiles' => true], $dir);
foreach(array_keys($data) as $item) {
foreach (array_keys($data) as $item) {
$data[$item]['level'] = $lvl + 1;
}
echo html_buildlist($data, 'idx', 'media_nstree_item', 'media_nstree_li');
@ -219,7 +219,7 @@ class Ajax
$NS = cleanID($INPUT->post->str('ns'));
$sort = $INPUT->post->bool('recent') ? 'date' : 'natural';
if($INPUT->post->str('do') == 'media') {
if ($INPUT->post->str('do') == 'media') {
tpl_mediaFileList();
} else {
tpl_mediaContent(true, $sort);
@ -239,11 +239,11 @@ class Ajax
require_once(DOKU_INC . 'lib/exe/mediamanager.php');
$image = '';
if($INPUT->has('image')) $image = cleanID($INPUT->str('image'));
if(isset($IMG)) $image = $IMG;
if(isset($JUMPTO)) $image = $JUMPTO;
if ($INPUT->has('image')) $image = cleanID($INPUT->str('image'));
if (isset($IMG)) $image = $IMG;
if (isset($JUMPTO)) $image = $JUMPTO;
$rev = false;
if(isset($REV) && !$JUMPTO) $rev = $REV;
if (isset($REV) && !$JUMPTO) $rev = $REV;
html_msgarea();
tpl_mediaFileDetails($image, $rev);
@ -259,7 +259,7 @@ class Ajax
global $INPUT;
$image = '';
if($INPUT->has('image')) $image = cleanID($INPUT->str('image'));
if ($INPUT->has('image')) $image = cleanID($INPUT->str('image'));
(new MediaDiff($image))->preference('fromAjax', true)->show();
}
@ -273,9 +273,9 @@ class Ajax
global $NS, $MSG, $INPUT;
$id = '';
if(isset($_FILES['qqfile']['tmp_name'])) {
if (isset($_FILES['qqfile']['tmp_name'])) {
$id = $INPUT->post->str('mediaid', $_FILES['qqfile']['name']);
} elseif($INPUT->get->has('qqfile')) {
} elseif ($INPUT->get->has('qqfile')) {
$id = $INPUT->get->str('qqfile');
}
@ -285,17 +285,17 @@ class Ajax
$ns = $NS . ':' . getNS($id);
$AUTH = auth_quickaclcheck("$ns:*");
if($AUTH >= AUTH_UPLOAD) {
if ($AUTH >= AUTH_UPLOAD) {
io_createNamespace("$ns:xxx", 'media');
}
if(isset($_FILES['qqfile']['error']) && $_FILES['qqfile']['error']) unset($_FILES['qqfile']);
if (isset($_FILES['qqfile']['error']) && $_FILES['qqfile']['error']) unset($_FILES['qqfile']);
$res = false;
if(isset($_FILES['qqfile']['tmp_name'])) $res = media_upload($NS, $AUTH, $_FILES['qqfile']);
if($INPUT->get->has('qqfile')) $res = media_upload_xhr($NS, $AUTH);
if (isset($_FILES['qqfile']['tmp_name'])) $res = media_upload($NS, $AUTH, $_FILES['qqfile']);
if ($INPUT->get->has('qqfile')) $res = media_upload_xhr($NS, $AUTH);
if($res) {
if ($res) {
$result = [
'success' => true,
'link' => media_managerURL(['ns' => $ns, 'image' => $NS . ':' . $id], '&'),
@ -304,8 +304,8 @@ class Ajax
];
} else {
$error = '';
if(isset($MSG)) {
foreach($MSG as $msg) {
if (isset($MSG)) {
foreach ($MSG as $msg) {
$error .= $msg['msg'];
}
}
@ -363,8 +363,7 @@ class Ajax
$nsd = utf8_encodeFN(str_replace(':', '/', $ns));
$data = [];
if($q !== '' && $ns === '') {
if ($q !== '' && $ns === '') {
// use index to lookup matching pages
$pages = ft_pageLookup($id, true);
@ -380,8 +379,8 @@ class Ajax
// them seperately
$dirs = [];
foreach($pages as $pid => $title) {
if(strpos(getNS($pid), $id) !== false) {
foreach ($pages as $pid => $title) {
if (strpos(getNS($pid), $id) !== false) {
// match was in the namespace
$dirs[getNS($pid)] = 1; // assoc array avoids dupes
} else {
@ -390,12 +389,10 @@ class Ajax
}
unset($pages[$pid]);
}
foreach(array_keys($dirs) as $dir) {
foreach (array_keys($dirs) as $dir) {
$data[] = ['id' => $dir, 'type' => 'd'];
}
} else {
$opts = [
'depth' => 1,
'listfiles' => true,
@ -404,12 +401,12 @@ class Ajax
'firsthead' => true,
'sneakyacl' => $conf['sneaky_index']
];
if($id) $opts['filematch'] = '^.*\/' . $id;
if($id) $opts['dirmatch'] = '^.*\/' . $id;
if ($id) $opts['filematch'] = '^.*\/' . $id;
if ($id) $opts['dirmatch'] = '^.*\/' . $id;
search($data, $conf['datadir'], 'search_universal', $opts, $nsd);
// add back to upper
if($ns) {
if ($ns) {
array_unshift(
$data,
['id' => getNS($ns), 'type' => 'u']
@ -419,22 +416,22 @@ class Ajax
// fixme sort results in a useful way ?
if(!count($data)) {
if (!count($data)) {
echo $lang['nothingfound'];
exit;
}
// output the found data
$even = 1;
foreach($data as $item) {
foreach ($data as $item) {
$even *= -1; //zebra
if(($item['type'] == 'd' || $item['type'] == 'u') && $item['id'] !== '') $item['id'] .= ':';
if (($item['type'] == 'd' || $item['type'] == 'u') && $item['id'] !== '') $item['id'] .= ':';
$link = wl($item['id']);
echo '<div class="' . (($even > 0) ? 'even' : 'odd') . ' type_' . $item['type'] . '">';
if($item['type'] == 'u') {
if ($item['type'] == 'u') {
$name = $lang['upperns'];
} else {
$name = hsc($item['id']);
@ -442,7 +439,7 @@ class Ajax
echo '<a href="' . $link . '" title="' . hsc($item['id']) . '" class="wikilink1">' . $name . '</a>';
if(!blank($item['title'])) {
if (!blank($item['title'])) {
echo '<span>' . hsc($item['title']) . '</span>';
}
echo '</div>';

View File

@ -74,7 +74,6 @@ class CacheRenderer extends CacheParser
// page implies metadata and possibly some other dependencies
if (isset($this->page)) {
// for xhtml this will render the metadata if needed
$valid = p_get_metadata($this->page, 'date valid');
if (!empty($valid['age'])) {

View File

@ -616,7 +616,6 @@ abstract class ChangeLog
'sizechange' => -io_getSizeFile($this->getFilename($lastRev)),
'timestamp' => false,
];
} else { // item file exists, with timestamp $fileRev
// here, file timestamp $fileRev is different with last revision timestamp $lastRev in changelog
$isJustCreated = $lastRev === false || (

View File

@ -46,7 +46,7 @@ class DebugHelper
$backtrace = debug_backtrace();
for ($i = 0; $i < $callerOffset; ++$i) {
if(count($backtrace) > 1) array_shift($backtrace);
if (count($backtrace) > 1) array_shift($backtrace);
}
[$self, $call] = $backtrace;
@ -69,7 +69,7 @@ class DebugHelper
protected static function formatCall($call)
{
$thing = '';
if(!empty($call['class'])) {
if (!empty($call['class'])) {
$thing .= $call['class'] . '::';
}
$thing .= $call['function'] . '()';

View File

@ -27,7 +27,7 @@ class Draft
$this->id = $ID;
$this->client = $client;
$this->cname = getCacheName("$client\n$ID", '.draft');
if(file_exists($this->cname) && file_exists(wikiFN($ID))) {
if (file_exists($this->cname) && file_exists(wikiFN($ID))) {
if (filemtime($this->cname) < filemtime(wikiFN($ID))) {
// remove stale draft
$this->deleteDraft();

View File

@ -165,7 +165,7 @@ EOT;
);
self::logException($ex);
if($ex->getSeverity() === E_WARNING && $conf['hidewarnings']) {
if ($ex->getSeverity() === E_WARNING && $conf['hidewarnings']) {
return true;
}

View File

@ -85,7 +85,7 @@ abstract class AdminPlugin extends Plugin
$data['hasAccess'] = false;
$event = new Event('ADMINPLUGIN_ACCESS_CHECK', $data);
if($event->advise_before()) {
if ($event->advise_before()) {
if ($this->forAdminOnly()) {
$data['hasAccess'] = auth_isadmin();
} else {

View File

@ -96,7 +96,6 @@ class PluginController
//plugin already loaded?
if (!empty($DOKU_PLUGINS[$type][$name])) {
if ($new || !$DOKU_PLUGINS[$type][$name]->isSingleton()) {
return class_exists($class, true) ? new $class() : null;
}
@ -128,7 +127,6 @@ class PluginController
return null;
}
$DOKU_PLUGINS[$type][$name] = new $class();
} catch (\Throwable $e) {
ErrorHandler::showExceptionMsg($e, sprintf('Failed to load plugin %s', $plugin));
return null;
@ -210,7 +208,6 @@ class PluginController
if (array_key_exists($plugin, $this->masterList) && $this->masterList[$plugin] == 0) {
$all_plugins[$plugin] = 0;
} elseif (array_key_exists($plugin, $this->masterList) && $this->masterList[$plugin] == 1) {
$all_plugins[$plugin] = 1;
} else {
@ -345,7 +342,6 @@ class PluginController
$plugins = [];
foreach ($master_list as $plugin) {
if (file_exists(DOKU_PLUGIN . "$plugin/$type.php")) {
$plugins[] = $plugin;
continue;
@ -363,7 +359,6 @@ class PluginController
closedir($dp);
}
}
}//foreach
return $plugins;

View File

@ -160,7 +160,7 @@ class MediaFile
/** @return JpegMeta */
public function getMeta()
{
if($this->meta === null) $this->meta = new JpegMeta($this->path);
if ($this->meta === null) $this->meta = new JpegMeta($this->path);
return $this->meta;
}
}

View File

@ -51,7 +51,7 @@ abstract class Resolver
*/
protected function resolvePrefix($id)
{
if($id === '') return $id;
if ($id === '') return $id;
// relative to current page (makes the current page a start page)
if ($id[0] === '~') {

View File

@ -119,7 +119,7 @@ class DropdownElement extends InputElement
// setter
$this->values = $this->setValuesInOptGroups((array) $value);
if(!$this->values) {
if (!$this->values) {
// unknown value set, select first option instead
$this->values = $this->setValuesInOptGroups((array) $this->getFirstOptionKey());
}

View File

@ -97,7 +97,6 @@ class LegacyForm extends Form
throw new \UnexpectedValueException('Unsupported legacy field ' . $ctl['elem']);
default:
throw new \UnexpectedValueException('Unknown legacy field ' . $ctl['elem']);
}
} else {
$this->addHTML($element);
@ -120,9 +119,9 @@ class LegacyForm extends Form
foreach ($legacy as $key => $val) {
if ($key[0] == '_') {
$control[substr($key, 1)] = $val;
} elseif($key == 'name') {
} elseif ($key == 'name') {
$control[$key] = $val;
} elseif($key == 'id') {
} elseif ($key == 'id') {
$control[$key] = $val;
} else {
$attributes[$key] = $val;

View File

@ -319,8 +319,7 @@ class HTTPClient
if ($match[1] > $this->max_bodysize) {
if ($this->max_bodysize_abort)
throw new HTTPClientException('Reported content length exceeds allowed response size');
else
$this->error = 'Reported content length exceeds allowed response size';
else $this->error = 'Reported content length exceeds allowed response size';
}
}
@ -466,7 +465,6 @@ class HTTPClient
}
}
}
} catch (HTTPClientException $err) {
$this->error = $err->getMessage();
if ($err->getCode())

View File

@ -43,7 +43,7 @@ class Mailer
global $INPUT;
$server = parse_url(DOKU_URL, PHP_URL_HOST);
if(strpos($server, '.') === false) $server .= '.localhost';
if (strpos($server, '.') === false) $server .= '.localhost';
$this->partid = substr(md5(uniqid(random_int(0, mt_getrandmax()), true)), 0, 8).'@'.$server;
$this->boundary = '__________'.md5(uniqid(random_int(0, mt_getrandmax()), true));
@ -56,7 +56,7 @@ class Mailer
$this->allowhtml = (bool)$conf['htmlmail'];
// add some default headers for mailfiltering FS#2247
if(!empty($conf['mailreturnpath'])) {
if (!empty($conf['mailreturnpath'])) {
$this->setHeader('Return-Path', $conf['mailreturnpath']);
}
$this->setHeader('X-Mailer', 'DokuWiki');
@ -81,7 +81,7 @@ class Mailer
*/
public function attachFile($path, $mime, $name = '', $embed = '')
{
if(!$name) {
if (!$name) {
$name = PhpString::basename($path);
}
@ -103,7 +103,7 @@ class Mailer
*/
public function attachContent($data, $mime, $name = '', $embed = '')
{
if(!$name) {
if (!$name) {
[, $ext] = explode('/', $mime);
$name = count($this->attach).".$ext";
}
@ -131,7 +131,7 @@ class Mailer
$media = cleanID($matches[1]);
[, $mime] = mimetype($media);
$file = mediaFN($media);
if(!file_exists($file)) return $matches[0]; //bad reference, keep as is
if (!file_exists($file)) return $matches[0]; //bad reference, keep as is
// attach it and set placeholder
$this->attachFile($file, $mime, '', 'autoembed'.$embeds);
@ -150,21 +150,21 @@ class Mailer
public function setHeader($header, $value, $clean = true)
{
$header = str_replace(' ', '-', ucwords(strtolower(str_replace('-', ' ', $header)))); // streamline casing
if($clean) {
if ($clean) {
$header = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@]+/', '', $header);
$value = preg_replace('/[^a-zA-Z0-9_ \-\.\+\@<>]+/', '', $value);
}
// empty value deletes
if(is_array($value)){
if (is_array($value)) {
$value = array_map('trim', $value);
$value = array_filter($value);
if(!$value) $value = '';
}else{
if (!$value) $value = '';
} else {
$value = trim($value);
}
if($value === '') {
if(isset($this->headers[$header])) unset($this->headers[$header]);
if ($value === '') {
if (isset($this->headers[$header])) unset($this->headers[$header]);
} else {
$this->headers[$header] = $value;
}
@ -205,27 +205,27 @@ class Mailer
$textrep = (array)$textrep;
// create HTML from text if not given
if($html === null) {
if ($html === null) {
$html = $text;
$html = hsc($html);
$html = preg_replace('/^----+$/m', '<hr >', $html);
$html = nl2br($html);
}
if($wrap) {
if ($wrap) {
$wrapper = rawLocale('mailwrap', 'html');
$html = preg_replace('/\n-- <br \/>.*$/s', '', $html); //strip signature
$html = str_replace('@EMAILSIGNATURE@', '', $html); //strip @EMAILSIGNATURE@
$html = str_replace('@HTMLBODY@', $html, $wrapper);
}
if(strpos($text, '@EMAILSIGNATURE@') === false) {
if (strpos($text, '@EMAILSIGNATURE@') === false) {
$text .= '@EMAILSIGNATURE@';
}
// copy over all replacements missing for HTML (autolink URLs)
foreach($textrep as $key => $value) {
if(isset($htmlrep[$key])) continue;
if(media_isexternal($value)) {
foreach ($textrep as $key => $value) {
if (isset($htmlrep[$key])) continue;
if (media_isexternal($value)) {
$htmlrep[$key] = '<a href="'.hsc($value).'">'.hsc($value).'</a>';
} else {
$htmlrep[$key] = hsc($value);
@ -244,10 +244,10 @@ class Mailer
$hrep = array_merge($this->replacements['html'], $htmlrep);
// Apply replacements
foreach($trep as $key => $substitution) {
foreach ($trep as $key => $substitution) {
$text = str_replace('@'.strtoupper($key).'@', $substitution, $text);
}
foreach($hrep as $key => $substitution) {
foreach ($hrep as $key => $substitution) {
$html = str_replace('@'.strtoupper($key).'@', $substitution, $html);
}
@ -377,7 +377,7 @@ class Mailer
public function cleanAddress($addresses)
{
$headers = '';
if(!is_array($addresses)){
if (!is_array($addresses)) {
$count = preg_match_all('/\s*(?:("[^"]*"[^,]+),*)|([^,]+)\s*,*/', $addresses, $matches, PREG_SET_ORDER);
$addresses = [];
if ($count !== false && is_array($matches)) {
@ -387,12 +387,12 @@ class Mailer
}
}
foreach($addresses as $part) {
foreach ($addresses as $part) {
$part = preg_replace('/[\r\n\0]+/', ' ', $part); // remove attack vectors
$part = trim($part);
// parse address
if(preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
if (preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
$text = trim($matches[1]);
$addr = $matches[2];
} else {
@ -400,32 +400,32 @@ class Mailer
$addr = $part;
}
// skip empty ones
if(empty($addr)) {
if (empty($addr)) {
continue;
}
// FIXME: is there a way to encode the localpart of a emailaddress?
if(!Clean::isASCII($addr)) {
if (!Clean::isASCII($addr)) {
msg(hsc("E-Mail address <$addr> is not ASCII"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
continue;
}
if(!mail_isvalid($addr)) {
if (!mail_isvalid($addr)) {
msg(hsc("E-Mail address <$addr> is not valid"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
continue;
}
// text was given
if(!empty($text) && !isWindows()) { // No named recipients for To: in Windows (see FS#652)
if (!empty($text) && !isWindows()) { // No named recipients for To: in Windows (see FS#652)
// add address quotes
$addr = "<$addr>";
if(defined('MAILHEADER_ASCIIONLY')) {
if (defined('MAILHEADER_ASCIIONLY')) {
$text = Clean::deaccent($text);
$text = Clean::strip($text);
}
if(strpos($text, ',') !== false || !Clean::isASCII($text)) {
if (strpos($text, ',') !== false || !Clean::isASCII($text)) {
$text = '=?UTF-8?B?'.base64_encode($text).'?=';
}
} else {
@ -433,14 +433,14 @@ class Mailer
}
// add to header comma seperated
if($headers != '') {
if ($headers != '') {
$headers .= ', ';
}
$headers .= $text.' '.$addr;
}
$headers = trim($headers);
if(empty($headers)) return false;
if (empty($headers)) return false;
return $headers;
}
@ -458,14 +458,14 @@ class Mailer
$mime = '';
$part = 1;
// embedded attachments
foreach($this->attach as $media) {
foreach ($this->attach as $media) {
$media['name'] = str_replace(':', '_', cleanID($media['name'], true));
// create content id
$cid = 'part'.$part.'.'.$this->partid;
// replace wildcards
if($media['embed']) {
if ($media['embed']) {
$this->html = str_replace('%%'.$media['embed'].'%%', 'cid:'.$cid, $this->html);
}
@ -473,7 +473,7 @@ class Mailer
$mime .= $this->wrappedHeaderLine('Content-Type', $media['mime'].'; id="'.$cid.'"');
$mime .= $this->wrappedHeaderLine('Content-Transfer-Encoding', 'base64');
$mime .= $this->wrappedHeaderLine('Content-ID', "<$cid>");
if($media['embed']) {
if ($media['embed']) {
$mime .= $this->wrappedHeaderLine('Content-Disposition', 'inline; filename='.$media['name']);
} else {
$mime .= $this->wrappedHeaderLine('Content-Disposition', 'attachment; filename='.$media['name']);
@ -497,12 +497,12 @@ class Mailer
{
// no HTML mails allowed? remove HTML body
if(!$this->allowhtml) {
if (!$this->allowhtml) {
$this->html = '';
}
// check for body
if(!$this->text && !$this->html) {
if (!$this->text && !$this->html) {
return false;
}
@ -511,7 +511,7 @@ class Mailer
$body = '';
if(!$this->html && !count($this->attach)) { // we can send a simple single part message
if (!$this->html && !count($this->attach)) { // we can send a simple single part message
$this->headers['Content-Type'] = 'text/plain; charset=UTF-8';
$this->headers['Content-Transfer-Encoding'] = 'base64';
$body .= chunk_split(base64_encode($this->text), 72, MAILHEADER_EOL);
@ -522,7 +522,7 @@ class Mailer
$attachments = $this->prepareAttachments();
// do we have alternative text content?
if($this->text && $this->html) {
if ($this->text && $this->html) {
$this->headers['Content-Type'] = 'multipart/alternative;'.MAILHEADER_EOL.
' boundary="'.$this->boundary.'XX"';
$body .= '--'.$this->boundary.'XX'.MAILHEADER_EOL;
@ -547,7 +547,7 @@ class Mailer
$body .= '--'.$this->boundary.'--'.MAILHEADER_EOL;
// close open multipart/alternative boundary
if($this->text && $this->html) {
if ($this->text && $this->html) {
$body .= '--'.$this->boundary.'XX--'.MAILHEADER_EOL;
}
}
@ -563,18 +563,18 @@ class Mailer
global $conf;
// clean up addresses
if(empty($this->headers['From'])) $this->from($conf['mailfrom']);
if (empty($this->headers['From'])) $this->from($conf['mailfrom']);
$addrs = ['To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender'];
foreach($addrs as $addr) {
if(isset($this->headers[$addr])) {
foreach ($addrs as $addr) {
if (isset($this->headers[$addr])) {
$this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
}
}
if(isset($this->headers['Subject'])) {
if (isset($this->headers['Subject'])) {
// add prefix to subject
if(empty($conf['mailprefix'])) {
if(PhpString::strlen($conf['title']) < 20) {
if (empty($conf['mailprefix'])) {
if (PhpString::strlen($conf['title']) < 20) {
$prefix = '['.$conf['title'].']';
} else {
$prefix = '['.PhpString::substr($conf['title'], 0, 20).'...]';
@ -583,16 +583,16 @@ class Mailer
$prefix = '['.$conf['mailprefix'].']';
}
$len = strlen($prefix);
if(substr($this->headers['Subject'], 0, $len) !== $prefix) {
if (substr($this->headers['Subject'], 0, $len) !== $prefix) {
$this->headers['Subject'] = $prefix.' '.$this->headers['Subject'];
}
// encode subject
if(defined('MAILHEADER_ASCIIONLY')) {
if (defined('MAILHEADER_ASCIIONLY')) {
$this->headers['Subject'] = Clean::deaccent($this->headers['Subject']);
$this->headers['Subject'] = Clean::strip($this->headers['Subject']);
}
if(!Clean::isASCII($this->headers['Subject'])) {
if (!Clean::isASCII($this->headers['Subject'])) {
$this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
}
}
@ -619,7 +619,7 @@ class Mailer
protected function prepareHeaders()
{
$headers = '';
foreach($this->headers as $key => $val) {
foreach ($this->headers as $key => $val) {
if ($val === '' || $val === null) continue;
$headers .= $this->wrappedHeaderLine($key, $val);
}
@ -638,7 +638,7 @@ class Mailer
{
$this->cleanHeaders();
$body = $this->prepareBody();
if($body === false) return false;
if ($body === false) return false;
$headers = $this->prepareHeaders();
return $headers.MAILHEADER_EOL.$body;
@ -694,7 +694,7 @@ class Mailer
'MAIL' => '<a href="mailto:"' . hsc($mail) . '">' . hsc($mail) . '</a>'
];
$signature = $lang['email_signature_text'];
if(!empty($lang['email_signature_html'])) {
if (!empty($lang['email_signature_html'])) {
$signature = $lang['email_signature_html'];
}
$signature = str_replace(
@ -737,18 +737,18 @@ class Mailer
// do our thing if BEFORE hook approves
$evt = new Event('MAIL_MESSAGE_SEND', $data);
if($evt->advise_before(true)) {
if ($evt->advise_before(true)) {
// clean up before using the headers
$this->cleanHeaders();
// any recipients?
if(trim($this->headers['To']) === '' &&
if (trim($this->headers['To']) === '' &&
trim($this->headers['Cc']) === '' &&
trim($this->headers['Bcc']) === ''
) return false;
// The To: header is special
if(array_key_exists('To', $this->headers)) {
if (array_key_exists('To', $this->headers)) {
$to = (string)$this->headers['To'];
unset($this->headers['To']);
} else {
@ -756,7 +756,7 @@ class Mailer
}
// so is the subject
if(array_key_exists('Subject', $this->headers)) {
if (array_key_exists('Subject', $this->headers)) {
$subject = (string)$this->headers['Subject'];
unset($this->headers['Subject']);
} else {
@ -765,16 +765,16 @@ class Mailer
// make the body
$body = $this->prepareBody();
if($body === false) return false;
if ($body === false) return false;
// cook the headers
$headers = $this->prepareHeaders();
// add any headers set by legacy plugins
if(trim($data['headers'])) {
if (trim($data['headers'])) {
$headers .= MAILHEADER_EOL.trim($data['headers']);
}
if(!function_exists('mail')){
if (!function_exists('mail')) {
$emsg = $lang['email_fail'] . $subject;
error_log($emsg);
msg(hsc($emsg), -1, __LINE__, __FILE__, MSG_MANAGERS_ONLY);
@ -783,8 +783,8 @@ class Mailer
}
// send the thing
if($to === '') $to = '(undisclosed-recipients)'; // #1422
if($this->sendparam === null) {
if ($to === '') $to = '(undisclosed-recipients)'; // #1422
if ($this->sendparam === null) {
$success = @mail($to, $subject, $body, $headers);
} else {
$success = @mail($to, $subject, $body, $headers, $this->sendparam);

View File

@ -61,7 +61,6 @@ class Manifest
];
foreach ($look as $svgLogo) {
$svgLogoFN = mediaFN($svgLogo);
if (file_exists($svgLogoFN)) {

View File

@ -45,7 +45,7 @@ class Parser
protected function addBaseMode($BaseMode)
{
$this->modes['base'] = $BaseMode;
if(!$this->lexer) {
if (!$this->lexer) {
$this->lexer = new Lexer($this->handler, 'base', true);
}
$this->modes['base']->Lexer = $this->lexer;
@ -62,7 +62,7 @@ class Parser
*/
public function addMode($name, ModeInterface $Mode)
{
if(!isset($this->modes['base'])) {
if (!isset($this->modes['base'])) {
$this->addBaseMode(new Base());
}
$Mode->Lexer = $this->lexer; // FIXME should be done by setter
@ -77,23 +77,21 @@ class Parser
protected function connectModes()
{
if($this->connected) {
if ($this->connected) {
return;
}
foreach(array_keys($this->modes) as $mode) {
foreach (array_keys($this->modes) as $mode) {
// Base isn't connected to anything
if($mode == 'base') {
if ($mode == 'base') {
continue;
}
$this->modes[$mode]->preConnect();
foreach(array_keys($this->modes) as $cm) {
if($this->modes[$cm]->accepts($mode)) {
foreach (array_keys($this->modes) as $cm) {
if ($this->modes[$cm]->accepts($mode)) {
$this->modes[$mode]->connectTo($cm);
}
}
$this->modes[$mode]->postConnect();

View File

@ -42,70 +42,70 @@ class PassHash
$clear = md5($clear);
}
$len = strlen($hash);
if(preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) {
if (preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) {
$method = 'smd5';
$salt = $m[1];
$magic = '1';
} elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) {
} elseif (preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) {
$method = 'apr1';
$salt = $m[1];
$magic = 'apr1';
} elseif(preg_match('/^\$S\$(.{52})$/', $hash, $m)) {
} elseif (preg_match('/^\$S\$(.{52})$/', $hash, $m)) {
$method = 'drupal_sha512';
$salt = $m[1];
$magic = 'S';
} elseif(preg_match('/^\$P\$(.{31})$/', $hash, $m)) {
} elseif (preg_match('/^\$P\$(.{31})$/', $hash, $m)) {
$method = 'pmd5';
$salt = $m[1];
$magic = 'P';
} elseif(preg_match('/^\$H\$(.{31})$/', $hash, $m)) {
} elseif (preg_match('/^\$H\$(.{31})$/', $hash, $m)) {
$method = 'pmd5';
$salt = $m[1];
$magic = 'H';
} elseif(preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) {
} elseif (preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) {
$method = 'djangopbkdf2';
$magic = ['algo' => $m[1], 'iter' => $m[2]];
$salt = $m[3];
} elseif(preg_match('/^PBKDF2(SHA\d+)\$(\d+)\$([[:xdigit:]]+)\$([[:xdigit:]]+)$/', $hash, $m)) {
} elseif (preg_match('/^PBKDF2(SHA\d+)\$(\d+)\$([[:xdigit:]]+)\$([[:xdigit:]]+)$/', $hash, $m)) {
$method = 'seafilepbkdf2';
$magic = ['algo' => $m[1], 'iter' => $m[2]];
$salt = $m[3];
} elseif(preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
} elseif (preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
$method = 'djangosha1';
$salt = $m[1];
} elseif(preg_match('/^md5\$(.{5})\$/', $hash, $m)) {
} elseif (preg_match('/^md5\$(.{5})\$/', $hash, $m)) {
$method = 'djangomd5';
$salt = $m[1];
} elseif(preg_match('/^\$2(a|y)\$(.{2})\$/', $hash, $m)) {
} elseif (preg_match('/^\$2(a|y)\$(.{2})\$/', $hash, $m)) {
$method = 'bcrypt';
$salt = $hash;
} elseif(substr($hash, 0, 6) == '{SSHA}') {
} elseif (substr($hash, 0, 6) == '{SSHA}') {
$method = 'ssha';
$salt = substr(base64_decode(substr($hash, 6)), 20);
} elseif(substr($hash, 0, 6) == '{SMD5}') {
} elseif (substr($hash, 0, 6) == '{SMD5}') {
$method = 'lsmd5';
$salt = substr(base64_decode(substr($hash, 6)), 16);
} elseif(preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) {
} elseif (preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) {
$method = 'mediawiki';
$salt = $m[1];
} elseif(preg_match('/^\$(5|6)\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) {
} elseif (preg_match('/^\$(5|6)\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) {
$method = 'sha2';
$salt = $m[3];
$magic = ['prefix' => $m[1], 'rounds' => $m[2]];
} elseif(preg_match('/^\$(argon2id?)/', $hash, $m)) {
if(!defined('PASSWORD_'.strtoupper($m[1]))) {
} elseif (preg_match('/^\$(argon2id?)/', $hash, $m)) {
if (!defined('PASSWORD_'.strtoupper($m[1]))) {
throw new \Exception('This PHP installation has no '.strtoupper($m[1]).' support');
}
return password_verify($clear, $hash);
} elseif($len == 32) {
} elseif ($len == 32) {
$method = 'md5';
} elseif($len == 40) {
} elseif ($len == 40) {
$method = 'sha1';
} elseif($len == 16) {
} elseif ($len == 16) {
$method = 'mysql';
} elseif($len == 41 && $hash[0] == '*') {
} elseif ($len == 41 && $hash[0] == '*') {
$method = 'my411';
} elseif($len == 34) {
} elseif ($len == 34) {
$method = 'kmd5';
$salt = $hash;
} else {
@ -116,7 +116,7 @@ class PassHash
//crypt and compare
$call = 'hash_'.$method;
$newhash = $this->$call($clear, $salt, $magic);
if(\hash_equals($newhash, $hash)) {
if (\hash_equals($newhash, $hash)) {
return true;
}
return false;
@ -132,7 +132,7 @@ class PassHash
{
$salt = '';
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for($i = 0; $i < $len; $i++) {
for ($i = 0; $i < $len; $i++) {
$salt .= $chars[$this->random(0, 61)];
}
return $salt;
@ -150,11 +150,11 @@ class PassHash
*/
public function init_salt(&$salt, $len = 32, $cut = true)
{
if(is_null($salt)) {
if (is_null($salt)) {
$salt = $this->gen_salt($len);
$cut = true; // for new hashes we alway apply length restriction
}
if(strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len);
if (strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len);
}
// Password hashing methods follow below
@ -180,7 +180,7 @@ class PassHash
{
$this->init_salt($salt, 8);
if(defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') {
if (defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') {
return crypt($clear, '$1$'.$salt.'$');
} else {
// Fall back to PHP-only implementation
@ -227,25 +227,25 @@ class PassHash
$len = strlen($clear);
$text = $clear.'$'.$magic.'$'.$salt;
$bin = pack("H32", md5($clear.$salt.$clear));
for($i = $len; $i > 0; $i -= 16) {
for ($i = $len; $i > 0; $i -= 16) {
$text .= substr($bin, 0, min(16, $i));
}
for($i = $len; $i > 0; $i >>= 1) {
for ($i = $len; $i > 0; $i >>= 1) {
$text .= ($i & 1) ? chr(0) : $clear[0];
}
$bin = pack("H32", md5($text));
for($i = 0; $i < 1000; $i++) {
for ($i = 0; $i < 1000; $i++) {
$new = ($i & 1) ? $clear : $bin;
if($i % 3) $new .= $salt;
if($i % 7) $new .= $clear;
if ($i % 3) $new .= $salt;
if ($i % 7) $new .= $clear;
$new .= ($i & 1) ? $bin : $clear;
$bin = pack("H32", md5($new));
}
$tmp = '';
for($i = 0; $i < 5; $i++) {
for ($i = 0; $i < 5; $i++) {
$k = $i + 6;
$j = $i + 12;
if($j == 16) $j = 5;
if ($j == 16) $j = 5;
$tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
}
$tmp = chr(0).chr(0).$bin[11].$tmp;
@ -329,8 +329,8 @@ class PassHash
$nr2 = 0x12345671;
$add = 7;
$charArr = preg_split("//", $clear);
foreach($charArr as $char) {
if(($char == '') || ($char == ' ') || ($char == '\t')) continue;
foreach ($charArr as $char) {
if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
$charVal = ord($char);
$nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
$nr2 += ($nr2 << 8) ^ $nr;
@ -403,14 +403,14 @@ class PassHash
protected function stretched_hash($algo, $clear, $salt = null, $magic = 'P', $compute = 8)
{
$itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if(is_null($salt)) {
if (is_null($salt)) {
$this->init_salt($salt);
$salt = $itoa64[$compute].$salt; // prefix iteration count
}
$iterc = $salt[0]; // pos 0 of salt is log2(iteration count)
$iter = strpos($itoa64, $iterc);
if($iter > 30) {
if ($iter > 30) {
throw new \Exception("Too high iteration count ($iter) in ".
self::class.'::'.__FUNCTION__);
}
@ -422,7 +422,7 @@ class PassHash
$hash = hash($algo, $salt . $clear, true);
do {
$hash = hash($algo, $hash.$clear, true);
} while(--$iter);
} while (--$iter);
// encode
$output = '';
@ -431,18 +431,18 @@ class PassHash
do {
$value = ord($hash[$i++]);
$output .= $itoa64[$value & 0x3f];
if($i < $count)
if ($i < $count)
$value |= ord($hash[$i]) << 8;
$output .= $itoa64[($value >> 6) & 0x3f];
if($i++ >= $count)
if ($i++ >= $count)
break;
if($i < $count)
if ($i < $count)
$value |= ord($hash[$i]) << 16;
$output .= $itoa64[($value >> 12) & 0x3f];
if($i++ >= $count)
if ($i++ >= $count)
break;
$output .= $itoa64[($value >> 18) & 0x3f];
} while($i < $count);
} while ($i < $count);
return '$'.$magic.'$'.$iterc.$salt.$output;
}
@ -564,21 +564,21 @@ class PassHash
public function hash_seafilepbkdf2($clear, $salt = null, $opts = [])
{
$this->init_salt($salt, 64);
if(empty($opts['algo'])) {
if (empty($opts['algo'])) {
$prefixalgo='SHA256';
} else {
$prefixalgo=$opts['algo'];
}
$algo = strtolower($prefixalgo);
if(empty($opts['iter'])) {
if (empty($opts['iter'])) {
$iter = 10000;
} else {
$iter = (int) $opts['iter'];
}
if(!function_exists('hash_pbkdf2')) {
if (!function_exists('hash_pbkdf2')) {
throw new Exception('This PHP installation has no PBKDF2 support');
}
if(!in_array($algo, hash_algos())) {
if (!in_array($algo, hash_algos())) {
throw new Exception("This PHP installation has no $algo support");
}
@ -601,20 +601,20 @@ class PassHash
public function hash_djangopbkdf2($clear, $salt = null, $opts = [])
{
$this->init_salt($salt, 12);
if(empty($opts['algo'])) {
if (empty($opts['algo'])) {
$algo = 'sha256';
} else {
$algo = $opts['algo'];
}
if(empty($opts['iter'])) {
if (empty($opts['iter'])) {
$iter = 24000;
} else {
$iter = (int) $opts['iter'];
}
if(!function_exists('hash_pbkdf2')) {
if (!function_exists('hash_pbkdf2')) {
throw new \Exception('This PHP installation has no PBKDF2 support');
}
if(!in_array($algo, hash_algos())) {
if (!in_array($algo, hash_algos())) {
throw new \Exception("This PHP installation has no $algo support");
}
@ -671,12 +671,12 @@ class PassHash
*/
public function hash_bcrypt($clear, $salt = null, $compute = 10)
{
if(!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH !== 1) {
if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH !== 1) {
throw new \Exception('This PHP installation has no bcrypt support');
}
if(is_null($salt)) {
if($compute < 4 || $compute > 31) $compute = 8;
if (is_null($salt)) {
if ($compute < 4 || $compute > 31) $compute = 8;
$salt = '$2y$'.str_pad($compute, 2, '0', STR_PAD_LEFT).'$'.
$this->gen_salt(22);
}
@ -702,26 +702,26 @@ class PassHash
*/
public function hash_sha2($clear, $salt = null, $opts = [])
{
if(empty($opts['prefix'])) {
if (empty($opts['prefix'])) {
$prefix = '6';
} else {
$prefix = $opts['prefix'];
}
if(empty($opts['rounds'])) {
if (empty($opts['rounds'])) {
$rounds = null;
} else {
$rounds = $opts['rounds'];
}
if($prefix == '5' && (!defined('CRYPT_SHA256') || CRYPT_SHA256 !== 1)) {
if ($prefix == '5' && (!defined('CRYPT_SHA256') || CRYPT_SHA256 !== 1)) {
throw new \Exception('This PHP installation has no SHA256 support');
}
if($prefix == '6' && (!defined('CRYPT_SHA512') || CRYPT_SHA512 !== 1)) {
if ($prefix == '6' && (!defined('CRYPT_SHA512') || CRYPT_SHA512 !== 1)) {
throw new \Exception('This PHP installation has no SHA512 support');
}
$this->init_salt($salt, 8, false);
if(empty($rounds)) {
if (empty($rounds)) {
return crypt($clear, '$'.$prefix.'$'.$salt.'$');
}else{
} else {
return crypt($clear, '$'.$prefix.'$'.$rounds.'$'.$salt.'$');
}
}
@ -772,7 +772,7 @@ class PassHash
*/
public function hash_argon2i($clear)
{
if(!defined('PASSWORD_ARGON2I')) {
if (!defined('PASSWORD_ARGON2I')) {
throw new \Exception('This PHP installation has no ARGON2I support');
}
return password_hash($clear, PASSWORD_ARGON2I);
@ -791,7 +791,7 @@ class PassHash
*/
public function hash_argon2id($clear)
{
if(!defined('PASSWORD_ARGON2ID')) {
if (!defined('PASSWORD_ARGON2ID')) {
throw new \Exception('This PHP installation has no ARGON2ID support');
}
return password_hash($clear, PASSWORD_ARGON2ID);
@ -818,7 +818,7 @@ class PassHash
public static function hmac($algo, $data, $key, $raw_output = false)
{
// use native function if available and not in unit test
if(function_exists('hash_hmac') && !defined('SIMPLE_TEST')){
if (function_exists('hash_hmac') && !defined('SIMPLE_TEST')) {
return hash_hmac($algo, $data, $key, $raw_output);
}
@ -828,13 +828,13 @@ class PassHash
$opad = str_repeat(chr(0x5C), $size);
$ipad = str_repeat(chr(0x36), $size);
if(strlen($key) > $size) {
if (strlen($key) > $size) {
$key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
} else {
$key = str_pad($key, $size, chr(0x00));
}
for($i = 0; $i < strlen($key) - 1; $i++) {
for ($i = 0; $i < strlen($key) - 1; $i++) {
$ochar = $opad[$i] ^ $key[$i];
$ichar = $ipad[$i] ^ $key[$i];
$opad[$i] = $ochar;

View File

@ -120,7 +120,7 @@ class SafeFN
$converted = true;
}
}
if($converted) $safe .= self::$post_indicator;
if ($converted) $safe .= self::$post_indicator;
return $safe;
}

View File

@ -118,9 +118,9 @@ class Indexer
$words = [];
foreach ($tokens as $w => $c) {
$l = wordlen($w);
if (isset($words[$l])){
if (isset($words[$l])) {
$words[$l][$w] = $c + ($words[$l][$w] ?? 0);
}else{
} else {
$words[$l] = [$w => $c];
}
}
@ -225,7 +225,7 @@ class Indexer
$addwords = true;
}
// test if value is already in the index
if (isset($val_idx[$id]) && $val_idx[$id] <= 0){
if (isset($val_idx[$id]) && $val_idx[$id] <= 0) {
$val_idx[$id] = 0;
} else { // else add it
$val_idx[$id] = 1;
@ -464,9 +464,9 @@ class Indexer
@unlink($conf['indexdir'].'/pageword.idx');
@unlink($conf['indexdir'].'/metadata.idx');
$dir = @opendir($conf['indexdir']);
if($dir!==false){
while(($f = readdir($dir)) !== false){
if(substr($f, -4)=='.idx' &&
if ($dir!==false) {
while (($f = readdir($dir)) !== false) {
if (substr($f, -4)=='.idx' &&
(substr($f, 0, 1)=='i' || substr($f, 0, 1)=='w'
|| substr($f, -6)=='_w.idx' || substr($f, -6)=='_i.idx' || substr($f, -6)=='_p.idx'))
@unlink($conf['indexdir']."/$f");
@ -615,7 +615,7 @@ class Indexer
foreach (array_keys($wids) as $wlen) {
$wids[$wlen] = array_unique($wids[$wlen]);
$index = $this->getIndex('i', $wlen);
foreach($wids[$wlen] as $ixid) {
foreach ($wids[$wlen] as $ixid) {
if ($ixid < count($index))
$docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
}
@ -634,8 +634,7 @@ class Indexer
if (!page_exists($hitkey, '', false)) continue;
if (!isset($final[$word][$hitkey]))
$final[$word][$hitkey] = $hitcnt;
else
$final[$word][$hitkey] += $hitcnt;
else $final[$word][$hitkey] += $hitcnt;
}
}
}
@ -664,8 +663,7 @@ class Indexer
{
if (!is_array($value))
$value_array = [$value];
else
$value_array =& $value;
else $value_array =& $value;
// the matching ids for the provided value(s)
$value_ids = [];
@ -702,7 +700,7 @@ class Indexer
}
if (!$caret || !$dollar) {
$re = $caret.preg_quote($xval, '/').$dollar;
foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
foreach (array_keys(preg_grep('/'.$re.'/', $words)) as $i)
$value_ids[$i][] = $val;
} elseif (($i = array_search($val, $words, true)) !== false) {
$value_ids[$i][] = $val;
@ -822,7 +820,7 @@ class Indexer
if ($wlen >= $ixlen) break;
foreach ($tokens[$xword] as $w) {
if (is_null($w[1])) continue;
foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
foreach (array_keys(preg_grep($w[1], $word_idx)) as $wid) {
$wids[$ixlen][] = $wid;
$result[$w[0]][] = "$ixlen*$wid";
}
@ -892,8 +890,7 @@ class Indexer
if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
$result[$val] = $cnt;
}
}
elseif (!is_null($key)) {
} elseif (!is_null($key)) {
$metaname = idx_cleanName($key);
$index = $this->getIndex($metaname.'_i', '');
$val_idx = [];
@ -909,8 +906,7 @@ class Indexer
$result[$words[$wid]] = $freq;
}
}
}
else {
} else {
$lengths = idx_listIndexLengths();
foreach ($lengths as $length) {
if ($length < $minlen) continue;
@ -946,7 +942,7 @@ class Indexer
$lock = $conf['lockdir'].'/_indexer.lock';
while (!@mkdir($lock)) {
usleep(50);
if(is_dir($lock) && time()-@filemtime($lock) > 60*5){
if (is_dir($lock) && time()-@filemtime($lock) > 60*5) {
// looks like a stale lock - remove it
if (!@rmdir($lock)) {
$status = "removing the stale lock failed";
@ -954,7 +950,7 @@ class Indexer
} else {
$status = "stale lock removed";
}
}elseif($run++ == 1000){
} elseif ($run++ == 1000) {
// we waited 5 seconds for that lock
return false;
}
@ -1180,7 +1176,7 @@ class Indexer
*/
protected function updateTuple($line, $id, $count)
{
if ($line != ''){
if ($line != '') {
$line = preg_replace('/(^|:)'.preg_quote($id, '/').'\*\d*/', '', $line);
}
$line = trim($line, ':');

View File

@ -46,7 +46,7 @@ class Item
{
$id = trim($id);
$date = @filemtime(wikiFN($id));
if(!$date) return null;
if (!$date) return null;
return new Item(wl($id, '', true), $date, $changefreq, $priority);
}

View File

@ -35,18 +35,18 @@ class Mapper
public static function generate()
{
global $conf;
if($conf['sitemap'] < 1 || !is_numeric($conf['sitemap'])) return false;
if ($conf['sitemap'] < 1 || !is_numeric($conf['sitemap'])) return false;
$sitemap = Mapper::getFilePath();
if (file_exists($sitemap)) {
if(!is_writable($sitemap)) return false;
if (!is_writable($sitemap)) return false;
} elseif (!is_writable(dirname($sitemap))) {
return false;
}
if(@filesize($sitemap) &&
@filemtime($sitemap) > (time()-($conf['sitemap']*86400))){ // 60*60*24=86400
if (@filesize($sitemap) &&
@filemtime($sitemap) > (time()-($conf['sitemap']*86400))) { // 60*60*24=86400
Logger::debug('Sitemapper::generate(): Sitemap up to date');
return false;
}
@ -58,10 +58,10 @@ class Mapper
$items = [];
// build the sitemap items
foreach($pages as $id){
foreach ($pages as $id) {
//skip hidden, non existing and restricted files
if(isHiddenPage($id)) continue;
if(auth_aclcheck($id, '', []) < AUTH_READ) continue;
if (isHiddenPage($id)) continue;
if (auth_aclcheck($id, '', []) < AUTH_READ) continue;
$item = Item::createFromID($id);
if ($item instanceof Item)
$items[] = $item;
@ -160,7 +160,7 @@ class Mapper
foreach ($data['ping_urls'] as $name => $url) {
Logger::debug("Sitemapper::PingSearchEngines(): pinging $name");
$resp = $http->get($url);
if($http->error) {
if ($http->error) {
Logger::debug("Sitemapper:pingSearchengines(): $http->error", $resp);
}
}

View File

@ -30,14 +30,14 @@ class TaskRunner
// check if user abort worked, if yes send output early
$defer = !@ignore_user_abort() || $conf['broken_iua'];
$output = $INPUT->has('debug') && $conf['allowdebug'];
if(!$defer && !$output){
if (!$defer && !$output) {
$this->sendGIF();
}
$ID = cleanID($INPUT->str('id'));
// Catch any possible output (e.g. errors)
if(!$output) {
if (!$output) {
ob_start();
} else {
header('Content-Type: text/plain');
@ -58,9 +58,9 @@ class TaskRunner
}
}
if(!$output) {
if (!$output) {
ob_end_clean();
if($defer) {
if ($defer) {
$this->sendGIF();
}
}

View File

@ -58,7 +58,6 @@ class PageView extends Ui
echo $html;
echo '<div class="clearer"></div>';
echo '</div></div>';
} else {
if ($REV || $DATE_AT) {
// print intro for old revisions

View File

@ -91,7 +91,6 @@ class UserProfile extends Ui
if ($auth->canDo('delUser') && actionOK('profile_delete')) {
// create the profiledelete form
$form = new Form(['id' => 'dw__profiledelete']);
$form->addTagOpen('div')->addClass('no');

View File

@ -138,7 +138,6 @@ class PhpString
if ($length === null) {
$length_pattern = '(.*)$'; // the rest of the string
} else {
if (!isset($strlen)) $strlen = self::strlen($str); // see notes
if ($offset > $strlen) return ''; // another trivial case
@ -261,7 +260,7 @@ class PhpString
*/
public static function strtolower($string)
{
if($string === null) return ''; // pre-8.1 behaviour
if ($string === null) return ''; // pre-8.1 behaviour
if (UTF8_MBSTRING) {
if (class_exists('Normalizer', $autoload = false)) {
return \Normalizer::normalize(mb_strtolower($string, 'utf-8'));

View File

@ -45,7 +45,6 @@ class Unicode
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
$in = ord($str[$i]);
if ($mState === 0) {
@ -102,7 +101,6 @@ class Unicode
E_USER_WARNING
);
return false;
}
} elseif (0x80 === (0xC0 & $in)) {
// When mState is non-zero, we expect a continuation of the multi-octet
@ -117,7 +115,6 @@ class Unicode
* Unicode codepoint to be output
*/
if (0 === --$mState) {
/*
* Check for illegal sequences and codepoints.
*/
@ -130,7 +127,6 @@ class Unicode
(($mUcs4 & 0xFFFFF800) === 0xD800) ||
// Codepoints outside the Unicode range are illegal
($mUcs4 > 0x10FFFF)) {
if ($strict) {
trigger_error(
'utf8_to_unicode: Illegal sequence or codepoint ' .
@ -140,7 +136,6 @@ class Unicode
return false;
}
}
if (0xFEFF !== $mUcs4) {
@ -201,7 +196,6 @@ class Unicode
ob_start();
foreach (array_keys($arr) as $k) {
if (($arr[$k] >= 0) && ($arr[$k] <= 0x007f)) {
# ASCII range (including control chars)
echo chr($arr[$k]);
@ -235,7 +229,6 @@ class Unicode
echo chr(0x80 | (($arr[$k] >> 6) & 0x3f));
echo chr(0x80 | ($arr[$k] & 0x3f));
} elseif ($strict) {
trigger_error(
'unicode_to_utf8: Codepoint out of Unicode range ' .
'at index: ' . $k . ', value: ' . $arr[$k],

View File

@ -51,20 +51,20 @@ function act_sendheaders($headers)
function act_clean($act)
{
// check if the action was given as array key
if(is_array($act)){
if (is_array($act)) {
[$act] = array_keys($act);
}
// no action given
if($act === null) return 'show';
if ($act === null) return 'show';
//remove all bad chars
$act = strtolower($act);
$act = preg_replace('/[^1-9a-z_]+/', '', $act);
if($act == 'export_html') $act = 'export_xhtml';
if($act == 'export_htmlbody') $act = 'export_xhtmlbody';
if ($act == 'export_html') $act = 'export_xhtml';
if ($act == 'export_htmlbody') $act = 'export_xhtmlbody';
if($act === '') $act = 'show';
if ($act === '') $act = 'show';
return $act;
}

View File

@ -41,7 +41,7 @@ function auth_setup()
global $plugin_controller;
$AUTH_ACL = [];
if(!$conf['useacl']) return false;
if (!$conf['useacl']) return false;
// try to load auth backend from plugins
foreach ($plugin_controller->getList('auth') as $plugin) {
@ -51,7 +51,7 @@ function auth_setup()
}
}
if(!isset($auth) || !$auth){
if (!isset($auth) || !$auth) {
msg($lang['authtempfail'], -1);
return false;
}
@ -66,12 +66,12 @@ function auth_setup()
// do the login either by cookie or provided credentials XXX
$INPUT->set('http_credentials', false);
if(!$conf['rememberme']) $INPUT->set('r', false);
if (!$conf['rememberme']) $INPUT->set('r', false);
// Populate Basic Auth user/password from Authorization header
// Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
$header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
if(preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
$userpass = explode(':', base64_decode($matches[1]));
[$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
}
@ -126,18 +126,18 @@ function auth_loadACL()
/* @var Input $INPUT */
global $INPUT;
if(!is_readable($config_cascade['acl']['default'])) return [];
if (!is_readable($config_cascade['acl']['default'])) return [];
$acl = file($config_cascade['acl']['default']);
$out = [];
foreach($acl as $line) {
foreach ($acl as $line) {
$line = trim($line);
if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
[$id, $rest] = preg_split('/[ \t]+/', $line, 2);
// substitute user wildcard first (its 1:1)
if(strstr($line, '%USER%')){
if (strstr($line, '%USER%')) {
// if user is not logged in, this ACL line is meaningless - skip it
if (!$INPUT->server->has('REMOTE_USER')) continue;
@ -146,10 +146,10 @@ function auth_loadACL()
}
// substitute group wildcard (its 1:m)
if(strstr($line, '%GROUP%')){
if (strstr($line, '%GROUP%')) {
// if user is not logged in, grps is empty, no output will be added (i.e. skipped)
if(isset($USERINFO['grps'])){
foreach((array) $USERINFO['grps'] as $grp){
if (isset($USERINFO['grps'])) {
foreach ((array) $USERINFO['grps'] as $grp) {
$nid = str_replace('%GROUP%', cleanID($grp), $id);
$nrest = str_replace('%GROUP%', '@'.auth_nameencode($grp), $rest);
$out[] = "$nid\t$nrest";
@ -218,11 +218,11 @@ function auth_login($user, $pass, $sticky = false, $silent = false)
/* @var Input $INPUT */
global $INPUT;
if(!$auth) return false;
if (!$auth) return false;
if(!empty($user)) {
if (!empty($user)) {
//usual login
if(!empty($pass) && $auth->checkPass($user, $pass)) {
if (!empty($pass) && $auth->checkPass($user, $pass)) {
// make logininfo globally available
$INPUT->server->set('REMOTE_USER', $user);
$secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
@ -230,7 +230,7 @@ function auth_login($user, $pass, $sticky = false, $silent = false)
return true;
} else {
//invalid credentials - log off
if(!$silent) {
if (!$silent) {
http_status(403, 'Login failed');
msg($lang['badlogin'], -1);
}
@ -240,7 +240,7 @@ function auth_login($user, $pass, $sticky = false, $silent = false)
} else {
// read cookie information
[$user, $sticky, $pass] = auth_getCookie();
if($user && $pass) {
if ($user && $pass) {
// we got a cookie - see if we can trust it
// get session info
@ -253,7 +253,6 @@ function auth_login($user, $pass, $sticky = false, $silent = false)
($session['pass'] == sha1($pass)) && //still crypted
($session['buid'] == auth_browseruid())
) {
// he has session, cookie and browser right - let him in
$INPUT->server->set('REMOTE_USER', $user);
$USERINFO = $session['info']; //FIXME move all references to session
@ -324,11 +323,11 @@ function auth_cookiesalt($addsession = false, $secure = false)
$file = $conf['metadir'].'/_htcookiesalt2';
}
$salt = io_readFile($file);
if(empty($salt)) {
if (empty($salt)) {
$salt = bin2hex(auth_randombytes(64));
io_saveFile($file, $salt);
}
if($addsession) {
if ($addsession) {
$salt .= session_id();
}
return $salt;
@ -427,13 +426,13 @@ function auth_logoff($keepbc = false)
// make sure the session is writable (it usually is)
@session_start();
if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
unset($_SESSION[DOKU_COOKIE]['auth']['user']);
if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
unset($_SESSION[DOKU_COOKIE]['auth']['info']);
if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
unset($_SESSION[DOKU_COOKIE]['bc']);
$INPUT->server->remove('REMOTE_USER');
$USERINFO = null; //FIXME
@ -447,7 +446,7 @@ function auth_logoff($keepbc = false)
'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
]);
if($auth) $auth->logOff();
if ($auth) $auth->logOff();
}
/**
@ -477,9 +476,9 @@ function auth_ismanager($user = null, $groups = null, $adminonly = false, $recac
global $INPUT;
if(!$auth) return false;
if(is_null($user)) {
if(!$INPUT->server->has('REMOTE_USER')) {
if (!$auth) return false;
if (is_null($user)) {
if (!$INPUT->server->has('REMOTE_USER')) {
return false;
} else {
$user = $INPUT->server->str('REMOTE_USER');
@ -548,10 +547,10 @@ function auth_isMember($memberlist, $user, array $groups)
{
/* @var AuthPlugin $auth */
global $auth;
if(!$auth) return false;
if (!$auth) return false;
// clean user and groups
if(!$auth->isCaseSensitive()) {
if (!$auth->isCaseSensitive()) {
$user = PhpString::strtolower($user);
$groups = array_map([PhpString::class, 'strtolower'], $groups);
}
@ -565,15 +564,15 @@ function auth_isMember($memberlist, $user, array $groups)
$members = array_filter($members);
// compare cleaned values
foreach($members as $member) {
if($member == '@ALL' ) return true;
if(!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
if($member[0] == '@') {
foreach ($members as $member) {
if ($member == '@ALL' ) return true;
if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
if ($member[0] == '@') {
$member = $auth->cleanGroup(substr($member, 1));
if(in_array($member, $groups)) return true;
if (in_array($member, $groups)) return true;
} else {
$member = $auth->cleanUser($member);
if($member == $user) return true;
if ($member == $user) return true;
}
}
@ -598,7 +597,7 @@ function auth_quickaclcheck($id)
/* @var Input $INPUT */
global $INPUT;
# if no ACL is used always return upload rights
if(!$conf['useacl']) return AUTH_UPLOAD;
if (!$conf['useacl']) return AUTH_UPLOAD;
return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
}
@ -646,19 +645,19 @@ function auth_aclcheck_cb($data)
global $auth;
// if no ACL is used always return upload rights
if(!$conf['useacl']) return AUTH_UPLOAD;
if(!$auth) return AUTH_NONE;
if(!is_array($AUTH_ACL)) return AUTH_NONE;
if (!$conf['useacl']) return AUTH_UPLOAD;
if (!$auth) return AUTH_NONE;
if (!is_array($AUTH_ACL)) return AUTH_NONE;
//make sure groups is an array
if(!is_array($groups)) $groups = [];
if (!is_array($groups)) $groups = [];
//if user is superuser or in superusergroup return 255 (acl_admin)
if(auth_isadmin($user, $groups)) {
if (auth_isadmin($user, $groups)) {
return AUTH_ADMIN;
}
if(!$auth->isCaseSensitive()) {
if (!$auth->isCaseSensitive()) {
$user = PhpString::strtolower($user);
$groups = array_map([PhpString::class, 'strtolower'], $groups);
}
@ -666,7 +665,7 @@ function auth_aclcheck_cb($data)
$groups = array_map([$auth, 'cleanGroup'], $groups);
//prepend groups with @ and nameencode
foreach($groups as &$group) {
foreach ($groups as &$group) {
$group = '@'.auth_nameencode($group);
}
@ -677,33 +676,33 @@ function auth_aclcheck_cb($data)
$groups[] = '@ALL';
//add User
if($user) $groups[] = $user;
if ($user) $groups[] = $user;
//check exact match first
$matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
if(count($matches)) {
foreach($matches as $match) {
if (count($matches)) {
foreach ($matches as $match) {
$match = preg_replace('/#.*$/', '', $match); //ignore comments
$acl = preg_split('/[ \t]+/', $match);
if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
$acl[1] = PhpString::strtolower($acl[1]);
}
if(!in_array($acl[1], $groups)) {
if (!in_array($acl[1], $groups)) {
continue;
}
if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
if($acl[2] > $perm) {
if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
if ($acl[2] > $perm) {
$perm = $acl[2];
}
}
if($perm > -1) {
if ($perm > -1) {
//we had a match - return it
return (int) $perm;
}
}
//still here? do the namespace checks
if($ns) {
if ($ns) {
$path = $ns.':*';
} else {
$path = '*'; //root document
@ -711,32 +710,32 @@ function auth_aclcheck_cb($data)
do {
$matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
if(count($matches)) {
foreach($matches as $match) {
if (count($matches)) {
foreach ($matches as $match) {
$match = preg_replace('/#.*$/', '', $match); //ignore comments
$acl = preg_split('/[ \t]+/', $match);
if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
$acl[1] = PhpString::strtolower($acl[1]);
}
if(!in_array($acl[1], $groups)) {
if (!in_array($acl[1], $groups)) {
continue;
}
if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
if($acl[2] > $perm) {
if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
if ($acl[2] > $perm) {
$perm = $acl[2];
}
}
//we had a match - return it
if($perm != -1) {
if ($perm != -1) {
return (int) $perm;
}
}
//get next higher namespace
$ns = getNS($ns);
if($path != '*') {
if ($path != '*') {
$path = $ns.':*';
if($path == ':*') $path = '*';
if ($path == ':*') $path = '*';
} else {
//we did this already
//looks like there is something wrong with the ACL
@ -744,7 +743,7 @@ function auth_aclcheck_cb($data)
msg('No ACL setup yet! Denying access to everyone.');
return AUTH_NONE;
}
} while(1); //this should never loop endless
} while (1); //this should never loop endless
return AUTH_NONE;
}
@ -772,11 +771,11 @@ function auth_nameencode($name, $skip_group = false)
$name = (string) $name;
// never encode wildcard FS#1955
if($name == '%USER%') return $name;
if($name == '%GROUP%') return $name;
if ($name == '%USER%') return $name;
if ($name == '%GROUP%') return $name;
if(!isset($cache[$name][$skip_group])) {
if($skip_group && $name[0] == '@') {
if (!isset($cache[$name][$skip_group])) {
if ($skip_group && $name[0] == '@') {
$cache[$name][$skip_group] = '@'.preg_replace_callback(
'/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
'auth_nameencode_callback',
@ -826,14 +825,14 @@ function auth_pwgen($foruser = '')
];
$evt = new Event('AUTH_PASSWORD_GENERATE', $data);
if($evt->advise_before(true)) {
if ($evt->advise_before(true)) {
$c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
$v = 'aeiou'; //vowels
$a = $c.$v; //both
$s = '!$%&?+*~#-_:.;,'; // specials
//use thre syllables...
for($i = 0; $i < 3; $i++) {
for ($i = 0; $i < 3; $i++) {
$data['password'] .= $c[auth_random(0, strlen($c) - 1)];
$data['password'] .= $v[auth_random(0, strlen($v) - 1)];
$data['password'] .= $a[auth_random(0, strlen($a) - 1)];
@ -860,12 +859,12 @@ function auth_sendPassword($user, $password)
global $lang;
/* @var AuthPlugin $auth */
global $auth;
if(!$auth) return false;
if (!$auth) return false;
$user = $auth->cleanUser($user);
$userinfo = $auth->getUserData($user, $requireGroups = false);
if(!$userinfo['mail']) return false;
if (!$userinfo['mail']) return false;
$text = rawLocale('password');
$trep = [
@ -898,8 +897,8 @@ function register()
global $auth;
global $INPUT;
if(!$INPUT->post->bool('save')) return false;
if(!actionOK('register')) return false;
if (!$INPUT->post->bool('save')) return false;
if (!actionOK('register')) return false;
// gather input
$login = trim($auth->cleanUser($INPUT->post->str('login')));
@ -908,29 +907,29 @@ function register()
$pass = $INPUT->post->str('pass');
$passchk = $INPUT->post->str('passchk');
if(empty($login) || empty($fullname) || empty($email)) {
if (empty($login) || empty($fullname) || empty($email)) {
msg($lang['regmissing'], -1);
return false;
}
if($conf['autopasswd']) {
if ($conf['autopasswd']) {
$pass = auth_pwgen($login); // automatically generate password
} elseif(empty($pass) || empty($passchk)) {
} elseif (empty($pass) || empty($passchk)) {
msg($lang['regmissing'], -1); // complain about missing passwords
return false;
} elseif($pass != $passchk) {
} elseif ($pass != $passchk) {
msg($lang['regbadpass'], -1); // complain about misspelled passwords
return false;
}
//check mail
if(!mail_isvalid($email)) {
if (!mail_isvalid($email)) {
msg($lang['regbadmail'], -1);
return false;
}
//okay try to create the user
if(!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
msg($lang['regfail'], -1);
return false;
}
@ -940,13 +939,13 @@ function register()
$subscription->sendRegister($login, $fullname, $email);
// are we done?
if(!$conf['autopasswd']) {
if (!$conf['autopasswd']) {
msg($lang['regsuccess2'], 1);
return true;
}
// autogenerated password? then send password to user
if(auth_sendPassword($login, $pass)) {
if (auth_sendPassword($login, $pass)) {
msg($lang['regsuccess'], 1);
return true;
} else {
@ -969,10 +968,10 @@ function updateprofile()
/* @var Input $INPUT */
global $INPUT;
if(!$INPUT->post->bool('save')) return false;
if(!checkSecurityToken()) return false;
if (!$INPUT->post->bool('save')) return false;
if (!checkSecurityToken()) return false;
if(!actionOK('profile')) {
if (!actionOK('profile')) {
msg($lang['profna'], -1);
return false;
}
@ -983,7 +982,7 @@ function updateprofile()
$changes['mail'] = $INPUT->post->str('email');
// check misspelled passwords
if($changes['pass'] != $INPUT->post->str('passchk')) {
if ($changes['pass'] != $INPUT->post->str('passchk')) {
msg($lang['regbadpass'], -1);
return false;
}
@ -993,13 +992,13 @@ function updateprofile()
$changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
// no empty name and email (except the backend doesn't support them)
if((empty($changes['name']) && $auth->canDo('modName')) ||
if ((empty($changes['name']) && $auth->canDo('modName')) ||
(empty($changes['mail']) && $auth->canDo('modMail'))
) {
msg($lang['profnoempty'], -1);
return false;
}
if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
msg($lang['regbadmail'], -1);
return false;
}
@ -1007,29 +1006,29 @@ function updateprofile()
$changes = array_filter($changes);
// check for unavailable capabilities
if(!$auth->canDo('modName')) unset($changes['name']);
if(!$auth->canDo('modMail')) unset($changes['mail']);
if(!$auth->canDo('modPass')) unset($changes['pass']);
if (!$auth->canDo('modName')) unset($changes['name']);
if (!$auth->canDo('modMail')) unset($changes['mail']);
if (!$auth->canDo('modPass')) unset($changes['pass']);
// anything to do?
if($changes === []) {
if ($changes === []) {
msg($lang['profnochange'], -1);
return false;
}
if($conf['profileconfirm']) {
if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
if ($conf['profileconfirm']) {
if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
msg($lang['badpassconfirm'], -1);
return false;
}
}
if(!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
msg($lang['proffail'], -1);
return false;
}
if($changes['pass']) {
if ($changes['pass']) {
// update cookie and session with the changed data
[/* user */, $sticky, /* pass */] = auth_getCookie();
$pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
@ -1059,22 +1058,22 @@ function auth_deleteprofile()
/* @var Input $INPUT */
global $INPUT;
if(!$INPUT->post->bool('delete')) return false;
if(!checkSecurityToken()) return false;
if (!$INPUT->post->bool('delete')) return false;
if (!checkSecurityToken()) return false;
// action prevented or auth module disallows
if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
msg($lang['profnodelete'], -1);
return false;
}
if(!$INPUT->post->bool('confirm_delete')){
if (!$INPUT->post->bool('confirm_delete')) {
msg($lang['profconfdeletemissing'], -1);
return false;
}
if($conf['profileconfirm']) {
if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
if ($conf['profileconfirm']) {
if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
msg($lang['badpassconfirm'], -1);
return false;
}
@ -1082,7 +1081,7 @@ function auth_deleteprofile()
$deleted = [];
$deleted[] = $INPUT->server->str('REMOTE_USER');
if($auth->triggerUserMod('delete', [$deleted])) {
if ($auth->triggerUserMod('delete', [$deleted])) {
// force and immediate logout including removing the sticky cookie
auth_logoff();
return true;
@ -1114,24 +1113,24 @@ function act_resendpwd()
/* @var Input $INPUT */
global $INPUT;
if(!actionOK('resendpwd')) {
if (!actionOK('resendpwd')) {
msg($lang['resendna'], -1);
return false;
}
$token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
if($token) {
if ($token) {
// we're in token phase - get user info from token
$tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
if(!file_exists($tfile)) {
if (!file_exists($tfile)) {
msg($lang['resendpwdbadauth'], -1);
$INPUT->remove('pwauth');
return false;
}
// token is only valid for 3 days
if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
msg($lang['resendpwdbadauth'], -1);
$INPUT->remove('pwauth');
@unlink($tfile);
@ -1140,36 +1139,34 @@ function act_resendpwd()
$user = io_readfile($tfile);
$userinfo = $auth->getUserData($user, $requireGroups = false);
if(!$userinfo['mail']) {
if (!$userinfo['mail']) {
msg($lang['resendpwdnouser'], -1);
return false;
}
if(!$conf['autopasswd']) { // we let the user choose a password
if (!$conf['autopasswd']) { // we let the user choose a password
$pass = $INPUT->str('pass');
// password given correctly?
if(!$pass) return false;
if($pass != $INPUT->str('passchk')) {
if (!$pass) return false;
if ($pass != $INPUT->str('passchk')) {
msg($lang['regbadpass'], -1);
return false;
}
// change it
if(!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
msg($lang['proffail'], -1);
return false;
}
} else { // autogenerate the password and send by mail
$pass = auth_pwgen($user);
if(!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
msg($lang['proffail'], -1);
return false;
}
if(auth_sendPassword($user, $pass)) {
if (auth_sendPassword($user, $pass)) {
msg($lang['resendpwdsuccess'], 1);
} else {
msg($lang['regmailfail'], -1);
@ -1178,13 +1175,12 @@ function act_resendpwd()
@unlink($tfile);
return true;
} else {
// we're in request phase
if(!$INPUT->post->bool('save')) return false;
if (!$INPUT->post->bool('save')) return false;
if(!$INPUT->post->str('login')) {
if (!$INPUT->post->str('login')) {
msg($lang['resendpwdmissing'], -1);
return false;
} else {
@ -1192,7 +1188,7 @@ function act_resendpwd()
}
$userinfo = $auth->getUserData($user, $requireGroups = false);
if(!$userinfo['mail']) {
if (!$userinfo['mail']) {
msg($lang['resendpwdnouser'], -1);
return false;
}
@ -1211,7 +1207,7 @@ function act_resendpwd()
$mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
$mail->subject($lang['regpwmail']);
$mail->setBody($text, $trep);
if($mail->send()) {
if ($mail->send()) {
msg($lang['resendpwdconfirm'], 1);
} else {
msg($lang['regmailfail'], -1);
@ -1237,12 +1233,12 @@ function act_resendpwd()
function auth_cryptPassword($clear, $method = '', $salt = null)
{
global $conf;
if(empty($method)) $method = $conf['passcrypt'];
if (empty($method)) $method = $conf['passcrypt'];
$pass = new PassHash();
$call = 'hash_'.$method;
if(!method_exists($pass, $call)) {
if (!method_exists($pass, $call)) {
msg("Unsupported crypt method $method", -1);
return false;
}
@ -1280,7 +1276,7 @@ function auth_setCookie($user, $pass, $sticky)
global $auth;
global $USERINFO;
if(!$auth) return false;
if (!$auth) return false;
$USERINFO = $auth->getUserData($user);
// set cookie
@ -1312,7 +1308,7 @@ function auth_setCookie($user, $pass, $sticky)
*/
function auth_getCookie()
{
if(!isset($_COOKIE[DOKU_COOKIE])) {
if (!isset($_COOKIE[DOKU_COOKIE])) {
return [null, null, null];
}
[$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');

View File

@ -223,7 +223,7 @@ function getRecents($first, $num, $ns = '', $flags = 0)
} else {
$lines_position--;
$x = $rec;
if ($flags & RECENTS_MEDIA_CHANGES){
if ($flags & RECENTS_MEDIA_CHANGES) {
$x['media'] = true;
} else {
$x['media'] = false;
@ -234,7 +234,8 @@ function getRecents($first, $num, $ns = '', $flags = 0)
$recent[] = $x;
$count++;
// break when we have enough entries
if ($count >= $num) { break; }
if ($count >= $num) {
break; }
}
return $recent;
}

View File

@ -73,11 +73,11 @@ function sexplode($separator, $string, $limit, $default = null)
*/
function blank(&$in, $trim = false)
{
if(is_null($in)) return true;
if(is_array($in)) return $in === [];
if($in === "\0") return true;
if($trim && trim($in) === '') return true;
if(strlen($in) > 0) return false;
if (is_null($in)) return true;
if (is_array($in)) return $in === [];
if ($in === "\0") return true;
if ($trim && trim($in) === '') return true;
if (strlen($in) > 0) return false;
return empty($in);
}
@ -127,7 +127,7 @@ function getSecurityToken()
$session = session_id();
// CSRF checks are only for logged in users - do not generate for anonymous
if(trim($user) == '' || trim($session) == '') return '';
if (trim($user) == '' || trim($session) == '') return '';
return PassHash::hmac('md5', $session.$user, auth_cookiesalt());
}
@ -141,10 +141,10 @@ function checkSecurityToken($token = null)
{
/** @var Input $INPUT */
global $INPUT;
if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
if (!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
if(is_null($token)) $token = $INPUT->str('sectok');
if(getSecurityToken() != $token) {
if (is_null($token)) $token = $INPUT->str('sectok');
if (getSecurityToken() != $token) {
msg('Security Token did not match. Possible CSRF attack.', -1);
return false;
}
@ -162,7 +162,7 @@ function checkSecurityToken($token = null)
function formSecurityToken($print = true)
{
$ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
if($print) echo $ret;
if ($print) echo $ret;
return $ret;
}
@ -187,23 +187,22 @@ function basicinfo($id, $htmlClient = true)
$info = [];
$info['isadmin'] = false;
$info['ismanager'] = false;
if($INPUT->server->has('REMOTE_USER')) {
if ($INPUT->server->has('REMOTE_USER')) {
$info['userinfo'] = $USERINFO;
$info['perm'] = auth_quickaclcheck($id);
$info['client'] = $INPUT->server->str('REMOTE_USER');
if($info['perm'] == AUTH_ADMIN) {
if ($info['perm'] == AUTH_ADMIN) {
$info['isadmin'] = true;
$info['ismanager'] = true;
} elseif(auth_ismanager()) {
} elseif (auth_ismanager()) {
$info['ismanager'] = true;
}
// if some outside auth were used only REMOTE_USER is set
if(empty($info['userinfo']['name'])) {
if (empty($info['userinfo']['name'])) {
$info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
}
} else {
$info['perm'] = auth_aclcheck($id, '', null);
$info['client'] = clientIP(true);
@ -371,8 +370,8 @@ function buildURLparams($params, $sep = '&amp;')
{
$url = '';
$amp = false;
foreach($params as $key => $val) {
if($amp) $url .= $sep;
foreach ($params as $key => $val) {
if ($amp) $url .= $sep;
$url .= rawurlencode($key).'=';
$url .= rawurlencode((string) $val);
@ -396,10 +395,10 @@ function buildAttributes($params, $skipEmptyStrings = false)
{
$url = '';
$white = false;
foreach($params as $key => $val) {
if($key[0] == '_') continue;
if($val === '' && $skipEmptyStrings) continue;
if($white) $url .= ' ';
foreach ($params as $key => $val) {
if ($key[0] == '_') continue;
if ($val === '' && $skipEmptyStrings) continue;
if ($white) $url .= ' ';
$url .= $key.'="';
$url .= hsc($val);
@ -420,7 +419,7 @@ function breadcrumbs()
{
// we prepare the breadcrumbs early for quick session closing
static $crumbs = null;
if($crumbs != null) return $crumbs;
if ($crumbs != null) return $crumbs;
global $ID;
global $ACT;
@ -431,30 +430,30 @@ function breadcrumbs()
$crumbs = $_SESSION[DOKU_COOKIE]['bc'] ?? [];
//we only save on show and existing visible readable wiki documents
$file = wikiFN($ID);
if($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
if ($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
$_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
return $crumbs;
}
// page names
$name = noNSorNS($ID);
if(useHeading('navigation')) {
if (useHeading('navigation')) {
// get page title
$title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
if($title) {
if ($title) {
$name = $title;
}
}
//remove ID from array
if(isset($crumbs[$ID])) {
if (isset($crumbs[$ID])) {
unset($crumbs[$ID]);
}
//add to array
$crumbs[$ID] = $name;
//reduce size
while(count($crumbs) > $conf['breadcrumbs']) {
while (count($crumbs) > $conf['breadcrumbs']) {
array_shift($crumbs);
}
//save to session
@ -489,15 +488,15 @@ function idfilter($id, $ue = true)
$id = (string) $id;
if($conf['useslash'] && $conf['userewrite']) {
if ($conf['useslash'] && $conf['userewrite']) {
$id = strtr($id, ':', '/');
} elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
} elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
$conf['userewrite'] &&
strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
) {
$id = strtr($id, ':', ';');
}
if($ue) {
if ($ue) {
$id = rawurlencode($id);
$id = str_replace('%3A', ':', $id); //keep as colon
$id = str_replace('%3B', ';', $id); //keep as semicolon
@ -522,37 +521,37 @@ function idfilter($id, $ue = true)
function wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;')
{
global $conf;
if(is_array($urlParameters)) {
if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
if(isset($urlParameters['at']) && $conf['date_at_format']) {
if (is_array($urlParameters)) {
if (isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
if (isset($urlParameters['at']) && $conf['date_at_format']) {
$urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
}
$urlParameters = buildURLparams($urlParameters, $separator);
} else {
$urlParameters = str_replace(',', $separator, $urlParameters);
}
if($id === '') {
if ($id === '') {
$id = $conf['start'];
}
$id = idfilter($id);
if($absolute) {
if ($absolute) {
$xlink = DOKU_URL;
} else {
$xlink = DOKU_BASE;
}
if($conf['userewrite'] == 2) {
if ($conf['userewrite'] == 2) {
$xlink .= DOKU_SCRIPT.'/'.$id;
if($urlParameters) $xlink .= '?'.$urlParameters;
} elseif($conf['userewrite']) {
if ($urlParameters) $xlink .= '?'.$urlParameters;
} elseif ($conf['userewrite']) {
$xlink .= $id;
if($urlParameters) $xlink .= '?'.$urlParameters;
} elseif($id !== '') {
if ($urlParameters) $xlink .= '?'.$urlParameters;
} elseif ($id !== '') {
$xlink .= DOKU_SCRIPT.'?id='.$id;
if($urlParameters) $xlink .= $separator.$urlParameters;
if ($urlParameters) $xlink .= $separator.$urlParameters;
} else {
$xlink .= DOKU_SCRIPT;
if($urlParameters) $xlink .= '?'.$urlParameters;
if ($urlParameters) $xlink .= '?'.$urlParameters;
}
return $xlink;
@ -574,7 +573,7 @@ function wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp
function exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;')
{
global $conf;
if(is_array($urlParameters)) {
if (is_array($urlParameters)) {
$urlParameters = buildURLparams($urlParameters, $sep);
} else {
$urlParameters = str_replace(',', $sep, $urlParameters);
@ -582,21 +581,21 @@ function exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false
$format = rawurlencode($format);
$id = idfilter($id);
if($abs) {
if ($abs) {
$xlink = DOKU_URL;
} else {
$xlink = DOKU_BASE;
}
if($conf['userewrite'] == 2) {
if ($conf['userewrite'] == 2) {
$xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
if($urlParameters) $xlink .= $sep.$urlParameters;
} elseif($conf['userewrite'] == 1) {
if ($urlParameters) $xlink .= $sep.$urlParameters;
} elseif ($conf['userewrite'] == 1) {
$xlink .= '_export/'.$format.'/'.$id;
if($urlParameters) $xlink .= '?'.$urlParameters;
if ($urlParameters) $xlink .= '?'.$urlParameters;
} else {
$xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
if($urlParameters) $xlink .= $sep.$urlParameters;
if ($urlParameters) $xlink .= $sep.$urlParameters;
}
return $xlink;
@ -621,29 +620,29 @@ function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
{
global $conf;
$isexternalimage = media_isexternal($id);
if(!$isexternalimage) {
if (!$isexternalimage) {
$id = cleanID($id);
}
if(is_array($more)) {
if (is_array($more)) {
// add token for resized images
$w = $more['w'] ?? null;
$h = $more['h'] ?? null;
if($w || $h || $isexternalimage){
if ($w || $h || $isexternalimage) {
$more['tok'] = media_get_token($id, $w, $h);
}
// strip defaults for shorter URLs
if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
if(empty($more['w'])) unset($more['w']);
if(empty($more['h'])) unset($more['h']);
if(isset($more['id']) && $direct) unset($more['id']);
if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
if (isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
if (empty($more['w'])) unset($more['w']);
if (empty($more['h'])) unset($more['h']);
if (isset($more['id']) && $direct) unset($more['id']);
if (isset($more['rev']) && !$more['rev']) unset($more['rev']);
$more = buildURLparams($more, $sep);
} else {
$matches = [];
if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage){
if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage) {
$resize = ['w'=>0, 'h'=>0];
foreach ($matches as $match){
foreach ($matches as $match) {
$resize[$match[1]] = $match[2];
}
$more .= $more === '' ? '' : $sep;
@ -654,14 +653,14 @@ function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
$more = str_replace(',', $sep, $more);
}
if($abs) {
if ($abs) {
$xlink = DOKU_URL;
} else {
$xlink = DOKU_BASE;
}
// external URLs are always direct without rewriting
if($isexternalimage) {
if ($isexternalimage) {
$xlink .= 'lib/exe/fetch.php';
$xlink .= '?'.$more;
$xlink .= $sep.'media='.rawurlencode($id);
@ -672,7 +671,7 @@ function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
// decide on scriptname
if ($direct) {
if($conf['userewrite'] == 1) {
if ($conf['userewrite'] == 1) {
$script = '_media';
} else {
$script = 'lib/exe/fetch.php';
@ -686,7 +685,7 @@ function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
// build URL based on rewrite mode
if ($conf['userewrite']) {
$xlink .= $script.'/'.$id;
if($more) $xlink .= '?'.$more;
if ($more) $xlink .= '?'.$more;
} elseif ($more) {
$xlink .= $script.'?'.$more;
$xlink .= $sep.'media='.$id;
@ -747,9 +746,9 @@ function checkwordblock($text = '')
/* @var Input $INPUT */
global $INPUT;
if(!$conf['usewordblock']) return false;
if (!$conf['usewordblock']) return false;
if(!$text) $text = "$PRE $TEXT $SUF $SUM";
if (!$text) $text = "$PRE $TEXT $SUF $SUM";
// we prepare the text a tiny bit to prevent spammers circumventing URL checks
// phpcs:disable Generic.Files.LineLength.TooLong
@ -765,21 +764,21 @@ function checkwordblock($text = '')
// MAX_PATTERN_SIZE in modern PCRE
$chunksize = 200;
while($blocks = array_splice($wordblocks, 0, $chunksize)) {
while ($blocks = array_splice($wordblocks, 0, $chunksize)) {
$re = [];
// build regexp from blocks
foreach($blocks as $block) {
foreach ($blocks as $block) {
$block = preg_replace('/#.*$/', '', $block);
$block = trim($block);
if(empty($block)) continue;
if (empty($block)) continue;
$re[] = $block;
}
if(count($re) && preg_match('#('.implode('|', $re).')#si', $text, $matches)) {
if (count($re) && preg_match('#('.implode('|', $re).')#si', $text, $matches)) {
// prepare event data
$data = [];
$data['matches'] = $matches;
$data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
if($INPUT->server->str('REMOTE_USER')) {
if ($INPUT->server->str('REMOTE_USER')) {
$data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
$data['userinfo']['name'] = $INFO['userinfo']['name'];
$data['userinfo']['mail'] = $INFO['userinfo']['mail'];
@ -813,28 +812,28 @@ function clientIP($single = false)
$ip = [];
$ip[] = $INPUT->server->str('REMOTE_ADDR');
if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
if ($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
$ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
}
if($INPUT->server->str('HTTP_X_REAL_IP')) {
if ($INPUT->server->str('HTTP_X_REAL_IP')) {
$ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
}
// remove any non-IP stuff
$cnt = count($ip);
for($i = 0; $i < $cnt; $i++) {
if(filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
for ($i = 0; $i < $cnt; $i++) {
if (filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
unset($ip[$i]);
}
}
$ip = array_values(array_unique($ip));
if($ip === [] || !$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
if ($ip === [] || !$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
if(!$single) return implode(',', $ip);
if (!$single) return implode(',', $ip);
// skip trusted local addresses
foreach($ip as $i) {
if(!empty($conf['trustedproxy']) && preg_match('/'.$conf['trustedproxy'].'/', $i)) {
foreach ($ip as $i) {
if (!empty($conf['trustedproxy']) && preg_match('/'.$conf['trustedproxy'].'/', $i)) {
continue;
} else {
return $i;
@ -861,11 +860,11 @@ function clientismobile()
/* @var Input $INPUT */
global $INPUT;
if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
if ($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
if (preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
if (!$INPUT->server->has('HTTP_USER_AGENT')) return false;
$uamatches = implode(
'|',
@ -880,7 +879,7 @@ function clientismobile()
]
);
if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
if (preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
return false;
}
@ -910,13 +909,13 @@ function link_isinterwiki($link)
function gethostsbyaddrs($ips)
{
global $conf;
if(!$conf['dnslookups']) return $ips;
if (!$conf['dnslookups']) return $ips;
$hosts = [];
$ips = explode(',', $ips);
if(is_array($ips)) {
foreach($ips as $ip) {
if (is_array($ips)) {
foreach ($ips as $ip) {
$hosts[] = gethostbyaddr(trim($ip));
}
return implode(',', $hosts);
@ -944,17 +943,17 @@ function checklock($id)
$lock = wikiLockFN($id);
//no lockfile
if(!file_exists($lock)) return false;
if (!file_exists($lock)) return false;
//lockfile expired
if((time() - filemtime($lock)) > $conf['locktime']) {
if ((time() - filemtime($lock)) > $conf['locktime']) {
@unlink($lock);
return false;
}
//my own lock
@[$ip, $session] = explode("\n", io_readFile($lock));
if($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
if ($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
return false;
}
@ -974,12 +973,12 @@ function lock($id)
/* @var Input $INPUT */
global $INPUT;
if($conf['locktime'] == 0) {
if ($conf['locktime'] == 0) {
return;
}
$lock = wikiLockFN($id);
if($INPUT->server->str('REMOTE_USER')) {
if ($INPUT->server->str('REMOTE_USER')) {
io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
} else {
io_saveFile($lock, clientIP()."\n".session_id());
@ -1000,9 +999,9 @@ function unlock($id)
global $INPUT;
$lock = wikiLockFN($id);
if(file_exists($lock)) {
if (file_exists($lock)) {
@[$ip, $session] = explode("\n", io_readFile($lock));
if($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
if ($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
@unlink($lock);
return true;
}
@ -1028,7 +1027,7 @@ function cleanText($text)
// if the text is not valid UTF-8 we simply assume latin1
// this won't break any worse than it breaks with the wrong encoding
// but might actually fix the problem in many cases
if(!Clean::isUtf8($text)) $text = utf8_encode($text);
if (!Clean::isUtf8($text)) $text = utf8_encode($text);
return $text;
}
@ -1091,7 +1090,7 @@ function pageTemplate($id)
{
global $conf;
if(is_array($id)) $id = $id[0];
if (is_array($id)) $id = $id[0];
// prepare initial event data
$data = [
@ -1102,19 +1101,19 @@ function pageTemplate($id)
];
$evt = new Event('COMMON_PAGETPL_LOAD', $data);
if($evt->advise_before(true)) {
if ($evt->advise_before(true)) {
// the before event might have loaded the content already
if(empty($data['tpl'])) {
if (empty($data['tpl'])) {
// if the before event did not set a template file, try to find one
if(empty($data['tplfile'])) {
if (empty($data['tplfile'])) {
$path = dirname(wikiFN($id));
if(file_exists($path.'/_template.txt')) {
if (file_exists($path.'/_template.txt')) {
$data['tplfile'] = $path.'/_template.txt';
} else {
// search upper namespaces for templates
$len = strlen(rtrim($conf['datadir'], '/'));
while(strlen($path) >= $len) {
if(file_exists($path.'/__template.txt')) {
while (strlen($path) >= $len) {
if (file_exists($path.'/__template.txt')) {
$data['tplfile'] = $path.'/__template.txt';
break;
}
@ -1125,7 +1124,7 @@ function pageTemplate($id)
// load the content
$data['tpl'] = io_readFile($data['tplfile']);
}
if($data['doreplace']) parsePageTemplate($data);
if ($data['doreplace']) parsePageTemplate($data);
}
$evt->advise_after();
unset($evt);
@ -1262,13 +1261,13 @@ function rawWikiSlices($range, $id, $rev = '')
*/
function con($pre, $text, $suf, $pretty = false)
{
if($pretty) {
if($pre !== '' && substr($pre, -1) !== "\n" &&
if ($pretty) {
if ($pre !== '' && substr($pre, -1) !== "\n" &&
substr($text, 0, 1) !== "\n"
) {
$pre .= "\n";
}
if($suf !== '' && substr($text, -1) !== "\n" &&
if ($suf !== '' && substr($text, -1) !== "\n" &&
substr($suf, 0, 1) !== "\n"
) {
$text .= "\n";
@ -1312,7 +1311,7 @@ function saveWikiText($id, $text, $summary, $minor = false)
// get COMMON_WIKIPAGE_SAVE event data
$data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
if(!$data) return; // save was cancelled (for no changes or by a plugin)
if (!$data) return; // save was cancelled (for no changes or by a plugin)
// send notify mails
['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
@ -1403,32 +1402,32 @@ function getGoogleQuery()
/* @var Input $INPUT */
global $INPUT;
if(!$INPUT->server->has('HTTP_REFERER')) {
if (!$INPUT->server->has('HTTP_REFERER')) {
return '';
}
$url = parse_url($INPUT->server->str('HTTP_REFERER'));
// only handle common SEs
if(!array_key_exists('host', $url)) return '';
if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
if (!array_key_exists('host', $url)) return '';
if (!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
$query = [];
if(!array_key_exists('query', $url)) return '';
if (!array_key_exists('query', $url)) return '';
parse_str($url['query'], $query);
$q = '';
if(isset($query['q'])){
if (isset($query['q'])) {
$q = $query['q'];
}elseif(isset($query['p'])){
} elseif (isset($query['p'])) {
$q = $query['p'];
}elseif(isset($query['query'])){
} elseif (isset($query['query'])) {
$q = $query['query'];
}
$q = trim($q);
if(!$q) return '';
if (!$q) return '';
// ignore if query includes a full URL
if(strpos($q, '//') !== false) return '';
if (strpos($q, '//') !== false) return '';
$q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
return $q;
}
@ -1450,7 +1449,7 @@ function filesize_h($size, $dec = 1)
$count = count($sizes);
$i = 0;
while($size >= 1024 && ($i < $count - 1)) {
while ($size >= 1024 && ($i < $count - 1)) {
$size /= 1024;
$i++;
}
@ -1471,22 +1470,22 @@ function datetime_h($dt)
global $lang;
$ago = time() - $dt;
if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
if ($ago > 24 * 60 * 60 * 30 * 12 * 2) {
return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
}
if($ago > 24 * 60 * 60 * 30 * 2) {
if ($ago > 24 * 60 * 60 * 30 * 2) {
return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
}
if($ago > 24 * 60 * 60 * 7 * 2) {
if ($ago > 24 * 60 * 60 * 7 * 2) {
return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
}
if($ago > 24 * 60 * 60 * 2) {
if ($ago > 24 * 60 * 60 * 2) {
return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
}
if($ago > 60 * 60 * 2) {
if ($ago > 60 * 60 * 2) {
return sprintf($lang['hours'], round($ago / (60 * 60)));
}
if($ago > 60 * 2) {
if ($ago > 60 * 2) {
return sprintf($lang['minutes'], round($ago / (60)));
}
return sprintf($lang['seconds'], $ago);
@ -1509,9 +1508,9 @@ function dformat($dt = null, $format = '')
{
global $conf;
if(is_null($dt)) $dt = time();
if (is_null($dt)) $dt = time();
$dt = (int) $dt;
if(!$format) $format = $conf['dformat'];
if (!$format) $format = $conf['dformat'];
$format = str_replace('%f', datetime_h($dt), $format);
return strftime($format, $dt);
@ -1548,7 +1547,7 @@ function obfuscate($email)
{
global $conf;
switch($conf['mailguard']) {
switch ($conf['mailguard']) {
case 'visible' :
$obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
return strtr($email, $obfuscate);
@ -1635,9 +1634,9 @@ function preg_quote_cb($string)
function shorten($keep, $short, $max, $min = 9, $char = '…')
{
$max -= PhpString::strlen($keep);
if($max < $min) return $keep;
if ($max < $min) return $keep;
$len = PhpString::strlen($short);
if($len <= $max) return $keep.$short;
if ($len <= $max) return $keep.$short;
$half = floor($max / 2);
return $keep .
PhpString::substr($short, 0, $half - 1) .
@ -1695,22 +1694,22 @@ function userlink($username = null, $textonly = false)
'userlink' => '', // formatted user name as will be returned
'textonly' => $textonly,
];
if($username === null) {
if ($username === null) {
$data['username'] = $username = $INPUT->server->str('REMOTE_USER');
if($textonly){
if ($textonly) {
$data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
}else {
} else {
$data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
'(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
}
}
$evt = new Event('COMMON_USER_LINK', $data);
if($evt->advise_before(true)) {
if(empty($data['name'])) {
if($auth) $info = $auth->getUserData($username);
if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
switch($conf['showuseras']) {
if ($evt->advise_before(true)) {
if (empty($data['name'])) {
if ($auth) $info = $auth->getUserData($username);
if ($conf['showuseras'] != 'loginname' && isset($info) && $info) {
switch ($conf['showuseras']) {
case 'username':
case 'username_link':
$data['name'] = $textonly ? $info['name'] : hsc($info['name']);
@ -1728,28 +1727,27 @@ function userlink($username = null, $textonly = false)
/** @var Doku_Renderer_xhtml $xhtml_renderer */
static $xhtml_renderer = null;
if(!$data['textonly'] && empty($data['link']['url'])) {
if(in_array($conf['showuseras'], ['email_link', 'username_link'])) {
if(!isset($info)) {
if($auth) $info = $auth->getUserData($username);
if (!$data['textonly'] && empty($data['link']['url'])) {
if (in_array($conf['showuseras'], ['email_link', 'username_link'])) {
if (!isset($info)) {
if ($auth) $info = $auth->getUserData($username);
}
if(isset($info) && $info) {
if($conf['showuseras'] == 'email_link') {
if (isset($info) && $info) {
if ($conf['showuseras'] == 'email_link') {
$data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
} else {
if(is_null($xhtml_renderer)) {
if (is_null($xhtml_renderer)) {
$xhtml_renderer = p_get_renderer('xhtml');
}
if(empty($xhtml_renderer->interwiki)) {
if (empty($xhtml_renderer->interwiki)) {
$xhtml_renderer->interwiki = getInterwiki();
}
$shortcut = 'user';
$exists = null;
$data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
$data['link']['class'] .= ' interwiki iw_user';
if($exists !== null) {
if($exists) {
if ($exists !== null) {
if ($exists) {
$data['link']['class'] .= ' wikilink1';
} else {
$data['link']['class'] .= ' wikilink2';
@ -1760,17 +1758,16 @@ function userlink($username = null, $textonly = false)
} else {
$data['textonly'] = true;
}
} else {
$data['textonly'] = true;
}
}
if($data['textonly']) {
if ($data['textonly']) {
$data['userlink'] = $data['name'];
} else {
$data['link']['name'] = $data['name'];
if(is_null($xhtml_renderer)) {
if (is_null($xhtml_renderer)) {
$xhtml_renderer = p_get_renderer('xhtml');
}
$data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
@ -1795,16 +1792,16 @@ function license_img($type)
{
global $license;
global $conf;
if(!$conf['license']) return '';
if(!is_array($license[$conf['license']])) return '';
if (!$conf['license']) return '';
if (!is_array($license[$conf['license']])) return '';
$try = [];
$try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
$try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
if(substr($conf['license'], 0, 3) == 'cc-') {
if (substr($conf['license'], 0, 3) == 'cc-') {
$try[] = 'lib/images/license/'.$type.'/cc.png';
}
foreach($try as $src) {
if(file_exists(DOKU_INC.$src)) return $src;
foreach ($try as $src) {
if (file_exists(DOKU_INC.$src)) return $src;
}
return '';
}
@ -1825,20 +1822,20 @@ function license_img($type)
function is_mem_available($mem, $bytes = 1_048_576)
{
$limit = trim(ini_get('memory_limit'));
if(empty($limit)) return true; // no limit set!
if($limit == -1) return true; // unlimited
if (empty($limit)) return true; // no limit set!
if ($limit == -1) return true; // unlimited
// parse limit to bytes
$limit = php_to_byte($limit);
// get used memory if possible
if(function_exists('memory_get_usage')) {
if (function_exists('memory_get_usage')) {
$used = memory_get_usage();
} else {
$used = $bytes;
}
if($used + $mem > $limit) {
if ($used + $mem > $limit) {
return false;
}
@ -1864,7 +1861,7 @@ function send_redirect($url)
//are there any undisplayed messages? keep them in session for display
global $MSG;
if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
if (isset($MSG) && count($MSG) && !defined('NOSESSION')) {
//reopen session, store data and close session again
@session_start();
$_SESSION[DOKU_COOKIE]['msg'] = $MSG;
@ -1874,7 +1871,7 @@ function send_redirect($url)
session_write_close();
// check if running on IIS < 6 with CGI-PHP
if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
if ($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
(strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
(preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
$matches[1] < 6
@ -1885,10 +1882,10 @@ function send_redirect($url)
}
// no exits during unit tests
if(defined('DOKU_UNITTEST')) {
if (defined('DOKU_UNITTEST')) {
// pass info about the redirect back to the test suite
$testRequest = TestRequest::getRunning();
if($testRequest !== null) {
if ($testRequest !== null) {
$testRequest->addData('send_redirect', $url);
}
return;
@ -1917,9 +1914,9 @@ function send_redirect($url)
*/
function valid_input_set($param, $valid_values, $array, $exc = '')
{
if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
return $array[$param];
} elseif(isset($valid_values['default'])) {
} elseif (isset($valid_values['default'])) {
return $valid_values['default'];
} else {
throw new Exception($exc);
@ -1937,14 +1934,14 @@ function valid_input_set($param, $valid_values, $array, $exc = '')
function get_doku_pref($pref, $default)
{
$enc_pref = urlencode($pref);
if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
if (isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
$parts = explode('#', $_COOKIE['DOKU_PREFS']);
$cnt = count($parts);
// due to #2721 there might be duplicate entries,
// so we read from the end
for($i = $cnt-2; $i >= 0; $i -= 2) {
if($parts[$i] === $enc_pref) {
for ($i = $cnt-2; $i >= 0; $i -= 2) {
if ($parts[$i] === $enc_pref) {
return urldecode($parts[$i + 1]);
}
}
@ -1974,7 +1971,7 @@ function set_doku_pref($pref, $val)
$seen = false;
for ($i = 0; $i < $cnt; $i += 2) {
if ($parts[$i] === $enc_pref) {
if (!$seen){
if (!$seen) {
if ($val !== false) {
$parts[$i + 1] = rawurlencode($val ?? '');
} else {
@ -1996,9 +1993,9 @@ function set_doku_pref($pref, $val)
}
$cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
if(defined('DOKU_UNITTEST')) {
if (defined('DOKU_UNITTEST')) {
$_COOKIE['DOKU_PREFS'] = $cookieVal;
}else{
} else {
setcookie('DOKU_PREFS', $cookieVal, [
'expires' => time() + 365 * 24 * 3600,
'path' => $cookieDir,
@ -2034,17 +2031,17 @@ function stripsourcemaps(&$text)
function inlineSVG($file, $maxsize = 2048)
{
$file = trim($file);
if($file === '') return false;
if(!file_exists($file)) return false;
if(filesize($file) > $maxsize) return false;
if(!is_readable($file)) return false;
if ($file === '') return false;
if (!file_exists($file)) return false;
if (filesize($file) > $maxsize) return false;
if (!is_readable($file)) return false;
$content = file_get_contents($file);
$content = preg_replace('/<!--.*?(-->)/s', '', $content); // comments
$content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
$content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
$content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
$content = trim($content);
if(substr($content, 0, 5) !== '<svg ') return false;
if (substr($content, 0, 5) !== '<svg ') return false;
return $content;
}

View File

@ -5,7 +5,7 @@
* This file contains a few functions that might be missing from the PHP build
*/
if(!function_exists('ctype_space')) {
if (!function_exists('ctype_space')) {
/**
* Check for whitespace character(s)
*
@ -15,13 +15,13 @@ if(!function_exists('ctype_space')) {
*/
function ctype_space($text)
{
if(!is_string($text)) return false; #FIXME original treats between -128 and 255 inclusive as ASCII chars
if(trim($text) === '') return true;
if (!is_string($text)) return false; #FIXME original treats between -128 and 255 inclusive as ASCII chars
if (trim($text) === '') return true;
return false;
}
}
if(!function_exists('ctype_digit')) {
if (!function_exists('ctype_digit')) {
/**
* Check for numeric character(s)
*
@ -31,13 +31,13 @@ if(!function_exists('ctype_digit')) {
*/
function ctype_digit($text)
{
if(!is_string($text)) return false; #FIXME original treats between -128 and 255 inclusive as ASCII chars
if(preg_match('/^\d+$/', $text)) return true;
if (!is_string($text)) return false; #FIXME original treats between -128 and 255 inclusive as ASCII chars
if (preg_match('/^\d+$/', $text)) return true;
return false;
}
}
if(!function_exists('gzopen') && function_exists('gzopen64')) {
if (!function_exists('gzopen') && function_exists('gzopen64')) {
/**
* work around for PHP compiled against certain zlib versions #865
*
@ -54,7 +54,7 @@ if(!function_exists('gzopen') && function_exists('gzopen64')) {
}
}
if(!function_exists('gzseek') && function_exists('gzseek64')) {
if (!function_exists('gzseek') && function_exists('gzseek64')) {
/**
* work around for PHP compiled against certain zlib versions #865
*
@ -71,7 +71,7 @@ if(!function_exists('gzseek') && function_exists('gzseek64')) {
}
}
if(!function_exists('gztell') && function_exists('gztell64')) {
if (!function_exists('gztell') && function_exists('gztell64')) {
/**
* work around for PHP compiled against certain zlib versions #865
*

View File

@ -36,16 +36,16 @@ function mimetype($file, $knownonly = true)
return [false, false, false];
}
$ext = strtolower(substr($file, $ext + 1));
if (!isset($mtypes[$ext])){
if (!isset($mtypes[$ext])) {
if ($knownonly) {
return [false, false, false];
} else {
return [$ext, 'application/octet-stream', true];
}
}
if($mtypes[$ext][0] == '!'){
if ($mtypes[$ext][0] == '!') {
return [$ext, substr($mtypes[$ext], 1), true];
}else{
} else {
return [$ext, $mtypes[$ext], false];
}
}
@ -141,9 +141,9 @@ function getCdnUrls()
// load version info
$versions = [];
$lines = file(DOKU_INC . 'lib/scripts/jquery/versions');
foreach($lines as $line) {
foreach ($lines as $line) {
$line = trim(preg_replace('/#.*$/', '', $line));
if($line === '') continue;
if ($line === '') continue;
[$key, $val] = sexplode('=', $line, 2, '');
$key = trim($key);
$val = trim($val);
@ -153,14 +153,14 @@ function getCdnUrls()
$src = [];
$data = ['versions' => $versions, 'src' => &$src];
$event = new Event('CONFUTIL_CDN_SELECT', $data);
if($event->advise_before()) {
if(!$conf['jquerycdn']) {
if ($event->advise_before()) {
if (!$conf['jquerycdn']) {
$jqmod = md5(implode('-', $versions));
$src[] = DOKU_BASE . 'lib/exe/jquery.php' . '?tseed=' . $jqmod;
} elseif($conf['jquerycdn'] == 'jquery') {
} elseif ($conf['jquerycdn'] == 'jquery') {
$src[] = sprintf('https://code.jquery.com/jquery-%s.min.js', $versions['JQ_VERSION']);
$src[] = sprintf('https://code.jquery.com/ui/%s/jquery-ui.min.js', $versions['JQUI_VERSION']);
} elseif($conf['jquerycdn'] == 'cdnjs') {
} elseif ($conf['jquerycdn'] == 'cdnjs') {
$src[] = sprintf(
'https://cdnjs.cloudflare.com/ajax/libs/jquery/%s/jquery.min.js',
$versions['JQ_VERSION']
@ -225,18 +225,18 @@ function linesToHash($lines, $lower = false)
{
$conf = [];
// remove BOM
if(isset($lines[0]) && substr($lines[0], 0, 3) === pack('CCC', 0xef, 0xbb, 0xbf))
if (isset($lines[0]) && substr($lines[0], 0, 3) === pack('CCC', 0xef, 0xbb, 0xbf))
$lines[0] = substr($lines[0], 3);
foreach($lines as $line) {
foreach ($lines as $line) {
//ignore comments (except escaped ones)
$line = preg_replace('/(?<![&\\\\])#.*$/', '', $line);
$line = str_replace('\\#', '#', $line);
$line = trim($line);
if($line === '') continue;
if ($line === '') continue;
$line = preg_split('/\s+/', $line, 2);
$line = array_pad($line, 2, '');
// Build the associative array
if($lower) {
if ($lower) {
$conf[strtolower($line[0])] = $line[1];
} else {
$conf[$line[0]] = $line[1];
@ -308,7 +308,7 @@ function retrieveConfig($type, $fn, $params = null, $combine = 'array_merge')
{
global $config_cascade;
if(!is_array($params)) $params = [];
if (!is_array($params)) $params = [];
$combined = [];
if (!is_array($config_cascade[$type])) trigger_error('Missing config cascade for "'.$type.'"', E_USER_WARNING);
@ -357,7 +357,7 @@ function getConfigFiles($type)
function actionOK($action)
{
static $disabled = null;
if(is_null($disabled) || defined('SIMPLE_TEST')){
if (is_null($disabled) || defined('SIMPLE_TEST')) {
global $conf;
/** @var AuthPlugin $auth */
global $auth;
@ -365,13 +365,13 @@ function actionOK($action)
// prepare disabled actions array and handle legacy options
$disabled = explode(',', $conf['disableactions']);
$disabled = array_map('trim', $disabled);
if((isset($conf['openregister']) && !$conf['openregister']) || is_null($auth) || !$auth->canDo('addUser')) {
if ((isset($conf['openregister']) && !$conf['openregister']) || is_null($auth) || !$auth->canDo('addUser')) {
$disabled[] = 'register';
}
if((isset($conf['resendpasswd']) && !$conf['resendpasswd']) || is_null($auth) || !$auth->canDo('modPass')) {
if ((isset($conf['resendpasswd']) && !$conf['resendpasswd']) || is_null($auth) || !$auth->canDo('modPass')) {
$disabled[] = 'resendpwd';
}
if((isset($conf['subscribers']) && !$conf['subscribers']) || is_null($auth)) {
if ((isset($conf['subscribers']) && !$conf['subscribers']) || is_null($auth)) {
$disabled[] = 'subscribe';
}
if (is_null($auth) || !$auth->canDo('Profile')) {
@ -404,7 +404,7 @@ function actionOK($action)
function useHeading($linktype)
{
static $useHeading = null;
if(defined('DOKU_UNITTEST')) $useHeading = null; // don't cache during unit tests
if (defined('DOKU_UNITTEST')) $useHeading = null; // don't cache during unit tests
if (is_null($useHeading)) {
global $conf;

View File

@ -49,8 +49,8 @@ function sendFile($file, $mime, $dl, $cache, $public = false, $orig = null, $csp
}
// smart http caching headers
if($maxage) {
if($public) {
if ($maxage) {
if ($public) {
// cache publically
header('Expires: '.gmdate("D, d M Y H:i:s", $expires).' GMT');
header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.$maxage);
@ -92,7 +92,7 @@ function sendFile($file, $mime, $dl, $cache, $public = false, $orig = null, $csp
// send file contents
$fp = @fopen($file, "rb");
if($fp) {
if ($fp) {
http_rangeRequest($fp, filesize($file), $mime);
} else {
http_status(500);
@ -150,20 +150,20 @@ function checkFileStatus(&$media, &$file, $rev = '', $width = 0, $height = 0)
global $MIME, $EXT, $CACHE, $INPUT;
//media to local file
if(media_isexternal($media)) {
if (media_isexternal($media)) {
//check token for external image and additional for resized and cached images
if(media_get_token($media, $width, $height) !== $INPUT->str('tok')) {
if (media_get_token($media, $width, $height) !== $INPUT->str('tok')) {
return [412, 'Precondition Failed'];
}
//handle external images
if(strncmp($MIME, 'image/', 6) == 0) $file = media_get_from_URL($media, $EXT, $CACHE);
if(!$file) {
if (strncmp($MIME, 'image/', 6) == 0) $file = media_get_from_URL($media, $EXT, $CACHE);
if (!$file) {
//download failed - redirect to original URL
return [302, $media];
}
} else {
$media = cleanID($media);
if(empty($media)) {
if (empty($media)) {
return [400, 'Bad request'];
}
// check token for resized images
@ -172,14 +172,14 @@ function checkFileStatus(&$media, &$file, $rev = '', $width = 0, $height = 0)
}
//check permissions (namespace only)
if(auth_quickaclcheck(getNS($media).':X') < AUTH_READ) {
if (auth_quickaclcheck(getNS($media).':X') < AUTH_READ) {
return [403, 'Forbidden'];
}
$file = mediaFN($media, $rev);
}
//check file existance
if(!file_exists($file)) {
if (!file_exists($file)) {
return [404, 'Not Found'];
}
@ -200,7 +200,7 @@ function calc_cache($cache)
{
global $conf;
if(strtolower($cache) == 'nocache') return 0; //never cache
if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
if (strtolower($cache) == 'nocache') return 0; //never cache
if (strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
return -1; //cache endless
}

View File

@ -134,8 +134,7 @@ class Doku_Form
{
if (is_null($value))
unset($this->_hidden[$name]);
else
$this->_hidden[$name] = $value;
else $this->_hidden[$name] = $value;
}
/**
@ -327,7 +326,7 @@ class Doku_Form
global $INPUT;
$value = (array_key_exists($INPUT->post->str($name), $entries)) ?
$INPUT->str($name) : key($entries);
foreach($entries as $val => $cap) {
foreach ($entries as $val => $cap) {
$data = ($value === $val) ? array('checked' => 'checked') : array();
$this->addElement(form_makeRadioField($name, $val, $cap, '', '', $data));
}
@ -653,8 +652,7 @@ function form_makeMenuField($name, $values, $selected = '', $label = null, $id =
foreach ($values as $val) {
if (is_array($val))
@list($val, $text) = $val;
else
$text = null;
else $text = null;
$options[] = array($val, $text, $val===$selected);
}
}
@ -1085,13 +1083,12 @@ function form_menufield($attrs)
$selected = false;
$cnt = count($attrs['_options']);
for($n=0; $n < $cnt; $n++){
for ($n=0; $n < $cnt; $n++) {
@list($value,$text,$select) = $attrs['_options'][$n];
$p = '';
if (!is_null($text))
$p .= ' value="'. formText($value) .'"';
else
$text = $value;
else $text = $value;
if (!empty($select) && !$selected) {
$p .= ' selected="selected"';
$selected = true;

View File

@ -15,7 +15,7 @@ use dokuwiki\Utf8\Sort;
/**
* create snippets for the first few results only
*/
if(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER', 15);
if (!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER', 15);
/**
* The fulltext search
@ -85,7 +85,7 @@ function _ft_pageSearch(&$data)
case 'W-:':
case 'W_:': // word
$word = substr($token, 3);
if(isset($lookup[$word])) {
if (isset($lookup[$word])) {
$stack[] = (array)$lookup[$word];
}
break;
@ -97,7 +97,7 @@ function _ft_pageSearch(&$data)
// all words in this phrase
$pages = end($stack);
$pages_matched = [];
foreach(array_keys($pages) as $id){
foreach (array_keys($pages) as $id) {
$evdata = [
'id' => $id,
'phrase' => $phrase,
@ -179,13 +179,13 @@ function ft_backlinks($id, $ignore_perms = false)
{
$result = idx_get_indexer()->lookupKey('relation_references', $id);
if($result === []) return $result;
if ($result === []) return $result;
// check ACL permissions
foreach(array_keys($result) as $idx){
if((!$ignore_perms && (
foreach (array_keys($result) as $idx) {
if ((!$ignore_perms && (
isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
)) || !page_exists($result[$idx], '', false)){
)) || !page_exists($result[$idx], '', false)) {
unset($result[$idx]);
}
}
@ -211,13 +211,13 @@ function ft_mediause($id, $ignore_perms = false)
{
$result = idx_get_indexer()->lookupKey('relation_media', $id);
if($result === []) return $result;
if ($result === []) return $result;
// check ACL permissions
foreach(array_keys($result) as $idx){
if((!$ignore_perms && (
foreach (array_keys($result) as $idx) {
if ((!$ignore_perms && (
isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
)) || !page_exists($result[$idx], '', false)){
)) || !page_exists($result[$idx], '', false)) {
unset($result[$idx]);
}
}
@ -323,8 +323,8 @@ function _ft_pageLookup(&$data)
// discard hidden pages
// discard nonexistent pages
// check ACL permissions
foreach(array_keys($pages) as $idx){
if(!isVisiblePage($idx) || !page_exists($idx) ||
foreach (array_keys($pages) as $idx) {
if (!isVisiblePage($idx) || !page_exists($idx) ||
auth_quickaclcheck($idx) < AUTH_READ) {
unset($pages[$idx]);
}
@ -401,9 +401,9 @@ function ft_pagesorter($a, $b)
{
$ac = count(explode(':', $a));
$bc = count(explode(':', $b));
if($ac < $bc){
if ($ac < $bc) {
return -1;
}elseif($ac > $bc){
} elseif ($ac > $bc) {
return 1;
}
return Sort::strcmp($a, $b);
@ -474,11 +474,8 @@ function ft_snippet($id, $highlight)
for ($cnt=4; $cnt--;) {
if (0) {
} elseif (preg_match('/'.$re3.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
} elseif (preg_match('/'.$re2.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
} elseif (preg_match('/'.$re1.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
} else {
break;
}
@ -557,7 +554,7 @@ function ft_snippet($id, $highlight)
function ft_snippet_re_preprocess($term)
{
// do not process asian terms where word boundaries are not explicit
if(Asian::isAsianWords($term)) return $term;
if (Asian::isAsianWords($term)) return $term;
if (UTF8_PROPERTYSUPPORT) {
// unicode word boundaries
@ -570,19 +567,19 @@ function ft_snippet_re_preprocess($term)
$BR = '\b';
}
if(substr($term, 0, 2) == '\\*'){
if (substr($term, 0, 2) == '\\*') {
$term = substr($term, 2);
}else{
} else {
$term = $BL.$term;
}
if(substr($term, -2, 2) == '\\*'){
if (substr($term, -2, 2) == '\\*') {
$term = substr($term, 0, -2);
}else{
} else {
$term .= $BR;
}
if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
if ($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
return $term;
}
@ -600,7 +597,7 @@ function ft_snippet_re_preprocess($term)
function ft_resultCombine($args)
{
$array_count = count($args);
if($array_count == 1){
if ($array_count == 1) {
return $args[0];
}

View File

@ -475,7 +475,6 @@ function html_buildlist($data, $class, $func, $lifunc = null, $forcewrapper = fa
$open++;
}
$level = $item['level'];
} elseif ($item['level'] < $level) {
//close last item
$html .= '</li>'."\n";
@ -849,7 +848,7 @@ function html_TOC($toc)
*/
function html_list_toc($item)
{
if (isset($item['hid'])){
if (isset($item['hid'])) {
$link = '#'.$item['hid'];
} else {
$link = $item['link'];
@ -942,11 +941,11 @@ function html_flashobject($swf, $width, $height, $params = null, $flashvars = nu
$out = '';
// prepare the object attributes
if(is_null($atts)) $atts = [];
if (is_null($atts)) $atts = [];
$atts['width'] = (int) $width;
$atts['height'] = (int) $height;
if(!$atts['width']) $atts['width'] = 425;
if(!$atts['height']) $atts['height'] = 350;
if (!$atts['width']) $atts['width'] = 425;
if (!$atts['height']) $atts['height'] = 350;
// add object attributes for standard compliant browsers
$std = $atts;
@ -967,19 +966,19 @@ function html_flashobject($swf, $width, $height, $params = null, $flashvars = nu
$out .= '<!--><!-- -->'.NL;
// print params
if(is_array($params)) foreach($params as $key => $val){
if (is_array($params)) foreach ($params as $key => $val) {
$out .= ' <param name="'.hsc($key).'" value="'.hsc($val).'" />'.NL;
}
// add flashvars
if(is_array($flashvars)){
if (is_array($flashvars)) {
$out .= ' <param name="FlashVars" value="'.buildURLparams($flashvars).'" />'.NL;
}
// alternative content
if($alt){
if ($alt) {
$out .= $alt.NL;
}else{
} else {
$out .= $lang['noflash'].NL;
}

View File

@ -62,8 +62,8 @@ function wordlen($w)
$l = strlen($w);
// If left alone, all chinese "words" will get put into w3.idx
// So the "length" of a "word" is faked
if(preg_match_all('/[\xE2-\xEF]/', $w, $leadbytes)) {
foreach($leadbytes[0] as $b)
if (preg_match_all('/[\xE2-\xEF]/', $w, $leadbytes)) {
foreach ($leadbytes[0] as $b)
$l += ord($b) - 0xE1;
}
return $l;
@ -98,9 +98,9 @@ function & idx_get_stopwords()
if (is_null($stopwords)) {
global $conf;
$swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
if(file_exists($swfile)){
if (file_exists($swfile)) {
$stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
}else{
} else {
$stopwords = [];
}
}
@ -139,10 +139,10 @@ function idx_addPage($page, $verbose = false, $force = false)
}
// check if indexing needed
if(!$force && file_exists($idxtag)){
if(trim(io_readFile($idxtag)) == idx_get_version()){
if (!$force && file_exists($idxtag)) {
if (trim(io_readFile($idxtag)) == idx_get_version()) {
$last = @filemtime($idxtag);
if($last > @filemtime(wikiFN($page))){
if ($last > @filemtime(wikiFN($page))) {
if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
return false;
}
@ -176,13 +176,11 @@ function idx_addPage($page, $verbose = false, $force = false)
$metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED);
if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null)
$metadata['relation_references'] = array_keys($references);
else
$metadata['relation_references'] = [];
else $metadata['relation_references'] = [];
if (($media = p_get_metadata($page, 'relation media', METADATA_RENDER_UNLIMITED)) !== null)
$metadata['relation_media'] = array_keys($media);
else
$metadata['relation_media'] = [];
else $metadata['relation_media'] = [];
$data = ['page' => $page, 'body' => $body, 'metadata' => $metadata, 'pid' => $pid];
$evt = new Event('INDEXER_PAGE_ADD', $data);

View File

@ -11,10 +11,10 @@ use dokuwiki\Debug\DebugHelper;
use dokuwiki\HTTP\DokuHTTPClient;
use dokuwiki\Logger;
if(!defined('DOKU_MESSAGEURL')){
if(in_array('ssl', stream_get_transports())) {
if (!defined('DOKU_MESSAGEURL')) {
if (in_array('ssl', stream_get_transports())) {
define('DOKU_MESSAGEURL', 'https://update.dokuwiki.org/check/');
}else{
} else {
define('DOKU_MESSAGEURL', 'http://update.dokuwiki.org/check/');
}
}
@ -29,36 +29,36 @@ function checkUpdateMessages()
global $conf;
global $INFO;
global $updateVersion;
if(!$conf['updatecheck']) return;
if($conf['useacl'] && !$INFO['ismanager']) return;
if (!$conf['updatecheck']) return;
if ($conf['useacl'] && !$INFO['ismanager']) return;
$cf = getCacheName($updateVersion, '.updmsg');
$lm = @filemtime($cf);
$is_http = substr(DOKU_MESSAGEURL, 0, 5) != 'https';
// check if new messages needs to be fetched
if($lm < time()-(60*60*24) || $lm < @filemtime(DOKU_INC.DOKU_SCRIPT)){
if ($lm < time()-(60*60*24) || $lm < @filemtime(DOKU_INC.DOKU_SCRIPT)) {
@touch($cf);
Logger::debug("checkUpdateMessages(): downloading messages to ".$cf.($is_http?' (without SSL)':' (with SSL)'));
$http = new DokuHTTPClient();
$http->timeout = 12;
$resp = $http->get(DOKU_MESSAGEURL.$updateVersion);
if(is_string($resp) && ($resp == "" || substr(trim($resp), -1) == '%')) {
if (is_string($resp) && ($resp == "" || substr(trim($resp), -1) == '%')) {
// basic sanity check that this is either an empty string response (ie "no messages")
// or it looks like one of our messages, not WiFi login or other interposed response
io_saveFile($cf, $resp);
} else {
Logger::debug("checkUpdateMessages(): unexpected HTTP response received", $http->error);
}
}else{
} else {
Logger::debug("checkUpdateMessages(): messages up to date");
}
$data = io_readFile($cf);
// show messages through the usual message mechanism
$msgs = explode("\n%\n", $data);
foreach($msgs as $msg){
if($msg) msg($msg, 2);
foreach ($msgs as $msg) {
if ($msg) msg($msg, 2);
}
}
@ -72,11 +72,11 @@ function getVersionData()
{
$version = [];
//import version string
if(file_exists(DOKU_INC.'VERSION')){
if (file_exists(DOKU_INC.'VERSION')) {
//official release
$version['date'] = trim(io_readFile(DOKU_INC.'VERSION'));
$version['type'] = 'Release';
}elseif(is_dir(DOKU_INC.'.git')){
} elseif (is_dir(DOKU_INC.'.git')) {
$version['type'] = 'Git';
$version['date'] = 'unknown';
@ -126,7 +126,7 @@ function getVersionData()
}
}
}
}else{
} else {
global $updateVersion;
$version['date'] = 'update version '.$updateVersion;
$version['type'] = 'snapshot?';
@ -160,9 +160,9 @@ function check()
if ($INFO['isadmin'] || $INFO['ismanager']) {
msg('DokuWiki version: '.getVersion(), 1);
if(version_compare(phpversion(), '7.4.0', '<')){
if (version_compare(phpversion(), '7.4.0', '<')) {
msg('Your PHP version is too old ('.phpversion().' vs. 7.4+ needed)', -1);
}else{
} else {
msg('PHP version '.phpversion(), 1);
}
} elseif (version_compare(phpversion(), '7.4.0', '<')) {
@ -170,7 +170,7 @@ function check()
}
$mem = php_to_byte(ini_get('memory_limit'));
if($mem){
if ($mem) {
if ($mem === -1) {
msg('PHP memory is unlimited', 1);
} elseif ($mem < 16_777_216) {
@ -208,31 +208,31 @@ function check()
}
}
if(is_writable(DOKU_CONF)){
if (is_writable(DOKU_CONF)) {
msg('conf directory is writable', 1);
}else{
} else {
msg('conf directory is not writable', -1);
}
if($conf['authtype'] == 'plain'){
if ($conf['authtype'] == 'plain') {
global $config_cascade;
if(is_writable($config_cascade['plainauth.users']['default'])){
if (is_writable($config_cascade['plainauth.users']['default'])) {
msg('conf/users.auth.php is writable', 1);
}else{
} else {
msg('conf/users.auth.php is not writable', 0);
}
}
if(function_exists('mb_strpos')){
if(defined('UTF8_NOMBSTRING')){
if (function_exists('mb_strpos')) {
if (defined('UTF8_NOMBSTRING')) {
msg('mb_string extension is available but will not be used', 0);
}else{
} else {
msg('mb_string extension is available and will be used', 1);
if(ini_get('mbstring.func_overload') != 0){
if (ini_get('mbstring.func_overload') != 0) {
msg('mb_string function overloading is enabled, this will cause problems and should be disabled', -1);
}
}
}else{
} else {
msg('mb_string extension not available - PHP only replacements will be used', 0);
}
@ -244,25 +244,25 @@ function check()
}
$loc = setlocale(LC_ALL, 0);
if(!$loc){
if (!$loc) {
msg('No valid locale is set for your PHP setup. You should fix this', -1);
}elseif(stripos($loc, 'utf') === false){
} elseif (stripos($loc, 'utf') === false) {
msg('Your locale <code>'.hsc($loc).'</code> seems not to be a UTF-8 locale,
you should fix this if you encounter problems.', 0);
}else{
} else {
msg('Valid locale '.hsc($loc).' found.', 1);
}
if($conf['allowdebug']){
if ($conf['allowdebug']) {
msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0', -1);
}else{
} else {
msg('Debugging support is disabled', 1);
}
if(!empty($INFO['userinfo']['name'])){
if (!empty($INFO['userinfo']['name'])) {
msg('You are currently logged in as '.$INPUT->server->str('REMOTE_USER').' ('.$INFO['userinfo']['name'].')', 0);
msg('You are part of the groups '.implode(', ', $INFO['userinfo']['grps']), 0);
}else{
} else {
msg('You are currently not logged in', 0);
}
@ -299,7 +299,7 @@ function check()
}
}
if($index_corrupted) {
if ($index_corrupted) {
msg(
'The search index is corrupted. It might produce wrong results and most
probably needs to be rebuilt. See
@ -307,7 +307,7 @@ function check()
for ways to rebuild the search index.',
-1
);
} elseif(!empty($lengths)) {
} elseif (!empty($lengths)) {
msg('The search index seems to be working', 1);
} else {
msg(
@ -324,11 +324,11 @@ function check()
$http->timeout = 3;
$http->sendRequest('http://www.dokuwiki.org', '', 'HEAD');
$now = time();
if(isset($http->resp_headers['date'])) {
if (isset($http->resp_headers['date'])) {
$time = strtotime($http->resp_headers['date']);
$diff = $time - $now;
if(abs($diff) < 4) {
if (abs($diff) < 4) {
msg("Server time seems to be okay. Diff: {$diff}s", 1);
} else {
msg("Your server's clock seems to be out of sync!
@ -375,17 +375,17 @@ function msg($message, $lvl = 0, $line = '', $file = '', $allow = MSG_PUBLIC)
$evt = new Event('INFOUTIL_MSG_SHOW', $msgdata);
if ($evt->advise_before()) {
/* Show msg normally - event could suppress message show */
if($msgdata['line'] || $msgdata['file']) {
if ($msgdata['line'] || $msgdata['file']) {
$basename = PhpString::basename($msgdata['file']);
$msgdata['msg'] .=' ['.$basename.':'.$msgdata['line'].']';
}
if(!isset($MSG)) $MSG = [];
if (!isset($MSG)) $MSG = [];
$MSG[] = $msgdata;
if(isset($MSG_shown) || headers_sent()){
if(function_exists('html_msgarea')){
if (isset($MSG_shown) || headers_sent()) {
if (function_exists('html_msgarea')) {
html_msgarea();
}else{
} else {
print "ERROR(".$msgdata['lvl'].") ".$msgdata['msg']."\n";
}
unset($GLOBALS['MSG']);
@ -415,7 +415,7 @@ function info_msg_allowed($msg)
// restricted msg, but no authentication
if (empty($auth)) return false;
switch ($msg['allow']){
switch ($msg['allow']) {
case MSG_USERS_ONLY:
return !empty($INFO['userinfo']);
@ -446,11 +446,11 @@ function info_msg_allowed($msg)
*/
function dbg($msg, $hidden = false)
{
if($hidden){
if ($hidden) {
echo "<!--\n";
print_r($msg);
echo "\n-->";
}else{
} else {
echo '<pre class="dbg">';
echo hsc(print_r($msg, true));
echo '</pre>';
@ -470,7 +470,7 @@ function dbglog($msg, $header = '')
dbg_deprecated('\\dokuwiki\\Logger');
// was the msg as single line string? use it as header
if($header === '' && is_string($msg) && strpos($msg, "\n") === false) {
if ($header === '' && is_string($msg) && strpos($msg, "\n") === false) {
$header = $msg;
$msg = '';
}
@ -514,15 +514,15 @@ function dbg_backtrace()
$call['class'] . $call['type'] . $call['function'] : $call['function'];
$params = [];
if (isset($call['args'])){
foreach($call['args'] as $arg){
if(is_object($arg)){
if (isset($call['args'])) {
foreach ($call['args'] as $arg) {
if (is_object($arg)) {
$params[] = '[Object '.get_class($arg).']';
}elseif(is_array($arg)){
} elseif (is_array($arg)) {
$params[] = '[Array]';
}elseif(is_null($arg)){
} elseif (is_null($arg)) {
$params[] = '[NULL]';
}else{
} else {
$params[] = '"'.$arg.'"';
}
}
@ -553,11 +553,11 @@ function dbg_backtrace()
*/
function debug_guard(&$data)
{
foreach($data as $key => $value){
if(preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i', $key)){
foreach ($data as $key => $value) {
if (preg_match('/(notify|pass|auth|secret|ftp|userinfo|token|buid|mail|proxy)/i', $key)) {
$data[$key] = '***';
continue;
}
if(is_array($value)) debug_guard($data[$key]);
if (is_array($value)) debug_guard($data[$key]);
}
}

View File

@ -29,13 +29,13 @@ $preload = fullpath(__DIR__).'/preload.php';
if (file_exists($preload)) include($preload);
// define the include path
if(!defined('DOKU_INC')) define('DOKU_INC', fullpath(__DIR__.'/../').'/');
if (!defined('DOKU_INC')) define('DOKU_INC', fullpath(__DIR__.'/../').'/');
// define Plugin dir
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
// define config path (packagers may want to change this to /etc/dokuwiki/)
if(!defined('DOKU_CONF')) define('DOKU_CONF', DOKU_INC.'conf/');
if (!defined('DOKU_CONF')) define('DOKU_CONF', DOKU_INC.'conf/');
// check for error reporting override or set error reporting to sane values
if (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF.'report_e_all')) {
@ -88,7 +88,7 @@ $license = [];
foreach (['default', 'local'] as $config_group) {
if (empty($config_cascade['license'][$config_group])) continue;
foreach ($config_cascade['license'][$config_group] as $config_file) {
if(file_exists($config_file)){
if (file_exists($config_file)) {
include($config_file);
}
}
@ -98,20 +98,20 @@ foreach (['default', 'local'] as $config_group) {
date_default_timezone_set(@date_default_timezone_get());
// define baseURL
if(!defined('DOKU_REL')) define('DOKU_REL', getBaseURL(false));
if(!defined('DOKU_URL')) define('DOKU_URL', getBaseURL(true));
if(!defined('DOKU_BASE')){
if($conf['canonical']){
if (!defined('DOKU_REL')) define('DOKU_REL', getBaseURL(false));
if (!defined('DOKU_URL')) define('DOKU_URL', getBaseURL(true));
if (!defined('DOKU_BASE')) {
if ($conf['canonical']) {
define('DOKU_BASE', DOKU_URL);
}else{
} else {
define('DOKU_BASE', DOKU_REL);
}
}
// define whitespace
if(!defined('NL')) define('NL', "\n");
if(!defined('DOKU_LF')) define('DOKU_LF', "\n");
if(!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
if (!defined('NL')) define('NL', "\n");
if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
// define cookie and session id, append server port when securecookie is configured FS#1664
if (!defined('DOKU_COOKIE')) {
@ -121,9 +121,9 @@ if (!defined('DOKU_COOKIE')) {
}
// define main script
if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT', 'doku.php');
if (!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT', 'doku.php');
if(!defined('DOKU_TPL')) {
if (!defined('DOKU_TPL')) {
/**
* @deprecated 2012-10-13 replaced by more dynamic method
* @see tpl_basedir()
@ -131,7 +131,7 @@ if(!defined('DOKU_TPL')) {
define('DOKU_TPL', DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
}
if(!defined('DOKU_TPLINC')) {
if (!defined('DOKU_TPLINC')) {
/**
* @deprecated 2012-10-13 replaced by more dynamic method
* @see tpl_incdir()
@ -162,20 +162,20 @@ if ($conf['gzip_output'] &&
}
// init session
if(!headers_sent() && !defined('NOSESSION')) {
if(!defined('DOKU_SESSION_NAME')) define('DOKU_SESSION_NAME', "DokuWiki");
if(!defined('DOKU_SESSION_LIFETIME')) define('DOKU_SESSION_LIFETIME', 0);
if(!defined('DOKU_SESSION_PATH')) {
if (!headers_sent() && !defined('NOSESSION')) {
if (!defined('DOKU_SESSION_NAME')) define('DOKU_SESSION_NAME', "DokuWiki");
if (!defined('DOKU_SESSION_LIFETIME')) define('DOKU_SESSION_LIFETIME', 0);
if (!defined('DOKU_SESSION_PATH')) {
$cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
define('DOKU_SESSION_PATH', $cookieDir);
}
if(!defined('DOKU_SESSION_DOMAIN')) define('DOKU_SESSION_DOMAIN', '');
if (!defined('DOKU_SESSION_DOMAIN')) define('DOKU_SESSION_DOMAIN', '');
// start the session
init_session();
// load left over messages
if(isset($_SESSION[DOKU_COOKIE]['msg'])) {
if (isset($_SESSION[DOKU_COOKIE]['msg'])) {
$MSG = $_SESSION[DOKU_COOKIE]['msg'];
unset($_SESSION[DOKU_COOKIE]['msg']);
}
@ -185,7 +185,7 @@ if(!headers_sent() && !defined('NOSESSION')) {
$_REQUEST = array_merge($_GET, $_POST);
// we don't want a purge URL to be digged
if(isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
if (isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
// precalculate file creation modes
init_creationmodes();
@ -208,10 +208,10 @@ ErrorHandler::register();
// disable gzip if not available
define('DOKU_HAS_BZIP', function_exists('bzopen'));
define('DOKU_HAS_GZIP', function_exists('gzopen'));
if($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
if ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
$conf['compression'] = 'gz';
}
if($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
if ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
$conf['compression'] = 0;
}
@ -263,7 +263,7 @@ function init_session()
]);
// make sure the session cookie contains a valid session ID
if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
if (isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
unset($_COOKIE[DOKU_SESSION_NAME]);
}
@ -292,10 +292,10 @@ function init_paths()
'logdir' => 'log',
];
foreach($paths as $c => $p) {
foreach ($paths as $c => $p) {
$path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c];
$conf[$c] = init_path($path);
if(empty($conf[$c])) {
if (empty($conf[$c])) {
$path = fullpath($path);
nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
You should check your config and permission settings.
@ -308,7 +308,8 @@ function init_paths()
$conf['changelog_old'] = init_path(
$conf['changelog'] ?? $conf['savedir'] . '/changes.log'
);
if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
if ($conf['changelog_old']=='') {
unset($conf['changelog_old']); }
// hardcoded changelog because it is now a cache that lives in meta
$conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
$conf['media_changelog'] = $conf['metadir'].'/_media.changes';
@ -354,13 +355,13 @@ function init_files()
$files = [$conf['indexdir'].'/page.idx'];
foreach($files as $file){
if(!file_exists($file)){
foreach ($files as $file) {
if (!file_exists($file)) {
$fh = @fopen($file, 'a');
if($fh){
if ($fh) {
fclose($fh);
if($conf['fperm']) chmod($file, $conf['fperm']);
}else{
if ($conf['fperm']) chmod($file, $conf['fperm']);
} else {
nice_die("$file is not writable. Check your permissions settings!");
}
}
@ -383,20 +384,20 @@ function init_path($path)
{
// check existence
$p = fullpath($path);
if(!file_exists($p)){
if (!file_exists($p)) {
$p = fullpath(DOKU_INC.$path);
if(!file_exists($p)){
if (!file_exists($p)) {
return '';
}
}
// check writability
if(!@is_writable($p)){
if (!@is_writable($p)) {
return '';
}
// check accessability (execute bit) for directories
if(@is_dir($p) && !file_exists("$p/.")){
if (@is_dir($p) && !file_exists("$p/.")) {
return '';
}
@ -423,17 +424,17 @@ function init_creationmodes()
// get system umask, fallback to 0 if none available
$umask = @umask();
if(!$umask) $umask = 0000;
if (!$umask) $umask = 0000;
// check what is set automatically by the system on file creation
// and set the fperm param if it's not what we want
$auto_fmode = 0666 & ~$umask;
if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
if ($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
// check what is set automatically by the system on directory creation
// and set the dperm param if it's not what we want.
$auto_dmode = 0777 & ~$umask;
if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
if ($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
}
/**
@ -454,22 +455,22 @@ function getBaseURL($abs = null)
{
global $conf;
//if canonical url enabled always return absolute
if(is_null($abs)) $abs = $conf['canonical'];
if (is_null($abs)) $abs = $conf['canonical'];
if(!empty($conf['basedir'])){
if (!empty($conf['basedir'])) {
$dir = $conf['basedir'];
}elseif(substr($_SERVER['SCRIPT_NAME'], -4) == '.php'){
} elseif (substr($_SERVER['SCRIPT_NAME'], -4) == '.php') {
$dir = dirname($_SERVER['SCRIPT_NAME']);
}elseif(substr($_SERVER['PHP_SELF'], -4) == '.php'){
} elseif (substr($_SERVER['PHP_SELF'], -4) == '.php') {
$dir = dirname($_SERVER['PHP_SELF']);
}elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
} elseif ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
$dir = preg_replace(
'/^'.preg_quote($_SERVER['DOCUMENT_ROOT'], '/').'/',
'',
$_SERVER['SCRIPT_FILENAME']
);
$dir = dirname('/'.$dir);
}else{
} else {
$dir = '.'; //probably wrong
}
@ -483,42 +484,42 @@ function getBaseURL($abs = null)
$dir = preg_replace('!lib/plugins/.*$!', '', $dir);
//finish here for relative URLs
if(!$abs) return $dir;
if (!$abs) return $dir;
//use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/').$dir;
if (!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/').$dir;
//split hostheader into host and port
if(isset($_SERVER['HTTP_HOST'])){
if (isset($_SERVER['HTTP_HOST'])) {
$parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
$host = $parsed_host['host'] ?? null;
$port = $parsed_host['port'] ?? null;
}elseif(isset($_SERVER['SERVER_NAME'])){
} elseif (isset($_SERVER['SERVER_NAME'])) {
$parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
$host = $parsed_host['host'] ?? null;
$port = $parsed_host['port'] ?? null;
}else{
} else {
$host = php_uname('n');
$port = '';
}
if(is_null($port)){
if (is_null($port)) {
$port = '';
}
if(!is_ssl()){
if (!is_ssl()) {
$proto = 'http://';
if ($port == '80') {
$port = '';
}
}else{
} else {
$proto = 'https://';
if ($port == '443') {
$port = '';
}
}
if($port !== '') $port = ':'.$port;
if ($port !== '') $port = ':'.$port;
return $proto.$host.$port.$dir;
}
@ -534,14 +535,14 @@ function getBaseURL($abs = null)
function is_ssl()
{
// check if we are behind a reverse proxy
if(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
if($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
return true;
} else {
return false;
}
}
if(!isset($_SERVER['HTTPS']) ||
if (!isset($_SERVER['HTTPS']) ||
preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'])) {
return false;
} else {
@ -578,7 +579,7 @@ function nice_die($msg)
</body>
</html>
EOT;
if(defined('DOKU_UNITTEST')) {
if (defined('DOKU_UNITTEST')) {
throw new RuntimeException('nice_die: '.$msg);
}
exit(1);
@ -606,9 +607,9 @@ function fullpath($path, $exists = false)
$iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
// find the (indestructable) root of the path - keeps windows stuff intact
if($path[0] == '/'){
if ($path[0] == '/') {
$root = '/';
}elseif($iswin){
} elseif ($iswin) {
// match drive letter and UNC paths
if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
$root = $match[1].'/';
@ -621,10 +622,10 @@ function fullpath($path, $exists = false)
$path = str_replace('\\', '/', $path);
// if the given path wasn't absolute already, prepend the script path and retry
if(!$root){
if (!$root) {
$base = dirname($_SERVER['SCRIPT_FILENAME']);
$path = $base.'/'.$path;
if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
$run++;
return fullpath($path, $exists);
}
@ -634,7 +635,7 @@ function fullpath($path, $exists = false)
// canonicalize
$path=explode('/', $path);
$newpath=[];
foreach($path as $p) {
foreach ($path as $p) {
if ($p === '' || $p === '.') continue;
if ($p==='..') {
array_pop($newpath);
@ -645,7 +646,7 @@ function fullpath($path, $exists = false)
$finalpath = $root.implode('/', $newpath);
// check for existence when needed (except when unit testing)
if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
return false;
}
return $finalpath;

View File

@ -33,17 +33,18 @@ function io_sweepNS($id, $basedir = 'datadir')
$delone = false;
//scan all namespaces
while(($id = getNS($id)) !== false){
while (($id = getNS($id)) !== false) {
$dir = $conf[$basedir].'/'.utf8_encodeFN(str_replace(':', '/', $id));
//try to delete dir else return
if(@rmdir($dir)) {
if (@rmdir($dir)) {
if ($ns_type!==false) {
$data = [$id, $ns_type];
$delone = true; // we deleted at least one dir
Event::createAndTrigger('IO_NAMESPACE_DELETED', $data);
}
} else { return $delone; }
} else {
return $delone; }
}
return $delone;
}
@ -70,7 +71,8 @@ function io_sweepNS($id, $basedir = 'datadir')
*/
function io_readWikiPage($file, $id, $rev = false)
{
if (empty($rev)) { $rev = false; }
if (empty($rev)) {
$rev = false; }
$data = [[$file, true], getNS($id), noNS($id), $rev];
return Event::createAndTrigger('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
}
@ -109,22 +111,22 @@ function _io_readWikiPage_action($data)
function io_readFile($file, $clean = true)
{
$ret = '';
if(file_exists($file)){
if (file_exists($file)) {
if (substr($file, -3) == '.gz') {
if(!DOKU_HAS_GZIP) return false;
if (!DOKU_HAS_GZIP) return false;
$ret = gzfile($file);
if(is_array($ret)) $ret = implode('', $ret);
if (is_array($ret)) $ret = implode('', $ret);
} elseif (substr($file, -4) == '.bz2') {
if(!DOKU_HAS_BZIP) return false;
if (!DOKU_HAS_BZIP) return false;
$ret = bzfile($file);
} else{
} else {
$ret = file_get_contents($file);
}
}
if($ret === null) return false;
if($ret !== false && $clean){
if ($ret === null) return false;
if ($ret !== false && $clean) {
return cleanText($ret);
}else{
} else {
return $ret;
}
}
@ -141,20 +143,20 @@ function io_readFile($file, $clean = true)
function bzfile($file, $array = false)
{
$bz = bzopen($file, "r");
if($bz === false) return false;
if ($bz === false) return false;
if($array) $lines = [];
if ($array) $lines = [];
$str = '';
while (!feof($bz)) {
//8192 seems to be the maximum buffersize?
$buffer = bzread($bz, 8192);
if(($buffer === false) || (bzerrno($bz) !== 0)) {
if (($buffer === false) || (bzerrno($bz) !== 0)) {
return false;
}
$str .= $buffer;
if($array) {
if ($array) {
$pos = strpos($str, "\n");
while($pos !== false) {
while ($pos !== false) {
$lines[] = substr($str, 0, $pos+1);
$str = substr($str, $pos+1);
$pos = strpos($str, "\n");
@ -162,8 +164,8 @@ function bzfile($file, $array = false)
}
}
bzclose($bz);
if($array) {
if($str !== '') $lines[] = $str;
if ($array) {
if ($str !== '') $lines[] = $str;
return $lines;
}
return $str;
@ -193,8 +195,10 @@ function bzfile($file, $array = false)
*/
function io_writeWikiPage($file, $content, $id, $rev = false)
{
if (empty($rev)) { $rev = false; }
if ($rev===false) { io_createNamespace($id); } // create namespaces as needed
if (empty($rev)) {
$rev = false; }
if ($rev===false) {
io_createNamespace($id); } // create namespaces as needed
$data = [[$file, $content, false], getNS($id), noNS($id), $rev];
return Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
}
@ -211,7 +215,7 @@ function _io_writeWikiPage_action($data)
if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
$ok = io_saveFile(...$data[0]);
// for attic files make sure the file has the mtime of the revision
if($ok && is_int($data[3]) && $data[3] > 0) {
if ($ok && is_int($data[3]) && $data[3] > 0) {
@touch($data[0][0], $data[3]);
}
return $ok;
@ -237,30 +241,30 @@ function _io_saveFile($file, $content, $append)
$fileexists = file_exists($file);
if (substr($file, -3) == '.gz') {
if(!DOKU_HAS_GZIP) return false;
if (!DOKU_HAS_GZIP) return false;
$fh = @gzopen($file, $mode.'9');
if(!$fh) return false;
if (!$fh) return false;
gzwrite($fh, $content);
gzclose($fh);
} elseif (substr($file, -4) == '.bz2') {
if(!DOKU_HAS_BZIP) return false;
if($append) {
if (!DOKU_HAS_BZIP) return false;
if ($append) {
$bzcontent = bzfile($file);
if($bzcontent === false) return false;
if ($bzcontent === false) return false;
$content = $bzcontent.$content;
}
$fh = @bzopen($file, 'w');
if(!$fh) return false;
if (!$fh) return false;
bzwrite($fh, $content);
bzclose($fh);
} else{
} else {
$fh = @fopen($file, $mode);
if(!$fh) return false;
if (!$fh) return false;
fwrite($fh, $content);
fclose($fh);
}
if(!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
if (!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
return true;
}
@ -284,7 +288,7 @@ function io_saveFile($file, $content, $append = false)
{
io_makeFileDir($file);
io_lock($file);
if(!_io_saveFile($file, $content, $append)) {
if (!_io_saveFile($file, $content, $append)) {
msg("Writing $file failed", -1);
io_unlock($file);
return false;
@ -332,12 +336,12 @@ function io_replaceInFile($file, $oldline, $newline, $regex = false, $maxlines =
// load into array
if (substr($file, -3) == '.gz') {
if(!DOKU_HAS_GZIP) return false;
if (!DOKU_HAS_GZIP) return false;
$lines = gzfile($file);
} elseif (substr($file, -4) == '.bz2') {
if(!DOKU_HAS_BZIP) return false;
if (!DOKU_HAS_BZIP) return false;
$lines = bzfile($file, true);
} else{
} else {
$lines = file($file);
}
@ -349,28 +353,28 @@ function io_replaceInFile($file, $oldline, $newline, $regex = false, $maxlines =
if ($maxlines > 0) {
$count = 0;
$matched = 0;
foreach($lines as $i => $line) {
if($count >= $maxlines) break;
foreach ($lines as $i => $line) {
if ($count >= $maxlines) break;
// $matched will be set to 0|1 depending on whether pattern is matched and line replaced
$lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
if ($matched) $count++;
}
} elseif ($maxlines == 0) {
$lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
if ((string)$newline !== ''){
if ((string)$newline !== '') {
$lines[] = $newline;
}
} else {
$lines = preg_replace($pattern, $replace, $lines);
}
if(count($lines)){
if(!_io_saveFile($file, implode('', $lines), false)) {
if (count($lines)) {
if (!_io_saveFile($file, implode('', $lines), false)) {
msg("Removing content from $file failed", -1);
io_unlock($file);
return false;
}
}else{
} else {
@unlink($file);
}
@ -420,8 +424,8 @@ function io_lock($file)
//waited longer than 3 seconds? -> stale lock
if ((time() - $timeStart) > 3) break;
$locked = @mkdir($lockDir);
if($locked){
if($conf['dperm']) chmod($lockDir, $conf['dperm']);
if ($locked) {
if ($conf['dperm']) chmod($lockDir, $conf['dperm']);
break;
}
usleep(50);
@ -473,7 +477,8 @@ function io_createNamespace($id, $ns_type = 'pages')
while (!@is_dir($tmp) && !(file_exists($tmp) && !is_dir($tmp))) {
array_pop($ns_stack);
$ns = implode(':', $ns_stack);
if (strlen($ns)==0) { break; }
if (strlen($ns)==0) {
break; }
$missing[] = $ns;
$tmp = dirname(call_user_func($types[$ns_type], $ns));
}
@ -497,7 +502,7 @@ function io_createNamespace($id, $ns_type = 'pages')
function io_makeFileDir($file)
{
$dir = dirname($file);
if(!@is_dir($dir)){
if (!@is_dir($dir)) {
io_mkdir_p($dir) || msg("Creating directory $dir failed", -1);
}
}
@ -518,9 +523,9 @@ function io_mkdir_p($target)
if (@is_dir($target)||empty($target)) return 1; // best case check first
if (file_exists($target) && !is_dir($target)) return 0;
//recursion
if (io_mkdir_p(substr($target, 0, strrpos($target, '/')))){
if (io_mkdir_p(substr($target, 0, strrpos($target, '/')))) {
$ret = @mkdir($target); // crawl back up & create dir tree
if($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
if ($ret && !empty($conf['dperm'])) chmod($target, $conf['dperm']);
return $ret;
}
return 0;
@ -536,15 +541,15 @@ function io_mkdir_p($target)
*/
function io_rmdir($path, $removefiles = false)
{
if(!is_string($path) || $path == "") return false;
if(!file_exists($path)) return true; // it's already gone or was never there, count as success
if (!is_string($path) || $path == "") return false;
if (!file_exists($path)) return true; // it's already gone or was never there, count as success
if (is_dir($path) && !is_link($path)) {
$dirs = [];
$files = [];
if(!$dh = @opendir($path)) return false;
while(false !== ($f = readdir($dh))) {
if($f == '..' || $f == '.') continue;
if (!$dh = @opendir($path)) return false;
while (false !== ($f = readdir($dh))) {
if ($f == '..' || $f == '.') continue;
// collect dirs and files first
if (is_dir("$path/$f") && !is_link("$path/$f")) {
@ -554,16 +559,15 @@ function io_rmdir($path, $removefiles = false)
} else {
return false; // abort when non empty
}
}
closedir($dh);
// now traverse into directories first
foreach($dirs as $dir) {
if(!io_rmdir($dir, $removefiles)) return false; // abort on any error
foreach ($dirs as $dir) {
if (!io_rmdir($dir, $removefiles)) return false; // abort on any error
}
// now delete files
foreach($files as $file) {
if(!@unlink($file)) return false; //abort on any error
foreach ($files as $file) {
if (!@unlink($file)) return false; //abort on any error
}
// remove self
return @rmdir($path);
@ -589,7 +593,7 @@ function io_mktmpdir()
$dir = md5(uniqid(random_int(0, mt_getrandmax()), true));
$tmpdir = $base.'/'.$dir;
if(io_mkdir_p($tmpdir)) {
if (io_mkdir_p($tmpdir)) {
return($tmpdir);
} else {
return false;
@ -627,7 +631,7 @@ function io_download($url, $file, $useAttachment = false, $defaultName = '', $ma
$http->keep_alive = false; // we do single ops here, no need for keep-alive
$data = $http->get($url);
if(!$data) return false;
if (!$data) return false;
$name = '';
if ($useAttachment) {
@ -636,10 +640,8 @@ function io_download($url, $file, $useAttachment = false, $defaultName = '', $ma
$match=[];
if (is_string($content_disposition) &&
preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
$name = PhpString::basename($match[1]);
}
}
if (!$name) {
@ -652,10 +654,10 @@ function io_download($url, $file, $useAttachment = false, $defaultName = '', $ma
$fileexists = file_exists($file);
$fp = @fopen($file, "w");
if(!$fp) return false;
if (!$fp) return false;
fwrite($fp, $data);
fclose($fp);
if(!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
if (!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
if ($useAttachment) return $name;
return true;
}
@ -673,9 +675,9 @@ function io_download($url, $file, $useAttachment = false, $defaultName = '', $ma
function io_rename($from, $to)
{
global $conf;
if(!@rename($from, $to)){
if(@copy($from, $to)){
if($conf['fperm']) chmod($to, $conf['fperm']);
if (!@rename($from, $to)) {
if (@copy($from, $to)) {
if ($conf['fperm']) chmod($to, $conf['fperm']);
@unlink($from);
return true;
}
@ -703,7 +705,7 @@ function io_exec($cmd, $input, &$output)
2=>["pipe", "w"]
];
$ph = proc_open($cmd, $descspec, $pipes);
if(!$ph) return -1;
if (!$ph) return -1;
fclose($pipes[2]); // ignore stderr
fwrite($pipes[0], $input);
fclose($pipes[0]);
@ -729,25 +731,25 @@ function io_exec($cmd, $input, &$output)
function io_grep($file, $pattern, $max = 0, $backref = false)
{
$fh = @fopen($file, 'r');
if(!$fh) return false;
if (!$fh) return false;
$matches = [];
$cnt = 0;
$line = '';
while (!feof($fh)) {
$line .= fgets($fh, 4096); // read full line
if(substr($line, -1) != "\n") continue;
if (substr($line, -1) != "\n") continue;
// check if line matches
if(preg_match($pattern, $line, $match)){
if($backref){
if (preg_match($pattern, $line, $match)) {
if ($backref) {
$matches[] = $match;
}else{
} else {
$matches[] = $line;
}
$cnt++;
}
if($max && $max == $cnt) break;
if ($max && $max == $cnt) break;
$line = '';
}
fclose($fh);
@ -770,26 +772,26 @@ function io_getSizeFile($file)
if (substr($file, -3) == '.gz') {
$fp = @fopen($file, "rb");
if($fp === false) return 0;
if ($fp === false) return 0;
fseek($fp, -4, SEEK_END);
$buffer = fread($fp, 4);
fclose($fp);
$array = unpack("V", $buffer);
$uncompressedsize = end($array);
} elseif (substr($file, -4) == '.bz2') {
if(!DOKU_HAS_BZIP) return 0;
if (!DOKU_HAS_BZIP) return 0;
$bz = bzopen($file, "r");
if($bz === false) return 0;
if ($bz === false) return 0;
$uncompressedsize = 0;
while (!feof($bz)) {
//8192 seems to be the maximum buffersize?
$buffer = bzread($bz, 8192);
if(($buffer === false) || (bzerrno($bz) !== 0)) {
if (($buffer === false) || (bzerrno($bz) !== 0)) {
return 0;
}
$uncompressedsize += strlen($buffer);
}
} else{
} else {
$uncompressedsize = filesize($file);
}

View File

@ -54,7 +54,7 @@ require_once(DOKU_INC.'inc/legacy.php');
function load_autoload($name)
{
static $classes = null;
if($classes === null) $classes = [
if ($classes === null) $classes = [
'Diff' => DOKU_INC.'inc/DifferenceEngine.php',
'UnifiedDiffFormatter' => DOKU_INC.'inc/DifferenceEngine.php',
'TableDiffFormatter' => DOKU_INC.'inc/DifferenceEngine.php',
@ -76,7 +76,7 @@ function load_autoload($name)
'Doku_Renderer_metadata' => DOKU_INC.'inc/parser/metadata.php'
];
if(isset($classes[$name])){
if (isset($classes[$name])) {
require($classes[$name]);
return true;
}
@ -103,10 +103,10 @@ function load_autoload($name)
}
// plugin namespace
if(substr($name, 0, 16) === 'dokuwiki/plugin/') {
if (substr($name, 0, 16) === 'dokuwiki/plugin/') {
$name = str_replace('/test/', '/_test/', $name); // no underscore in test namespace
$file = DOKU_PLUGIN . substr($name, 16) . '.php';
if(file_exists($file)) {
if (file_exists($file)) {
try {
require $file;
} catch (\Throwable $e) {
@ -117,10 +117,10 @@ function load_autoload($name)
}
// template namespace
if(substr($name, 0, 18) === 'dokuwiki/template/') {
if (substr($name, 0, 18) === 'dokuwiki/template/') {
$name = str_replace('/test/', '/_test/', $name); // no underscore in test namespace
$file = DOKU_INC.'lib/tpl/' . substr($name, 18) . '.php';
if(file_exists($file)) {
if (file_exists($file)) {
try {
require $file;
} catch (\Throwable $e) {
@ -131,16 +131,16 @@ function load_autoload($name)
}
// our own namespace
if(substr($name, 0, 9) === 'dokuwiki/') {
if (substr($name, 0, 9) === 'dokuwiki/') {
$file = DOKU_INC . 'inc/' . substr($name, 9) . '.php';
if(file_exists($file)) {
if (file_exists($file)) {
require $file;
return true;
}
}
// Plugin loading
if(preg_match(
if (preg_match(
'/^(' . implode('|', PluginController::PLUGIN_TYPES) . ')_plugin_(' .
DOKU_PLUGIN_NAME_REGEX .
')(?:_([^_]+))?$/',
@ -150,7 +150,7 @@ function load_autoload($name)
// try to load the wanted plugin file
$c = ((count($m) === 4) ? "/{$m[3]}" : '');
$plg = DOKU_PLUGIN . "{$m[2]}/{$m[1]}$c.php";
if(file_exists($plg)){
if (file_exists($plg)) {
try {
require $plg;
} catch (\Throwable $e) {

View File

@ -43,22 +43,22 @@ function mail_setup()
// auto constructed address
$host = @parse_url(DOKU_URL, PHP_URL_HOST);
if(!$host) $host = 'example.com';
if (!$host) $host = 'example.com';
$noreply = 'noreply@'.$host;
$replace = [];
if(!empty($USERINFO['mail'])){
if (!empty($USERINFO['mail'])) {
$replace['@MAIL@'] = $USERINFO['mail'];
}else{
} else {
$replace['@MAIL@'] = $noreply;
}
// use 'noreply' if no user
$replace['@USER@'] = $INPUT->server->str('REMOTE_USER', 'noreply', true);
if(!empty($USERINFO['name'])){
if (!empty($USERINFO['name'])) {
$replace['@NAME@'] = $USERINFO['name'];
}else{
} else {
$replace['@NAME@'] = '';
}
@ -70,9 +70,9 @@ function mail_setup()
);
// any replacements done? set different mailfromnone
if($from != $conf['mailfrom']){
if ($from != $conf['mailfrom']) {
$conf['mailfromnobody'] = $noreply;
}else{
} else {
$conf['mailfromnobody'] = $from;
}
$conf['mailfrom'] = $from;
@ -131,7 +131,7 @@ function mail_quotedprintable_encode($sText, $maxlen = 74, $bEmulate_imap_8bit =
// here is, where I don't agree with imap_8_bit,
// please correct me, if I'm wrong,
// or comment next line for RFC2045 conformance, if you like
if (!($bEmulate_imap_8bit && ($i==count($aLines)-1))){
if (!($bEmulate_imap_8bit && ($i==count($aLines)-1))) {
if (($iLastChar==0x09)||($iLastChar==0x20)) {
$sLine[$iLength-1]='=';
$sLine .= ($iLastChar==0x09)?'09':'20';
@ -152,7 +152,7 @@ function mail_quotedprintable_encode($sText, $maxlen = 74, $bEmulate_imap_8bit =
// at the very first character of the line
// and after soft linebreaks, as well,
// but this wouldn't be caught by such an easy RegExp
if($maxlen){
if ($maxlen) {
preg_match_all('/.{1,'.($maxlen - 2).'}([^=]{0,2})?/', $sLine, $aMatch);
$sLine = implode('=' . MAILHEADER_EOL, $aMatch[0]); // add soft crlf's
}

View File

@ -40,15 +40,14 @@ function media_filesinuse($data, $id)
echo '<p>'.hsc($lang['ref_inuse']).'</p>';
$hidden=0; //count of hits without read permission
foreach($data as $row){
if(auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)){
foreach ($data as $row) {
if (auth_quickaclcheck($row) >= AUTH_READ && isVisiblePage($row)) {
echo '<div class="search_result">';
echo '<span class="mediaref_ref">'.hsc($row).'</span>';
echo '</div>';
}else
$hidden++;
} else $hidden++;
}
if ($hidden){
if ($hidden) {
print '<div class="mediaref_hidden">'.$lang['ref_hidden'].'</div>';
}
}
@ -66,8 +65,8 @@ function media_filesinuse($data, $id)
*/
function media_metasave($id, $auth, $data)
{
if($auth < AUTH_UPLOAD) return false;
if(!checkSecurityToken()) return false;
if ($auth < AUTH_UPLOAD) return false;
if (!checkSecurityToken()) return false;
global $lang;
global $conf;
$src = mediaFN($id);
@ -75,23 +74,23 @@ function media_metasave($id, $auth, $data)
$meta = new JpegMeta($src);
$meta->_parseAll();
foreach($data as $key => $val){
foreach ($data as $key => $val) {
$val=trim($val);
if(empty($val)){
if (empty($val)) {
$meta->deleteField($key);
}else{
} else {
$meta->setField($key, $val);
}
}
$old = @filemtime($src);
if(!file_exists(mediaFN($id, $old)) && file_exists($src)) {
if (!file_exists(mediaFN($id, $old)) && file_exists($src)) {
// add old revision to the attic
media_saveOldRevision($id);
}
$filesize_old = filesize($src);
if($meta->save()){
if($conf['fperm']) chmod($src, $conf['fperm']);
if ($meta->save()) {
if ($conf['fperm']) chmod($src, $conf['fperm']);
@clearstatcache(true, $src);
$new = @filemtime($src);
$filesize_new = filesize($src);
@ -102,7 +101,7 @@ function media_metasave($id, $auth, $data)
msg($lang['metasaveok'], 1);
return $id;
}else{
} else {
msg($lang['metasaveerr'], -1);
return false;
}
@ -132,9 +131,9 @@ function media_isexternal($id)
*/
function media_ispublic($id)
{
if(media_isexternal($id)) return true;
if (media_isexternal($id)) return true;
$id = cleanID($id);
if(auth_aclcheck(getNS($id).':*', '', []) >= AUTH_READ) return true;
if (auth_aclcheck(getNS($id).':*', '', []) >= AUTH_READ) return true;
return false;
}
@ -227,9 +226,9 @@ function media_inuse($id)
{
global $conf;
if($conf['refcheck']){
if ($conf['refcheck']) {
$mediareferences = ft_mediause($id, true);
if($mediareferences === []) {
if ($mediareferences === []) {
return false;
} else {
return $mediareferences;
@ -258,8 +257,8 @@ function media_delete($id, $auth)
{
global $lang;
$auth = auth_quickaclcheck(ltrim(getNS($id).':*', ':'));
if($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
if(media_inuse($id)) return DOKU_MEDIA_INUSE;
if ($auth < AUTH_DELETE) return DOKU_MEDIA_NOT_AUTH;
if (media_inuse($id)) return DOKU_MEDIA_INUSE;
$file = mediaFN($id);
@ -275,13 +274,13 @@ function media_delete($id, $auth)
$evt = new Event('MEDIA_DELETE_FILE', $data);
if ($evt->advise_before()) {
$old = @filemtime($file);
if(!file_exists(mediaFN($id, $old)) && file_exists($file)) {
if (!file_exists(mediaFN($id, $old)) && file_exists($file)) {
// add old revision to the attic
media_saveOldRevision($id);
}
$data['unl'] = @unlink($file);
if($data['unl']) {
if ($data['unl']) {
$sizechange = 0 - $data['size'];
addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_DELETE, $lang['deleted'], '', null, $sizechange);
@ -291,7 +290,7 @@ function media_delete($id, $auth)
$evt->advise_after();
unset($evt);
if($data['unl'] && $data['del']){
if ($data['unl'] && $data['del']) {
return DOKU_MEDIA_DELETED | DOKU_MEDIA_EMPTY_NS;
}
@ -307,7 +306,7 @@ function media_delete($id, $auth)
*/
function media_upload_xhr($ns, $auth)
{
if(!checkSecurityToken()) return false;
if (!checkSecurityToken()) return false;
global $INPUT;
$id = $INPUT->get->str('qqfile');
@ -353,26 +352,26 @@ function media_upload_xhr($ns, $auth)
*/
function media_upload($ns, $auth, $file = false)
{
if(!checkSecurityToken()) return false;
if (!checkSecurityToken()) return false;
global $lang;
global $INPUT;
// get file and id
$id = $INPUT->post->str('mediaid');
if (!$file) $file = $_FILES['upload'];
if(empty($id)) $id = $file['name'];
if (empty($id)) $id = $file['name'];
// check for errors (messages are done in lib/exe/mediamanager.php)
if($file['error']) return false;
if ($file['error']) return false;
// check extensions
[$fext, $fmime] = mimetype($file['name']);
[$iext, $imime] = mimetype($id);
if($fext && !$iext){
if ($fext && !$iext) {
// no extension specified in id - read original one
$id .= '.'.$fext;
$imime = $fmime;
}elseif($fext && $fext != $iext){
} elseif ($fext && $fext != $iext) {
// extension was changed, print warning
msg(sprintf($lang['mediaextchange'], $fext, $iext));
}
@ -408,7 +407,7 @@ function media_upload($ns, $auth, $file = false)
*/
function copy_uploaded_file($from, $to)
{
if(!is_uploaded_file($from)) return false;
if (!is_uploaded_file($from)) return false;
$ok = copy($from, $to);
@unlink($from);
return $ok;
@ -438,7 +437,7 @@ function copy_uploaded_file($from, $to)
*/
function media_save($file, $id, $ow, $auth, $move)
{
if($auth < AUTH_UPLOAD) {
if ($auth < AUTH_UPLOAD) {
return ["You don't have permissions to upload files.", -1];
}
@ -467,23 +466,23 @@ function media_save($file, $id, $ow, $auth, $move)
$regex = implode('|', $types);
// because a temp file was created already
if(!preg_match('/\.('.$regex.')$/i', $fn)) {
if (!preg_match('/\.('.$regex.')$/i', $fn)) {
return [$lang['uploadwrong'], -1];
}
//check for overwrite
$overwrite = file_exists($fn);
$auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
if($overwrite && (!$ow || $auth < $auth_ow)) {
if ($overwrite && (!$ow || $auth < $auth_ow)) {
return [$lang['uploadexist'], 0];
}
// check for valid content
$ok = media_contentcheck($file['name'], $file['mime']);
if($ok == -1){
if ($ok == -1) {
return [sprintf($lang['uploadbadcontent'], '.' . $file['ext']), -1];
}elseif($ok == -2){
} elseif ($ok == -2) {
return [$lang['uploadspam'], -1];
}elseif($ok == -3){
} elseif ($ok == -3) {
return [$lang['uploadxss'], -1];
}
@ -511,7 +510,7 @@ function media_save($file, $id, $ow, $auth, $move)
function _media_upload_action($data)
{
// fixme do further sanity tests of given data?
if(is_array($data) && count($data)===6) {
if (is_array($data) && count($data)===6) {
return media_upload_finish($data[0], $data[1], $data[2], $data[3], $data[4], $data[5]);
} else {
return false; //callback error
@ -540,7 +539,7 @@ function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'mov
global $REV;
$old = @filemtime($fn);
if(!file_exists(mediaFN($id, $old)) && file_exists($fn)) {
if (!file_exists(mediaFN($id, $old)) && file_exists($fn)) {
// add old revision to the attic if missing
media_saveOldRevision($id);
}
@ -550,7 +549,7 @@ function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'mov
$filesize_old = file_exists($fn) ? filesize($fn) : 0;
if($move($fn_tmp, $fn)) {
if ($move($fn_tmp, $fn)) {
@clearstatcache(true, $fn);
$new = @filemtime($fn);
// Set the correct permission here.
@ -562,7 +561,7 @@ function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'mov
// add a log entry to the media changelog
$filesize_new = filesize($fn);
$sizechange = $filesize_new - $filesize_old;
if($REV) {
if ($REV) {
addMediaLogEntry(
$new,
$id,
@ -572,13 +571,13 @@ function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'mov
null,
$sizechange
);
} elseif($overwrite) {
} elseif ($overwrite) {
addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange);
} else {
addMediaLogEntry($new, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'], '', null, $sizechange);
}
return $id;
}else{
} else {
return [$lang['uploadfail'], -1];
}
}
@ -606,7 +605,7 @@ function media_saveOldRevision($id)
// there was an external edit,
// there is no log entry for current version of file
$sizechange = filesize($oldf);
if(!file_exists(mediaMetaFN($id, '.changes'))) {
if (!file_exists(mediaMetaFN($id, '.changes'))) {
addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'], '', null, $sizechange);
} else {
$oldRev = $medialog->getRevisions(-1, 1); // from changelog
@ -647,30 +646,30 @@ function media_saveOldRevision($id)
function media_contentcheck($file, $mime)
{
global $conf;
if($conf['iexssprotect']){
if ($conf['iexssprotect']) {
$fh = @fopen($file, 'rb');
if($fh){
if ($fh) {
$bytes = fread($fh, 256);
fclose($fh);
if(preg_match('/<(script|a|img|html|body|iframe)[\s>]/i', $bytes)){
if (preg_match('/<(script|a|img|html|body|iframe)[\s>]/i', $bytes)) {
return -3; //XSS: possibly malicious content
}
}
}
if(substr($mime, 0, 6) == 'image/'){
if (substr($mime, 0, 6) == 'image/') {
$info = @getimagesize($file);
if($mime == 'image/gif' && $info[2] != 1){
if ($mime == 'image/gif' && $info[2] != 1) {
return -1; // uploaded content did not match the file extension
}elseif($mime == 'image/jpeg' && $info[2] != 2){
} elseif ($mime == 'image/jpeg' && $info[2] != 2) {
return -1;
}elseif($mime == 'image/png' && $info[2] != 3){
} elseif ($mime == 'image/png' && $info[2] != 3) {
return -1;
}
# fixme maybe check other images types as well
}elseif(substr($mime, 0, 5) == 'text/'){
} elseif (substr($mime, 0, 5) == 'text/') {
global $TEXT;
$TEXT = io_readFile($file);
if(checkwordblock()){
if (checkwordblock()) {
return -2; //blocked by the spam blacklist
}
}
@ -690,7 +689,7 @@ function media_contentcheck($file, $mime)
function media_notify($id, $file, $mime, $old_rev = false, $current_rev = false)
{
global $conf;
if(empty($conf['notify'])) return; //notify enabled?
if (empty($conf['notify'])) return; //notify enabled?
$subscription = new MediaSubscriptionSender();
$subscription->sendMediaDiff($conf['notify'], 'uploadmail', $id, $old_rev, $current_rev);
@ -712,14 +711,14 @@ function media_filelist($ns, $auth = null, $jump = '', $fullscreenview = false,
$ns = cleanID($ns);
// check auth our self if not given (needed for ajax calls)
if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if (is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if (!$fullscreenview) echo '<h1 id="media__ns">:'.hsc($ns).'</h1>'.NL;
if($auth < AUTH_READ){
if ($auth < AUTH_READ) {
// FIXME: print permission warning here instead?
echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
}else{
} else {
if (!$fullscreenview) {
media_uploadform($ns, $auth);
media_searchform($ns);
@ -737,13 +736,13 @@ function media_filelist($ns, $auth = null, $jump = '', $fullscreenview = false,
$sort
);
if(!count($data)){
if (!count($data)) {
echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
}else {
} else {
if ($fullscreenview) {
echo '<ul class="' . _media_get_list_type() . '">';
}
foreach($data as $item){
foreach ($data as $item) {
if (!$fullscreenview) {
//FIXME old call: media_printfile($item,$auth,$jump);
$display = new DisplayRow($item);
@ -776,7 +775,7 @@ function media_tabs_files($selected_tab = '')
{
global $lang;
$tabs = [];
foreach([
foreach ([
'files' => 'mediaselect',
'upload' => 'media_uploadtab',
'search' => 'media_searchtab'
@ -937,11 +936,11 @@ function _media_get_display_param($param, $values)
function media_tab_files($ns, $auth = null, $jump = '')
{
global $lang;
if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if (is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if($auth < AUTH_READ){
if ($auth < AUTH_READ) {
echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
}else{
} else {
media_filelist($ns, $auth, $jump, true, _media_get_sort_type());
}
}
@ -958,7 +957,7 @@ function media_tab_files($ns, $auth = null, $jump = '')
function media_tab_upload($ns, $auth = null, $jump = '')
{
global $lang;
if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if (is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
echo '<div class="upload">'.NL;
if ($auth >= AUTH_UPLOAD) {
@ -1004,14 +1003,13 @@ function media_tab_search($ns, $auth = null)
function media_tab_view($image, $ns, $auth = null, $rev = '')
{
global $lang;
if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if (is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if ($image && $auth >= AUTH_READ) {
$meta = new JpegMeta(mediaFN($image, $rev));
media_preview($image, $auth, $rev, $meta);
media_preview_buttons($image, $auth, $rev);
media_details($image, $auth, $rev, $meta);
} else {
echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
}
@ -1028,7 +1026,7 @@ function media_tab_view($image, $ns, $auth = null, $rev = '')
*/
function media_tab_edit($image, $ns, $auth = null)
{
if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if (is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if ($image) {
[, $mime] = mimetype($image);
@ -1050,11 +1048,11 @@ function media_tab_history($image, $ns, $auth = null)
global $lang;
global $INPUT;
if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if (is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
$do = $INPUT->str('mediado');
if ($auth >= AUTH_READ && $image) {
if ($do == 'diff'){
if ($do == 'diff') {
(new MediaDiff($image))->show(); //media_diff($image, $ns, $auth);
} else {
$first = $INPUT->int('first', -1);
@ -1120,7 +1118,6 @@ function media_preview_buttons($image, $auth, $rev = '')
echo '<ul class="actions">';
if ($auth >= AUTH_DELETE && !$rev && file_exists(mediaFN($image))) {
// delete button
$form = new Form([
'id' => 'mediamanager__btn_delete',
@ -1136,7 +1133,6 @@ function media_preview_buttons($image, $auth, $rev = '')
$auth_ow = (($conf['mediarevisions']) ? AUTH_UPLOAD : AUTH_DELETE);
if ($auth >= $auth_ow && !$rev) {
// upload new version button
$form = new Form([
'id' => 'mediamanager__btn_update',
@ -1151,7 +1147,6 @@ function media_preview_buttons($image, $auth, $rev = '')
}
if ($auth >= AUTH_UPLOAD && $rev && $conf['mediarevisions'] && file_exists(mediaFN($image, $rev))) {
// restore button
$form = new Form([
'id' => 'mediamanager__btn_restore',
@ -1266,7 +1261,7 @@ function media_details($image, $auth, $rev = '', $meta = false)
$tags = media_file_tags($meta);
echo '<dl>'.NL;
foreach($tags as $tag){
foreach ($tags as $tag) {
if ($tag['value']) {
$value = cleanText($tag['value']);
echo '<dt>'.$lang[$tag['tag'][1]].'</dt><dd>';
@ -1279,11 +1274,11 @@ function media_details($image, $auth, $rev = '', $meta = false)
echo '<dl>'.NL;
echo '<dt>'.$lang['reference'].':</dt>';
$media_usage = ft_mediause($image, true);
if($media_usage !== []){
foreach($media_usage as $path){
if ($media_usage !== []) {
foreach ($media_usage as $path) {
echo '<dd>'.html_wikilink($path).'</dd>';
}
}else{
} else {
echo '<dd>'.$lang['nothingfound'].'</dd>';
}
echo '</dl>'.NL;
@ -1445,13 +1440,13 @@ function media_searchlist($query, $ns, $auth = null, $fullscreen = false, $sort
media_searchform($ns, $query);
}
if(!count($evdata['data'])){
if (!count($evdata['data'])) {
echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
}else {
} else {
if ($fullscreen) {
echo '<ul class="' . _media_get_list_type() . '">';
}
foreach($evdata['data'] as $item){
foreach ($evdata['data'] as $item) {
if (!$fullscreen) {
// FIXME old call: media_printfile($item,$item['perm'],'',true);
$display = new DisplayRow($item);
@ -1574,7 +1569,7 @@ function media_uploadform($ns, $auth, $fullscreen = false)
->val(noNS($id));
$form->addButton('', $lang['btn_upload'])->attr('type', 'submit');
$form->addTagClose('p');
if ($auth >= $auth_ow){
if ($auth >= $auth_ow) {
$form->addTagOpen('p');
$attrs = [];
if ($update) $attrs['checked'] = 'checked';
@ -1617,9 +1612,9 @@ function media_getuploadsize()
$suho = php_to_byte(@ini_get('suhosin.post.max_value_length'));
$upld = php_to_byte(@ini_get('upload_max_filesize'));
if($post && ($post < $okay || $okay === 0)) $okay = $post;
if($suho && ($suho < $okay || $okay == 0)) $okay = $suho;
if($upld && ($upld < $okay || $okay == 0)) $okay = $upld;
if ($post && ($post < $okay || $okay === 0)) $okay = $post;
if ($suho && ($suho < $okay || $okay == 0)) $okay = $suho;
if ($upld && ($upld < $okay || $okay == 0)) $okay = $upld;
return $okay;
}
@ -1674,7 +1669,7 @@ function media_nstree($ns)
// currently selected namespace
$ns = cleanID($ns);
if(empty($ns)){
if (empty($ns)) {
global $ID;
$ns = (string)getNS($ID);
}
@ -1726,7 +1721,7 @@ function media_nstree_item($item)
global $INPUT;
$pos = strrpos($item['id'], ':');
$label = substr($item['id'], $pos > 0 ? $pos + 1 : 0);
if(empty($item['label'])) $item['label'] = $label;
if (empty($item['label'])) $item['label'] = $label;
$ret = '';
if ($INPUT->str('do') != 'media')
@ -1751,11 +1746,11 @@ function media_nstree_item($item)
function media_nstree_li($item)
{
$class='media level'.$item['level'];
if($item['open']){
if ($item['open']) {
$class .= ' open';
$img = DOKU_BASE.'lib/images/minus.gif';
$alt = '';
}else{
} else {
$class .= ' closed';
$img = DOKU_BASE.'lib/images/plus.gif';
$alt = '+';
@ -1780,9 +1775,9 @@ function media_nstree_li($item)
function media_mod_image($file, $ext, $w, $h = 0, $crop = false)
{
global $conf;
if(!$h) $h = 0;
if (!$h) $h = 0;
// we wont scale up to infinity
if($w > 2000 || $h > 2000) return $file;
if ($w > 2000 || $h > 2000) return $file;
$operation = $crop ? 'crop' : 'resize';
@ -1792,13 +1787,13 @@ function media_mod_image($file, $ext, $w, $h = 0, $crop = false)
];
$cache = new CacheImageMod($file, $w, $h, $ext, $crop);
if(!$cache->useCache()) {
if (!$cache->useCache()) {
try {
Slika::run($file, $options)
->autorotate()
->$operation($w, $h)
->save($cache->cache, $ext);
if($conf['fperm']) @chmod($cache->cache, $conf['fperm']);
if ($conf['fperm']) @chmod($cache->cache, $conf['fperm']);
} catch (Exception $e) {
Logger::debug($e->getMessage());
return $file;
@ -1892,10 +1887,10 @@ function media_get_from_URL($url, $ext, $cache)
$mtime = @filemtime($local); // 0 if not exists
//decide if download needed:
if(($mtime == 0) || // cache does not exist
if (($mtime == 0) || // cache does not exist
($cache != -1 && $mtime < time() - $cache) // 'recache' and cache has expired
) {
if(media_image_download($url, $local)) {
if (media_image_download($url, $local)) {
return $local;
} else {
return false;
@ -1903,7 +1898,7 @@ function media_get_from_URL($url, $ext, $cache)
}
//if cache exists use it else
if($mtime) return $local;
if ($mtime) return $local;
//else return false
return false;
@ -1929,18 +1924,18 @@ function media_image_download($url, $file)
$http->header_regexp = '!\r\nContent-Type: image/(jpe?g|gif|png)!i';
$data = $http->get($url);
if(!$data) return false;
if (!$data) return false;
$fileexists = file_exists($file);
$fp = @fopen($file, "w");
if(!$fp) return false;
if (!$fp) return false;
fwrite($fp, $data);
fclose($fp);
if(!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
if (!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
// check if it is really an image
$info = @getimagesize($file);
if(!$info){
if (!$info) {
@unlink($file);
return false;
}
@ -1968,7 +1963,7 @@ function media_resize_imageIM($ext, $from, $from_w, $from_h, $to, $to_w, $to_h)
global $conf;
// check if convert is configured
if(!$conf['im_convert']) return false;
if (!$conf['im_convert']) return false;
// prepare command
$cmd = $conf['im_convert'];
@ -2006,7 +2001,7 @@ function media_crop_imageIM($ext, $from, $from_w, $from_h, $to, $to_w, $to_h, $o
dbg_deprecated('splitbrain\\Slika');
// check if convert is configured
if(!$conf['im_convert']) return false;
if (!$conf['im_convert']) return false;
// prepare command
$cmd = $conf['im_convert'];
@ -2044,49 +2039,48 @@ function media_resize_imageGD($ext, $from, $from_w, $from_h, $to, $to_w, $to_h,
global $conf;
dbg_deprecated('splitbrain\\Slika');
if($conf['gdlib'] < 1) return false; //no GDlib available or wanted
if ($conf['gdlib'] < 1) return false; //no GDlib available or wanted
// check available memory
if(!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))){
if (!is_mem_available(($from_w * $from_h * 4) + ($to_w * $to_h * 4))) {
return false;
}
// create an image of the given filetype
$image = false;
if ($ext == 'jpg' || $ext == 'jpeg'){
if(!function_exists("imagecreatefromjpeg")) return false;
if ($ext == 'jpg' || $ext == 'jpeg') {
if (!function_exists("imagecreatefromjpeg")) return false;
$image = @imagecreatefromjpeg($from);
}elseif($ext == 'png') {
if(!function_exists("imagecreatefrompng")) return false;
} elseif ($ext == 'png') {
if (!function_exists("imagecreatefrompng")) return false;
$image = @imagecreatefrompng($from);
}elseif($ext == 'gif') {
if(!function_exists("imagecreatefromgif")) return false;
} elseif ($ext == 'gif') {
if (!function_exists("imagecreatefromgif")) return false;
$image = @imagecreatefromgif($from);
}
if(!$image) return false;
if (!$image) return false;
$newimg = false;
if(($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif'){
if (($conf['gdlib']>1) && function_exists("imagecreatetruecolor") && $ext != 'gif') {
$newimg = @imagecreatetruecolor($to_w, $to_h);
}
if(!$newimg) $newimg = @imagecreate($to_w, $to_h);
if(!$newimg){
if (!$newimg) $newimg = @imagecreate($to_w, $to_h);
if (!$newimg) {
imagedestroy($image);
return false;
}
//keep png alpha channel if possible
if($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')){
if ($ext == 'png' && $conf['gdlib']>1 && function_exists('imagesavealpha')) {
imagealphablending($newimg, false);
imagesavealpha($newimg, true);
}
//keep gif transparent color if possible
if($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
if ($ext == 'gif' && function_exists('imagefill') && function_exists('imagecolorallocate')) {
if (function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) {
$transcolorindex = @imagecolortransparent($image);
if($transcolorindex >= 0 ) { //transparent color exists
if ($transcolorindex >= 0 ) { //transparent color exists
$transcolor = @imagecolorsforindex($image, $transcolorindex);
$transcolorindex = @imagecolorallocate(
$newimg,
@ -2096,42 +2090,42 @@ function media_resize_imageGD($ext, $from, $from_w, $from_h, $to, $to_w, $to_h,
);
@imagefill($newimg, 0, 0, $transcolorindex);
@imagecolortransparent($newimg, $transcolorindex);
}else{ //filling with white
} else { //filling with white
$whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
@imagefill($newimg, 0, 0, $whitecolorindex);
}
}else{ //filling with white
} else { //filling with white
$whitecolorindex = @imagecolorallocate($newimg, 255, 255, 255);
@imagefill($newimg, 0, 0, $whitecolorindex);
}
}
//try resampling first
if(function_exists("imagecopyresampled")){
if(!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
if (function_exists("imagecopyresampled")) {
if (!@imagecopyresampled($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h)) {
imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
}
}else{
} else {
imagecopyresized($newimg, $image, 0, 0, $ofs_x, $ofs_y, $to_w, $to_h, $from_w, $from_h);
}
$okay = false;
if ($ext == 'jpg' || $ext == 'jpeg'){
if(!function_exists('imagejpeg')){
if ($ext == 'jpg' || $ext == 'jpeg') {
if (!function_exists('imagejpeg')) {
$okay = false;
}else{
} else {
$okay = imagejpeg($newimg, $to, $conf['jpg_quality']);
}
}elseif($ext == 'png') {
if(!function_exists('imagepng')){
} elseif ($ext == 'png') {
if (!function_exists('imagepng')) {
$okay = false;
}else{
} else {
$okay = imagepng($newimg, $to);
}
}elseif($ext == 'gif') {
if(!function_exists('imagegif')){
} elseif ($ext == 'gif') {
if (!function_exists('imagegif')) {
$okay = false;
}else{
} else {
$okay = imagegif($newimg, $to);
}
}
@ -2160,10 +2154,10 @@ function media_alternativefiles($src, $exts)
[$srcExt, /* srcMime */] = mimetype($src);
$filebase = substr($src, 0, -1 * (strlen($srcExt)+1));
foreach($exts as $ext) {
foreach ($exts as $ext) {
$fileid = $filebase.'.'.$ext;
$file = mediaFN($fileid);
if(file_exists($file)) {
if (file_exists($file)) {
[/* fileExt */, $fileMime] = mimetype($file);
$files[$fileMime] = $fileid;
}
@ -2227,8 +2221,8 @@ function media_trackfiles($src)
$baseid=pathinfo($src, PATHINFO_FILENAME);
$pattern=mediaFN($baseid).'.*.*.vtt';
$list=glob($pattern);
foreach($list as $track) {
if(preg_match($re, $track, $matches)){
foreach ($list as $track) {
if (preg_match($re, $track, $matches)) {
$files[$baseid.'.'.$matches[1].'.'.$matches[2].'.vtt']=[$kinds[$matches[1]], $matches[2]];
}
}

View File

@ -357,10 +357,8 @@ function p_set_metadata($id, $data, $render = false, $persistent = true)
// now add the passed metadata
$protected = ['description', 'date', 'contributor'];
foreach ($data as $key => $value) {
// be careful with sub-arrays of $meta['relation']
if ($key == 'relation') {
foreach ($value as $subkey => $subvalue) {
if (isset($meta['current'][$key][$subkey]) && is_array($meta['current'][$key][$subkey])) {
$meta['current'][$key][$subkey] = array_replace($meta['current'][$key][$subkey], (array)$subvalue);
@ -381,7 +379,6 @@ function p_set_metadata($id, $data, $render = false, $persistent = true)
// be careful with some senisitive arrays of $meta
} elseif (in_array($key, $protected)) {
// these keys, must have subkeys - a legitimate value must be an array
if (is_array($value)) {
$meta['current'][$key] = empty($meta['current'][$key]) ?
@ -433,7 +430,6 @@ function p_purge_metadata($id)
} else {
$meta['current'][$key] = '';
}
}
return p_save_metadata($id, $meta);
}
@ -518,7 +514,6 @@ function p_render_metadata($id, $orig)
$orig['page'] = $id;
$evt = new Event('PARSER_METADATA_RENDER', $orig);
if ($evt->advise_before()) {
// get instructions
$instructions = p_cached_instructions(wikiFN($id), false, $id);
if (is_null($instructions)) {
@ -801,7 +796,6 @@ function p_xhtml_cached_geshi($code, $language, $wrapper = 'pre', array $options
$ctime > filemtime(reset($config_cascade['main']['default']))) { // dokuwiki changed
$highlighted_code = io_readFile($cache, false);
} else {
$geshi = new GeSHi($code, $language);
$geshi->set_encoding('utf-8');
$geshi->enable_classes();

View File

@ -11,10 +11,10 @@ use dokuwiki\Extension\AdminPlugin;
use dokuwiki\Extension\PluginController;
use dokuwiki\Extension\PluginInterface;
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
// note that only [a-z0-9]+ is officially supported,
// this is only to support plugins that don't follow these conventions, too
if(!defined('DOKU_PLUGIN_NAME_REGEX')) define('DOKU_PLUGIN_NAME_REGEX', '[a-zA-Z0-9\x7f-\xff]+');
if (!defined('DOKU_PLUGIN_NAME_REGEX')) define('DOKU_PLUGIN_NAME_REGEX', '[a-zA-Z0-9\x7f-\xff]+');
/**
* Original plugin functions, remain for backwards compatibility

View File

@ -32,16 +32,16 @@ function search(&$data, $base, $func, $opts, $dir = '', $lvl = 1, $sort = 'natur
$filepaths = [];
// safeguard against runaways #1452
if($base == '' || $base == '/') {
if ($base == '' || $base == '/') {
throw new RuntimeException('No valid $base passed to search() - possible misconfiguration or bug');
}
//read in directories and files
$dh = @opendir($base.'/'.$dir);
if(!$dh) return;
while(($file = readdir($dh)) !== false){
if(preg_match('/^[\._]/', $file)) continue; //skip hidden files and upper dirs
if(is_dir($base.'/'.$dir.'/'.$file)){
if (!$dh) return;
while (($file = readdir($dh)) !== false) {
if (preg_match('/^[\._]/', $file)) continue; //skip hidden files and upper dirs
if (is_dir($base.'/'.$dir.'/'.$file)) {
$dirs[] = $dir.'/'.$file;
continue;
}
@ -59,13 +59,13 @@ function search(&$data, $base, $func, $opts, $dir = '', $lvl = 1, $sort = 'natur
}
//give directories to userfunction then recurse
foreach($dirs as $dir){
if (call_user_func_array($func, [&$data, $base, $dir, 'd', $lvl, $opts])){
foreach ($dirs as $dir) {
if (call_user_func_array($func, [&$data, $base, $dir, 'd', $lvl, $opts])) {
search($data, $base, $func, $opts, $dir, $lvl+1, $sort);
}
}
//now handle the files
foreach($files as $file){
foreach ($files as $file) {
call_user_func_array($func, [&$data, $base, $file, 'f', $lvl, $opts]);
}
}
@ -192,29 +192,29 @@ function search_media(&$data, $base, $file, $type, $lvl, $opts)
{
//we do nothing with directories
if($type == 'd') {
if(empty($opts['depth'])) return true; // recurse forever
if ($type == 'd') {
if (empty($opts['depth'])) return true; // recurse forever
$depth = substr_count($file, '/');
if($depth >= $opts['depth']) return false; // depth reached
if ($depth >= $opts['depth']) return false; // depth reached
return true;
}
$info = [];
$info['id'] = pathID($file, true);
if($info['id'] != cleanID($info['id'])){
if(!empty($opts['showmsg']))
if ($info['id'] != cleanID($info['id'])) {
if (!empty($opts['showmsg']))
msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped', -1);
return false; // skip non-valid files
}
//check ACL for namespace (we have no ACL for mediafiles)
$info['perm'] = auth_quickaclcheck(getNS($info['id']).':*');
if(empty($opts['skipacl']) && $info['perm'] < AUTH_READ){
if (empty($opts['skipacl']) && $info['perm'] < AUTH_READ) {
return false;
}
//check pattern filter
if(!empty($opts['pattern']) && !@preg_match($opts['pattern'], $info['id'])){
if (!empty($opts['pattern']) && !@preg_match($opts['pattern'], $info['id'])) {
return false;
}
@ -222,13 +222,13 @@ function search_media(&$data, $base, $file, $type, $lvl, $opts)
$info['size'] = filesize($base.'/'.$file);
$info['mtime'] = filemtime($base.'/'.$file);
$info['writable'] = is_writable($base.'/'.$file);
if(preg_match("/\.(jpe?g|gif|png)$/", $file)){
if (preg_match("/\.(jpe?g|gif|png)$/", $file)) {
$info['isimg'] = true;
$info['meta'] = new JpegMeta($base.'/'.$file);
}else{
} else {
$info['isimg'] = false;
}
if(!empty($opts['hash'])){
if (!empty($opts['hash'])) {
$info['hash'] = md5(io_readFile(mediaFN($info['id']), false));
}
@ -260,28 +260,28 @@ function search_mediafiles(&$data, $base, $file, $type, $lvl, $opts)
{
//we do nothing with directories
if($type == 'd') {
if(empty($opts['depth'])) return true; // recurse forever
if ($type == 'd') {
if (empty($opts['depth'])) return true; // recurse forever
$depth = substr_count($file, '/');
if($depth >= $opts['depth']) return false; // depth reached
if ($depth >= $opts['depth']) return false; // depth reached
return true;
}
$id = pathID($file, true);
if($id != cleanID($id)){
if($opts['showmsg'])
if ($id != cleanID($id)) {
if ($opts['showmsg'])
msg(hsc($id).' is not a valid file name for DokuWiki - skipped', -1);
return false; // skip non-valid files
}
//check ACL for namespace (we have no ACL for mediafiles)
$info['perm'] = auth_quickaclcheck(getNS($id).':*');
if(empty($opts['skipacl']) && $info['perm'] < AUTH_READ){
if (empty($opts['skipacl']) && $info['perm'] < AUTH_READ) {
return false;
}
//check pattern filter
if(!empty($opts['pattern']) && !@preg_match($opts['pattern'], $id)){
if (!empty($opts['pattern']) && !@preg_match($opts['pattern'], $id)) {
return false;
}
@ -307,12 +307,12 @@ function search_mediafiles(&$data, $base, $file, $type, $lvl, $opts)
function search_list(&$data, $base, $file, $type, $lvl, $opts)
{
//we do nothing with directories
if($type == 'd') return false;
if ($type == 'd') return false;
//only search txt files
if(substr($file, -4) == '.txt'){
if (substr($file, -4) == '.txt') {
//check ACL
$id = pathID($file);
if(auth_quickaclcheck($id) < AUTH_READ){
if (auth_quickaclcheck($id) < AUTH_READ) {
return false;
}
$data[]['id'] = $id;
@ -339,16 +339,16 @@ function search_list(&$data, $base, $file, $type, $lvl, $opts)
function search_pagename(&$data, $base, $file, $type, $lvl, $opts)
{
//we do nothing with directories
if($type == 'd') return true;
if ($type == 'd') return true;
//only search txt files
if(substr($file, -4) != '.txt') return true;
if (substr($file, -4) != '.txt') return true;
//simple stringmatching
if (!empty($opts['query'])){
if(strpos($file, (string) $opts['query']) !== false){
if (!empty($opts['query'])) {
if (strpos($file, (string) $opts['query']) !== false) {
//check ACL
$id = pathID($file);
if(auth_quickaclcheck($id) < AUTH_READ){
if (auth_quickaclcheck($id) < AUTH_READ) {
return false;
}
$data[]['id'] = $id;
@ -377,32 +377,32 @@ function search_pagename(&$data, $base, $file, $type, $lvl, $opts)
*/
function search_allpages(&$data, $base, $file, $type, $lvl, $opts)
{
if(isset($opts['depth']) && $opts['depth']){
if (isset($opts['depth']) && $opts['depth']) {
$parts = explode('/', ltrim($file, '/'));
if(($type == 'd' && count($parts) >= $opts['depth'])
|| ($type != 'd' && count($parts) > $opts['depth'])){
if (($type == 'd' && count($parts) >= $opts['depth'])
|| ($type != 'd' && count($parts) > $opts['depth'])) {
return false; // depth reached
}
}
//we do nothing with directories
if($type == 'd'){
if ($type == 'd') {
return true;
}
//only search txt files
if(substr($file, -4) != '.txt') return true;
if (substr($file, -4) != '.txt') return true;
$item = [];
$item['id'] = pathID($file);
if(empty($opts['skipacl']) && auth_quickaclcheck($item['id']) < AUTH_READ){
if (empty($opts['skipacl']) && auth_quickaclcheck($item['id']) < AUTH_READ) {
return false;
}
$item['rev'] = filemtime($base.'/'.$file);
$item['mtime'] = $item['rev'];
$item['size'] = filesize($base.'/'.$file);
if(!empty($opts['hash'])){
if (!empty($opts['hash'])) {
$item['hash'] = md5(trim(rawWiki($item['id'])));
}
@ -427,11 +427,11 @@ function search_allpages(&$data, $base, $file, $type, $lvl, $opts)
*/
function sort_search_fulltext($a, $b)
{
if($a['count'] > $b['count']){
if ($a['count'] > $b['count']) {
return -1;
}elseif($a['count'] < $b['count']){
} elseif ($a['count'] < $b['count']) {
return 1;
}else{
} else {
return Sort::strcmp($a['id'], $b['id']);
}
}
@ -451,7 +451,7 @@ function pathID($path, $keeptxt = false)
{
$id = utf8_decodeFN($path);
$id = str_replace('/', ':', $id);
if(!$keeptxt) $id = preg_replace('#\.txt$#', '', $id);
if (!$keeptxt) $id = preg_replace('#\.txt$#', '', $id);
$id = trim($id, ':');
return $id;
}
@ -501,23 +501,23 @@ function search_universal(&$data, $base, $file, $type, $lvl, $opts)
// get ID and check if it is a valid one
$item['id'] = pathID($file, ($type == 'd' || !empty($opts['keeptxt'])));
if($item['id'] != cleanID($item['id'])){
if(!empty($opts['showmsg'])){
if ($item['id'] != cleanID($item['id'])) {
if (!empty($opts['showmsg'])) {
msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped', -1);
}
return false; // skip non-valid files
}
$item['ns'] = getNS($item['id']);
if($type == 'd') {
if ($type == 'd') {
// decide if to recursion into this directory is wanted
if(empty($opts['depth'])){
if (empty($opts['depth'])) {
$return = true; // recurse forever
}else{
} else {
$depth = substr_count($file, '/');
if($depth >= $opts['depth']){
if ($depth >= $opts['depth']) {
$return = false; // depth reached
}else{
} else {
$return = true;
}
}
@ -531,30 +531,30 @@ function search_universal(&$data, $base, $file, $type, $lvl, $opts)
}
// check ACL
if(empty($opts['skipacl'])){
if($type == 'd'){
if (empty($opts['skipacl'])) {
if ($type == 'd') {
$item['perm'] = auth_quickaclcheck($item['id'].':*');
}else{
} else {
$item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
}
}else{
} else {
$item['perm'] = AUTH_DELETE;
}
// are we done here maybe?
if($type == 'd'){
if(empty($opts['listdirs'])) return $return;
if ($type == 'd') {
if (empty($opts['listdirs'])) return $return;
//neither list nor recurse forbidden items:
if(empty($opts['skipacl']) && !empty($opts['sneakyacl']) && $item['perm'] < AUTH_READ) return false;
if(!empty($opts['dirmatch']) && !preg_match('/'.$opts['dirmatch'].'/', $file)) return $return;
if(!empty($opts['nsmatch']) && !preg_match('/'.$opts['nsmatch'].'/', $item['ns'])) return $return;
}else{
if(empty($opts['listfiles'])) return $return;
if(empty($opts['skipacl']) && $item['perm'] < AUTH_READ) return $return;
if(!empty($opts['pagesonly']) && (substr($file, -4) != '.txt')) return $return;
if(empty($opts['showhidden']) && isHiddenPage($item['id'])) return $return;
if(!empty($opts['filematch']) && !preg_match('/'.$opts['filematch'].'/', $file)) return $return;
if(!empty($opts['idmatch']) && !preg_match('/'.$opts['idmatch'].'/', $item['id'])) return $return;
if (empty($opts['skipacl']) && !empty($opts['sneakyacl']) && $item['perm'] < AUTH_READ) return false;
if (!empty($opts['dirmatch']) && !preg_match('/'.$opts['dirmatch'].'/', $file)) return $return;
if (!empty($opts['nsmatch']) && !preg_match('/'.$opts['nsmatch'].'/', $item['ns'])) return $return;
} else {
if (empty($opts['listfiles'])) return $return;
if (empty($opts['skipacl']) && $item['perm'] < AUTH_READ) return $return;
if (!empty($opts['pagesonly']) && (substr($file, -4) != '.txt')) return $return;
if (empty($opts['showhidden']) && isHiddenPage($item['id'])) return $return;
if (!empty($opts['filematch']) && !preg_match('/'.$opts['filematch'].'/', $file)) return $return;
if (!empty($opts['idmatch']) && !preg_match('/'.$opts['idmatch'].'/', $item['id'])) return $return;
}
// still here? prepare the item
@ -562,7 +562,7 @@ function search_universal(&$data, $base, $file, $type, $lvl, $opts)
$item['level'] = $lvl;
$item['open'] = $return;
if(!empty($opts['meta'])){
if (!empty($opts['meta'])) {
$item['file'] = PhpString::basename($file);
$item['size'] = filesize($base.'/'.$file);
$item['mtime'] = filemtime($base.'/'.$file);
@ -571,9 +571,9 @@ function search_universal(&$data, $base, $file, $type, $lvl, $opts)
$item['executable'] = is_executable($base.'/'.$file);
}
if($type == 'f'){
if(!empty($opts['hash'])) $item['hash'] = md5(io_readFile($base.'/'.$file, false));
if(!empty($opts['firsthead'])) $item['title'] = p_get_first_heading($item['id'], METADATA_DONT_RENDER);
if ($type == 'f') {
if (!empty($opts['hash'])) $item['hash'] = md5(io_readFile($base.'/'.$file, false));
if (!empty($opts['firsthead'])) $item['title'] = p_get_first_heading($item['id'], METADATA_DONT_RENDER);
}
// finally add the item

File diff suppressed because it is too large Load Diff

View File

@ -20,8 +20,7 @@ function toolbar_JSdefines($varname)
$menu = [];
$evt = new Event('TOOLBAR_DEFINE', $menu);
if ($evt->advise_before()){
if ($evt->advise_before()) {
// build button array
$menu = array_merge($menu, [
[

View File

@ -30,18 +30,15 @@ if (preg_match('/^\/_media\/(.*)/', $_SERVER['SCRIPT_NAME'], $m)) {
// media dispatcher
$_GET['media'] = $m[1];
require $_SERVER['DOCUMENT_ROOT'] . '/lib/exe/fetch.php';
} elseif (preg_match('/^\/_detail\/(.*)/', $_SERVER['SCRIPT_NAME'], $m)) {
// image detail view
$_GET['media'] = $m[1];
require $_SERVER['DOCUMENT_ROOT'] . '/lib/exe/detail.php';
} elseif (preg_match('/^\/_export\/([^\/]+)\/(.*)/', $_SERVER['SCRIPT_NAME'], $m)) {
// exports
$_GET['do'] = 'export_' . $m[1];
$_GET['id'] = $m[2];
require $_SERVER['DOCUMENT_ROOT'] . '/doku.php';
} elseif (
$_SERVER['SCRIPT_NAME'] !== '/index.php' &&
file_exists($_SERVER['DOCUMENT_ROOT'] . $_SERVER['SCRIPT_NAME'])

View File

@ -137,7 +137,6 @@ 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])) {
continue;

View File

@ -33,7 +33,7 @@ $smi_list = '';
foreach (glob('*.svg') as $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.'" /> ';

View File

@ -542,7 +542,7 @@ class auth_plugin_authad extends AuthPlugin
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)] = [];
}

View File

@ -221,7 +221,7 @@ class auth_plugin_authplain extends AuthPlugin
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;
}
@ -340,12 +340,12 @@ class auth_plugin_authplain extends AuthPlugin
$groups = [];
if ($this->users === null) $this->loadUserData();
foreach($this->users as $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);
@ -442,7 +442,7 @@ class auth_plugin_authplain extends AuthPlugin
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);
}

View File

@ -41,24 +41,24 @@ class admin_plugin_config extends AdminPlugin
// 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, ['do' => 'admin', 'page' => 'config'], true, '&'));
@ -83,7 +83,7 @@ class admin_plugin_config extends AdminPlugin
echo '<div id="config__manager">';
if($this->configuration->isLocked()) {
if ($this->configuration->isLocked()) {
echo '<div class="info">' . $this->getLang('locked') . '</div>';
}
@ -98,12 +98,12 @@ class admin_plugin_config extends AdminPlugin
$in_fieldset = false;
$first_plugin_fieldset = true;
$first_template_fieldset = true;
foreach($this->configuration->getSettings() as $setting) {
foreach ($this->configuration->getSettings() as $setting) {
if ($setting instanceof SettingHidden) {
continue;
} elseif ($setting instanceof SettingFieldset) {
// config setting group
if($in_fieldset) {
if ($in_fieldset) {
echo '</table>';
echo '</div>';
echo '</fieldset>';
@ -148,13 +148,13 @@ class admin_plugin_config extends AdminPlugin
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
*
@ -172,7 +172,7 @@ class admin_plugin_config extends AdminPlugin
echo '<fieldset>';
echo '<div class="table">';
echo '<table class="inline">';
foreach($undefined_settings as $setting) {
foreach ($undefined_settings as $setting) {
[$label, $input] = $setting->html($this);
echo '<tr>';
echo '<td class="label">' . $label . '</td>';
@ -189,7 +189,7 @@ class admin_plugin_config extends AdminPlugin
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>';
@ -207,7 +207,7 @@ class admin_plugin_config extends AdminPlugin
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;
}
@ -229,8 +229,8 @@ class admin_plugin_config extends AdminPlugin
// gather settings data into three sub arrays
$labels = ['dokuwiki' => [], 'plugin' => [], 'template' => []];
foreach($this->configuration->getSettings() as $setting) {
if($setting instanceof SettingFieldset) {
foreach ($this->configuration->getSettings() as $setting) {
if ($setting instanceof SettingFieldset) {
$labels[$setting->getType()][] = $setting;
}
}
@ -240,8 +240,8 @@ class admin_plugin_config extends AdminPlugin
$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(
@ -251,7 +251,7 @@ class admin_plugin_config extends AdminPlugin
);
// 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);
@ -259,7 +259,7 @@ class admin_plugin_config extends AdminPlugin
}
// 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);
}
@ -285,7 +285,7 @@ class admin_plugin_config extends AdminPlugin
*/
public function addLang($key, $value)
{
if(!$this->localised) $this->setupLocale();
if (!$this->localised) $this->setupLocale();
$this->lang[$key] = $value;
}
}

View File

@ -27,13 +27,13 @@ class ConfigParser
*/
public function parse($file)
{
if(!file_exists($file)) return [];
if (!file_exists($file)) return [];
$config = [];
$contents = @php_strip_whitespace($file);
// fallback to simply including the file #3271
if($contents === null) {
if ($contents === null) {
$conf = [];
include $file;
return $conf;
@ -44,19 +44,19 @@ class ConfigParser
preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER);
$counter = count($matches);
for($i = 0; $i < $counter; $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]);
}
@ -87,9 +87,9 @@ class ConfigParser
'\\"' => '"'
];
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

View File

@ -108,12 +108,12 @@ class Configuration
{
$ok = true;
foreach($this->settings as $key => $obj) {
foreach ($this->settings as $key => $obj) {
$value = $input[$key] ?? null;
if($obj->update($value)) {
if ($obj->update($value)) {
$this->changed = true;
}
if($obj->hasError()) $ok = false;
if ($obj->hasError()) $ok = false;
}
return $ok;
@ -167,10 +167,10 @@ class Configuration
];
$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);
}
@ -192,7 +192,7 @@ class Configuration
*/
protected function instantiateClass($key)
{
if(isset($this->metadata[$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);
@ -214,12 +214,12 @@ class Configuration
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 {

View File

@ -49,7 +49,7 @@ class Loader
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(
@ -128,7 +128,7 @@ class Loader
$lang = [];
// plugins
foreach($this->plugins as $plugin) {
foreach ($this->plugins as $plugin) {
$lang = array_merge(
$lang,
$this->loadExtensionLang(
@ -183,7 +183,7 @@ class Loader
protected function loadConfigs($files)
{
$conf = [];
foreach($files as $file) {
foreach ($files as $file) {
$conf = array_merge($conf, $this->parser->parse($file));
}
return $conf;
@ -201,19 +201,19 @@ class Loader
*/
protected function loadExtensionMeta($file, $type, $extname)
{
if(!file_exists($file)) return [];
if (!file_exists($file)) return [];
$prefix = $type . Configuration::KEYMARKER . $extname . Configuration::KEYMARKER;
// include file
$meta = [];
include $file;
if($meta === []) return [];
if ($meta === []) return [];
// read data
$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;
}
@ -232,16 +232,16 @@ class Loader
*/
protected function loadExtensionConf($file, $type, $extname)
{
if(!file_exists($file)) return [];
if (!file_exists($file)) return [];
$prefix = $type . Configuration::KEYMARKER . $extname . Configuration::KEYMARKER;
// parse file
$conf = $this->parser->parse($file);
if(empty($conf)) return [];
if (empty($conf)) return [];
// read data
$data = [];
foreach($conf as $key => $value) {
foreach ($conf as $key => $value) {
$data[$prefix . $key] = $value;
}
@ -264,16 +264,16 @@ class Loader
// include files
$lang = [];
if(file_exists($dir . 'lang/en/settings.php')) {
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 = [];
foreach($lang as $key => $val) {
foreach ($lang as $key => $val) {
$strings[$prefix . $key] = $val;
}

View File

@ -41,8 +41,8 @@ class Setting
{
$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;
}
@ -76,15 +76,15 @@ class Setting
*/
public function update($input)
{
if(is_null($input)) return false;
if($this->isProtected()) return false;
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;
@ -142,8 +142,8 @@ class Setting
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 {
@ -224,9 +224,9 @@ class Setting
*/
public function shouldBeSaved()
{
if($this->isProtected()) return false;
if($this->local === null) return false;
if($this->default == $this->local) return false;
if ($this->isProtected()) return false;
if ($this->local === null) return false;
if ($this->default == $this->local) return false;
return true;
}
@ -274,7 +274,7 @@ class Setting
public function prompt(\admin_plugin_config $plugin)
{
$prompt = $plugin->getLang($this->key);
if(!$prompt) $prompt = htmlspecialchars(str_replace(['____', '_'], ' ', $this->key));
if (!$prompt) $prompt = htmlspecialchars(str_replace(['____', '_'], ' ', $this->key));
return $prompt;
}
@ -315,8 +315,8 @@ class Setting
*/
public function caution()
{
if(empty($this->caution)) return false;
if(!in_array($this->caution, Setting::$validCautions)) {
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 . '"'
);

View File

@ -43,16 +43,16 @@ class SettingArray extends Setting
*/
public function update($input)
{
if(is_null($input)) return false;
if($this->isProtected()) return false;
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;

View File

@ -15,7 +15,7 @@ class SettingAuthtype extends SettingMultichoice
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;
}
@ -30,21 +30,21 @@ class SettingAuthtype extends SettingMultichoice
// 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;
@ -52,7 +52,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();
}

View File

@ -15,8 +15,8 @@ class SettingCompression extends SettingMultichoice
{
// 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);
}

View File

@ -17,13 +17,13 @@ class SettingDirchoice extends SettingMultichoice
// populate $this->_choices with a list of directories
$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);
}

View File

@ -16,8 +16,8 @@ class SettingDisableactions extends SettingMulticheckbox
// 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);

View File

@ -13,18 +13,18 @@ class SettingEmail extends SettingString
/** @inheritdoc */
public function update($input)
{
if(is_null($input)) return false;
if($this->isProtected()) return false;
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);
@ -32,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 = [$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;

View File

@ -11,14 +11,14 @@ class SettingImConvert extends SettingString
/** @inheritdoc */
public function update($input)
{
if($this->isProtected()) return false;
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;

View File

@ -15,7 +15,7 @@ class SettingLicense extends SettingMultichoice
{
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
}

View File

@ -15,16 +15,16 @@ class SettingMulticheckbox extends SettingString
/** @inheritdoc */
public function update($input)
{
if($this->isProtected()) return false;
if ($this->isProtected()) return false;
// split any combined values + convert from array to comma separated string
$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;
@ -56,7 +56,7 @@ 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);
@ -74,17 +74,16 @@ 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') {
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)))
@ -115,15 +114,15 @@ class SettingMulticheckbox extends SettingString
{
$array = explode(',', $str);
if(!empty($this->combine)) {
foreach($this->combine as $key => $combinators) {
if (!empty($this->combine)) {
foreach ($this->combine as $key => $combinators) {
$idx = [];
foreach($combinators as $val) {
if(($idx[] = array_search($val, $array)) === false) break;
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;
}
}
@ -149,11 +148,10 @@ class SettingMulticheckbox extends SettingString
$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);
}

View File

@ -16,7 +16,7 @@ class SettingMultichoice extends SettingString
$disable = '';
$nochoice = '';
if($this->isProtected()) {
if ($this->isProtected()) {
$value = $this->protected;
$disable = ' disabled="disabled"';
} else {
@ -24,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');
}
@ -39,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);
@ -60,13 +60,13 @@ class SettingMultichoice extends SettingString
/** @inheritdoc */
public function update($input)
{
if(is_null($input)) return false;
if($this->isProtected()) return false;
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;

View File

@ -19,9 +19,9 @@ class SettingNumeric extends SettingString
{
$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) ||
if ((!is_null($this->min) && $numeric_local < $this->min) ||
(!is_null($this->max) && $numeric_local > $this->max)) {
$this->error = true;
$this->input = $input;
@ -35,7 +35,7 @@ class SettingNumeric extends SettingString
/** @inheritdoc */
public function out($var, $fmt = 'php')
{
if($fmt != 'php') return '';
if ($fmt != 'php') return '';
$local = $this->local === '' ? "''" : $this->local;
$out = '$' . $var . "['" . $this->getArrayKey() . "'] = " . $local . ";\n";

View File

@ -16,8 +16,8 @@ class SettingNumericopt extends SettingNumeric
*/
public function update($input)
{
if($input === '') {
if($input == $this->local) return false;
if ($input === '') {
if ($input == $this->local) return false;
$this->local = $input;
return true;
}

View File

@ -14,12 +14,12 @@ class SettingOnoff extends SettingNumeric
*/
protected function cleanValue($value)
{
if($value === null) return null;
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;
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;
@ -30,7 +30,7 @@ class SettingOnoff extends SettingNumeric
{
$disable = '';
if($this->isProtected()) {
if ($this->isProtected()) {
$value = $this->protected;
$disable = ' disabled="disabled"';
} else {
@ -49,11 +49,11 @@ class SettingOnoff extends SettingNumeric
/** @inheritdoc */
public function update($input)
{
if($this->isProtected()) return false;
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;

View File

@ -13,10 +13,10 @@ class SettingPassword extends SettingString
/** @inheritdoc */
public function update($input)
{
if($this->isProtected()) return false;
if(!$input) return false;
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;

View File

@ -17,14 +17,14 @@ class SettingRegex extends SettingString
// 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;

View File

@ -20,9 +20,9 @@ class SettingRenderer extends SettingMultichoice
{
$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();
@ -39,9 +39,9 @@ class SettingRenderer extends SettingMultichoice
// 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)

View File

@ -11,12 +11,12 @@ class SettingSavedir extends SettingString
/** @inheritdoc */
public function update($input)
{
if($this->isProtected()) 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(!init_path($input)) {
if (!init_path($input)) {
$this->error = true;
$this->input = $input;
return false;

Some files were not shown because too many files have changed in this diff Show More