Apply rector fixes to the rest of inc

This commit is contained in:
Andreas Gohr 2023-08-29 19:42:15 +02:00
parent bcaec9f47d
commit 24870174d2
40 changed files with 1365 additions and 1380 deletions

View File

@ -22,9 +22,13 @@ use Rector\CodingStyle\Rector\Stmt\NewlineAfterStatementRector;
use Rector\CodingStyle\Rector\String_\SymplifyQuoteEscapeRector;
use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessParamTagRector;
use Rector\DeadCode\Rector\For_\RemoveDeadContinueRector;
use Rector\DeadCode\Rector\For_\RemoveDeadIfForeachForRector;
use Rector\DeadCode\Rector\If_\RemoveAlwaysTrueIfConditionRector;
use Rector\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector;
use Rector\DeadCode\Rector\Property\RemoveUselessVarTagRector;
use Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector;
use Rector\DeadCode\Rector\Stmt\RemoveUnreachableStatementRector;
use Rector\Php71\Rector\ClassConst\PublicConstantVisibilityRector;
use Rector\Php71\Rector\FuncCall\CountOnNullRector;
use Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector;
@ -34,18 +38,13 @@ use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector;
return static function (RectorConfig $rectorConfig): void {
define('DOKU_INC', __DIR__ . '/../');
define('DOKU_BASE','/');
define('DOKU_URL','http://localhost/');
define('DOKU_COOKIE','DWCOOKIE');
$rectorConfig->paths([
__DIR__ . '/../inc',
__DIR__ . '/../lib',
]);
$rectorConfig->bootstrapFiles([
__DIR__ . '/../inc/load.php',
__DIR__ . '/../inc/init.php',
]);
$rectorConfig->importNames();
@ -71,6 +70,8 @@ return static function (RectorConfig $rectorConfig): void {
__DIR__ . '/../lib/plugins/*/vendor/*',
__DIR__ . '/../lib/tpl/*/vendor/*',
__DIR__ . '/../lib/plugins/*/skel/*', // dev plugin
__DIR__ . '/../inc/deprecated.php',
__DIR__ . '/../inc/form.php',
// third party libs, not yet moved to composer
__DIR__ . '/../inc/DifferenceEngine.php',
@ -104,5 +105,6 @@ return static function (RectorConfig $rectorConfig): void {
JoinStringConcatRector::class, // this does not count variables, so it creates overlong lines
RemoveExtraParametersRector::class, // this actually broke code
RemoveUnusedNonEmptyArrayBeforeForeachRector::class, // seems unreliable when checking on array keys
RemoveAlwaysTrueIfConditionRector::class, // fails with if(defined(...)) constructs
]);
};

View File

@ -2,6 +2,7 @@
namespace dokuwiki;
use dokuwiki\Extension\Event;
use dokuwiki\Action\AbstractAction;
use dokuwiki\Action\Exception\ActionDisabledException;
use dokuwiki\Action\Exception\ActionException;
@ -19,7 +20,7 @@ class ActionRouter {
protected $action;
/** @var ActionRouter */
protected static $instance = null;
protected static $instance;
/** @var int transition counter */
protected $transitions = 0;
@ -42,7 +43,6 @@ class ActionRouter {
$this->disabled = explode(',', $conf['disableactions']);
$this->disabled = array_map('trim', $this->disabled);
$this->transitions = 0;
$ACT = act_clean($ACT);
$this->setupAction($ACT);
@ -56,7 +56,7 @@ class ActionRouter {
* @return ActionRouter
*/
public static function getInstance($reinit = false) {
if((self::$instance === null) || $reinit) {
if((!self::$instance instanceof \dokuwiki\ActionRouter) || $reinit) {
self::$instance = new ActionRouter();
}
return self::$instance;
@ -76,7 +76,7 @@ class ActionRouter {
try {
// give plugins an opportunity to process the actionname
$evt = new Extension\Event('ACTION_ACT_PREPROCESS', $actionname);
$evt = new Event('ACTION_ACT_PREPROCESS', $actionname);
if ($evt->advise_before()) {
$this->action = $this->loadAction($actionname);
$this->checkAction($this->action);
@ -92,7 +92,7 @@ class ActionRouter {
$actionname = $e->getNewAction();
// this one should trigger a user message
if(is_a($e, ActionDisabledException::class)) {
if($e instanceof ActionDisabledException) {
msg('Action disabled: ' . hsc($presetup), -1);
}
@ -147,8 +147,8 @@ class ActionRouter {
* @param \Exception|FatalException $e
* @throws FatalException during unit testing
*/
protected function handleFatalException(\Exception $e) {
if(is_a($e, FatalException::class)) {
protected function handleFatalException(\Throwable $e) {
if($e instanceof FatalException) {
http_status($e->getCode());
} else {
http_status(500);
@ -178,8 +178,8 @@ class ActionRouter {
public function loadAction($actionname) {
$actionname = strtolower($actionname); // FIXME is this needed here? should we run a cleanup somewhere else?
$parts = explode('_', $actionname);
while(!empty($parts)) {
$load = join('_', $parts);
while($parts !== []) {
$load = implode('_', $parts);
$class = 'dokuwiki\\Action\\' . str_replace('_', '', ucwords($load, '_'));
if(class_exists($class)) {
return new $class($actionname);

View File

@ -2,6 +2,9 @@
namespace dokuwiki;
use dokuwiki\Extension\Event;
use dokuwiki\Ui\MediaDiff;
use dokuwiki\Ui\Index;
use dokuwiki\Ui;
use dokuwiki\Utf8\Sort;
@ -23,7 +26,7 @@ class Ajax {
if(method_exists($this, $callfn)) {
$this->$callfn();
} else {
$evt = new Extension\Event('AJAX_CALL_UNKNOWN', $call);
$evt = new Event('AJAX_CALL_UNKNOWN', $call);
if($evt->advise_before()) {
print "AJAX call '" . hsc($call) . "' unknown!\n";
} else {
@ -52,7 +55,7 @@ class Ajax {
$data = ft_pageLookup($query, true, useHeading('navigation'));
if(!count($data)) return;
if($data === []) return;
print '<strong>' . $lang['quickhits'] . '</strong>';
print '<ul>';
@ -93,7 +96,7 @@ class Ajax {
if(empty($query)) return;
$data = ft_pageLookup($query);
if(!count($data)) return;
if($data === []) return;
$data = array_keys($data);
// limit results to 15 hits
@ -104,15 +107,15 @@ class Ajax {
Sort::sort($data);
/* now construct a json */
$suggestions = array(
$query, // the original query
$data, // some suggestions
array(), // no description
array() // no urls
);
$suggestions = [
$query, // the original query
$data, // some suggestions
[], // no description
[], // no urls
];
header('Content-Type: application/x-suggestions+json');
print json_encode($suggestions);
print json_encode($suggestions, JSON_THROW_ON_ERROR);
}
/**
@ -152,7 +155,7 @@ class Ajax {
} else {
$response['errors'] = array_merge($response['errors'], $draft->getErrors());
}
echo json_encode($response);
echo json_encode($response, JSON_THROW_ON_ERROR);
}
/**
@ -189,8 +192,8 @@ class Ajax {
$lvl = count(explode(':', $ns));
$data = array();
search($data, $conf['mediadir'], 'search_index', array('nofiles' => true), $dir);
$data = [];
search($data, $conf['mediadir'], 'search_index', ['nofiles' => true], $dir);
foreach(array_keys($data) as $item) {
$data[$item]['level'] = $lvl + 1;
}
@ -247,7 +250,7 @@ class Ajax {
$image = '';
if($INPUT->has('image')) $image = cleanID($INPUT->str('image'));
(new Ui\MediaDiff($image))->preference('fromAjax', true)->show();
(new MediaDiff($image))->preference('fromAjax', true)->show();
}
/**
@ -282,12 +285,12 @@ class Ajax {
if($INPUT->get->has('qqfile')) $res = media_upload_xhr($NS, $AUTH);
if($res) {
$result = array(
$result = [
'success' => true,
'link' => media_managerURL(array('ns' => $ns, 'image' => $NS . ':' . $id), '&'),
'link' => media_managerURL(['ns' => $ns, 'image' => $NS . ':' . $id], '&'),
'id' => $NS . ':' . $id,
'ns' => $NS
);
];
} else {
$error = '';
if(isset($MSG)) {
@ -295,14 +298,11 @@ class Ajax {
$error .= $msg['msg'];
}
}
$result = array(
'error' => $error,
'ns' => $NS
);
$result = ['error' => $error, 'ns' => $NS];
}
header('Content-Type: application/json');
echo json_encode($result);
echo json_encode($result, JSON_THROW_ON_ERROR);
}
/**
@ -320,12 +320,12 @@ class Ajax {
$lvl = count(explode(':', $ns));
$data = array();
search($data, $conf['datadir'], 'search_index', array('ns' => $ns), $dir);
$data = [];
search($data, $conf['datadir'], 'search_index', ['ns' => $ns], $dir);
foreach (array_keys($data) as $item) {
$data[$item]['level'] = $lvl + 1;
}
$idx = new Ui\Index;
$idx = new Index;
echo html_buildlist($data, 'idx', [$idx,'formatListItem'], [$idx,'tagListItem']);
}
@ -344,11 +344,12 @@ class Ajax {
$ns = getNS($q);
$ns = cleanID($ns);
$id = cleanID($id);
$nsd = utf8_encodeFN(str_replace(':', '/', $ns));
$data = array();
$data = [];
if($q !== '' && $ns === '') {
// use index to lookup matching pages
@ -356,15 +357,15 @@ class Ajax {
// If 'useheading' option is 'always' or 'content',
// search page titles with original query as well.
if ($conf['useheading'] == '1' || $conf['useheading'] == 'content') {
if ($conf['useheading'] == '1' || $conf['useheading'] == 'content') {
$pages = array_merge($pages, ft_pageLookup($q, true, true));
asort($pages, SORT_STRING);
}
// result contains matches in pages and namespaces
// we now extract the matching namespaces to show
// them seperately
$dirs = array();
$dirs = [];
foreach($pages as $pid => $title) {
if(strpos(getNS($pid), $id) !== false) {
@ -372,31 +373,24 @@ class Ajax {
$dirs[getNS($pid)] = 1; // assoc array avoids dupes
} else {
// it is a matching page, add it to the result
$data[] = array(
'id' => $pid,
'title' => $title,
'type' => 'f',
);
$data[] = ['id' => $pid, 'title' => $title, 'type' => 'f'];
}
unset($pages[$pid]);
}
foreach($dirs as $dir => $junk) {
$data[] = array(
'id' => $dir,
'type' => 'd',
);
foreach(array_keys($dirs) as $dir) {
$data[] = ['id' => $dir, 'type' => 'd'];
}
} else {
$opts = array(
$opts = [
'depth' => 1,
'listfiles' => true,
'listdirs' => true,
'pagesonly' => true,
'firsthead' => true,
'sneakyacl' => $conf['sneaky_index'],
);
'sneakyacl' => $conf['sneaky_index']
];
if($id) $opts['filematch'] = '^.*\/' . $id;
if($id) $opts['dirmatch'] = '^.*\/' . $id;
search($data, $conf['datadir'], 'search_universal', $opts, $nsd);
@ -404,10 +398,7 @@ class Ajax {
// add back to upper
if($ns) {
array_unshift(
$data, array(
'id' => getNS($ns),
'type' => 'u',
)
$data, ['id' => getNS($ns), 'type' => 'u']
);
}
}

View File

@ -2,6 +2,7 @@
namespace dokuwiki;
use dokuwiki\Extension\Event;
/**
* Class Draft
*
@ -86,7 +87,7 @@ class Draft
'cname' => $this->cname,
'errors' => [],
];
$event = new Extension\Event('DRAFT_SAVE', $draft);
$event = new Event('DRAFT_SAVE', $draft);
if ($event->advise_before()) {
$draft['hasBeenSaved'] = io_saveFile($draft['cname'], serialize($draft));
if ($draft['hasBeenSaved']) {

View File

@ -126,7 +126,7 @@ EOT;
*/
public static function logException($e)
{
if (is_a($e, \ErrorException::class)) {
if ($e instanceof \ErrorException) {
$prefix = self::ERRORCODES[$e->getSeverity()];
} else {
$prefix = get_class($e);

View File

@ -1,12 +1,13 @@
<?php
use SimplePie\SimplePie;
use dokuwiki\FeedParserFile;
use SimplePie\File;
/**
* We override some methods of the original SimplePie class here
*/
class FeedParser extends \SimplePie\SimplePie {
class FeedParser extends SimplePie {
/**
* Constructor. Set some defaults

View File

@ -2,6 +2,8 @@
namespace dokuwiki;
use SimplePie\File;
use SimplePie\SimplePie;
use dokuwiki\HTTP\DokuHTTPClient;
/**
@ -9,7 +11,7 @@ use dokuwiki\HTTP\DokuHTTPClient;
*
* Replaces SimplePie's own class
*/
class FeedParserFile extends \SimplePie\File
class FeedParserFile extends File
{
protected $http;
/** @noinspection PhpMissingParentConstructorInspection */
@ -22,13 +24,7 @@ class FeedParserFile extends \SimplePie\File
* @inheritdoc
*/
public function __construct(
$url,
$timeout = 10,
$redirects = 5,
$headers = null,
$useragent = null,
$force_fsockopen = false,
$curl_options = array()
$url
) {
$this->http = new DokuHTTPClient();
$this->success = $this->http->sendRequest($url);
@ -37,7 +33,7 @@ class FeedParserFile extends \SimplePie\File
$this->body = $this->http->resp_body;
$this->error = $this->http->error;
$this->method = \SimplePie\SimplePie::FILE_SOURCE_REMOTE | \SimplePie\SimplePie::FILE_SOURCE_FSOCKOPEN;
$this->method = SimplePie::FILE_SOURCE_REMOTE | SimplePie::FILE_SOURCE_FSOCKOPEN;
return $this->success;
}

View File

@ -172,9 +172,7 @@ class Logger
$details = json_encode($details, JSON_PRETTY_PRINT);
}
$details = explode("\n", $details);
$loglines = array_map(function ($line) {
return ' ' . $line;
}, $details);
$loglines = array_map(static fn($line) => ' ' . $line, $details);
} elseif ($details) {
$loglines = [$details];
} else {
@ -221,8 +219,8 @@ class Logger
protected function writeLogLines($lines, $logfile)
{
if (defined('DOKU_UNITTEST')) {
fwrite(STDERR, "\n[" . $this->facility . '] ' . join("\n", $lines) . "\n");
fwrite(STDERR, "\n[" . $this->facility . '] ' . implode("\n", $lines) . "\n");
}
return io_saveFile($logfile, join("\n", $lines) . "\n", true);
return io_saveFile($logfile, implode("\n", $lines) . "\n", true);
}
}

View File

@ -8,7 +8,8 @@
*
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\Utf8\PhpString;
use dokuwiki\Utf8\Clean;
use dokuwiki\Extension\Event;
/**
@ -16,18 +17,18 @@ use dokuwiki\Extension\Event;
*/
class Mailer {
protected $headers = array();
protected $attach = array();
protected $headers = [];
protected $attach = [];
protected $html = '';
protected $text = '';
protected $boundary = '';
protected $partid = '';
protected $sendparam = null;
protected $sendparam;
protected $allowhtml = true;
protected $replacements = array('text'=> array(), 'html' => array());
protected $replacements = ['text'=> [], 'html' => []];
/**
* Constructor
@ -42,12 +43,13 @@ class Mailer {
$server = parse_url(DOKU_URL, PHP_URL_HOST);
if(strpos($server,'.') === false) $server .= '.localhost';
$this->partid = substr(md5(uniqid(mt_rand(), true)),0, 8).'@'.$server;
$this->boundary = '__________'.md5(uniqid(mt_rand(), true));
$this->partid = substr(md5(uniqid(random_int(0, mt_getrandmax()), true)),0, 8).'@'.$server;
$this->boundary = '__________'.md5(uniqid(random_int(0, mt_getrandmax()), true));
$listid = implode('.', array_reverse(explode('/', DOKU_BASE))).$server;
$listid = strtolower(trim($listid, '.'));
$messageid = uniqid(mt_rand(), true) . "@$server";
$messageid = uniqid(random_int(0, mt_getrandmax()), true) . "@$server";
$this->allowhtml = (bool)$conf['htmlmail'];
@ -77,15 +79,15 @@ class Mailer {
*/
public function attachFile($path, $mime, $name = '', $embed = '') {
if(!$name) {
$name = \dokuwiki\Utf8\PhpString::basename($path);
$name = PhpString::basename($path);
}
$this->attach[] = array(
$this->attach[] = [
'data' => file_get_contents($path),
'mime' => $mime,
'name' => $name,
'embed' => $embed
);
];
}
/**
@ -98,16 +100,16 @@ class Mailer {
*/
public function attachContent($data, $mime, $name = '', $embed = '') {
if(!$name) {
list(, $ext) = explode('/', $mime);
[, $ext] = explode('/', $mime);
$name = count($this->attach).".$ext";
}
$this->attach[] = array(
$this->attach[] = [
'data' => $data,
'mime' => $mime,
'name' => $name,
'embed' => $embed
);
];
}
/**
@ -122,7 +124,7 @@ class Mailer {
// get file and mime type
$media = cleanID($matches[1]);
list(, $mime) = mimetype($media);
[, $mime] = mimetype($media);
$file = mediaFN($media);
if(!file_exists($file)) return $matches[0]; //bad reference, keep as is
@ -225,12 +227,12 @@ class Mailer {
// embed media from templates
$html = preg_replace_callback(
'/@MEDIA\(([^\)]+)\)@/',
array($this, 'autoEmbedCallBack'), $html
[$this, 'autoEmbedCallBack'], $html
);
// add default token replacements
$trep = array_merge($this->replacements['text'], (array)$textrep);
$hrep = array_merge($this->replacements['html'], (array)$htmlrep);
$trep = array_merge($this->replacements['text'], $textrep);
$hrep = array_merge($this->replacements['html'], $htmlrep);
// Apply replacements
foreach($trep as $key => $substitution) {
@ -359,10 +361,10 @@ class Mailer {
$headers = '';
if(!is_array($addresses)){
$count = preg_match_all('/\s*(?:("[^"]*"[^,]+),*)|([^,]+)\s*,*/', $addresses, $matches, PREG_SET_ORDER);
$addresses = array();
$addresses = [];
if ($count !== false && is_array($matches)) {
foreach ($matches as $match) {
array_push($addresses, rtrim($match[0], ','));
$addresses[] = rtrim($match[0], ',');
}
}
}
@ -385,7 +387,7 @@ class Mailer {
}
// FIXME: is there a way to encode the localpart of a emailaddress?
if(!\dokuwiki\Utf8\Clean::isASCII($addr)) {
if(!Clean::isASCII($addr)) {
msg(hsc("E-Mail address <$addr> is not ASCII"), -1, __LINE__, __FILE__, MSG_ADMINS_ONLY);
continue;
}
@ -401,11 +403,11 @@ class Mailer {
$addr = "<$addr>";
if(defined('MAILHEADER_ASCIIONLY')) {
$text = \dokuwiki\Utf8\Clean::deaccent($text);
$text = \dokuwiki\Utf8\Clean::strip($text);
$text = Clean::deaccent($text);
$text = Clean::strip($text);
}
if(strpos($text, ',') !== false || !\dokuwiki\Utf8\Clean::isASCII($text)) {
if(strpos($text, ',') !== false || !Clean::isASCII($text)) {
$text = '=?UTF-8?B?'.base64_encode($text).'?=';
}
} else {
@ -541,7 +543,7 @@ class Mailer {
// clean up addresses
if(empty($this->headers['From'])) $this->from($conf['mailfrom']);
$addrs = array('To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender');
$addrs = ['To', 'From', 'Cc', 'Bcc', 'Reply-To', 'Sender'];
foreach($addrs as $addr) {
if(isset($this->headers[$addr])) {
$this->headers[$addr] = $this->cleanAddress($this->headers[$addr]);
@ -551,25 +553,25 @@ class Mailer {
if(isset($this->headers['Subject'])) {
// add prefix to subject
if(empty($conf['mailprefix'])) {
if(\dokuwiki\Utf8\PhpString::strlen($conf['title']) < 20) {
if(PhpString::strlen($conf['title']) < 20) {
$prefix = '['.$conf['title'].']';
} else {
$prefix = '['.\dokuwiki\Utf8\PhpString::substr($conf['title'], 0, 20).'...]';
$prefix = '['.PhpString::substr($conf['title'], 0, 20).'...]';
}
} else {
$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')) {
$this->headers['Subject'] = \dokuwiki\Utf8\Clean::deaccent($this->headers['Subject']);
$this->headers['Subject'] = \dokuwiki\Utf8\Clean::strip($this->headers['Subject']);
$this->headers['Subject'] = Clean::deaccent($this->headers['Subject']);
$this->headers['Subject'] = Clean::strip($this->headers['Subject']);
}
if(!\dokuwiki\Utf8\Clean::isASCII($this->headers['Subject'])) {
if(!Clean::isASCII($this->headers['Subject'])) {
$this->headers['Subject'] = '=?UTF-8?B?'.base64_encode($this->headers['Subject']).'?=';
}
}
@ -636,7 +638,7 @@ class Mailer {
$name = $INFO['userinfo']['name'] ?? '';
$mail = $INFO['userinfo']['mail'] ?? '';
$this->replacements['text'] = array(
$this->replacements['text'] = [
'DATE' => dformat(),
'BROWSER' => $INPUT->server->str('HTTP_USER_AGENT'),
'IPADDRESS' => $ip,
@ -646,7 +648,8 @@ class Mailer {
'USER' => $INPUT->server->str('REMOTE_USER'),
'NAME' => $name,
'MAIL' => $mail
);
];
$signature = str_replace(
'@DOKUWIKIURL@',
$this->replacements['text']['DOKUWIKIURL'],
@ -654,7 +657,7 @@ class Mailer {
);
$this->replacements['text']['EMAILSIGNATURE'] = "\n-- \n" . $signature . "\n";
$this->replacements['html'] = array(
$this->replacements['html'] = [
'DATE' => '<i>' . hsc(dformat()) . '</i>',
'BROWSER' => hsc($INPUT->server->str('HTTP_USER_AGENT')),
'IPADDRESS' => '<code>' . hsc($ip) . '</code>',
@ -663,22 +666,15 @@ class Mailer {
'DOKUWIKIURL' => '<a href="' . DOKU_URL . '">' . DOKU_URL . '</a>',
'USER' => hsc($INPUT->server->str('REMOTE_USER')),
'NAME' => hsc($name),
'MAIL' => '<a href="mailto:"' . hsc($mail) . '">' .
hsc($mail) . '</a>'
);
'MAIL' => '<a href="mailto:"' . hsc($mail) . '">' . hsc($mail) . '</a>'
];
$signature = $lang['email_signature_text'];
if(!empty($lang['email_signature_html'])) {
$signature = $lang['email_signature_html'];
}
$signature = str_replace(
array(
'@DOKUWIKIURL@',
"\n"
),
array(
$this->replacements['html']['DOKUWIKIURL'],
'<br />'
),
['@DOKUWIKIURL@', "\n"],
[$this->replacements['html']['DOKUWIKIURL'], '<br />'],
$signature
);
$this->replacements['html']['EMAILSIGNATURE'] = $signature;
@ -697,7 +693,7 @@ class Mailer {
$success = false;
// prepare hook data
$data = array(
$data = [
// pass the whole mail class to plugin
'mail' => $this,
// pass references for backward compatibility
@ -711,7 +707,7 @@ class Mailer {
'headers' => '', // plugins shouldn't use this
// signal if we mailed successfully to AFTER event
'success' => &$success,
);
];
// do our thing if BEFORE hook approves
$evt = new Event('MAIL_MESSAGE_SEND', $data);

View File

@ -30,7 +30,7 @@ class Manifest
$manifest['start_url'] = DOKU_REL;
}
$styleUtil = new \dokuwiki\StyleUtils();
$styleUtil = new StyleUtils();
$styleIni = $styleUtil->cssStyleini();
$replacements = $styleIni['replacements'];
@ -39,9 +39,9 @@ class Manifest
}
if (empty($manifest['theme_color'])) {
$manifest['theme_color'] = !empty($replacements['__theme_color__'])
? $replacements['__theme_color__']
: $replacements['__background_alt__'];
$manifest['theme_color'] = empty($replacements['__theme_color__'])
? $replacements['__background_alt__']
: $replacements['__theme_color__'];
}
if (empty($manifest['icons'])) {
@ -79,6 +79,6 @@ class Manifest
Event::createAndTrigger('MANIFEST_SEND', $manifest);
header('Content-Type: application/manifest+json');
echo json_encode($manifest);
echo json_encode($manifest, JSON_THROW_ON_ERROR);
}
}

View File

@ -62,17 +62,11 @@ class PassHash {
$magic = 'H';
} elseif(preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) {
$method = 'djangopbkdf2';
$magic = array(
'algo' => $m[1],
'iter' => $m[2],
);
$magic = ['algo' => $m[1], 'iter' => $m[2]];
$salt = $m[3];
} elseif(preg_match('/^PBKDF2(SHA\d+)\$(\d+)\$([[:xdigit:]]+)\$([[:xdigit:]]+)$/', $hash, $m)) {
$method = 'seafilepbkdf2';
$magic = array(
'algo' => $m[1],
'iter' => $m[2],
);
$magic = ['algo' => $m[1], 'iter' => $m[2]];
$salt = $m[3];
} elseif(preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
$method = 'djangosha1';
@ -95,10 +89,7 @@ class PassHash {
} elseif(preg_match('/^\$(5|6)\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) {
$method = 'sha2';
$salt = $m[3];
$magic = array(
'prefix' => $m[1],
'rounds' => $m[2],
);
$magic = ['prefix' => $m[1], 'rounds' => $m[2]];
} elseif(preg_match('/^\$(argon2id?)/', $hash, $m)) {
if(!defined('PASSWORD_'.strtoupper($m[1]))) {
throw new \Exception('This PHP installation has no '.strtoupper($m[1]).' support');
@ -406,7 +397,7 @@ class PassHash {
if($iter > 30) {
throw new \Exception("Too high iteration count ($iter) in ".
__CLASS__.'::'.__FUNCTION__);
self::class.'::'.__FUNCTION__);
}
$iter = 1 << $iter;
@ -550,7 +541,7 @@ class PassHash {
* @return string Hashed password
* @throws Exception when PHP is missing support for the method/algo
*/
public function hash_seafilepbkdf2($clear, $salt=null, $opts=array()) {
public function hash_seafilepbkdf2($clear, $salt=null, $opts=[]) {
$this->init_salt($salt, 64);
if(empty($opts['algo'])) {
$prefixalgo='SHA256';
@ -586,7 +577,7 @@ class PassHash {
* @return string Hashed password
* @throws \Exception when PHP is missing support for the method/algo
*/
public function hash_djangopbkdf2($clear, $salt=null, $opts=array()) {
public function hash_djangopbkdf2($clear, $salt=null, $opts=[]) {
$this->init_salt($salt, 12);
if(empty($opts['algo'])) {
$algo = 'sha256';
@ -618,7 +609,7 @@ class PassHash {
* @return string Hashed password
* @throws \Exception when PHP is missing support for the method/algo
*/
public function hash_djangopbkdf2_sha256($clear, $salt=null, $opts=array()) {
public function hash_djangopbkdf2_sha256($clear, $salt=null, $opts=[]) {
$opts['algo'] = 'sha256';
return $this->hash_djangopbkdf2($clear, $salt, $opts);
}
@ -632,7 +623,7 @@ class PassHash {
* @return string Hashed password
* @throws \Exception when PHP is missing support for the method/algo
*/
public function hash_djangopbkdf2_sha1($clear, $salt=null, $opts=array()) {
public function hash_djangopbkdf2_sha1($clear, $salt=null, $opts=[]) {
$opts['algo'] = 'sha1';
return $this->hash_djangopbkdf2($clear, $salt, $opts);
}
@ -655,7 +646,7 @@ class PassHash {
* @return string Hashed password
*/
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');
}
@ -684,7 +675,7 @@ class PassHash {
* @return string Hashed password
* @throws \Exception
*/
public function hash_sha2($clear, $salt = null, $opts = array()) {
public function hash_sha2($clear, $salt = null, $opts = []) {
if(empty($opts['prefix'])) {
$prefix = '6';
} else {
@ -695,10 +686,10 @@ class PassHash {
} 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);
@ -812,8 +803,8 @@ class PassHash {
}
for($i = 0; $i < strlen($key) - 1; $i++) {
$opad[$i] = $opad[$i] ^ $key[$i];
$ipad[$i] = $ipad[$i] ^ $key[$i];
$opad[$i] ^= $key[$i];
$ipad[$i] ^= $key[$i];
}
$output = $algo($opad . pack($pack, $algo($ipad . $data)));

View File

@ -1,5 +1,6 @@
<?php
use dokuwiki\Utf8\Unicode;
/**
* Class to safely store UTF-8 in a Filename
*
@ -45,7 +46,7 @@ class SafeFN {
* @author Christopher Smith <chris@jalakai.co.uk>
*/
public static function encode($filename) {
return self::unicodeToSafe(\dokuwiki\Utf8\Unicode::fromUtf8($filename));
return self::unicodeToSafe(Unicode::fromUtf8($filename));
}
/**
@ -74,7 +75,7 @@ class SafeFN {
* @author Christopher Smith <chris@jalakai.co.uk>
*/
public static function decode($filename) {
return \dokuwiki\Utf8\Unicode::toUtf8(self::safeToUnicode(strtolower($filename)));
return Unicode::toUtf8(self::safeToUnicode(strtolower($filename)));
}
public static function validatePrintableUtf8($printable_utf8) {
@ -105,8 +106,7 @@ class SafeFN {
$converted = false;
}
$safe .= chr($codepoint);
} else if ($codepoint == ord(self::$pre_indicator)) {
} elseif ($codepoint == ord(self::$pre_indicator)) {
$safe .= self::$pre_indicator;
$converted = true;
} else {
@ -128,7 +128,7 @@ class SafeFN {
*/
private static function safeToUnicode($safe) {
$unicode = array();
$unicode = [];
$split = preg_split('#(?=['.self::$post_indicator.self::$pre_indicator.'])#',$safe,-1,PREG_SPLIT_NO_EMPTY);
$converted = false;
@ -141,7 +141,7 @@ class SafeFN {
$unicode[] = ord($sub[$i]);
}
$converted = false;
} else if ($len==1) {
} elseif ($len==1) {
// a pre_indicator character in the real data
$unicode[] = ord($sub);
$converted = true;

View File

@ -2,6 +2,9 @@
namespace dokuwiki\Search;
use dokuwiki\Utf8\Asian;
use dokuwiki\Utf8\Clean;
use dokuwiki\Utf8\PhpString;
use dokuwiki\Extension\Event;
/**
@ -13,7 +16,7 @@ class Indexer {
/**
* @var array $pidCache Cache for getPID()
*/
protected $pidCache = array();
protected $pidCache = [];
/**
* Adds the contents of a page to the fulltext index
@ -39,7 +42,7 @@ class Indexer {
return false;
}
$pagewords = array();
$pagewords = [];
// get word usage in page
$words = $this->getPageWords($text);
if ($words === false) {
@ -67,10 +70,10 @@ class Indexer {
if ($pageword_idx !== '') {
$oldwords = explode(':',$pageword_idx);
$delwords = array_diff($oldwords, $pagewords);
$upwords = array();
$upwords = [];
foreach ($delwords as $word) {
if ($word != '') {
list($wlen, $wid) = explode('*', $word);
[$wlen, $wid] = explode('*', $word);
$wid = (int)$wid;
$upwords[$wlen][] = $wid;
}
@ -84,7 +87,7 @@ class Indexer {
}
}
// Save the reverse index
$pageword_idx = join(':', $pagewords);
$pageword_idx = implode(':', $pagewords);
if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) {
$this->unlock();
return false;
@ -109,18 +112,18 @@ class Indexer {
$tokens = $this->tokenizer($text);
$tokens = array_count_values($tokens); // count the frequency of each token
$words = array();
$words = [];
foreach ($tokens as $w=>$c) {
$l = wordlen($w);
if (isset($words[$l])){
$words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
$words[$l][$w] = $c + ($words[$l][$w] ?? 0);
}else{
$words[$l] = array($w => $c);
$words[$l] = [$w => $c];
}
}
// arrive here with $words = array(wordlen => array(word => frequency))
$index = array(); //resulting index
$index = []; //resulting index
foreach (array_keys($words) as $wlen) {
$word_idx = $this->getIndex('w', $wlen);
$word_idx_modified = false;
@ -133,7 +136,7 @@ class Indexer {
$word_idx_modified = true;
}
if (!isset($index[$wlen]))
$index[$wlen] = array();
$index[$wlen] = [];
$index[$wlen][$wid] = $freq;
}
// save back the word index
@ -162,7 +165,7 @@ class Indexer {
*/
public function addMetaKeys($page, $key, $value=null) {
if (!is_array($key)) {
$key = array($key => $value);
$key = [$key => $value];
} elseif (!is_null($value)) {
// $key is array, but $value is not null
trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
@ -195,7 +198,7 @@ class Indexer {
$metawords = $this->getIndex($metaname.'_w', '');
$addwords = false;
if (!is_array($values)) $values = array($values);
if (!is_array($values)) $values = [$values];
$val_idx = $this->getIndexKey($metaname.'_p', '', $pid);
if ($val_idx !== '') {
@ -203,7 +206,7 @@ class Indexer {
// -1 means remove, 0 keep, 1 add
$val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
} else {
$val_idx = array();
$val_idx = [];
}
foreach ($values as $val) {
@ -278,11 +281,11 @@ class Indexer {
$new_id = array_search($newpage, $pages, true);
if ($new_id !== false) {
// make sure the page is not in the index anymore
if ($this->deletePageNoLock($newpage) !== true) {
if (!$this->deletePageNoLock($newpage)) {
return false;
}
$pages[$new_id] = 'deleted:'.time().rand(0, 9999);
$pages[$new_id] = 'deleted:'.time().random_int(0, 9999);
}
$pages[$id] = $newpage;
@ -294,7 +297,7 @@ class Indexer {
}
// reset the pid cache
$this->pidCache = array();
$this->pidCache = [];
$this->unlock();
return true;
@ -328,15 +331,15 @@ class Indexer {
$pagekeys = $this->getIndex($key.'_p', '');
$parts = explode(':', $indexline);
foreach ($parts as $part) {
list($id, $count) = explode('*', $part);
[$id, $count] = explode('*', $part);
$newindexline = $this->updateTuple($newindexline, $id, $count);
$keyline = explode(':', $pagekeys[$id]);
// remove old meta value
$keyline = array_diff($keyline, array($oldid));
$keyline = array_diff($keyline, [$oldid]);
// add new meta value when not already present
if (!in_array($newid, $keyline)) {
array_push($keyline, $newid);
$keyline[] = $newid;
}
$pagekeys[$id] = implode(':', $keyline);
}
@ -400,10 +403,10 @@ class Indexer {
$pageword_idx = $this->getIndexKey('pageword', '', $pid);
if ($pageword_idx !== '') {
$delwords = explode(':',$pageword_idx);
$upwords = array();
$upwords = [];
foreach ($delwords as $word) {
if ($word != '') {
list($wlen,$wid) = explode('*', $word);
[$wlen, $wid] = explode('*', $word);
$wid = (int)$wid;
$upwords[$wlen][] = $wid;
}
@ -463,7 +466,7 @@ class Indexer {
@unlink($conf['indexdir'].'/lengths.idx');
// clear the pid cache
$this->pidCache = array();
$this->pidCache = [];
$this->unlock();
return true;
@ -493,32 +496,27 @@ class Indexer {
$evt = new Event('INDEXER_TEXT_PREPARE', $text);
if ($evt->advise_before(true)) {
if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
$text = \dokuwiki\Utf8\Asian::separateAsianWords($text);
$text = Asian::separateAsianWords($text);
}
}
$evt->advise_after();
unset($evt);
$text = strtr($text,
array(
"\r" => ' ',
"\n" => ' ',
"\t" => ' ',
"\xC2\xAD" => '', //soft-hyphen
)
["\r" => ' ', "\n" => ' ', "\t" => ' ', "\xC2\xAD" => '']
);
if (preg_match('/[^0-9A-Za-z ]/u', $text))
$text = \dokuwiki\Utf8\Clean::stripspecials($text, ' ', '\._\-:'.$wc);
$text = Clean::stripspecials($text, ' ', '\._\-:'.$wc);
$wordlist = explode(' ', $text);
foreach ($wordlist as $i => $word) {
$wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
\dokuwiki\Utf8\PhpString::strtolower($word) : strtolower($word);
PhpString::strtolower($word) : strtolower($word);
}
foreach ($wordlist as $i => $word) {
if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
|| array_search($word, $stopwords, true) !== false)
|| in_array($word, $stopwords, true))
unset($wordlist[$i]);
}
return array_values($wordlist);
@ -593,12 +591,12 @@ class Indexer {
* @author Andreas Gohr <andi@splitbrain.org>
*/
public function lookup(&$tokens) {
$result = array();
$result = [];
$wids = $this->getIndexWords($tokens, $result);
if (empty($wids)) return array();
if (empty($wids)) return [];
// load known words and documents
$page_idx = $this->getIndex('page', '');
$docs = array();
$docs = [];
foreach (array_keys($wids) as $wlen) {
$wids[$wlen] = array_unique($wids[$wlen]);
$index = $this->getIndex('i', $wlen);
@ -608,9 +606,9 @@ class Indexer {
}
}
// merge found pages into final result array
$final = array();
$final = [];
foreach ($result as $word => $res) {
$final[$word] = array();
$final[$word] = [];
foreach ($res as $wid) {
// handle the case when ($ixid < count($index)) has been false
// and thus $docs[$wid] hasn't been set.
@ -649,12 +647,12 @@ class Indexer {
*/
public function lookupKey($key, &$value, $func=null) {
if (!is_array($value))
$value_array = array($value);
$value_array = [$value];
else
$value_array =& $value;
// the matching ids for the provided value(s)
$value_ids = array();
$value_ids = [];
$metaname = idx_cleanName($key);
@ -668,7 +666,7 @@ class Indexer {
if (!is_null($func)) {
foreach ($value_array as $val) {
foreach ($words as $i => $word) {
if (call_user_func_array($func, array($val, $word)))
if (call_user_func_array($func, [$val, $word]))
$value_ids[$i][] = $val;
}
}
@ -690,9 +688,8 @@ class Indexer {
$re = $caret.preg_quote($xval, '/').$dollar;
foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
$value_ids[$i][] = $val;
} else {
if (($i = array_search($val, $words, true)) !== false)
$value_ids[$i][] = $val;
} elseif (($i = array_search($val, $words, true)) !== false) {
$value_ids[$i][] = $val;
}
}
}
@ -700,9 +697,9 @@ class Indexer {
unset($words); // free the used memory
// initialize the result so it won't be null
$result = array();
$result = [];
foreach ($value_array as $val) {
$result[$val] = array();
$result[$val] = [];
}
$page_idx = $this->getIndex('page', '');
@ -724,7 +721,7 @@ class Indexer {
// is an array with page_id => 1, page2_id => 1 etc. so take the keys only
$pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
foreach ($val_list as $val) {
$result[$val] = array_merge($result[$val], $pages);
$result[$val] = [...$result[$val], ...$pages];
}
}
}
@ -747,11 +744,11 @@ class Indexer {
* @author Tom N Harris <tnharris@whoopdedo.org>
*/
protected function getIndexWords(&$words, &$result) {
$tokens = array();
$tokenlength = array();
$tokenwild = array();
$tokens = [];
$tokenlength = [];
$tokenwild = [];
foreach ($words as $word) {
$result[$word] = array();
$result[$word] = [];
$caret = '^';
$dollar = '$';
$xword = $word;
@ -761,12 +758,12 @@ class Indexer {
if (substr($xword, 0, 1) == '*') {
$xword = substr($xword, 1);
$caret = '';
$wlen -= 1;
--$wlen;
}
if (substr($xword, -1, 1) == '*') {
$xword = substr($xword, 0, -1);
$dollar = '';
$wlen -= 1;
--$wlen;
}
if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
continue;
@ -774,22 +771,22 @@ class Indexer {
$tokenlength[$wlen][] = $xword;
if (!$caret || !$dollar) {
$re = $caret.preg_quote($xword, '/').$dollar;
$tokens[$xword][] = array($word, '/'.$re.'/');
$tokens[$xword][] = [$word, '/'.$re.'/'];
if (!isset($tokenwild[$xword]))
$tokenwild[$xword] = $wlen;
} else {
$tokens[$xword][] = array($word, null);
$tokens[$xword][] = [$word, null];
}
}
asort($tokenwild);
// $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
// $tokenlength = array( base word length => base word ... )
// $tokenwild = array( base word => base word length ... )
$length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
$length_filter = $tokenwild === [] ? $tokenlength : min(array_keys($tokenlength));
$indexes_known = $this->indexLengths($length_filter);
if (!empty($tokenwild)) sort($indexes_known);
if ($tokenwild !== []) sort($indexes_known);
// get word IDs
$wids = array();
$wids = [];
foreach ($indexes_known as $ixlen) {
$word_idx = $this->getIndex('w', $ixlen);
// handle exact search
@ -842,7 +839,7 @@ class Indexer {
return array_values($page_idx);
}
$pages = array();
$pages = [];
$lines = $this->getIndex($metaname.'_i', '');
foreach ($lines as $line) {
$pages = array_merge($pages, $this->parseTuples($page_idx, $line));
@ -867,7 +864,7 @@ class Indexer {
if ($max < $min)
$max = 0;
$result = array();
$result = [];
if ($key == 'title') {
$index = $this->getIndex('title', '');
@ -880,7 +877,7 @@ class Indexer {
elseif (!is_null($key)) {
$metaname = idx_cleanName($key);
$index = $this->getIndex($metaname.'_i', '');
$val_idx = array();
$val_idx = [];
foreach ($index as $wid => $line) {
$freq = $this->countTuples($line);
if ($freq >= $min && (!$max || $freq <= $max))
@ -977,7 +974,7 @@ class Indexer {
protected function getIndex($idx, $suffix) {
global $conf;
$fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
if (!file_exists($fn)) return array();
if (!file_exists($fn)) return [];
return file($fn, FILE_IGNORE_NEW_LINES);
}
@ -996,7 +993,7 @@ class Indexer {
$fn = $conf['indexdir'].'/'.$idx.$suffix;
$fh = @fopen($fn.'.tmp', 'w');
if (!$fh) return false;
fwrite($fh, join("\n", $lines));
fwrite($fh, implode("\n", $lines));
if (!empty($lines))
fwrite($fh, "\n");
fclose($fh);
@ -1124,17 +1121,17 @@ class Indexer {
*/
protected function indexLengths($filter) {
global $conf;
$idx = array();
$idx = [];
if (is_array($filter)) {
// testing if index files exist only
$path = $conf['indexdir']."/i";
foreach ($filter as $key => $value) {
foreach (array_keys($filter) as $key) {
if (file_exists($path.$key.'.idx'))
$idx[] = $key;
}
} else {
$lengths = idx_listIndexLengths();
foreach ($lengths as $key => $length) {
foreach ($lengths as $length) {
// keep all the values equal or superior
if ((int)$length >= (int)$filter)
$idx[] = $length;
@ -1179,12 +1176,12 @@ class Indexer {
* @return array
*/
protected function parseTuples(&$keys, $line) {
$result = array();
$result = [];
if ($line == '') return $result;
$parts = explode(':', $line);
foreach ($parts as $tuple) {
if ($tuple === '') continue;
list($key, $cnt) = explode('*', $tuple);
[$key, $cnt] = explode('*', $tuple);
if (!$cnt) continue;
if (isset($keys[$key])) {
$key = $keys[$key];
@ -1208,7 +1205,7 @@ class Indexer {
$parts = explode(':', $line);
foreach ($parts as $tuple) {
if ($tuple === '') continue;
list(/* $pid */, $cnt) = explode('*', $tuple);
[, $cnt] = explode('*', $tuple);
$freq += (int)$cnt;
}
return $freq;

View File

@ -8,6 +8,7 @@
namespace dokuwiki\Sitemap;
use dokuwiki\Extension\Event;
use dokuwiki\HTTP\DokuHTTPClient;
use dokuwiki\Logger;
@ -36,10 +37,10 @@ class Mapper {
$sitemap = Mapper::getFilePath();
if(file_exists($sitemap)){
if (file_exists($sitemap)) {
if(!is_writable($sitemap)) return false;
}else{
if(!is_writable(dirname($sitemap))) return false;
} elseif (!is_writable(dirname($sitemap))) {
return false;
}
if(@filesize($sitemap) &&
@ -52,23 +53,23 @@ class Mapper {
$pages = idx_get_indexer()->getPages();
Logger::debug('Sitemapper::generate(): creating sitemap using '.count($pages).' pages');
$items = array();
$items = [];
// build the sitemap items
foreach($pages as $id){
//skip hidden, non existing and restricted files
if(isHiddenPage($id)) continue;
if(auth_aclcheck($id,'',array()) < AUTH_READ) continue;
if(auth_aclcheck($id,'',[]) < AUTH_READ) continue;
$item = Item::createFromID($id);
if ($item !== null)
if ($item instanceof Item)
$items[] = $item;
}
$eventData = array('items' => &$items, 'sitemap' => &$sitemap);
$event = new \dokuwiki\Extension\Event('SITEMAP_GENERATE', $eventData);
$eventData = ['items' => &$items, 'sitemap' => &$sitemap];
$event = new Event('SITEMAP_GENERATE', $eventData);
if ($event->advise_before(true)) {
//save the new sitemap
$event->result = io_saveFile($sitemap, Mapper::getXML($items));
$event->result = io_saveFile($sitemap, (new Mapper())->getXML($items));
}
$event->advise_after();
@ -83,7 +84,7 @@ class Mapper {
*
* @author Michael Hamann
*/
private static function getXML($items) {
private function getXML($items) {
ob_start();
echo '<?xml version="1.0" encoding="UTF-8"?>'.NL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'.NL;
@ -138,16 +139,17 @@ class Mapper {
$http = new DokuHTTPClient();
$http->timeout = 8;
$encoded_sitemap_url = urlencode(wl('', array('do' => 'sitemap'), true, '&'));
$ping_urls = array(
$encoded_sitemap_url = urlencode(wl('', ['do' => 'sitemap'], true, '&'));
$ping_urls = [
'google' => 'https://www.google.com/ping?sitemap='.$encoded_sitemap_url,
'yandex' => 'https://webmaster.yandex.com/ping?sitemap='.$encoded_sitemap_url
);
];
$data = array('ping_urls' => $ping_urls,
'encoded_sitemap_url' => $encoded_sitemap_url
);
$event = new \dokuwiki\Extension\Event('SITEMAP_PING', $data);
$data = [
'ping_urls' => $ping_urls,
'encoded_sitemap_url' => $encoded_sitemap_url
];
$event = new Event('SITEMAP_PING', $data);
if ($event->advise_before(true)) {
foreach ($data['ping_urls'] as $name => $url) {
Logger::debug("Sitemapper::PingSearchEngines(): pinging $name");

View File

@ -17,7 +17,7 @@ class StyleUtils
/** @var bool $preview preview mode */
protected $preview;
/** @var array default replacements to be merged with custom style configs */
protected $defaultReplacements = array(
protected $defaultReplacements = [
'__text__' => "#000",
'__background__' => "#fff",
'__text_alt__' => "#999",
@ -26,8 +26,8 @@ class StyleUtils
'__background_neu__' => "#ddd",
'__border__' => "#ccc",
'__highlight__' => "#ff9",
'__link__' => "#00f",
);
'__link__' => "#00f"
];
/**
* StyleUtils constructor.
@ -66,7 +66,7 @@ class StyleUtils
global $conf;
global $config_cascade;
$stylesheets = array(); // mode, file => base
$stylesheets = []; // mode, file => base
// guaranteed placeholder => value
$replacements = $this->defaultReplacements;
@ -84,7 +84,7 @@ class StyleUtils
$combined['stylesheets'] = [];
$combined['replacements'] = [];
foreach (array('default', 'local', 'protected') as $config_group) {
foreach (['default', 'local', 'protected'] as $config_group) {
if (empty($config_cascade['styleini'][$config_group])) continue;
// set proper server dirs
@ -138,7 +138,7 @@ class StyleUtils
{
global $conf;
if (!file_exists($incbase . $file)) {
list($extension, $basename) = array_map('strrev', sexplode('.', strrev($file), 2, ''));
[$extension, $basename] = array_map('strrev', sexplode('.', strrev($file), 2, ''));
$newExtension = $extension === 'css' ? 'less' : 'css';
if (file_exists($incbase . $basename . '.' . $newExtension)) {
$stylesheets[$mode][$incbase . $basename . '.' . $newExtension] = $webbase;

View File

@ -47,12 +47,15 @@ class TaskRunner
$tmp = []; // No event data
$evt = new Event('INDEXER_TASKS_RUN', $tmp);
if ($evt->advise_before()) {
$this->runIndexer() or
$this->runSitemapper() or
$this->sendDigest() or
$this->runTrimRecentChanges() or
$this->runTrimRecentChanges(true) or
$evt->advise_after();
if (!(
$this->runIndexer() ||
$this->runSitemapper() ||
$this->sendDigest() ||
$this->runTrimRecentChanges() ||
$this->runTrimRecentChanges(true))
) {
$evt->advise_after();
}
}
if(!$output) {
@ -120,7 +123,8 @@ class TaskRunner
$trim_time = time() - $conf['recent_days'] * 86400;
$out_lines = [];
$old_lines = [];
for ($i = 0; $i < count($lines); $i++) {
$counter = count($lines);
for ($i = 0; $i < $counter; $i++) {
$log = ChangeLog::parseLogLine($lines[$i]);
if ($log === false) {
continue; // discard junk

View File

@ -5,7 +5,7 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\ActionRouter;
use dokuwiki\Extension\Event;
/**
@ -13,9 +13,9 @@ use dokuwiki\Extension\Event;
*/
function act_dispatch(){
// always initialize on first dispatch (test request may dispatch mutliple times on one request)
$router = \dokuwiki\ActionRouter::getInstance(true);
$router = ActionRouter::getInstance(true);
$headers = array('Content-Type: text/html; charset=utf-8');
$headers = ['Content-Type: text/html; charset=utf-8'];
Event::createAndTrigger('ACTION_HEADERS_SEND',$headers,'act_sendheaders');
// clear internal variables
@ -49,7 +49,7 @@ function act_sendheaders($headers) {
function act_clean($act){
// check if the action was given as array key
if(is_array($act)){
list($act) = array_keys($act);
[$act] = array_keys($act);
}
// no action given

View File

@ -8,7 +8,8 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use phpseclib\Crypt\AES;
use dokuwiki\Utf8\PhpString;
use dokuwiki\Extension\AuthPlugin;
use dokuwiki\Extension\Event;
use dokuwiki\Extension\PluginController;
@ -37,7 +38,7 @@ function auth_setup() {
global $lang;
/* @var PluginController $plugin_controller */
global $plugin_controller;
$AUTH_ACL = array();
$AUTH_ACL = [];
if(!$conf['useacl']) return false;
@ -71,7 +72,7 @@ function auth_setup() {
$header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
if(preg_match( '~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches )) {
$userpass = explode(':', base64_decode($matches[1]));
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = $userpass;
[$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
}
// if no credentials were given try to use HTTP auth (for SSO)
@ -95,12 +96,12 @@ function auth_setup() {
if ($ok === null) {
// external trust mechanism not in place, or returns no result,
// then attempt auth_login
$evdata = array(
$evdata = [
'user' => $INPUT->str('u'),
'password' => $INPUT->str('p'),
'sticky' => $INPUT->bool('r'),
'silent' => $INPUT->bool('http_credentials')
);
];
Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
}
@ -123,15 +124,15 @@ function auth_loadACL() {
/* @var Input $INPUT */
global $INPUT;
if(!is_readable($config_cascade['acl']['default'])) return array();
if(!is_readable($config_cascade['acl']['default'])) return [];
$acl = file($config_cascade['acl']['default']);
$out = array();
$out = [];
foreach($acl as $line) {
$line = trim($line);
if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
list($id,$rest) = preg_split('/[ \t]+/',$line,2);
[$id, $rest] = preg_split('/[ \t]+/',$line,2);
// substitute user wildcard first (its 1:1)
if(strstr($line, '%USER%')){
@ -213,8 +214,6 @@ function auth_login($user, $pass, $sticky = false, $silent = false) {
/* @var Input $INPUT */
global $INPUT;
$sticky ? $sticky = true : $sticky = false; //sanity check
if(!$auth) return false;
if(!empty($user)) {
@ -236,7 +235,7 @@ function auth_login($user, $pass, $sticky = false, $silent = false) {
}
} else {
// read cookie information
list($user, $sticky, $pass) = auth_getCookie();
[$user, $sticky, $pass] = auth_getCookie();
if($user && $pass) {
// we got a cookie - see if we can trust it
@ -366,7 +365,7 @@ function auth_random($min, $max) {
*/
function auth_encrypt($data, $secret) {
$iv = auth_randombytes(16);
$cipher = new \phpseclib\Crypt\AES();
$cipher = new AES();
$cipher->setPassword($secret);
/*
@ -389,7 +388,7 @@ function auth_encrypt($data, $secret) {
*/
function auth_decrypt($ciphertext, $secret) {
$iv = substr($ciphertext, 0, 16);
$cipher = new \phpseclib\Crypt\AES();
$cipher = new AES();
$cipher->setPassword($secret);
$cipher->setIV($iv);
@ -539,11 +538,11 @@ function auth_isMember($memberlist, $user, array $groups) {
// clean user and groups
if(!$auth->isCaseSensitive()) {
$user = \dokuwiki\Utf8\PhpString::strtolower($user);
$groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
$user = PhpString::strtolower($user);
$groups = array_map([PhpString::class, 'strtolower'], $groups);
}
$user = $auth->cleanUser($user);
$groups = array_map(array($auth, 'cleanGroup'), $groups);
$groups = array_map([$auth, 'cleanGroup'], $groups);
// extract the memberlist
$members = explode(',', $memberlist);
@ -554,7 +553,7 @@ function auth_isMember($memberlist, $user, array $groups) {
// compare cleaned values
foreach($members as $member) {
if($member == '@ALL' ) return true;
if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
if(!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
if($member[0] == '@') {
$member = $auth->cleanGroup(substr($member, 1));
if(in_array($member, $groups)) return true;
@ -585,7 +584,7 @@ function auth_quickaclcheck($id) {
global $INPUT;
# if no ACL is used always return upload rights
if(!$conf['useacl']) return AUTH_UPLOAD;
return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
}
/**
@ -600,11 +599,11 @@ function auth_quickaclcheck($id) {
* @return int permission level
*/
function auth_aclcheck($id, $user, $groups) {
$data = array(
$data = [
'id' => $id ?? '',
'user' => $user,
'groups' => $groups
);
];
return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
}
@ -635,7 +634,7 @@ function auth_aclcheck_cb($data) {
if(!is_array($AUTH_ACL)) return AUTH_NONE;
//make sure groups is an array
if(!is_array($groups)) $groups = array();
if(!is_array($groups)) $groups = [];
//if user is superuser or in superusergroup return 255 (acl_admin)
if(auth_isadmin($user, $groups)) {
@ -643,11 +642,11 @@ function auth_aclcheck_cb($data) {
}
if(!$auth->isCaseSensitive()) {
$user = \dokuwiki\Utf8\PhpString::strtolower($user);
$groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
$user = PhpString::strtolower($user);
$groups = array_map([PhpString::class, 'strtolower'], $groups);
}
$user = auth_nameencode($auth->cleanUser($user));
$groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
$groups = array_map([$auth, 'cleanGroup'], $groups);
//prepend groups with @ and nameencode
foreach($groups as &$group) {
@ -670,7 +669,7 @@ function auth_aclcheck_cb($data) {
$match = preg_replace('/#.*$/', '', $match); //ignore comments
$acl = preg_split('/[ \t]+/', $match);
if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
$acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
$acl[1] = PhpString::strtolower($acl[1]);
}
if(!in_array($acl[1], $groups)) {
continue;
@ -700,7 +699,7 @@ function auth_aclcheck_cb($data) {
$match = preg_replace('/#.*$/', '', $match); //ignore comments
$acl = preg_split('/[ \t]+/', $match);
if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
$acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
$acl[1] = PhpString::strtolower($acl[1]);
}
if(!in_array($acl[1], $groups)) {
continue;
@ -799,10 +798,10 @@ function auth_nameencode_callback($matches) {
* @return string pronouncable password
*/
function auth_pwgen($foruser = '') {
$data = array(
$data = [
'password' => '',
'foruser' => $foruser
);
];
$evt = new Event('AUTH_PASSWORD_GENERATE', $data);
if($evt->advise_before(true)) {
@ -846,11 +845,11 @@ function auth_sendPassword($user, $password) {
if(!$userinfo['mail']) return false;
$text = rawLocale('password');
$trep = array(
$trep = [
'FULLNAME' => $userinfo['name'],
'LOGIN' => $user,
'PASSWORD' => $password
);
];
$mail = new Mailer();
$mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
@ -907,7 +906,7 @@ function register() {
}
//okay try to create the user
if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
if(!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
msg($lang['regfail'], -1);
return false;
}
@ -953,7 +952,7 @@ function updateprofile() {
return false;
}
$changes = array();
$changes = [];
$changes['pass'] = $INPUT->post->str('newpass');
$changes['name'] = $INPUT->post->str('fullname');
$changes['mail'] = $INPUT->post->str('email');
@ -988,7 +987,7 @@ function updateprofile() {
if(!$auth->canDo('modPass')) unset($changes['pass']);
// anything to do?
if(!count($changes)) {
if($changes === []) {
msg($lang['profnochange'], -1);
return false;
}
@ -1000,14 +999,14 @@ function updateprofile() {
}
}
if(!$auth->triggerUserMod('modify', array($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']) {
// update cookie and session with the changed data
list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
[, $sticky, ] = auth_getCookie();
$pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
} else {
@ -1055,9 +1054,9 @@ function auth_deleteprofile(){
}
}
$deleted = array();
$deleted = [];
$deleted[] = $INPUT->server->str('REMOTE_USER');
if($auth->triggerUserMod('delete', array($deleted))) {
if($auth->triggerUserMod('delete', [$deleted])) {
// force and immediate logout including removing the sticky cookie
auth_logoff();
return true;
@ -1130,7 +1129,7 @@ function act_resendpwd() {
}
// change it
if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
if(!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
msg($lang['proffail'], -1);
return false;
}
@ -1138,7 +1137,7 @@ function act_resendpwd() {
} else { // autogenerate the password and send by mail
$pass = auth_pwgen($user);
if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
if(!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
msg($lang['proffail'], -1);
return false;
}
@ -1174,16 +1173,12 @@ function act_resendpwd() {
// generate auth token
$token = md5(auth_randombytes(16)); // random secret
$tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
$url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
$url = wl('', ['do'=> 'resendpwd', 'pwauth'=> $token], true, '&');
io_saveFile($tfile, $user);
$text = rawLocale('pwconfirm');
$trep = array(
'FULLNAME' => $userinfo['name'],
'LOGIN' => $user,
'CONFIRM' => $url
);
$trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url];
$mail = new Mailer();
$mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
@ -1287,13 +1282,13 @@ function auth_setCookie($user, $pass, $sticky) {
*/
function auth_getCookie() {
if(!isset($_COOKIE[DOKU_COOKIE])) {
return array(null, null, null);
return [null, null, null];
}
list($user, $sticky, $pass) = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
[$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
$sticky = (bool) $sticky;
$pass = base64_decode($pass);
$user = base64_decode($user);
return array($user, $sticky, $pass);
return [$user, $sticky, $pass];
}
//Setup VIM: ex: et ts=2 :

View File

@ -1,5 +1,6 @@
<?php
// phpcs:ignoreFile
use dokuwiki\Cache\Cache;
use dokuwiki\Cache\CacheParser;
use dokuwiki\Cache\CacheInstructions;
use dokuwiki\Cache\CacheRenderer;
@ -8,11 +9,11 @@ use dokuwiki\Debug\DebugHelper;
/**
* @deprecated since 2019-02-02 use \dokuwiki\Cache\Cache instead!
*/
class cache extends \dokuwiki\Cache\Cache
class cache extends Cache
{
public function __construct($key, $ext)
{
DebugHelper::dbgDeprecatedFunction(dokuwiki\Cache\Cache::class);
DebugHelper::dbgDeprecatedFunction(Cache::class);
parent::__construct($key, $ext);
}
}
@ -20,7 +21,7 @@ class cache extends \dokuwiki\Cache\Cache
/**
* @deprecated since 2019-02-02 use \dokuwiki\Cache\CacheParser instead!
*/
class cache_parser extends \dokuwiki\Cache\CacheParser
class cache_parser extends CacheParser
{
public function __construct($id, $file, $mode)
@ -34,7 +35,7 @@ class cache_parser extends \dokuwiki\Cache\CacheParser
/**
* @deprecated since 2019-02-02 use \dokuwiki\Cache\CacheRenderer instead!
*/
class cache_renderer extends \dokuwiki\Cache\CacheRenderer
class cache_renderer extends CacheRenderer
{
public function __construct($id, $file, $mode)
@ -47,7 +48,7 @@ class cache_renderer extends \dokuwiki\Cache\CacheRenderer
/**
* @deprecated since 2019-02-02 use \dokuwiki\Cache\CacheInstructions instead!
*/
class cache_instructions extends \dokuwiki\Cache\CacheInstructions
class cache_instructions extends CacheInstructions
{
public function __construct($id, $file)
{

View File

@ -5,7 +5,7 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\ChangeLog\MediaChangeLog;
use dokuwiki\ChangeLog\ChangeLog;
use dokuwiki\File\PageFile;
@ -58,14 +58,14 @@ function addLogEntry(
global $INPUT;
// check for special flags as keys
if (!is_array($flags)) $flags = array();
if (!is_array($flags)) $flags = [];
$flagExternalEdit = isset($flags['ExternalEdit']);
$id = cleanid($id);
if (!$date) $date = time(); //use current time if none supplied
$remote = (!$flagExternalEdit) ? clientIP(true) : '127.0.0.1';
$user = (!$flagExternalEdit) ? $INPUT->server->str('REMOTE_USER') : '';
$remote = ($flagExternalEdit) ? '127.0.0.1' : clientIP(true);
$user = ($flagExternalEdit) ? '' : $INPUT->server->str('REMOTE_USER');
$sizechange = ($sizechange === null) ? '' : (int)$sizechange;
// update changelog file and get the added entry that is also to be stored in metadata
@ -116,18 +116,18 @@ function addMediaLogEntry(
global $INPUT;
// check for special flags as keys
if (!is_array($flags)) $flags = array();
if (!is_array($flags)) $flags = [];
$flagExternalEdit = isset($flags['ExternalEdit']);
$id = cleanid($id);
if (!$date) $date = time(); //use current time if none supplied
$remote = (!$flagExternalEdit) ? clientIP(true) : '127.0.0.1';
$user = (!$flagExternalEdit) ? $INPUT->server->str('REMOTE_USER') : '';
$remote = ($flagExternalEdit) ? '127.0.0.1' : clientIP(true);
$user = ($flagExternalEdit) ? '' : $INPUT->server->str('REMOTE_USER');
$sizechange = ($sizechange === null) ? '' : (int)$sizechange;
// update changelog file and get the added entry
(new \dokuwiki\ChangeLog\MediaChangeLog($id, 1024))->addLogEntry([
(new MediaChangeLog($id, 1024))->addLogEntry([
'date' => $date,
'ip' => $remote,
'type' => $type,
@ -163,7 +163,7 @@ function addMediaLogEntry(
*/
function getRecents($first, $num, $ns = '', $flags = 0) {
global $conf;
$recent = array();
$recent = [];
$count = 0;
if (!$num)
@ -176,21 +176,21 @@ function getRecents($first, $num, $ns = '', $flags = 0) {
$lines = @file($conf['changelog']) ?: [];
}
if (!is_array($lines)) {
$lines = array();
$lines = [];
}
$lines_position = count($lines) - 1;
$media_lines_position = 0;
$media_lines = array();
$media_lines = [];
if ($flags & RECENTS_MEDIA_PAGES_MIXED) {
$media_lines = @file($conf['media_changelog']) ?: [];
if (!is_array($media_lines)) {
$media_lines = array();
$media_lines = [];
}
$media_lines_position = count($media_lines) - 1;
}
$seen = array(); // caches seen lines, _handleRecent() skips them
$seen = []; // caches seen lines, _handleRecent() skips them
// handle lines
while ($lines_position >= 0 || (($flags & RECENTS_MEDIA_PAGES_MIXED) && $media_lines_position >= 0)) {
@ -261,7 +261,7 @@ function getRecents($first, $num, $ns = '', $flags = 0) {
*/
function getRecentsSince($from, $to = null, $ns = '', $flags = 0) {
global $conf;
$recent = array();
$recent = [];
if ($to && $to < $from)
return $recent;
@ -278,7 +278,7 @@ function getRecentsSince($from, $to = null, $ns = '', $flags = 0) {
$lines = array_reverse($lines);
// handle lines
$seen = array(); // caches seen lines, _handleRecent() skips them
$seen = []; // caches seen lines, _handleRecent() skips them
foreach ($lines as $line) {
$rec = _handleRecent($line, $ns, $flags, $seen);

View File

@ -5,7 +5,11 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\PassHash;
use dokuwiki\Draft;
use dokuwiki\Utf8\Clean;
use dokuwiki\Utf8\PhpString;
use dokuwiki\Utf8\Conversion;
use dokuwiki\Cache\CacheInstructions;
use dokuwiki\Cache\CacheRenderer;
use dokuwiki\ChangeLog\PageChangeLog;
@ -68,7 +72,7 @@ function sexplode($separator, $string, $limit, $default = null)
*/
function blank(&$in, $trim = false) {
if(is_null($in)) return true;
if(is_array($in)) return empty($in);
if(is_array($in)) return $in === [];
if($in === "\0") return true;
if($trim && trim($in) === '') return true;
if(strlen($in) > 0) return false;
@ -119,7 +123,7 @@ function getSecurityToken() {
// CSRF checks are only for logged in users - do not generate for anonymous
if(trim($user) == '' || trim($session) == '') return '';
return \dokuwiki\PassHash::hmac('md5', $session.$user, auth_cookiesalt());
return PassHash::hmac('md5', $session.$user, auth_cookiesalt());
}
/**
@ -172,7 +176,7 @@ function basicinfo($id, $htmlClient=true){
global $INPUT;
// set info about manager/admin status.
$info = array();
$info = [];
$info['isadmin'] = false;
$info['ismanager'] = false;
if($INPUT->server->has('REMOTE_USER')) {
@ -269,16 +273,14 @@ function pageinfo() {
$pagelog = new PageChangeLog($ID, 1024);
if ($REV) {
$revinfo = $pagelog->getRevisionInfo($REV);
} elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
$revinfo = $info['meta']['last_change'];
} else {
if (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
$revinfo = $info['meta']['last_change'];
} else {
$revinfo = $pagelog->getRevisionInfo($info['lastmod']);
// cache most recent changelog line in metadata if missing and still valid
if ($revinfo !== false) {
$info['meta']['last_change'] = $revinfo;
p_set_metadata($ID, array('last_change' => $revinfo));
}
$revinfo = $pagelog->getRevisionInfo($info['lastmod']);
// cache most recent changelog line in metadata if missing and still valid
if ($revinfo !== false) {
$info['meta']['last_change'] = $revinfo;
p_set_metadata($ID, ['last_change' => $revinfo]);
}
}
//and check for an external edit
@ -286,7 +288,7 @@ function pageinfo() {
// cached changelog line no longer valid
$revinfo = false;
$info['meta']['last_change'] = $revinfo;
p_set_metadata($ID, array('last_change' => $revinfo));
p_set_metadata($ID, ['last_change' => $revinfo]);
}
if ($revinfo !== false) {
@ -305,7 +307,7 @@ function pageinfo() {
}
// draft
$draft = new \dokuwiki\Draft($ID, $info['client']);
$draft = new Draft($ID, $info['client']);
if ($draft->isDraftAvailable()) {
$info['draft'] = $draft->getDraftFilename();
}
@ -412,7 +414,7 @@ function breadcrumbs() {
global $INFO;
//first visit?
$crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
$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)) {
@ -607,8 +609,8 @@ function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
if(is_array($more)) {
// add token for resized images
$w = isset($more['w']) ? $more['w'] : null;
$h = isset($more['h']) ? $more['h'] : null;
$w = $more['w'] ?? null;
$h = $more['h'] ?? null;
if($w || $h || $isexternalimage){
$more['tok'] = media_get_token($id, $w, $h);
}
@ -620,9 +622,9 @@ function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
$more = buildURLparams($more, $sep);
} else {
$matches = array();
$matches = [];
if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
$resize = array('w'=>0, 'h'=>0);
$resize = ['w'=>0, 'h'=>0];
foreach ($matches as $match){
$resize[$match[1]] = $match[2];
}
@ -651,31 +653,27 @@ function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
$id = idfilter($id);
// decide on scriptname
if($direct) {
if ($direct) {
if($conf['userewrite'] == 1) {
$script = '_media';
} else {
$script = 'lib/exe/fetch.php';
}
} elseif ($conf['userewrite'] == 1) {
$script = '_detail';
} else {
if($conf['userewrite'] == 1) {
$script = '_detail';
} else {
$script = 'lib/exe/detail.php';
}
$script = 'lib/exe/detail.php';
}
// build URL based on rewrite mode
if($conf['userewrite']) {
if ($conf['userewrite']) {
$xlink .= $script.'/'.$id;
if($more) $xlink .= '?'.$more;
} elseif ($more) {
$xlink .= $script.'?'.$more;
$xlink .= $sep.'media='.$id;
} else {
if($more) {
$xlink .= $script.'?'.$more;
$xlink .= $sep.'media='.$id;
} else {
$xlink .= $script.'?media='.$id;
}
$xlink .= $script.'?media='.$id;
}
return $xlink;
@ -748,7 +746,7 @@ function checkwordblock($text = '') {
$chunksize = 200;
while($blocks = array_splice($wordblocks, 0, $chunksize)) {
$re = array();
$re = [];
// build regexp from blocks
foreach($blocks as $block) {
$block = preg_replace('/#.*$/', '', $block);
@ -756,9 +754,9 @@ function checkwordblock($text = '') {
if(empty($block)) continue;
$re[] = $block;
}
if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
if(count($re) && preg_match('#('.implode('|', $re).')#si', $text, $matches)) {
// prepare event data
$data = array();
$data = [];
$data['matches'] = $matches;
$data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
if($INPUT->server->str('REMOTE_USER')) {
@ -766,9 +764,7 @@ function checkwordblock($text = '') {
$data['userinfo']['name'] = $INFO['userinfo']['name'];
$data['userinfo']['mail'] = $INFO['userinfo']['mail'];
}
$callback = function () {
return true;
};
$callback = static fn() => true;
return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
}
}
@ -794,7 +790,7 @@ function clientIP($single = false) {
/* @var Input $INPUT */
global $INPUT, $conf;
$ip = array();
$ip = [];
$ip[] = $INPUT->server->str('REMOTE_ADDR');
if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
$ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
@ -811,9 +807,9 @@ function clientIP($single = false) {
}
}
$ip = array_values(array_unique($ip));
if(empty($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 join(',', $ip);
if(!$single) return implode(',', $ip);
// skip trusted local addresses
foreach($ip as $i) {
@ -849,7 +845,7 @@ function clientismobile() {
if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
$uamatches = join(
$uamatches = implode(
'|',
[
'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
@ -892,14 +888,14 @@ function gethostsbyaddrs($ips) {
global $conf;
if(!$conf['dnslookups']) return $ips;
$hosts = array();
$hosts = [];
$ips = explode(',', $ips);
if(is_array($ips)) {
foreach($ips as $ip) {
$hosts[] = gethostbyaddr(trim($ip));
}
return join(',', $hosts);
return implode(',', $hosts);
} else {
return gethostbyaddr(trim($ips));
}
@ -932,8 +928,8 @@ function checklock($id) {
}
//my own lock
@list($ip, $session) = explode("\n", io_readFile($lock));
if($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session == session_id())) {
@[$ip, $session] = explode("\n", io_readFile($lock));
if($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
return false;
}
@ -978,7 +974,7 @@ function unlock($id) {
$lock = wikiLockFN($id);
if(file_exists($lock)) {
@list($ip, $session) = explode("\n", io_readFile($lock));
@[$ip, $session] = explode("\n", io_readFile($lock));
if($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
@unlink($lock);
return true;
@ -1004,7 +1000,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(!\dokuwiki\Utf8\Clean::isUtf8($text)) $text = utf8_encode($text);
if(!Clean::isUtf8($text)) $text = utf8_encode($text);
return $text;
}
@ -1066,12 +1062,12 @@ function pageTemplate($id) {
if(is_array($id)) $id = $id[0];
// prepare initial event data
$data = array(
$data = [
'id' => $id, // the id of the page to be created
'tpl' => '', // the text used as template
'tplfile' => '', // the file above text was/should be loaded from
'doreplace' => true // should wildcard replacements be done on the text?
);
'doreplace' => true,
];
$evt = new Event('COMMON_PAGETPL_LOAD', $data);
if($evt->advise_before(true)) {
@ -1133,52 +1129,51 @@ function parsePageTemplate(&$data) {
$page = strtr($file, $conf['sepchar'], ' ');
$tpl = str_replace(
array(
'@ID@',
'@NS@',
'@CURNS@',
'@!CURNS@',
'@!!CURNS@',
'@!CURNS!@',
'@FILE@',
'@!FILE@',
'@!FILE!@',
'@PAGE@',
'@!PAGE@',
'@!!PAGE@',
'@!PAGE!@',
'@USER@',
'@NAME@',
'@MAIL@',
'@DATE@',
),
array(
$id,
getNS($id),
curNS($id),
\dokuwiki\Utf8\PhpString::ucfirst(curNS($id)),
\dokuwiki\Utf8\PhpString::ucwords(curNS($id)),
\dokuwiki\Utf8\PhpString::strtoupper(curNS($id)),
$file,
\dokuwiki\Utf8\PhpString::ucfirst($file),
\dokuwiki\Utf8\PhpString::strtoupper($file),
$page,
\dokuwiki\Utf8\PhpString::ucfirst($page),
\dokuwiki\Utf8\PhpString::ucwords($page),
\dokuwiki\Utf8\PhpString::strtoupper($page),
$INPUT->server->str('REMOTE_USER'),
$USERINFO ? $USERINFO['name'] : '',
$USERINFO ? $USERINFO['mail'] : '',
$conf['dformat'],
), $tpl
[
'@ID@',
'@NS@',
'@CURNS@',
'@!CURNS@',
'@!!CURNS@',
'@!CURNS!@',
'@FILE@',
'@!FILE@',
'@!FILE!@',
'@PAGE@',
'@!PAGE@',
'@!!PAGE@',
'@!PAGE!@',
'@USER@',
'@NAME@',
'@MAIL@',
'@DATE@'
],
[
$id,
getNS($id),
curNS($id),
PhpString::ucfirst(curNS($id)),
PhpString::ucwords(curNS($id)),
PhpString::strtoupper(curNS($id)),
$file,
PhpString::ucfirst($file),
PhpString::strtoupper($file),
$page,
PhpString::ucfirst($page),
PhpString::ucwords($page),
PhpString::strtoupper($page),
$INPUT->server->str('REMOTE_USER'),
$USERINFO ? $USERINFO['name'] : '',
$USERINFO ? $USERINFO['mail'] : '',
$conf['dformat']
],
$tpl
);
// we need the callback to work around strftime's char limit
$tpl = preg_replace_callback(
'/%./',
function ($m) {
return dformat(null, $m[0]);
},
static fn($m) => dformat(null, $m[0]),
$tpl
);
$data['tpl'] = $tpl;
@ -1204,12 +1199,12 @@ function rawWikiSlices($range, $id, $rev = '') {
$text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
// Parse range
list($from, $to) = sexplode('-', $range, 2);
[$from, $to] = sexplode('-', $range, 2);
// Make range zero-based, use defaults if marker is missing
$from = !$from ? 0 : ($from - 1);
$to = !$to ? strlen($text) : ($to - 1);
$from = $from ? $from - 1 : (0);
$to = $to ? $to - 1 : (strlen($text));
$slices = array();
$slices = [];
$slices[0] = substr($text, 0, $from);
$slices[1] = substr($text, $from, $to - $from);
$slices[2] = substr($text, $to);
@ -1283,7 +1278,7 @@ function saveWikiText($id, $text, $summary, $minor = false) {
if(!$data) return; // save was cancelled (for no changes or by a plugin)
// send notify mails
list('oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary) = $data;
['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
notify($id, 'admin', $rev, $summary, $minor, $new_rev);
notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
@ -1325,7 +1320,7 @@ function saveOldRevision($id) {
*
* @author Andreas Gohr <andi@splitbrain.org>
*/
function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array(), $current_rev = false) {
function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false) {
global $conf;
/* @var Input $INPUT */
global $INPUT;
@ -1338,10 +1333,10 @@ function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace =
} elseif ($who == 'subscribers') {
if (!actionOK('subscribe')) return false; //subscribers enabled?
if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
$data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
$data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
Event::createAndTrigger(
'COMMON_NOTIFY_ADDRESSLIST', $data,
array(new SubscriberManager(), 'notifyAddresses')
[new SubscriberManager(), 'notifyAddresses']
);
$to = $data['addresslist'];
if (empty($to)) return false;
@ -1376,7 +1371,7 @@ function getGoogleQuery() {
if(!array_key_exists('host', $url)) return '';
if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
$query = array();
$query = [];
if(!array_key_exists('query', $url)) return '';
parse_str($url['query'], $query);
@ -1409,7 +1404,7 @@ function getGoogleQuery() {
* @version 1.0.0
*/
function filesize_h($size, $dec = 1) {
$sizes = array('B', 'KB', 'MB', 'GB');
$sizes = ['B', 'KB', 'MB', 'GB'];
$count = count($sizes);
$i = 0;
@ -1509,11 +1504,11 @@ function obfuscate($email) {
switch($conf['mailguard']) {
case 'visible' :
$obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
$obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
return strtr($email, $obfuscate);
case 'hex' :
return \dokuwiki\Utf8\Conversion::toHtml($email, true);
return Conversion::toHtml($email, true);
case 'none' :
default :
@ -1548,16 +1543,16 @@ function unslash($string, $char = "'") {
function php_to_byte($value) {
switch (strtoupper(substr($value,-1))) {
case 'G':
$ret = intval(substr($value, 0, -1)) * 1024 * 1024 * 1024;
$ret = (int) substr($value, 0, -1) * 1024 * 1024 * 1024;
break;
case 'M':
$ret = intval(substr($value, 0, -1)) * 1024 * 1024;
$ret = (int) substr($value, 0, -1) * 1024 * 1024;
break;
case 'K':
$ret = intval(substr($value, 0, -1)) * 1024;
$ret = (int) substr($value, 0, -1) * 1024;
break;
default:
$ret = intval($value);
$ret = (int) $value;
break;
}
return $ret;
@ -1589,15 +1584,15 @@ function preg_quote_cb($string) {
* @return string
*/
function shorten($keep, $short, $max, $min = 9, $char = '…') {
$max = $max - \dokuwiki\Utf8\PhpString::strlen($keep);
$max -= PhpString::strlen($keep);
if($max < $min) return $keep;
$len = \dokuwiki\Utf8\PhpString::strlen($short);
$len = PhpString::strlen($short);
if($len <= $max) return $keep.$short;
$half = floor($max / 2);
return $keep .
\dokuwiki\Utf8\PhpString::substr($short, 0, $half - 1) .
PhpString::substr($short, 0, $half - 1) .
$char .
\dokuwiki\Utf8\PhpString::substr($short, $len - $half);
PhpString::substr($short, $len - $half);
}
/**
@ -1631,22 +1626,23 @@ function userlink($username = null, $textonly = false) {
global $INPUT;
// prepare initial event data
$data = array(
$data = [
'username' => $username, // the unique user name
'name' => '',
'link' => array( //setting 'link' to false disables linking
'target' => '',
'pre' => '',
'suf' => '',
'style' => '',
'more' => '',
'url' => '',
'title' => '',
'class' => ''
),
'link' => [
//setting 'link' to false disables linking
'target' => '',
'pre' => '',
'suf' => '',
'style' => '',
'more' => '',
'url' => '',
'title' => '',
'class' => '',
],
'userlink' => '', // formatted user name as will be returned
'textonly' => $textonly
);
'textonly' => $textonly,
];
if($username === null) {
$data['username'] = $username = $INPUT->server->str('REMOTE_USER');
if($textonly){
@ -1682,7 +1678,7 @@ function userlink($username = null, $textonly = false) {
if(!$data['textonly'] && empty($data['link']['url'])) {
if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
if(in_array($conf['showuseras'], ['email_link', 'username_link'])) {
if(!isset($info)) {
if($auth) $info = $auth->getUserData($username);
}
@ -1748,7 +1744,7 @@ function license_img($type) {
global $conf;
if(!$conf['license']) return '';
if(!is_array($license[$conf['license']])) return '';
$try = array();
$try = [];
$try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
$try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
if(substr($conf['license'], 0, 3) == 'cc-') {
@ -1773,7 +1769,7 @@ function license_img($type) {
* @param int $bytes already allocated memory (see above)
* @return bool
*/
function is_mem_available($mem, $bytes = 1048576) {
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
@ -1891,7 +1887,7 @@ function get_doku_pref($pref, $default) {
// 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) {
if($parts[$i] === $enc_pref) {
return urldecode($parts[$i + 1]);
}
}
@ -1912,14 +1908,14 @@ function set_doku_pref($pref, $val) {
$orig = get_doku_pref($pref, false);
$cookieVal = '';
if($orig !== false && ($orig !== $val)) {
if ($orig !== false && ($orig !== $val)) {
$parts = explode('#', $_COOKIE['DOKU_PREFS']);
$cnt = count($parts);
// urlencode $pref for the comparison
$enc_pref = rawurlencode($pref);
$seen = false;
for ($i = 0; $i < $cnt; $i += 2) {
if ($parts[$i] == $enc_pref) {
if ($parts[$i] === $enc_pref) {
if (!$seen){
if ($val !== false) {
$parts[$i + 1] = rawurlencode($val ?? '');
@ -1936,7 +1932,7 @@ function set_doku_pref($pref, $val) {
}
}
$cookieVal = implode('#', $parts);
} else if ($orig === false && $val !== false) {
} elseif ($orig === false && $val !== false) {
$cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
rawurlencode($pref) . '#' . rawurlencode($val);
}

View File

@ -6,86 +6,83 @@
* DokuWiki directory hierarchy. It can be overriden in inc/preload.php
*/
$config_cascade = array_merge(
array(
'main' => array(
'default' => array(DOKU_CONF . 'dokuwiki.php'),
'local' => array(DOKU_CONF . 'local.php'),
'protected' => array(DOKU_CONF . 'local.protected.php'),
),
'acronyms' => array(
'default' => array(DOKU_CONF . 'acronyms.conf'),
'local' => array(DOKU_CONF . 'acronyms.local.conf'),
),
'entities' => array(
'default' => array(DOKU_CONF . 'entities.conf'),
'local' => array(DOKU_CONF . 'entities.local.conf'),
),
'interwiki' => array(
'default' => array(DOKU_CONF . 'interwiki.conf'),
'local' => array(DOKU_CONF . 'interwiki.local.conf'),
),
'license' => array(
'default' => array(DOKU_CONF . 'license.php'),
'local' => array(DOKU_CONF . 'license.local.php'),
),
'manifest' => array(
'default' => array(DOKU_CONF . 'manifest.json'),
'local' => array(DOKU_CONF . 'manifest.local.json'),
),
'mediameta' => array(
'default' => array(DOKU_CONF . 'mediameta.php'),
'local' => array(DOKU_CONF . 'mediameta.local.php'),
),
'mime' => array(
'default' => array(DOKU_CONF . 'mime.conf'),
'local' => array(DOKU_CONF . 'mime.local.conf'),
),
'scheme' => array(
'default' => array(DOKU_CONF . 'scheme.conf'),
'local' => array(DOKU_CONF . 'scheme.local.conf'),
),
'smileys' => array(
'default' => array(DOKU_CONF . 'smileys.conf'),
'local' => array(DOKU_CONF . 'smileys.local.conf'),
),
'wordblock' => array(
'default' => array(DOKU_CONF . 'wordblock.conf'),
'local' => array(DOKU_CONF . 'wordblock.local.conf'),
),
'userstyle' => array(
'screen' => array(DOKU_CONF . 'userstyle.css', DOKU_CONF . 'userstyle.less'),
'print' => array(DOKU_CONF . 'userprint.css', DOKU_CONF . 'userprint.less'),
'feed' => array(DOKU_CONF . 'userfeed.css', DOKU_CONF . 'userfeed.less'),
'all' => array(DOKU_CONF . 'userall.css', DOKU_CONF . 'userall.less')
),
'userscript' => array(
'default' => array(DOKU_CONF . 'userscript.js')
),
'styleini' => array(
'default' => array(DOKU_INC . 'lib/tpl/%TEMPLATE%/' . 'style.ini'),
'local' => array(DOKU_CONF . 'tpl/%TEMPLATE%/' . 'style.ini')
),
'acl' => array(
'default' => DOKU_CONF . 'acl.auth.php',
),
'plainauth.users' => array(
'default' => DOKU_CONF . 'users.auth.php',
'protected' => '' // not used by default
),
'plugins' => array(
'default' => array(DOKU_CONF . 'plugins.php'),
'local' => array(DOKU_CONF . 'plugins.local.php'),
'protected' => array(
DOKU_CONF . 'plugins.required.php',
DOKU_CONF . 'plugins.protected.php',
),
),
'lang' => array(
'core' => array(DOKU_CONF . 'lang/'),
'plugin' => array(DOKU_CONF . 'plugin_lang/'),
'template' => array(DOKU_CONF . 'template_lang/')
)
),
[
'main' => [
'default' => [DOKU_CONF . 'dokuwiki.php'],
'local' => [DOKU_CONF . 'local.php'],
'protected' => [DOKU_CONF . 'local.protected.php']
],
'acronyms' => [
'default' => [DOKU_CONF . 'acronyms.conf'],
'local' => [DOKU_CONF . 'acronyms.local.conf']
],
'entities' => [
'default' => [DOKU_CONF . 'entities.conf'],
'local' => [DOKU_CONF . 'entities.local.conf']
],
'interwiki' => [
'default' => [DOKU_CONF . 'interwiki.conf'],
'local' => [DOKU_CONF . 'interwiki.local.conf']
],
'license' => [
'default' => [DOKU_CONF . 'license.php'],
'local' => [DOKU_CONF . 'license.local.php']
],
'manifest' => [
'default' => [DOKU_CONF . 'manifest.json'],
'local' => [DOKU_CONF . 'manifest.local.json']
],
'mediameta' => [
'default' => [DOKU_CONF . 'mediameta.php'],
'local' => [DOKU_CONF . 'mediameta.local.php']
],
'mime' => [
'default' => [DOKU_CONF . 'mime.conf'],
'local' => [DOKU_CONF . 'mime.local.conf']
],
'scheme' => [
'default' => [DOKU_CONF . 'scheme.conf'],
'local' => [DOKU_CONF . 'scheme.local.conf']
],
'smileys' => [
'default' => [DOKU_CONF . 'smileys.conf'],
'local' => [DOKU_CONF . 'smileys.local.conf']
],
'wordblock' => [
'default' => [DOKU_CONF . 'wordblock.conf'],
'local' => [DOKU_CONF . 'wordblock.local.conf']
],
'userstyle' => [
'screen' => [DOKU_CONF . 'userstyle.css', DOKU_CONF . 'userstyle.less'],
'print' => [DOKU_CONF . 'userprint.css', DOKU_CONF . 'userprint.less'],
'feed' => [DOKU_CONF . 'userfeed.css', DOKU_CONF . 'userfeed.less'],
'all' => [DOKU_CONF . 'userall.css', DOKU_CONF . 'userall.less']
],
'userscript' => [
'default' => [DOKU_CONF . 'userscript.js']
],
'styleini' => [
'default' => [DOKU_INC . 'lib/tpl/%TEMPLATE%/' . 'style.ini'],
'local' => [DOKU_CONF . 'tpl/%TEMPLATE%/' . 'style.ini']
],
'acl' => [
'default' => DOKU_CONF . 'acl.auth.php'
],
'plainauth.users' => [
'default' => DOKU_CONF . 'users.auth.php',
'protected' => ''
],
'plugins' => [
'default' => [DOKU_CONF . 'plugins.php'],
'local' => [DOKU_CONF . 'plugins.local.php'],
'protected' => [DOKU_CONF . 'plugins.required.php', DOKU_CONF . 'plugins.protected.php']
],
'lang' => [
'core' => [DOKU_CONF . 'lang/'],
'plugin' => [DOKU_CONF . 'plugin_lang/'],
'template' => [DOKU_CONF . 'template_lang/']
]
],
$config_cascade
);

View File

@ -32,20 +32,20 @@ function mimetype($file, $knownonly=true){
$mtypes = getMimeTypes(); // known mimetypes
$ext = strrpos($file, '.');
if ($ext === false) {
return array(false, false, false);
return [false, false, false];
}
$ext = strtolower(substr($file, $ext + 1));
if (!isset($mtypes[$ext])){
if ($knownonly) {
return array(false, false, false);
return [false, false, false];
} else {
return array($ext, 'application/octet-stream', true);
return [$ext, 'application/octet-stream', true];
}
}
if($mtypes[$ext][0] == '!'){
return array($ext, substr($mtypes[$ext],1), true);
return [$ext, substr($mtypes[$ext],1), true];
}else{
return array($ext, $mtypes[$ext], false);
return [$ext, $mtypes[$ext], false];
}
}
@ -113,7 +113,7 @@ function getEntities() {
function getInterwiki() {
static $wikis = null;
if ( !$wikis ) {
$wikis = retrieveConfig('interwiki','confToHash',array(true));
$wikis = retrieveConfig('interwiki','confToHash',[true]);
$wikis = array_filter($wikis, 'strlen');
//add sepecial case 'this'
@ -132,26 +132,23 @@ function getCdnUrls() {
global $conf;
// load version info
$versions = array();
$versions = [];
$lines = file(DOKU_INC . 'lib/scripts/jquery/versions');
foreach($lines as $line) {
$line = trim(preg_replace('/#.*$/', '', $line));
if($line === '') continue;
list($key, $val) = sexplode('=', $line, 2, '');
[$key, $val] = sexplode('=', $line, 2, '');
$key = trim($key);
$val = trim($val);
$versions[$key] = $val;
}
$src = array();
$data = array(
'versions' => $versions,
'src' => &$src
);
$src = [];
$data = ['versions' => $versions, 'src' => &$src];
$event = new Event('CONFUTIL_CDN_SELECT', $data);
if($event->advise_before()) {
if(!$conf['jquerycdn']) {
$jqmod = md5(join('-', $versions));
$jqmod = md5(implode('-', $versions));
$src[] = DOKU_BASE . 'lib/exe/jquery.php' . '?tseed=' . $jqmod;
} elseif($conf['jquerycdn'] == 'jquery') {
$src[] = sprintf('https://code.jquery.com/jquery-%s.min.js', $versions['JQ_VERSION']);
@ -216,9 +213,9 @@ function getSchemes() {
* @return array
*/
function linesToHash($lines, $lower = false) {
$conf = array();
$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) {
//ignore comments (except escaped ones)
@ -255,7 +252,7 @@ function linesToHash($lines, $lower = false) {
* @return array
*/
function confToHash($file,$lower=false) {
$conf = array();
$conf = [];
$lines = @file( $file );
if ( !$lines ) return $conf;
@ -272,7 +269,7 @@ function jsonToArray($file)
{
$json = file_get_contents($file);
$conf = json_decode($json, true);
$conf = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
if ($conf === null) {
return [];
@ -299,15 +296,15 @@ function jsonToArray($file)
function retrieveConfig($type,$fn,$params=null,$combine='array_merge') {
global $config_cascade;
if(!is_array($params)) $params = array();
if(!is_array($params)) $params = [];
$combined = array();
$combined = [];
if (!is_array($config_cascade[$type])) trigger_error('Missing config cascade for "'.$type.'"',E_USER_WARNING);
foreach (array('default','local','protected') as $config_group) {
foreach (['default', 'local', 'protected'] as $config_group) {
if (empty($config_cascade[$type][$config_group])) continue;
foreach ($config_cascade[$type][$config_group] as $file) {
if (file_exists($file)) {
$config = call_user_func_array($fn,array_merge(array($file),$params));
$config = call_user_func_array($fn,array_merge([$file],$params));
$combined = $combine($combined, $config);
}
}
@ -326,10 +323,10 @@ function retrieveConfig($type,$fn,$params=null,$combine='array_merge') {
*/
function getConfigFiles($type) {
global $config_cascade;
$files = array();
$files = [];
if (!is_array($config_cascade[$type])) trigger_error('Missing config cascade for "'.$type.'"',E_USER_WARNING);
foreach (array('default','local','protected') as $config_group) {
foreach (['default', 'local', 'protected'] as $config_group) {
if (empty($config_cascade[$type][$config_group])) continue;
$files = array_merge($files, $config_cascade[$type][$config_group]);
}
@ -411,7 +408,7 @@ function useHeading($linktype) {
$useHeading['navigation'] = true;
}
} else {
$useHeading = array();
$useHeading = [];
}
}

View File

@ -23,10 +23,9 @@
*/
// DOKU_FARMDIR needs to be set in preload.php, the fallback is the same as DOKU_INC would be (if it was set already)
if(!defined('DOKU_FARMDIR')) define('DOKU_FARMDIR', fullpath(dirname(__FILE__).'/../').'/');
if(!defined('DOKU_CONF')) define('DOKU_CONF', farm_confpath(DOKU_FARMDIR));
if(!defined('DOKU_FARM')) define('DOKU_FARM', false);
if (!defined('DOKU_FARMDIR')) define('DOKU_FARMDIR', fullpath(__DIR__ . '/../') . '/');
if (!defined('DOKU_CONF')) define('DOKU_CONF', farm_confpath(DOKU_FARMDIR));
if (!defined('DOKU_FARM')) define('DOKU_FARM', false);
/**
* Find the appropriate configuration directory.
@ -43,14 +42,15 @@ if(!defined('DOKU_FARM')) define('DOKU_FARM', false);
*
* @return string
*/
function farm_confpath($farm) {
function farm_confpath($farm)
{
// htaccess based or cli
// cli usage example: animal=your_animal bin/indexer.php
if(isset($_GET['animal']) || ('cli' == php_sapi_name() && isset($_SERVER['animal']))) {
if (isset($_GET['animal']) || ('cli' == PHP_SAPI && isset($_SERVER['animal']))) {
$mode = isset($_GET['animal']) ? 'htaccess' : 'cli';
$animal = $mode == 'htaccess' ? $_GET['animal'] : $_SERVER['animal'];
if(isset($_GET['animal'])) {
if (isset($_GET['animal'])) {
// now unset the parameter to not leak into new queries
// code by @splitbrain from farmer plugin
unset($_GET['animal']);
@ -62,98 +62,96 @@ function farm_confpath($farm) {
// check that $animal is a string and just a directory name and not a path
if (!is_string($animal) || strpbrk($animal, '\\/') !== false)
nice_die('Sorry! Invalid animal name!');
if(!is_dir($farm.'/'.$animal))
if (!is_dir($farm . '/' . $animal))
nice_die("Sorry! This Wiki doesn't exist!");
if(!defined('DOKU_FARM')) define('DOKU_FARM', $mode);
return $farm.'/'.$animal.'/conf/';
if (!defined('DOKU_FARM')) define('DOKU_FARM', $mode);
return $farm . '/' . $animal . '/conf/';
}
// virtual host based
$uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
$uri = explode('/', $_SERVER['SCRIPT_NAME'] ?: $_SERVER['SCRIPT_FILENAME']);
$server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
for ($i = count($uri) - 1; $i > 0; $i--) {
for ($j = count($server); $j > 0; $j--) {
$dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
if(is_dir("$farm/$dir/conf/")) {
if(!defined('DOKU_FARM')) define('DOKU_FARM', 'virtual');
if (is_dir("$farm/$dir/conf/")) {
if (!defined('DOKU_FARM')) define('DOKU_FARM', 'virtual');
return "$farm/$dir/conf/";
}
}
}
// default conf directory in farm
if(is_dir("$farm/default/conf/")) {
if(!defined('DOKU_FARM')) define('DOKU_FARM', 'default');
if (is_dir("$farm/default/conf/")) {
if (!defined('DOKU_FARM')) define('DOKU_FARM', 'default');
return "$farm/default/conf/";
}
// farmer
return DOKU_INC.'conf/';
return DOKU_INC . 'conf/';
}
/* Use default config files and local animal config files */
$config_cascade = array(
'main' => array(
'default' => array(DOKU_INC.'conf/dokuwiki.php'),
'local' => array(DOKU_CONF.'local.php'),
'protected' => array(DOKU_CONF.'local.protected.php'),
),
'acronyms' => array(
'default' => array(DOKU_INC.'conf/acronyms.conf'),
'local' => array(DOKU_CONF.'acronyms.local.conf'),
),
'entities' => array(
'default' => array(DOKU_INC.'conf/entities.conf'),
'local' => array(DOKU_CONF.'entities.local.conf'),
),
'interwiki' => array(
'default' => array(DOKU_INC.'conf/interwiki.conf'),
'local' => array(DOKU_CONF.'interwiki.local.conf'),
),
'license' => array(
'default' => array(DOKU_INC.'conf/license.php'),
'local' => array(DOKU_CONF.'license.local.php'),
),
'mediameta' => array(
'default' => array(DOKU_INC.'conf/mediameta.php'),
'local' => array(DOKU_CONF.'mediameta.local.php'),
),
'mime' => array(
'default' => array(DOKU_INC.'conf/mime.conf'),
'local' => array(DOKU_CONF.'mime.local.conf'),
),
'scheme' => array(
'default' => array(DOKU_INC.'conf/scheme.conf'),
'local' => array(DOKU_CONF.'scheme.local.conf'),
),
'smileys' => array(
'default' => array(DOKU_INC.'conf/smileys.conf'),
'local' => array(DOKU_CONF.'smileys.local.conf'),
),
'wordblock' => array(
'default' => array(DOKU_INC.'conf/wordblock.conf'),
'local' => array(DOKU_CONF.'wordblock.local.conf'),
),
'acl' => array(
'default' => DOKU_CONF.'acl.auth.php',
),
'plainauth.users' => array(
'default' => DOKU_CONF.'users.auth.php',
),
'plugins' => array( // needed since Angua
'default' => array(DOKU_INC.'conf/plugins.php'),
'local' => array(DOKU_CONF.'plugins.local.php'),
'protected' => array(
DOKU_INC.'conf/plugins.required.php',
DOKU_CONF.'plugins.protected.php',
),
),
'userstyle' => array(
'screen' => array(DOKU_CONF . 'userstyle.css', DOKU_CONF . 'userstyle.less'),
'print' => array(DOKU_CONF . 'userprint.css', DOKU_CONF . 'userprint.less'),
'feed' => array(DOKU_CONF . 'userfeed.css', DOKU_CONF . 'userfeed.less'),
'all' => array(DOKU_CONF . 'userall.css', DOKU_CONF . 'userall.less')
),
'userscript' => array(
'default' => array(DOKU_CONF . 'userscript.js')
),
);
$config_cascade = [
'main' => [
'default' => [DOKU_INC . 'conf/dokuwiki.php'],
'local' => [DOKU_CONF . 'local.php'],
'protected' => [DOKU_CONF . 'local.protected.php']
],
'acronyms' => [
'default' => [DOKU_INC . 'conf/acronyms.conf'],
'local' => [DOKU_CONF . 'acronyms.local.conf']
],
'entities' => [
'default' => [DOKU_INC . 'conf/entities.conf'],
'local' => [DOKU_CONF . 'entities.local.conf']
],
'interwiki' => [
'default' => [DOKU_INC . 'conf/interwiki.conf'],
'local' => [DOKU_CONF . 'interwiki.local.conf']
],
'license' => [
'default' => [DOKU_INC . 'conf/license.php'],
'local' => [DOKU_CONF . 'license.local.php']
],
'mediameta' => [
'default' => [DOKU_INC . 'conf/mediameta.php'],
'local' => [DOKU_CONF . 'mediameta.local.php']
],
'mime' => [
'default' => [DOKU_INC . 'conf/mime.conf'],
'local' => [DOKU_CONF . 'mime.local.conf']
],
'scheme' => [
'default' => [DOKU_INC . 'conf/scheme.conf'],
'local' => [DOKU_CONF . 'scheme.local.conf']
],
'smileys' => [
'default' => [DOKU_INC . 'conf/smileys.conf'],
'local' => [DOKU_CONF . 'smileys.local.conf']
],
'wordblock' => [
'default' => [DOKU_INC . 'conf/wordblock.conf'],
'local' => [DOKU_CONF . 'wordblock.local.conf']
],
'acl' => [
'default' => DOKU_CONF . 'acl.auth.php'
],
'plainauth.users' => [
'default' => DOKU_CONF . 'users.auth.php'
],
'plugins' => [
// needed since Angua
'default' => [DOKU_INC . 'conf/plugins.php'],
'local' => [DOKU_CONF . 'plugins.local.php'],
'protected' => [DOKU_INC . 'conf/plugins.required.php', DOKU_CONF . 'plugins.protected.php'],
],
'userstyle' => [
'screen' => [DOKU_CONF . 'userstyle.css', DOKU_CONF . 'userstyle.less'],
'print' => [DOKU_CONF . 'userprint.css', DOKU_CONF . 'userprint.less'],
'feed' => [DOKU_CONF . 'userfeed.css', DOKU_CONF . 'userfeed.less'],
'all' => [DOKU_CONF . 'userall.css', DOKU_CONF . 'userall.less']
],
'userscript' => [
'default' => [DOKU_CONF . 'userscript.js']
]
];

View File

@ -1,4 +1,6 @@
<?php
use dokuwiki\HTTP\Headers;
use dokuwiki\Utf8\PhpString;
/**
* Functions used by lib/exe/fetch.php
* (not included by other parts of dokuwiki)
@ -31,13 +33,13 @@ function sendFile($file, $mime, $dl, $cache, $public = false, $orig = null, $csp
header("Content-Type: $mime");
// send security policy if given
if (!empty($csp)) dokuwiki\HTTP\Headers::contentSecurityPolicy($csp);
if (!empty($csp)) Headers::contentSecurityPolicy($csp);
// calculate cache times
if($cache == -1) {
if ($cache == -1) {
$maxage = max($conf['cachetime'], 3600); // cachetime or one hour
$expires = time() + $maxage;
} else if($cache > 0) {
} elseif ($cache > 0) {
$maxage = $cache; // given time
$expires = time() + $maxage;
} else { // $cache == 0
@ -74,11 +76,11 @@ function sendFile($file, $mime, $dl, $cache, $public = false, $orig = null, $csp
//download or display?
if ($dl) {
header('Content-Disposition: attachment;' . rfc2231_encode(
'filename', \dokuwiki\Utf8\PhpString::basename($orig)) . ';'
'filename', PhpString::basename($orig)) . ';'
);
} else {
header('Content-Disposition: inline;' . rfc2231_encode(
'filename', \dokuwiki\Utf8\PhpString::basename($orig)) . ';'
'filename', PhpString::basename($orig)) . ';'
);
}
@ -114,9 +116,7 @@ function sendFile($file, $mime, $dl, $cache, $public = false, $orig = null, $csp
function rfc2231_encode($name, $value, $charset='utf-8', $lang='en') {
$internal = preg_replace_callback(
'/[\x00-\x20*\'%()<>@,;:\\\\"\/[\]?=\x80-\xFF]/',
function ($match) {
return rawurlencode($match[0]);
},
static fn($match) => rawurlencode($match[0]),
$value
);
if ( $value != $internal ) {
@ -148,37 +148,37 @@ function checkFileStatus(&$media, &$file, $rev = '', $width=0, $height=0) {
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')) {
return array(412, 'Precondition Failed');
return [412, 'Precondition Failed'];
}
//handle external images
if(strncmp($MIME, 'image/', 6) == 0) $file = media_get_from_URL($media, $EXT, $CACHE);
if(!$file) {
//download failed - redirect to original URL
return array(302, $media);
return [302, $media];
}
} else {
$media = cleanID($media);
if(empty($media)) {
return array(400, 'Bad request');
return [400, 'Bad request'];
}
// check token for resized images
if (($width || $height) && media_get_token($media, $width, $height) !== $INPUT->str('tok')) {
return array(412, 'Precondition Failed');
return [412, 'Precondition Failed'];
}
//check permissions (namespace only)
if(auth_quickaclcheck(getNS($media).':X') < AUTH_READ) {
return array(403, 'Forbidden');
return [403, 'Forbidden'];
}
$file = mediaFN($media, $rev);
}
//check file existance
if(!file_exists($file)) {
return array(404, 'Not Found');
return [404, 'Not Found'];
}
return array(200, null);
return [200, null];
}
/**

View File

@ -5,7 +5,8 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\Utf8\Asian;
use dokuwiki\Search\Indexer;
use dokuwiki\Extension\Event;
use dokuwiki\Utf8\Clean;
use dokuwiki\Utf8\PhpString;
@ -63,19 +64,19 @@ function _ft_pageSearch(&$data) {
$q = ft_queryParser($Indexer, $data['query']);
$data['highlight'] = $q['highlight'];
if (empty($q['parsed_ary'])) return array();
if (empty($q['parsed_ary'])) return [];
// lookup all words found in the query
$lookup = $Indexer->lookup($q['words']);
// get all pages in this dokuwiki site (!: includes nonexistent pages)
$pages_all = array();
$pages_all = [];
foreach ($Indexer->getPages() as $id) {
$pages_all[$id] = 0; // base: 0 hit
}
// process the query
$stack = array();
$stack = [];
foreach ($q['parsed_ary'] as $token) {
switch (substr($token, 0, 3)) {
case 'W+:':
@ -93,13 +94,13 @@ function _ft_pageSearch(&$data) {
// the end($stack) always points the pages that contain
// all words in this phrase
$pages = end($stack);
$pages_matched = array();
$pages_matched = [];
foreach(array_keys($pages) as $id){
$evdata = array(
$evdata = [
'id' => $id,
'phrase' => $phrase,
'text' => rawWiki($id)
);
];
$evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata);
if ($evt->advise_before() && $evt->result !== true) {
$text = PhpString::strtolower($evdata['text']);
@ -117,7 +118,7 @@ function _ft_pageSearch(&$data) {
case 'N+:':
case 'N-:': // namespace
$ns = cleanID(substr($token, 3)) . ':';
$pages_matched = array();
$pages_matched = [];
foreach (array_keys($pages_all) as $id) {
if (strpos($id, $ns) === 0) {
$pages_matched[$id] = 0; // namespace: always 0 hit
@ -126,22 +127,22 @@ function _ft_pageSearch(&$data) {
$stack[] = $pages_matched;
break;
case 'AND': // and operation
list($pages1, $pages2) = array_splice($stack, -2);
$stack[] = ft_resultCombine(array($pages1, $pages2));
[$pages1, $pages2] = array_splice($stack, -2);
$stack[] = ft_resultCombine([$pages1, $pages2]);
break;
case 'OR': // or operation
list($pages1, $pages2) = array_splice($stack, -2);
$stack[] = ft_resultUnite(array($pages1, $pages2));
[$pages1, $pages2] = array_splice($stack, -2);
$stack[] = ft_resultUnite([$pages1, $pages2]);
break;
case 'NOT': // not operation (unary)
$pages = array_pop($stack);
$stack[] = ft_resultComplement(array($pages_all, $pages));
$stack[] = ft_resultComplement([$pages_all, $pages]);
break;
}
}
$docs = array_pop($stack);
if (empty($docs)) return array();
if (empty($docs)) return [];
// check: settings, acls, existence
foreach (array_keys($docs) as $id) {
@ -175,11 +176,11 @@ function _ft_pageSearch(&$data) {
function ft_backlinks($id, $ignore_perms = false){
$result = idx_get_indexer()->lookupKey('relation_references', $id);
if(!count($result)) return $result;
if($result === []) return $result;
// check ACL permissions
foreach(array_keys($result) as $idx){
if(($ignore_perms !== true && (
if((!$ignore_perms && (
isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
)) || !page_exists($result[$idx], '', false)){
unset($result[$idx]);
@ -206,11 +207,11 @@ function ft_backlinks($id, $ignore_perms = false){
function ft_mediause($id, $ignore_perms = false){
$result = idx_get_indexer()->lookupKey('relation_media', $id);
if(!count($result)) return $result;
if($result === []) return $result;
// check ACL permissions
foreach(array_keys($result) as $idx){
if(($ignore_perms !== true && (
if((!$ignore_perms && (
isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
)) || !page_exists($result[$idx], '', false)){
unset($result[$idx]);
@ -282,7 +283,7 @@ function _ft_pageLookup(&$data){
$Indexer = idx_get_indexer();
$page_idx = $Indexer->getPages();
$pages = array();
$pages = [];
if ($id !== '' && $cleaned !== '') {
foreach ($page_idx as $p_id) {
if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
@ -342,7 +343,7 @@ function _ft_filterResultsByTime(array $results, $after, $before) {
$after = is_int($after) ? $after : strtotime($after);
$before = is_int($before) ? $before : strtotime($before);
foreach ($results as $id => $value) {
foreach (array_keys($results) as $id) {
$mTime = filemtime(wikiFN($id));
if ($after && $after > $mTime) {
unset($results[$id]);
@ -425,24 +426,27 @@ function ft_pagemtimesorter($a, $b) {
*/
function ft_snippet($id,$highlight){
$text = rawWiki($id);
$text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens
$evdata = array(
'id' => $id,
'text' => &$text,
'highlight' => &$highlight,
'snippet' => '',
);
$text = str_replace("\xC2\xAD",'',$text);
// remove soft-hyphens
$evdata = [
'id' => $id,
'text' => &$text,
'highlight' => &$highlight,
'snippet' => ''
];
$evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata);
if ($evt->advise_before()) {
$match = array();
$snippets = array();
$utf8_offset = $offset = $end = 0;
$match = [];
$snippets = [];
$utf8_offset = 0;
$offset = 0;
$end = 0;
$len = PhpString::strlen($text);
// build a regexp from the phrases to highlight
$re1 = '(' .
join(
implode(
'|',
array_map(
'ft_snippet_re_preprocess',
@ -458,14 +462,17 @@ function ft_snippet($id,$highlight){
for ($cnt=4; $cnt--;) {
if (0) {
} else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
} else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
} else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
} 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;
}
list($str,$idx) = $match[0];
[$str, $idx] = $match[0];
// convert $idx (a byte offset) into a utf8 character offset
$utf8_idx = PhpString::strlen(substr($text,0,$idx));
@ -478,16 +485,17 @@ function ft_snippet($id,$highlight){
$post = min($len-$utf8_idx-$utf8_len,100);
if ($pre>50 && $post>50) {
$pre = $post = 50;
} else if ($pre>50) {
$pre = 50;
$post = 50;
} elseif ($pre>50) {
$pre = min($pre,100-$post);
} else if ($post>50) {
} elseif ($post>50) {
$post = min($post, 100-$pre);
} else if ($offset == 0) {
} elseif ($offset == 0) {
// both are less than 50, means the context is the whole string
// make it so and break out of this loop - there is no need for the
// complex snippet calculations
$snippets = array($text);
$snippets = [$text];
break;
}
@ -518,7 +526,7 @@ function ft_snippet($id,$highlight){
$snippet = preg_replace(
'/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
'<strong class="search_hit">$1</strong>',
hsc(join('... ', $snippets))
hsc(implode('... ', $snippets))
);
$evdata['snippet'] = $snippet;
@ -537,7 +545,7 @@ function ft_snippet($id,$highlight){
*/
function ft_snippet_re_preprocess($term) {
// do not process asian terms where word boundaries are not explicit
if(\dokuwiki\Utf8\Asian::isAsianWords($term)) return $term;
if(Asian::isAsianWords($term)) return $term;
if (UTF8_PROPERTYSUPPORT) {
// unicode word boundaries
@ -559,7 +567,7 @@ function ft_snippet_re_preprocess($term) {
if(substr($term,-2,2) == '\\*'){
$term = substr($term,0,-2);
}else{
$term = $term.$BR;
$term .= $BR;
}
if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
@ -583,7 +591,7 @@ function ft_resultCombine($args){
return $args[0];
}
$result = array();
$result = [];
if ($array_count > 1) {
foreach ($args[0] as $key => $value) {
$result[$key] = $value;
@ -655,7 +663,7 @@ function ft_resultComplement($args) {
* @author Andreas Gohr <andi@splitbrain.org>
* @author Kazutaka Miyasaka <kazmiya@gmail.com>
*
* @param dokuwiki\Search\Indexer $Indexer
* @param Indexer $Indexer
* @param string $query search query
* @return array of search formulas
*/
@ -777,7 +785,7 @@ function ft_queryParser($Indexer, $query){
// adjustment: make highlightings right
$parens_level = 0;
$notgrp_levels = array();
$notgrp_levels = [];
$parsed_query_new = '';
$tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach ($tokens as $token) {
@ -802,9 +810,9 @@ function ft_queryParser($Indexer, $query){
* see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
* see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
*/
$parsed_ary = array();
$ope_stack = array();
$ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
$parsed_ary = [];
$ope_stack = [];
$ope_precedence = [')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5];
$ope_regex = '/([()]|OR|AND|NOT)/u';
$tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
@ -823,11 +831,11 @@ function ft_queryParser($Indexer, $query){
}
} else {
// operand
$token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
$token_decoded = str_replace(['OP', 'CP'], ['(', ')'], $token);
$parsed_ary[] = $token_decoded;
}
}
$parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
$parsed_ary = array_values([...$parsed_ary, ...array_reverse($ope_stack)]);
// cleanup: each double "NOT" in RPN array actually does nothing
$parsed_ary_count = count($parsed_ary);
@ -839,7 +847,7 @@ function ft_queryParser($Indexer, $query){
$parsed_ary = array_values($parsed_ary);
// build return value
$q = array();
$q = [];
$q['query'] = $query;
$q['parsed_str'] = $parsed_query;
$q['parsed_ary'] = $parsed_ary;
@ -876,8 +884,8 @@ function ft_queryParser($Indexer, $query){
break;
}
}
foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
$q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
foreach (['words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not'] as $key) {
$q[$key] = empty($q[$key]) ? [] : array_values(array_unique($q[$key]));
}
return $q;
@ -890,7 +898,7 @@ function ft_queryParser($Indexer, $query){
*
* @author Kazutaka Miyasaka <kazmiya@gmail.com>
*
* @param dokuwiki\Search\Indexer $Indexer
* @param Indexer $Indexer
* @param string $term
* @param bool $consider_asian
* @param bool $phrase_mode
@ -900,13 +908,13 @@ function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = f
$parsed = '';
if ($consider_asian) {
// successive asian characters need to be searched as a phrase
$words = \dokuwiki\Utf8\Asian::splitAsianWords($term);
$words = Asian::splitAsianWords($term);
foreach ($words as $word) {
$phrase_mode = $phrase_mode ? true : \dokuwiki\Utf8\Asian::isAsianWords($word);
$phrase_mode = $phrase_mode ? true : Asian::isAsianWords($word);
$parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
}
} else {
$term_noparen = str_replace(array('(', ')'), ' ', $term);
$term_noparen = str_replace(['(', ')'], ' ', $term);
$words = $Indexer->tokenizer($term_noparen, true);
// W_: no need to highlight
@ -915,7 +923,7 @@ function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = f
} elseif ($words[0] === $term) {
$parsed = '(W+:'.$words[0].')';
} elseif ($phrase_mode) {
$term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
$term_encoded = str_replace(['(', ')'], ['OP', 'CP'], $term);
$parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
} else {
$parsed = '((W+:'.implode(')(W+:', $words).'))';
@ -937,19 +945,19 @@ function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = f
*/
function ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
$query = implode(' ', $and);
if (!empty($not)) {
if ($not !== []) {
$query .= ' -' . implode(' -', $not);
}
if (!empty($phrases)) {
if ($phrases !== []) {
$query .= ' "' . implode('" "', $phrases) . '"';
}
if (!empty($ns)) {
if ($ns !== []) {
$query .= ' @' . implode(' @', $ns);
}
if (!empty($notns)) {
if ($notns !== []) {
$query .= ' ^' . implode(' ^', $notns);
}

View File

@ -5,7 +5,8 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\Ui\MediaRevisions;
use dokuwiki\Form\Form;
use dokuwiki\Action\Denied;
use dokuwiki\Action\Locked;
use dokuwiki\ChangeLog\PageChangeLog;
@ -60,7 +61,7 @@ function html_wikilink($id, $name = null, $search = '') {
*/
function html_login($svg = false) {
dbg_deprecated(Login::class .'::show()');
(new dokuwiki\Ui\Login($svg))->show();
(new Login($svg))->show();
}
@ -71,7 +72,7 @@ function html_login($svg = false) {
*/
function html_denied() {
dbg_deprecated(Denied::class .'::showBanner()');
(new dokuwiki\Action\Denied())->showBanner();
(new Denied())->showBanner();
}
/**
@ -106,7 +107,7 @@ function html_secedit($text, $show = true) {
*/
function html_secedit_button($matches){
$json = htmlspecialchars_decode($matches[1], ENT_QUOTES);
$data = json_decode($json, true);
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
if ($data === null) {
return '';
}
@ -142,7 +143,7 @@ function html_secedit_get_button($data) {
unset($data['secid']);
$params = array_merge(
array('do' => 'edit', 'rev' => $INFO['lastmod'], 'summary' => '['.$name.'] '),
['do' => 'edit', 'rev' => $INFO['lastmod'], 'summary' => '['.$name.'] '],
$data
);
@ -250,7 +251,7 @@ function html_showrev() {
*/
function html_show($txt=null) {
dbg_deprecated(PageView::class .'::show()');
(new dokuwiki\Ui\PageView($txt))->show();
(new PageView($txt))->show();
}
/**
@ -261,7 +262,7 @@ function html_show($txt=null) {
*/
function html_draft() {
dbg_deprecated(PageDraft::class .'::show()');
(new dokuwiki\Ui\PageDraft)->show();
(new PageDraft)->show();
}
/**
@ -279,7 +280,8 @@ function html_hilight($html, $phrases) {
$phrases = array_map('preg_quote_cb', $phrases);
$phrases = array_map('ft_snippet_re_preprocess', $phrases);
$phrases = array_filter($phrases);
$regex = join('|',$phrases);
$regex = implode('|',$phrases);
if ($regex === '') return $html;
if (!Clean::isUtf8($regex)) return $html;
@ -301,7 +303,7 @@ function html_hilight($html, $phrases) {
*/
function html_locked() {
dbg_deprecated(Locked::class .'::showBanner()');
(new dokuwiki\Action\Locked())->showBanner();
(new Locked())->showBanner();
}
/**
@ -318,10 +320,10 @@ function html_locked() {
function html_revisions($first = -1, $media_id = '') {
dbg_deprecated(PageRevisions::class .'::show()');
if ($media_id) {
(new dokuwiki\Ui\MediaRevisions($media_id))->show($first);
(new MediaRevisions($media_id))->show($first);
} else {
global $INFO;
(new dokuwiki\Ui\PageRevisions($INFO['id']))->show($first);
(new PageRevisions($INFO['id']))->show($first);
}
}
@ -339,7 +341,7 @@ function html_revisions($first = -1, $media_id = '') {
*/
function html_recent($first = 0, $show_changes = 'both') {
dbg_deprecated(Recent::class .'::show()');
(new dokuwiki\Ui\Recent($first, $show_changes))->show();
(new Recent($first, $show_changes))->show();
}
/**
@ -352,7 +354,7 @@ function html_recent($first = 0, $show_changes = 'both') {
*/
function html_index($ns) {
dbg_deprecated(Index::class .'::show()');
(new dokuwiki\Ui\Index($ns))->show();
(new Index($ns))->show();
}
/**
@ -368,7 +370,7 @@ function html_index($ns) {
*/
function html_list_index($item) {
dbg_deprecated(Index::class .'::formatListItem()');
return (new dokuwiki\Ui\Index)->formatListItem($item);
return (new Index)->formatListItem($item);
}
/**
@ -386,7 +388,7 @@ function html_list_index($item) {
*/
function html_li_index($item) {
dbg_deprecated(Index::class .'::tagListItem()');
return (new dokuwiki\Ui\Index)->tagListItem($item);
return (new Index)->tagListItem($item);
}
/**
@ -426,7 +428,7 @@ function html_li_default($item){
* @return string html of an unordered list
*/
function html_buildlist($data, $class, $func, $lifunc = null, $forcewrapper = false) {
if (count($data) === 0) {
if ($data === []) {
return '';
}
@ -438,9 +440,7 @@ function html_buildlist($data, $class, $func, $lifunc = null, $forcewrapper = fa
// set callback function to build the <li> tag, formerly defined as html_li_default()
if (!is_callable($lifunc)) {
$lifunc = function ($item) {
return '<li class="level'.$item['level'].'">';
};
$lifunc = static fn($item) => '<li class="level'.$item['level'].'">';
}
foreach ($data as $item) {
@ -499,7 +499,7 @@ function html_buildlist($data, $class, $func, $lifunc = null, $forcewrapper = fa
*/
function html_backlinks() {
dbg_deprecated(Backlinks::class .'::show()');
(new dokuwiki\Ui\Backlinks)->show();
(new Backlinks)->show();
}
/**
@ -532,7 +532,7 @@ function html_diff_head($l_rev, $r_rev, $id = null, $media = false, $inline = fa
function html_diff($text = '', $intro = true, $type = null) {
dbg_deprecated(PageDiff::class .'::show()');
global $INFO;
(new dokuwiki\Ui\PageDiff($INFO['id']))->compareWith($text)->preference([
(new PageDiff($INFO['id']))->compareWith($text)->preference([
'showIntro' => $intro,
'difftype' => $type,
])->show();
@ -577,7 +577,7 @@ function html_diff_navigationlink($difftype, $linktype, $lrev, $rrev = null) {
*/
function html_insert_softbreaks($diffhtml) {
dbg_deprecated(PageDiff::class .'::insertSoftbreaks()');
return (new dokuwiki\Ui\PageDiff)->insertSoftbreaks($diffhtml);
return (new PageDiff)->insertSoftbreaks($diffhtml);
}
/**
@ -591,7 +591,7 @@ function html_insert_softbreaks($diffhtml) {
*/
function html_conflict($text, $summary) {
dbg_deprecated(PageConflict::class .'::show()');
(new dokuwiki\Ui\PageConflict($text, $summary))->show();
(new PageConflict($text, $summary))->show();
}
/**
@ -607,7 +607,7 @@ function html_msgarea() {
if (!isset($MSG)) return;
$shown = array();
$shown = [];
foreach ($MSG as $msg) {
$hash = md5($msg['msg']);
if (isset($shown[$hash])) continue; // skip double messages
@ -630,7 +630,7 @@ function html_msgarea() {
*/
function html_register() {
dbg_deprecated(UserRegister::class .'::show()');
(new dokuwiki\Ui\UserRegister)->show();
(new UserRegister)->show();
}
/**
@ -642,7 +642,7 @@ function html_register() {
*/
function html_updateprofile() {
dbg_deprecated(UserProfile::class .'::show()');
(new dokuwiki\Ui\UserProfile)->show();
(new UserProfile)->show();
}
/**
@ -654,7 +654,7 @@ function html_updateprofile() {
*/
function html_edit() {
dbg_deprecated(Editor::class .'::show()');
(new dokuwiki\Ui\Editor)->show();
(new Editor)->show();
}
/**
@ -667,7 +667,7 @@ function html_edit() {
*/
function html_edit_form($param) {
dbg_deprecated(Editor::class .'::addTextarea()');
(new dokuwiki\Ui\Editor)->addTextarea($param);
(new Editor)->addTextarea($param);
}
/**
@ -754,7 +754,7 @@ function html_debug() {
print '</pre>';
if (function_exists('apache_get_version')) {
$apache = array();
$apache = [];
$apache['version'] = apache_get_version();
if (function_exists('apache_get_modules')) {
@ -777,7 +777,7 @@ function html_debug() {
*/
function html_resendpwd() {
dbg_deprecated(UserResendPwd::class .'::show()');
(new dokuwiki\Ui\UserResendPwd)->show();
(new UserResendPwd)->show();
}
/**
@ -789,7 +789,7 @@ function html_resendpwd() {
* @return string html
*/
function html_TOC($toc) {
if (!count($toc)) return '';
if ($toc === []) return '';
global $lang;
$out = '<!-- TOC START -->'.DOKU_LF;
$out .= '<div id="dw__toc" class="dw__toc">'.DOKU_LF;
@ -831,12 +831,12 @@ function html_list_toc($item) {
* @return array the toc item
*/
function html_mktocitem($link, $text, $level, $hash='#') {
return array(
'link' => $hash.$link,
'title' => $text,
'type' => 'ul',
'level' => $level
);
return [
'link' => $hash.$link,
'title' => $text,
'type' => 'ul',
'level' => $level
];
}
/**
@ -866,7 +866,7 @@ function html_form($name, $form) {
* @deprecated 2020-07-18
*/
function html_form_output($form) {
dbg_deprecated('use dokuwiki\Form\Form::toHTML()');
dbg_deprecated('use ' . Form::class . '::toHTML()');
$form->printForm();
}
@ -899,7 +899,7 @@ function html_flashobject($swf,$width,$height,$params=null,$flashvars=null,$atts
$out = '';
// prepare the object attributes
if(is_null($atts)) $atts = array();
if(is_null($atts)) $atts = [];
$atts['width'] = (int) $width;
$atts['height'] = (int) $height;
if(!$atts['width']) $atts['width'] = 425;
@ -1012,7 +1012,7 @@ function html_sizechange($sizechange, $form = null) {
if (!isset($form)) {
return '<span class="'.$class.'">'.$value.'</span>';
} else { // Doku_Form
$form->addElement(form_makeOpenTag('span', array('class' => $class)));
$form->addElement(form_makeOpenTag('span', ['class' => $class]));
$form->addElement($value);
$form->addElement(form_makeCloseTag('span'));
}

View File

@ -6,26 +6,27 @@
* @author Andreas Gohr <andi@splitbrain.org>
*/
define('HTTP_MULTIPART_BOUNDARY','D0KuW1K1B0uNDARY');
define('HTTP_HEADER_LF',"\r\n");
define('HTTP_CHUNK_SIZE',16*1024);
define('HTTP_MULTIPART_BOUNDARY', 'D0KuW1K1B0uNDARY');
define('HTTP_HEADER_LF', "\r\n");
define('HTTP_CHUNK_SIZE', 16 * 1024);
/**
* Checks and sets HTTP headers for conditional HTTP requests
*
* @author Simon Willison <swillison@gmail.com>
* @param int $timestamp lastmodified time of the cache file
* @returns void or exits with previously header() commands executed
* @link http://simonwillison.net/2003/Apr/23/conditionalGet/
*
* @param int $timestamp lastmodified time of the cache file
* @returns void or exits with previously header() commands executed
* @author Simon Willison <swillison@gmail.com>
*/
function http_conditionalRequest($timestamp){
function http_conditionalRequest($timestamp)
{
global $INPUT;
// A PHP implementation of conditional get, see
// http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/
$last_modified = substr(gmdate('r', $timestamp), 0, -5).'GMT';
$etag = '"'.md5($last_modified).'"';
$last_modified = substr(gmdate('r', $timestamp), 0, -5) . 'GMT';
$etag = '"' . md5($last_modified) . '"';
// Send the headers
header("Last-Modified: $last_modified");
header("ETag: $etag");
@ -33,7 +34,7 @@ function http_conditionalRequest($timestamp){
$if_modified_since = $INPUT->server->filter('stripslashes')->str('HTTP_IF_MODIFIED_SINCE', false);
$if_none_match = $INPUT->server->filter('stripslashes')->str('HTTP_IF_NONE_MATCH', false);
if (!$if_modified_since && !$if_none_match){
if (!$if_modified_since && !$if_none_match) {
return;
}
@ -57,26 +58,27 @@ function http_conditionalRequest($timestamp){
/**
* Let the webserver send the given file via x-sendfile method
*
* @author Chris Smith <chris@jalakai.co.uk>
*
* @param string $file absolute path of file to send
* @returns void or exits with previous header() commands executed
* @author Chris Smith <chris@jalakai.co.uk>
*
*/
function http_sendfile($file) {
function http_sendfile($file)
{
global $conf;
//use x-sendfile header to pass the delivery to compatible web servers
if($conf['xsendfile'] == 1){
if ($conf['xsendfile'] == 1) {
header("X-LIGHTTPD-send-file: $file");
ob_end_clean();
exit;
}elseif($conf['xsendfile'] == 2){
} elseif ($conf['xsendfile'] == 2) {
header("X-Sendfile: $file");
ob_end_clean();
exit;
}elseif($conf['xsendfile'] == 3){
} elseif ($conf['xsendfile'] == 3) {
// FS#2388 nginx just needs the relative path.
$file = DOKU_REL.substr($file, strlen(fullpath(DOKU_INC)) + 1);
$file = DOKU_REL . substr($file, strlen(fullpath(DOKU_INC)) + 1);
header("X-Accel-Redirect: $file");
ob_end_clean();
exit;
@ -89,79 +91,80 @@ function http_sendfile($file) {
* This function exits the running script
*
* @param resource $fh - file handle for an already open file
* @param int $size - size of the whole file
* @param int $mime - MIME type of the file
* @param int $size - size of the whole file
* @param int $mime - MIME type of the file
*
* @author Andreas Gohr <andi@splitbrain.org>
*/
function http_rangeRequest($fh,$size,$mime){
function http_rangeRequest($fh, $size, $mime)
{
global $INPUT;
$ranges = array();
$ranges = [];
$isrange = false;
header('Accept-Ranges: bytes');
if(!$INPUT->server->has('HTTP_RANGE')){
if (!$INPUT->server->has('HTTP_RANGE')) {
// no range requested - send the whole file
$ranges[] = array(0,$size,$size);
}else{
$ranges[] = [0, $size, $size];
} else {
$t = explode('=', $INPUT->server->str('HTTP_RANGE'));
if (!$t[0]=='bytes') {
if (!$t[0] == 'bytes') {
// we only understand byte ranges - send the whole file
$ranges[] = array(0,$size,$size);
}else{
$ranges[] = [0, $size, $size];
} else {
$isrange = true;
// handle multiple ranges
$r = explode(',',$t[1]);
foreach($r as $x){
$r = explode(',', $t[1]);
foreach ($r as $x) {
$p = explode('-', $x);
$start = (int)$p[0];
$end = (int)$p[1];
$end = (int)$p[1];
if (!$end) $end = $size - 1;
if ($start > $end || $start > $size || $end > $size){
if ($start > $end || $start > $size || $end > $size) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
print 'Bad Range Request!';
exit;
}
$len = $end - $start + 1;
$ranges[] = array($start,$end,$len);
$ranges[] = [$start, $end, $len];
}
}
}
$parts = count($ranges);
// now send the type and length headers
if(!$isrange){
header("Content-Type: $mime",true);
}else{
if (!$isrange) {
header("Content-Type: $mime", true);
} else {
header('HTTP/1.1 206 Partial Content');
if($parts == 1){
header("Content-Type: $mime",true);
}else{
header('Content-Type: multipart/byteranges; boundary='.HTTP_MULTIPART_BOUNDARY,true);
if ($parts == 1) {
header("Content-Type: $mime", true);
} else {
header('Content-Type: multipart/byteranges; boundary=' . HTTP_MULTIPART_BOUNDARY, true);
}
}
// send all ranges
for($i=0; $i<$parts; $i++){
list($start,$end,$len) = $ranges[$i];
for ($i = 0; $i < $parts; $i++) {
[$start, $end, $len] = $ranges[$i];
// multipart or normal headers
if($parts > 1){
echo HTTP_HEADER_LF.'--'.HTTP_MULTIPART_BOUNDARY.HTTP_HEADER_LF;
echo "Content-Type: $mime".HTTP_HEADER_LF;
echo "Content-Range: bytes $start-$end/$size".HTTP_HEADER_LF;
if ($parts > 1) {
echo HTTP_HEADER_LF . '--' . HTTP_MULTIPART_BOUNDARY . HTTP_HEADER_LF;
echo "Content-Type: $mime" . HTTP_HEADER_LF;
echo "Content-Range: bytes $start-$end/$size" . HTTP_HEADER_LF;
echo HTTP_HEADER_LF;
}else{
} else {
header("Content-Length: $len");
if($isrange){
if ($isrange) {
header("Content-Range: bytes $start-$end/$size");
}
}
// send file content
fseek($fh,$start); //seek to start of range
fseek($fh, $start); //seek to start of range
$chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
while (!feof($fh) && $chunk > 0) {
@set_time_limit(30); // large files can take a lot of time
@ -171,8 +174,8 @@ function http_rangeRequest($fh,$size,$mime){
$chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
}
}
if($parts > 1){
echo HTTP_HEADER_LF.'--'.HTTP_MULTIPART_BOUNDARY.'--'.HTTP_HEADER_LF;
if ($parts > 1) {
echo HTTP_HEADER_LF . '--' . HTTP_MULTIPART_BOUNDARY . '--' . HTTP_HEADER_LF;
}
// everything should be done here, exit (or return if testing)
@ -186,17 +189,18 @@ function http_rangeRequest($fh,$size,$mime){
* return true if there exists a gzip version of the uncompressed file
* (samepath/samefilename.sameext.gz) created after the uncompressed file
*
* @author Chris Smith <chris.eureka@jalakai.co.uk>
*
* @param string $uncompressed_file
* @return bool
* @author Chris Smith <chris.eureka@jalakai.co.uk>
*
*/
function http_gzip_valid($uncompressed_file) {
if(!DOKU_HAS_GZIP) return false;
function http_gzip_valid($uncompressed_file)
{
if (!DOKU_HAS_GZIP) return false;
$gzip = $uncompressed_file.'.gz';
$gzip = $uncompressed_file . '.gz';
if (filemtime($gzip) < filemtime($uncompressed_file)) { // filemtime returns false (0) if file doesn't exist
return copy($uncompressed_file, 'compress.zlib://'.$gzip);
return copy($uncompressed_file, 'compress.zlib://' . $gzip);
}
return true;
@ -210,24 +214,25 @@ function http_gzip_valid($uncompressed_file) {
* and the script is terminated.
*
* @param string $cache cache file name
* @param bool $cache_ok if cache can be used
* @param bool $cache_ok if cache can be used
*/
function http_cached($cache, $cache_ok) {
function http_cached($cache, $cache_ok)
{
global $conf;
// check cache age & handle conditional request
// since the resource files are timestamped, we can use a long max age: 1 year
header('Cache-Control: public, max-age=31536000');
header('Pragma: public');
if($cache_ok){
if ($cache_ok) {
http_conditionalRequest(filemtime($cache));
if($conf['allowdebug']) header("X-CacheUsed: $cache");
if ($conf['allowdebug']) header("X-CacheUsed: $cache");
// finally send output
if ($conf['gzip_output'] && http_gzip_valid($cache)) {
header('Vary: Accept-Encoding');
header('Content-Encoding: gzip');
readfile($cache.".gz");
readfile($cache . ".gz");
} else {
http_sendfile($cache);
readfile($cache);
@ -244,18 +249,19 @@ function http_cached($cache, $cache_ok) {
* @param string $file file name
* @param string $content
*/
function http_cached_finish($file, $content) {
function http_cached_finish($file, $content)
{
global $conf;
// save cache file
io_saveFile($file, $content);
if(DOKU_HAS_GZIP) io_saveFile("$file.gz",$content);
if (DOKU_HAS_GZIP) io_saveFile("$file.gz", $content);
// finally send output
if ($conf['gzip_output'] && DOKU_HAS_GZIP) {
header('Vary: Accept-Encoding');
header('Content-Encoding: gzip');
print gzencode($content,9,FORCE_GZIP);
print gzencode($content, 9, FORCE_GZIP);
} else {
print $content;
}
@ -266,7 +272,8 @@ function http_cached_finish($file, $content) {
*
* @return string
*/
function http_get_raw_post_data() {
function http_get_raw_post_data()
{
static $postData = null;
if ($postData === null) {
$postData = file_get_contents('php://input');
@ -279,13 +286,14 @@ function http_get_raw_post_data() {
*
* Inspired by CodeIgniter's set_status_header function
*
* @param int $code
* @param int $code
* @param string $text
*/
function http_status($code = 200, $text = '') {
function http_status($code = 200, $text = '')
{
global $INPUT;
static $stati = array(
static $stati = [
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
@ -293,14 +301,12 @@ function http_status($code = 200, $text = '') {
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
403 => 'Forbidden',
@ -318,25 +324,24 @@ function http_status($code = 200, $text = '') {
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
];
if($text == '' && isset($stati[$code])) {
if ($text == '' && isset($stati[$code])) {
$text = $stati[$code];
}
$server_protocol = $INPUT->server->str('SERVER_PROTOCOL', false);
if(substr(php_sapi_name(), 0, 3) == 'cgi' || defined('SIMPLE_TEST')) {
if (substr(PHP_SAPI, 0, 3) == 'cgi' || defined('SIMPLE_TEST')) {
header("Status: {$code} {$text}", true);
} elseif($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0') {
header($server_protocol." {$code} {$text}", true, $code);
} elseif ($server_protocol == 'HTTP/1.1' || $server_protocol == 'HTTP/1.0') {
header($server_protocol . " {$code} {$text}", true, $code);
} else {
header("HTTP/1.1 {$code} {$text}", true, $code);
}

View File

@ -6,7 +6,7 @@
* @author Andreas Gohr <andi@splitbrain.org>
* @author Tom N Harris <tnharris@whoopdedo.org>
*/
use dokuwiki\Utf8\Clean;
use dokuwiki\Extension\Event;
use dokuwiki\Search\Indexer;
@ -36,7 +36,7 @@ function idx_get_version(){
$version = INDEXER_VERSION;
// DokuWiki version is included for the convenience of plugins
$data = array('dokuwiki'=>$version);
$data = ['dokuwiki'=>$version];
Event::createAndTrigger('INDEXER_VERSION_GET', $data, null, false);
unset($data['dokuwiki']); // this needs to be first
ksort($data);
@ -97,7 +97,7 @@ function & idx_get_stopwords() {
if(file_exists($swfile)){
$stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
}else{
$stopwords = array();
$stopwords = [];
}
}
return $stopwords;
@ -167,19 +167,19 @@ function idx_addPage($page, $verbose=false, $force=false) {
return false;
}
$body = '';
$metadata = array();
$metadata = [];
$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'] = array();
$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'] = array();
$metadata['relation_media'] = [];
$data = compact('page', 'body', 'metadata', 'pid');
$data = ['page' => $page, 'body' => $body, 'metadata' => $metadata, 'pid' => $pid];
$evt = new Event('INDEXER_PAGE_ADD', $data);
if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page);
$evt->advise_after();
@ -253,7 +253,7 @@ function idx_tokenizer($string, $wc=false) {
function idx_getIndex($idx, $suffix) {
global $conf;
$fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
if (!file_exists($fn)) return array();
if (!file_exists($fn)) return [];
return file($fn);
}
@ -280,7 +280,7 @@ function idx_listIndexLengths() {
($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES))
!== false
) {
$idx = array();
$idx = [];
foreach ($lengths as $length) {
$idx[] = (int)$length;
}
@ -293,8 +293,8 @@ function idx_listIndexLengths() {
if ($conf['readdircache'] == 0 || $docache) {
$dir = @opendir($conf['indexdir']);
if ($dir === false)
return array();
$idx = array();
return [];
$idx = [];
while (($f = readdir($dir)) !== false) {
if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
$i = substr($f, 1, -4);
@ -313,7 +313,7 @@ function idx_listIndexLengths() {
return $idx;
}
return array();
return [];
}
/**
@ -329,17 +329,17 @@ function idx_listIndexLengths() {
*/
function idx_indexLengths($filter) {
global $conf;
$idx = array();
$idx = [];
if (is_array($filter)) {
// testing if index files exist only
$path = $conf['indexdir']."/i";
foreach ($filter as $key => $value) {
foreach (array_keys($filter) as $key) {
if (file_exists($path.$key.'.idx'))
$idx[] = $key;
}
} else {
$lengths = idx_listIndexLengths();
foreach ($lengths as $key => $length) {
foreach ($lengths as $length) {
// keep all the values equal or superior
if ((int)$length >= (int)$filter)
$idx[] = $length;
@ -360,7 +360,7 @@ function idx_indexLengths($filter) {
* @return string
*/
function idx_cleanName($name) {
$name = \dokuwiki\Utf8\Clean::romanize(trim((string)$name));
$name = Clean::romanize(trim((string)$name));
$name = preg_replace('#[ \./\\:-]+#', '_', $name);
$name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
return strtolower($name);

View File

@ -5,7 +5,9 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\Extension\Event;
use dokuwiki\Utf8\PhpString;
use dokuwiki\Debug\DebugHelper;
use dokuwiki\HTTP\DokuHTTPClient;
use dokuwiki\Logger;
@ -66,7 +68,7 @@ function checkUpdateMessages(){
* @author Andreas Gohr <andi@splitbrain.org>
*/
function getVersionData(){
$version = array();
$version = [];
//import version string
if(file_exists(DOKU_INC.'VERSION')){
//official release
@ -80,7 +82,7 @@ function getVersionData(){
if (function_exists('shell_exec')) {
$commitInfo = shell_exec("git log -1 --pretty=format:'%h %cd' --date=short");
if ($commitInfo) {
list($version['sha'], $date) = explode(' ', $commitInfo);
[$version['sha'], $date] = explode(' ', $commitInfo);
$version['date'] = hsc($date);
return $version;
}
@ -137,7 +139,7 @@ function getVersionData(){
*/
function getVersion(){
$version = getVersionData();
$sha = !empty($version['sha']) ? ' (' . $version['sha'] . ')' : '';
$sha = empty($version['sha']) ? '' : ' (' . $version['sha'] . ')';
return $version['type'] . ' ' . $version['date'] . $sha;
}
@ -152,31 +154,28 @@ function check(){
/* @var Input $INPUT */
global $INPUT;
if ($INFO['isadmin'] || $INFO['ismanager']){
if ($INFO['isadmin'] || $INFO['ismanager']) {
msg('DokuWiki version: '.getVersion(),1);
if(version_compare(phpversion(),'7.4.0','<')){
msg('Your PHP version is too old ('.phpversion().' vs. 7.4+ needed)',-1);
}else{
msg('PHP version '.phpversion(),1);
}
} else {
if(version_compare(phpversion(),'7.4.0','<')){
msg('Your PHP version is too old',-1);
}
} elseif (version_compare(phpversion(),'7.4.0','<')) {
msg('Your PHP version is too old',-1);
}
$mem = (int) php_to_byte(ini_get('memory_limit'));
$mem = php_to_byte(ini_get('memory_limit'));
if($mem){
if ($mem === -1) {
msg('PHP memory is unlimited', 1);
} else if ($mem < 16777216) {
} elseif ($mem < 16_777_216) {
msg('PHP is limited to less than 16MB RAM (' . filesize_h($mem) . ').
Increase memory_limit in php.ini', -1);
} else if ($mem < 20971520) {
} elseif ($mem < 20_971_520) {
msg('PHP is limited to less than 20MB RAM (' . filesize_h($mem) . '),
you might encounter problems with bigger pages. Increase memory_limit in php.ini', -1);
} else if ($mem < 33554432) {
} elseif ($mem < 33_554_432) {
msg('PHP is limited to less than 32MB RAM (' . filesize_h($mem) . '),
but that should be enough in most cases. If not, increase memory_limit in php.ini', 0);
} else {
@ -184,12 +183,10 @@ function check(){
}
}
if(is_writable($conf['changelog'])){
if (is_writable($conf['changelog'])) {
msg('Changelog is writable',1);
}else{
if (file_exists($conf['changelog'])) {
msg('Changelog is not writable',-1);
}
} elseif (file_exists($conf['changelog'])) {
msg('Changelog is not writable',-1);
}
if (isset($conf['changelog_old']) && file_exists($conf['changelog_old'])) {
@ -198,9 +195,9 @@ function check(){
if (file_exists($conf['changelog'].'_failed')) {
msg('Importing old changelog failed', -1);
} else if (file_exists($conf['changelog'].'_importing')) {
} elseif (file_exists($conf['changelog'].'_importing')) {
msg('Importing old changelog now.', 0);
} else if (file_exists($conf['changelog'].'_import_ok')) {
} elseif (file_exists($conf['changelog'].'_import_ok')) {
msg('Old changelog imported', 1);
if (!plugin_isdisabled('importoldchangelog')) {
msg('Importoldchangelog plugin not disabled after import', -1);
@ -285,14 +282,14 @@ function check(){
$lengths = idx_listIndexLengths();
$index_corrupted = false;
foreach ($lengths as $length) {
if (count(idx_getIndex('w', $length)) != count(idx_getIndex('i', $length))) {
if (count(idx_getIndex('w', $length)) !== count(idx_getIndex('i', $length))) {
$index_corrupted = true;
break;
}
}
foreach (idx_getIndex('metadata', '') as $index) {
if (count(idx_getIndex($index.'_w', '')) != count(idx_getIndex($index.'_i', ''))) {
if (count(idx_getIndex($index.'_w', '')) !== count(idx_getIndex($index.'_i', ''))) {
$index_corrupted = true;
break;
}
@ -369,15 +366,15 @@ function msg($message,$lvl=0,$line='',$file='',$allow=MSG_PUBLIC){
'file' => $file,
];
$evt = new \dokuwiki\Extension\Event('INFOUTIL_MSG_SHOW', $msgdata);
$evt = new Event('INFOUTIL_MSG_SHOW', $msgdata);
if ($evt->advise_before()) {
/* Show msg normally - event could suppress message show */
if($msgdata['line'] || $msgdata['file']) {
$basename = \dokuwiki\Utf8\PhpString::basename($msgdata['file']);
$basename = PhpString::basename($msgdata['file']);
$msgdata['msg'] .=' ['.$basename.':'.$msgdata['line'].']';
}
if(!isset($MSG)) $MSG = array();
if(!isset($MSG)) $MSG = [];
$MSG[] = $msgdata;
if(isset($MSG_shown) || headers_sent()){
if(function_exists('html_msgarea')){
@ -426,8 +423,6 @@ function info_msg_allowed($msg){
E_USER_WARNING);
return $INFO['isadmin'];
}
return false;
}
/**
@ -481,7 +476,7 @@ function dbglog($msg,$header=''){
* @triggers INFO_DEPRECATION_LOG
*/
function dbg_deprecated($alternative = '') {
\dokuwiki\Debug\DebugHelper::dbgDeprecatedFunction($alternative, 2);
DebugHelper::dbgDeprecatedFunction($alternative, 2);
}
/**
@ -497,14 +492,14 @@ function dbg_backtrace(){
array_shift($backtrace);
// Iterate backtrace
$calls = array();
$calls = [];
$depth = count($backtrace) - 1;
foreach ($backtrace as $i => $call) {
$location = $call['file'] . ':' . $call['line'];
$function = (isset($call['class'])) ?
$call['class'] . $call['type'] . $call['function'] : $call['function'];
$params = array();
$params = [];
if (isset($call['args'])){
foreach($call['args'] as $arg){
if(is_object($arg)){
@ -514,7 +509,7 @@ function dbg_backtrace(){
}elseif(is_null($arg)){
$params[] = '[NULL]';
}else{
$params[] = (string) '"'.$arg.'"';
$params[] = '"'.$arg.'"';
}
}
}

View File

@ -2,7 +2,9 @@
/**
* Initialize some defaults needed for DokuWiki
*/
use dokuwiki\Extension\PluginController;
use dokuwiki\ErrorHandler;
use dokuwiki\Input\Input;
use dokuwiki\Extension\Event;
use dokuwiki\Extension\EventHandler;
@ -19,14 +21,14 @@ function delta_time($start=0) {
define('DOKU_START_TIME', delta_time());
global $config_cascade;
$config_cascade = array();
$config_cascade = [];
// if available load a preload config file
$preload = fullpath(dirname(__FILE__)).'/preload.php';
$preload = fullpath(__DIR__).'/preload.php';
if (file_exists($preload)) include($preload);
// define the include path
if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(__DIR__.'/../').'/');
// define Plugin dir
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
@ -49,15 +51,15 @@ header('Vary: Cookie');
// init memory caches
global $cache_revinfo;
$cache_revinfo = array();
$cache_revinfo = [];
global $cache_wikifn;
$cache_wikifn = array();
$cache_wikifn = [];
global $cache_cleanid;
$cache_cleanid = array();
$cache_cleanid = [];
global $cache_authname;
$cache_authname = array();
$cache_authname = [];
global $cache_metadata;
$cache_metadata = array();
$cache_metadata = [];
// always include 'inc/config_cascade.php'
// previously in preload.php set fields of $config_cascade will be merged with the defaults
@ -65,10 +67,10 @@ include(DOKU_INC.'inc/config_cascade.php');
//prepare config array()
global $conf;
$conf = array();
$conf = [];
// load the global config file(s)
foreach (array('default','local','protected') as $config_group) {
foreach (['default', 'local', 'protected'] as $config_group) {
if (empty($config_cascade['main'][$config_group])) continue;
foreach ($config_cascade['main'][$config_group] as $config_file) {
if (file_exists($config_file)) {
@ -79,10 +81,10 @@ foreach (array('default','local','protected') as $config_group) {
//prepare license array()
global $license;
$license = array();
$license = [];
// load the license file(s)
foreach (array('default','local') as $config_group) {
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)){
@ -112,7 +114,7 @@ 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')) {
$serverPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : '';
$serverPort = $_SERVER['SERVER_PORT'] ?? '';
define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
unset($serverPort);
}
@ -146,7 +148,7 @@ if(!defined('DOKU_TPLINC')) {
@ini_set('pcre.backtrack_limit', '20971520');
// enable gzip compression if supported
$httpAcceptEncoding = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
$httpAcceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
$conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
global $ACT;
if ($conf['gzip_output'] &&
@ -193,14 +195,14 @@ init_files();
// setup plugin controller class (can be overwritten in preload.php)
global $plugin_controller_class, $plugin_controller;
if (empty($plugin_controller_class)) $plugin_controller_class = dokuwiki\Extension\PluginController::class;
if (empty($plugin_controller_class)) $plugin_controller_class = PluginController::class;
// load libraries
require_once(DOKU_INC.'vendor/autoload.php');
require_once(DOKU_INC.'inc/load.php');
// from now on everything is an exception
\dokuwiki\ErrorHandler::register();
ErrorHandler::register();
// disable gzip if not available
define('DOKU_HAS_BZIP', function_exists('bzopen'));
@ -214,7 +216,7 @@ if($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
// input handle class
global $INPUT;
$INPUT = new \dokuwiki\Input\Input();
$INPUT = new Input();
// initialize plugin controller
$plugin_controller = new $plugin_controller_class();
@ -301,7 +303,7 @@ function init_paths(){
// path to old changelog only needed for upgrading
$conf['changelog_old'] = init_path(
(isset($conf['changelog'])) ? ($conf['changelog']) : ($conf['savedir'] . '/changes.log')
$conf['changelog'] ?? $conf['savedir'] . '/changes.log'
);
if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
// hardcoded changelog because it is now a cache that lives in meta
@ -317,7 +319,7 @@ function init_paths(){
function init_lang($langCode) {
//prepare language array
global $lang, $config_cascade;
$lang = array();
$lang = [];
//load the language files
require(DOKU_INC.'inc/lang/en/lang.php');
@ -345,7 +347,7 @@ function init_lang($langCode) {
function init_files(){
global $conf;
$files = array($conf['indexdir'].'/page.idx');
$files = [$conf['indexdir'].'/page.idx'];
foreach($files as $file){
if(!file_exists($file)){
@ -478,12 +480,12 @@ function getBaseURL($abs=null){
//split hostheader into host and port
if(isset($_SERVER['HTTP_HOST'])){
$parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
$host = isset($parsed_host['host']) ? $parsed_host['host'] : null;
$port = isset($parsed_host['port']) ? $parsed_host['port'] : null;
$host = $parsed_host['host'] ?? null;
$port = $parsed_host['port'] ?? null;
}elseif(isset($_SERVER['SERVER_NAME'])){
$parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
$host = isset($parsed_host['host']) ? $parsed_host['host'] : null;
$port = isset($parsed_host['port']) ? $parsed_host['port'] : null;
$host = $parsed_host['host'] ?? null;
$port = $parsed_host['port'] ?? null;
}else{
$host = php_uname('n');
$port = '';
@ -540,7 +542,7 @@ function is_ssl() {
* @return bool
*/
function isWindows() {
return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? true : false;
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
/**
@ -593,10 +595,10 @@ function fullpath($path,$exists=false){
$root = '/';
}elseif($iswin){
// match drive letter and UNC paths
if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
if (preg_match('!^([a-zA-z]:)(.*)!',$path,$match)) {
$root = $match[1].'/';
$path = $match[2];
}else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
} elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)) {
$root = $match[1];
$path = $match[2];
}
@ -616,14 +618,14 @@ function fullpath($path,$exists=false){
// canonicalize
$path=explode('/', $path);
$newpath=array();
$newpath=[];
foreach($path as $p) {
if ($p === '' || $p === '.') continue;
if ($p==='..') {
array_pop($newpath);
continue;
}
array_push($newpath, $p);
$newpath[] = $p;
}
$finalpath = $root.implode('/', $newpath);

View File

@ -5,7 +5,7 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\Utf8\PhpString;
use dokuwiki\HTTP\DokuHTTPClient;
use dokuwiki\Extension\Event;
@ -26,8 +26,8 @@ use dokuwiki\Extension\Event;
*/
function io_sweepNS($id,$basedir='datadir'){
global $conf;
$types = array ('datadir'=>'pages', 'mediadir'=>'media');
$ns_type = (isset($types[$basedir])?$types[$basedir]:false);
$types = ['datadir'=>'pages', 'mediadir'=>'media'];
$ns_type = ($types[$basedir] ?? false);
$delone = false;
@ -38,7 +38,7 @@ function io_sweepNS($id,$basedir='datadir'){
//try to delete dir else return
if(@rmdir($dir)) {
if ($ns_type!==false) {
$data = array($id, $ns_type);
$data = [$id, $ns_type];
$delone = true; // we deleted at least one dir
Event::createAndTrigger('IO_NAMESPACE_DELETED', $data);
}
@ -69,7 +69,7 @@ function io_sweepNS($id,$basedir='datadir'){
*/
function io_readWikiPage($file, $id, $rev=false) {
if (empty($rev)) { $rev = false; }
$data = array(array($file, true), getNS($id), noNS($id), $rev);
$data = [[$file, true], getNS($id), noNS($id), $rev];
return Event::createAndTrigger('IO_WIKIPAGE_READ', $data, '_io_readWikiPage_action', false);
}
@ -83,7 +83,7 @@ function io_readWikiPage($file, $id, $rev=false) {
*/
function _io_readWikiPage_action($data) {
if (is_array($data) && is_array($data[0]) && count($data[0])===2) {
return call_user_func_array('io_readFile', $data[0]);
return io_readFile(...$data[0]);
} else {
return ''; //callback error
}
@ -106,14 +106,14 @@ function _io_readWikiPage_action($data) {
function io_readFile($file,$clean=true){
$ret = '';
if(file_exists($file)){
if(substr($file,-3) == '.gz'){
if (substr($file,-3) == '.gz') {
if(!DOKU_HAS_GZIP) return false;
$ret = gzfile($file);
if(is_array($ret)) $ret = join('', $ret);
}else if(substr($file,-4) == '.bz2'){
if(is_array($ret)) $ret = implode('', $ret);
} elseif (substr($file,-4) == '.bz2') {
if(!DOKU_HAS_BZIP) return false;
$ret = bzfile($file);
}else{
} else{
$ret = file_get_contents($file);
}
}
@ -138,7 +138,7 @@ function bzfile($file, $array=false) {
$bz = bzopen($file,"r");
if($bz === false) return false;
if($array) $lines = array();
if($array) $lines = [];
$str = '';
while (!feof($bz)) {
//8192 seems to be the maximum buffersize?
@ -146,7 +146,7 @@ function bzfile($file, $array=false) {
if(($buffer === false) || (bzerrno($bz) !== 0)) {
return false;
}
$str = $str . $buffer;
$str .= $buffer;
if($array) {
$pos = strpos($str, "\n");
while($pos !== false) {
@ -189,7 +189,7 @@ 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
$data = array(array($file, $content, false), getNS($id), noNS($id), $rev);
$data = [[$file, $content, false], getNS($id), noNS($id), $rev];
return Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data, '_io_writeWikiPage_action', false);
}
@ -202,7 +202,7 @@ function io_writeWikiPage($file, $content, $id, $rev=false) {
*/
function _io_writeWikiPage_action($data) {
if (is_array($data) && is_array($data[0]) && count($data[0])===3) {
$ok = call_user_func_array('io_saveFile', $data[0]);
$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) {
@touch($data[0][0], $data[3]);
@ -228,13 +228,13 @@ function _io_saveFile($file, $content, $append) {
$mode = ($append) ? 'ab' : 'wb';
$fileexists = file_exists($file);
if(substr($file,-3) == '.gz'){
if (substr($file,-3) == '.gz') {
if(!DOKU_HAS_GZIP) return false;
$fh = @gzopen($file,$mode.'9');
if(!$fh) return false;
gzwrite($fh, $content);
gzclose($fh);
}else if(substr($file,-4) == '.bz2'){
} elseif (substr($file,-4) == '.bz2') {
if(!DOKU_HAS_BZIP) return false;
if($append) {
$bzcontent = bzfile($file);
@ -245,14 +245,14 @@ function _io_saveFile($file, $content, $append) {
if(!$fh) return false;
bzwrite($fh, $content);
bzclose($fh);
}else{
} else{
$fh = @fopen($file,$mode);
if(!$fh) return false;
fwrite($fh, $content);
fclose($fh);
}
if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
if(!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
return true;
}
@ -321,13 +321,13 @@ function io_replaceInFile($file, $oldline, $newline, $regex=false, $maxlines=0)
io_lock($file);
// load into array
if(substr($file,-3) == '.gz'){
if (substr($file,-3) == '.gz') {
if(!DOKU_HAS_GZIP) return false;
$lines = gzfile($file);
}else if(substr($file,-4) == '.bz2'){
} elseif (substr($file,-4) == '.bz2') {
if(!DOKU_HAS_BZIP) return false;
$lines = bzfile($file, true);
}else{
} else{
$lines = file($file);
}
@ -345,9 +345,8 @@ function io_replaceInFile($file, $oldline, $newline, $regex=false, $maxlines=0)
$lines[$i] = preg_replace($pattern, $replace, $line, -1, $matched);
if ($matched) $count++;
}
} else if ($maxlines == 0) {
} elseif ($maxlines == 0) {
$lines = preg_grep($pattern, $lines, PREG_GREP_INVERT);
if ((string)$newline !== ''){
$lines[] = $newline;
}
@ -356,7 +355,7 @@ function io_replaceInFile($file, $oldline, $newline, $regex=false, $maxlines=0)
}
if(count($lines)){
if(!_io_saveFile($file, join('',$lines), false)) {
if(!_io_saveFile($file, implode('',$lines), false)) {
msg("Removing content from $file failed",-1);
io_unlock($file);
return false;
@ -447,13 +446,13 @@ function io_unlock($file){
*/
function io_createNamespace($id, $ns_type='pages') {
// verify ns_type
$types = array('pages'=>'wikiFN', 'media'=>'mediaFN');
$types = ['pages'=>'wikiFN', 'media'=>'mediaFN'];
if (!isset($types[$ns_type])) {
trigger_error('Bad $ns_type parameter for io_createNamespace().');
return;
}
// make event list
$missing = array();
$missing = [];
$ns_stack = explode(':', $id);
$ns = $id;
$tmp = dirname( $file = call_user_func($types[$ns_type], $ns) );
@ -469,7 +468,7 @@ function io_createNamespace($id, $ns_type='pages') {
// send the events
$missing = array_reverse($missing); // inside out
foreach ($missing as $ns) {
$data = array($ns, $ns_type);
$data = [$ns, $ns_type];
Event::createAndTrigger('IO_NAMESPACE_CREATED', $data);
}
}
@ -523,18 +522,17 @@ 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_dir($path) && !is_link($path)) {
$dirs = array();
$files = array();
if (is_dir($path) && !is_link($path)) {
$dirs = [];
$files = [];
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")) {
if (is_dir("$path/$f") && !is_link("$path/$f")) {
$dirs[] = "$path/$f";
} else if($removefiles) {
} elseif ($removefiles) {
$files[] = "$path/$f";
} else {
return false; // abort when non empty
@ -542,20 +540,17 @@ function io_rmdir($path, $removefiles = false) {
}
closedir($dh);
// now traverse into directories first
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
}
// remove self
return @rmdir($path);
} else if($removefiles) {
} elseif ($removefiles) {
return @unlink($path);
}
return false;
@ -573,7 +568,7 @@ function io_mktmpdir() {
global $conf;
$base = $conf['tmpdir'];
$dir = md5(uniqid(mt_rand(), true));
$dir = md5(uniqid(random_int(0, mt_getrandmax()), true));
$tmpdir = $base.'/'.$dir;
if(io_mkdir_p($tmpdir)) {
@ -605,7 +600,7 @@ function io_mktmpdir() {
* @param int $maxSize maximum file size
* @return bool|string if failed false, otherwise true or the name of the file in the given dir
*/
function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2097152){
function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=2_097_152){
global $conf;
$http = new DokuHTTPClient();
$http->max_bodysize = $maxSize;
@ -619,11 +614,11 @@ function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=20
if ($useAttachment) {
if (isset($http->resp_headers['content-disposition'])) {
$content_disposition = $http->resp_headers['content-disposition'];
$match=array();
$match=[];
if (is_string($content_disposition) &&
preg_match('/attachment;\s*filename\s*=\s*"([^"]*)"/i', $content_disposition, $match)) {
$name = \dokuwiki\Utf8\PhpString::basename($match[1]);
$name = PhpString::basename($match[1]);
}
}
@ -633,7 +628,7 @@ function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=20
$name = $defaultName;
}
$file = $file.$name;
$file .= $name;
}
$fileexists = file_exists($file);
@ -641,7 +636,7 @@ function io_download($url,$file,$useAttachment=false,$defaultName='',$maxSize=20
if(!$fp) return false;
fwrite($fp,$data);
fclose($fp);
if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
if(!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
if ($useAttachment) return $name;
return true;
}
@ -681,10 +676,11 @@ function io_rename($from,$to){
* @return int exit code from process
*/
function io_exec($cmd, $input, &$output){
$descspec = array(
0=>array("pipe","r"),
1=>array("pipe","w"),
2=>array("pipe","w"));
$descspec = [
0=>["pipe", "r"],
1=>["pipe", "w"],
2=>["pipe", "w"]
];
$ph = proc_open($cmd, $descspec, $pipes);
if(!$ph) return -1;
fclose($pipes[2]); // ignore stderr
@ -712,7 +708,7 @@ function io_exec($cmd, $input, &$output){
function io_grep($file,$pattern,$max=0,$backref=false){
$fh = @fopen($file,'r');
if(!$fh) return false;
$matches = array();
$matches = [];
$cnt = 0;
$line = '';
@ -749,21 +745,18 @@ function io_grep($file,$pattern,$max=0,$backref=false){
function io_getSizeFile($file) {
if (!file_exists($file)) return 0;
if(substr($file,-3) == '.gz'){
if (substr($file,-3) == '.gz') {
$fp = @fopen($file, "rb");
if($fp === false) return 0;
fseek($fp, -4, SEEK_END);
$buffer = fread($fp, 4);
fclose($fp);
$array = unpack("V", $buffer);
$uncompressedsize = end($array);
}else if(substr($file,-4) == '.bz2'){
} elseif (substr($file,-4) == '.bz2') {
if(!DOKU_HAS_BZIP) return 0;
$bz = bzopen($file,"r");
if($bz === false) return 0;
$uncompressedsize = 0;
while (!feof($bz)) {
//8192 seems to be the maximum buffersize?
@ -773,7 +766,7 @@ function io_getSizeFile($file) {
}
$uncompressedsize += strlen($buffer);
}
}else{
} else{
$uncompressedsize = filesize($file);
}

View File

@ -4,7 +4,7 @@
*
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\ErrorHandler;
use dokuwiki\Extension\PluginController;
// setup class autoloader
@ -53,7 +53,7 @@ require_once(DOKU_INC.'inc/legacy.php');
*/
function load_autoload($name){
static $classes = null;
if($classes === null) $classes = array(
if($classes === null) $classes = [
'Diff' => DOKU_INC.'inc/DifferenceEngine.php',
'UnifiedDiffFormatter' => DOKU_INC.'inc/DifferenceEngine.php',
'TableDiffFormatter' => DOKU_INC.'inc/DifferenceEngine.php',
@ -67,14 +67,13 @@ function load_autoload($name){
'FeedParser' => DOKU_INC.'inc/FeedParser.php',
'SafeFN' => DOKU_INC.'inc/SafeFN.class.php',
'Mailer' => DOKU_INC.'inc/Mailer.class.php',
'Doku_Handler' => DOKU_INC.'inc/parser/handler.php',
'Doku_Renderer' => DOKU_INC.'inc/parser/renderer.php',
'Doku_Renderer_xhtml' => DOKU_INC.'inc/parser/xhtml.php',
'Doku_Renderer_code' => DOKU_INC.'inc/parser/code.php',
'Doku_Renderer_xhtmlsummary' => DOKU_INC.'inc/parser/xhtmlsummary.php',
'Doku_Renderer_metadata' => DOKU_INC.'inc/parser/metadata.php',
);
'Doku_Renderer_metadata' => DOKU_INC.'inc/parser/metadata.php'
];
if(isset($classes[$name])){
require ($classes[$name]);
@ -110,7 +109,7 @@ function load_autoload($name){
try {
require $file;
} catch (\Throwable $e) {
\dokuwiki\ErrorHandler::showExceptionMsg($e, "Error loading plugin $name");
ErrorHandler::showExceptionMsg($e, "Error loading plugin $name");
}
return true;
}
@ -124,7 +123,7 @@ function load_autoload($name){
try {
require $file;
} catch (\Throwable $e) {
\dokuwiki\ErrorHandler::showExceptionMsg($e, "Error loading template $name");
ErrorHandler::showExceptionMsg($e, "Error loading template $name");
}
return true;
}
@ -154,7 +153,7 @@ function load_autoload($name){
try {
require $plg;
} catch (\Throwable $e) {
\dokuwiki\ErrorHandler::showExceptionMsg($e, "Error loading plugin {$m[2]}");
ErrorHandler::showExceptionMsg($e, "Error loading plugin {$m[2]}");
}
}
return true;

View File

@ -45,7 +45,7 @@ function mail_setup(){
if(!$host) $host = 'example.com';
$noreply = 'noreply@'.$host;
$replace = array();
$replace = [];
if(!empty($USERINFO['mail'])){
$replace['@MAIL@'] = $USERINFO['mail'];
}else{
@ -104,7 +104,7 @@ function mail_quotedprintable_encode($sText,$maxlen=74,$bEmulate_imap_8bit=true)
for ($i=0;$i<$cnt;$i++) {
$sLine =& $aLines[$i];
if (strlen($sLine)===0) continue; // do nothing, if empty
if ($sLine === '') continue; // do nothing, if empty
$sRegExp = '/[^\x09\x20\x21-\x3C\x3E-\x7E]/e';

View File

@ -5,7 +5,10 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\Ui\MediaRevisions;
use dokuwiki\Cache\CacheImageMod;
use splitbrain\slika\Exception;
use dokuwiki\PassHash;
use dokuwiki\ChangeLog\MediaChangeLog;
use dokuwiki\Extension\Event;
use dokuwiki\Form\Form;
@ -127,7 +130,7 @@ function media_isexternal($id){
function media_ispublic($id){
if(media_isexternal($id)) return true;
$id = cleanID($id);
if(auth_aclcheck(getNS($id).':*', '', array()) >= AUTH_READ) return true;
if(auth_aclcheck(getNS($id).':*', '', []) >= AUTH_READ) return true;
return false;
}
@ -171,17 +174,17 @@ function media_metaform($id, $auth) {
foreach ($fields as $key => $field) {
// get current value
if (empty($field[0])) continue;
$tags = array($field[0]);
$tags = [$field[0]];
if (is_array($field[3])) $tags = array_merge($tags, $field[3]);
$value = tpl_img_getTag($tags, '', $src);
$value = cleanText($value);
// prepare attributes
$p = array(
$p = [
'class' => 'edit',
'id' => 'meta__'.$key,
'name' => 'meta['.$field[0].']',
);
'name' => 'meta['.$field[0].']'
];
$form->addTagOpen('div')->addClass('row');
if ($field[2] == 'text') {
@ -220,7 +223,7 @@ function media_inuse($id) {
if($conf['refcheck']){
$mediareferences = ft_mediause($id,true);
if(!count($mediareferences)) {
if($mediareferences === []) {
return false;
} else {
return $mediareferences;
@ -254,7 +257,7 @@ function media_delete($id,$auth){
$file = mediaFN($id);
// trigger an event - MEDIA_DELETE_FILE
$data = array();
$data = [];
$data['id'] = $id;
$data['name'] = PhpString::basename($file);
$data['path'] = $file;
@ -300,7 +303,7 @@ function media_upload_xhr($ns,$auth){
global $INPUT;
$id = $INPUT->get->str('qqfile');
list($ext,$mime) = mimetype($id);
[$ext, $mime] = mimetype($id);
$input = fopen("php://input", "r");
if (!($tmp = io_mktmpdir())) return false;
$path = $tmp.'/'.md5($id);
@ -314,9 +317,7 @@ function media_upload_xhr($ns,$auth){
}
$res = media_save(
array('name' => $path,
'mime' => $mime,
'ext' => $ext),
['name' => $path, 'mime' => $mime, 'ext' => $ext],
$ns.':'.$id,
($INPUT->get->str('ow') == 'true'),
$auth,
@ -356,8 +357,8 @@ function media_upload($ns,$auth,$file=false){
if($file['error']) return false;
// check extensions
list($fext,$fmime) = mimetype($file['name']);
list($iext,$imime) = mimetype($id);
[$fext, $fmime] = mimetype($file['name']);
[$iext, $imime] = mimetype($id);
if($fext && !$iext){
// no extension specified in id - read original one
$id .= '.'.$fext;
@ -367,10 +368,17 @@ function media_upload($ns,$auth,$file=false){
msg(sprintf($lang['mediaextchange'],$fext,$iext));
}
$res = media_save(array('name' => $file['tmp_name'],
'mime' => $imime,
'ext' => $iext), $ns.':'.$id,
$INPUT->post->bool('ow'), $auth, 'copy_uploaded_file');
$res = media_save(
[
'name' => $file['tmp_name'],
'mime' => $imime,
'ext' => $iext
],
$ns . ':' . $id,
$INPUT->post->bool('ow'),
$auth,
'copy_uploaded_file'
);
if (is_array($res)) {
msg($res[0], $res[1]);
return false;
@ -420,11 +428,11 @@ function copy_uploaded_file($from, $to){
*/
function media_save($file, $id, $ow, $auth, $move) {
if($auth < AUTH_UPLOAD) {
return array("You don't have permissions to upload files.", -1);
return ["You don't have permissions to upload files.", -1];
}
if (!isset($file['mime']) || !isset($file['ext'])) {
list($ext, $mime) = mimetype($id);
[$ext, $mime] = mimetype($id);
if (!isset($file['mime'])) {
$file['mime'] = $mime;
}
@ -442,36 +450,34 @@ function media_save($file, $id, $ow, $auth, $move) {
// get filetype regexp
$types = array_keys(getMimeTypes());
$types = array_map(
function ($q) {
return preg_quote($q, "/");
},
static fn($q) => preg_quote($q, "/"),
$types
);
$regex = join('|',$types);
$regex = implode('|',$types);
// because a temp file was created already
if(!preg_match('/\.('.$regex.')$/i',$fn)) {
return array($lang['uploadwrong'],-1);
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)) {
return array($lang['uploadexist'], 0);
return [$lang['uploadexist'], 0];
}
// check for valid content
$ok = media_contentcheck($file['name'], $file['mime']);
if($ok == -1){
return array(sprintf($lang['uploadbadcontent'],'.' . $file['ext']),-1);
return [sprintf($lang['uploadbadcontent'],'.' . $file['ext']), -1];
}elseif($ok == -2){
return array($lang['uploadspam'],-1);
return [$lang['uploadspam'], -1];
}elseif($ok == -3){
return array($lang['uploadxss'],-1);
return [$lang['uploadxss'], -1];
}
// prepare event data
$data = array();
$data = [];
$data[0] = $file['name'];
$data[1] = $fn;
$data[2] = $id;
@ -560,7 +566,7 @@ function media_upload_finish($fn_tmp, $fn, $id, $imime, $overwrite, $move = 'mov
}
return $id;
}else{
return array($lang['uploadfail'],-1);
return [$lang['uploadfail'], -1];
}
}
@ -592,7 +598,7 @@ function media_saveOldRevision($id) {
$oldRev = $medialog->getRevisions(-1, 1); // from changelog
$oldRev = (int) (empty($oldRev) ? 0 : $oldRev[0]);
$filesize_old = filesize(mediaFN($id, $oldRev));
$sizechange = $sizechange - $filesize_old;
$sizechange -= $filesize_old;
addMediaLogEntry($date, $id, DOKU_CHANGE_TYPE_EDIT, '', '', null, $sizechange);
}
@ -703,9 +709,9 @@ function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false,$sort=fals
}
$dir = utf8_encodeFN(str_replace(':','/',$ns));
$data = array();
$data = [];
search($data,$conf['mediadir'],'search_mediafiles',
array('showmsg'=>true,'depth'=>1),$dir,1,$sort);
['showmsg'=>true, 'depth'=>1],$dir,1,$sort);
if(!count($data)){
echo '<div class="nothing">'.$lang['nothingfound'].'</div>'.NL;
@ -744,12 +750,16 @@ function media_filelist($ns,$auth=null,$jump='',$fullscreenview=false,$sort=fals
function media_tabs_files($selected_tab = ''){
global $lang;
$tabs = array();
foreach(array('files' => 'mediaselect',
'upload' => 'media_uploadtab',
'search' => 'media_searchtab') as $tab => $caption) {
$tabs[$tab] = array('href' => media_managerURL(['tab_files' => $tab], '&'),
'caption' => $lang[$caption]);
$tabs = [];
foreach([
'files' => 'mediaselect',
'upload' => 'media_uploadtab',
'search' => 'media_searchtab'
] as $tab => $caption) {
$tabs[$tab] = [
'href' => media_managerURL(['tab_files' => $tab], '&'),
'caption' => $lang[$caption]
];
}
html_tabs($tabs, $selected_tab);
@ -765,18 +775,24 @@ function media_tabs_files($selected_tab = ''){
function media_tabs_details($image, $selected_tab = '') {
global $lang, $conf;
$tabs = array();
$tabs['view'] = array('href' => media_managerURL(['tab_details' => 'view'], '&'),
'caption' => $lang['media_viewtab']);
$tabs = [];
$tabs['view'] = [
'href' => media_managerURL(['tab_details' => 'view'], '&'),
'caption' => $lang['media_viewtab']
];
list(, $mime) = mimetype($image);
[, $mime] = mimetype($image);
if ($mime == 'image/jpeg' && file_exists(mediaFN($image))) {
$tabs['edit'] = array('href' => media_managerURL(['tab_details' => 'edit'], '&'),
'caption' => $lang['media_edittab']);
$tabs['edit'] = [
'href' => media_managerURL(['tab_details' => 'edit'], '&'),
'caption' => $lang['media_edittab']
];
}
if ($conf['mediarevisions']) {
$tabs['history'] = array('href' => media_managerURL(['tab_details' => 'history'], '&'),
'caption' => $lang['media_historytab']);
$tabs['history'] = [
'href' => media_managerURL(['tab_details' => 'history'], '&'),
'caption' => $lang['media_historytab']
];
}
html_tabs($tabs, $selected_tab);
@ -807,15 +823,16 @@ function media_tab_files_options() {
$form->setHiddenField('q', $INPUT->str('q'));
}
$form->addHTML('<ul>'.NL);
foreach (array('list' => array('listType', array('thumbs', 'rows')),
'sort' => array('sortBy', array('name', 'date')))
as $group => $content) {
foreach ([
'list' => ['listType', ['thumbs', 'rows']],
'sort' => ['sortBy', ['name', 'date']]
] as $group => $content) {
$checked = "_media_get_{$group}_type";
$checked = $checked();
$form->addHTML('<li class="'. $content[0] .'">');
foreach ($content[1] as $option) {
$attrs = array();
$attrs = [];
if ($checked == $option) {
$attrs['checked'] = 'checked';
}
@ -843,7 +860,7 @@ function media_tab_files_options() {
* @return string - sort type
*/
function _media_get_sort_type() {
return _media_get_display_param('sort', array('default' => 'name', 'date'));
return _media_get_display_param('sort', ['default' => 'name', 'date']);
}
/**
@ -854,7 +871,7 @@ function _media_get_sort_type() {
* @return string - list type
*/
function _media_get_list_type() {
return _media_get_display_param('list', array('default' => 'thumbs', 'rows'));
return _media_get_display_param('list', ['default' => 'thumbs', 'rows']);
}
/**
@ -979,7 +996,7 @@ function media_tab_edit($image, $ns, $auth=null) {
if(is_null($auth)) $auth = auth_quickaclcheck("$ns:*");
if ($image) {
list(, $mime) = mimetype($image);
[, $mime] = mimetype($image);
if ($mime == 'image/jpeg') media_metaform($image,$auth);
}
}
@ -1002,10 +1019,10 @@ function media_tab_history($image, $ns, $auth=null) {
if ($auth >= AUTH_READ && $image) {
if ($do == 'diff'){
(new dokuwiki\Ui\MediaDiff($image))->show(); //media_diff($image, $ns, $auth);
(new MediaDiff($image))->show(); //media_diff($image, $ns, $auth);
} else {
$first = $INPUT->int('first',-1);
(new dokuwiki\Ui\MediaRevisions($image))->show($first);
(new MediaRevisions($image))->show($first);
}
} else {
echo '<div class="nothing">'.$lang['media_perm_read'].'</div>'.NL;
@ -1030,7 +1047,7 @@ function media_preview($image, $auth, $rev = '', $meta = false) {
global $lang;
echo '<div class="image">';
$more = array();
$more = [];
if ($rev) {
$more['rev'] = $rev;
} else {
@ -1128,18 +1145,18 @@ function media_preview_buttons($image, $auth, $rev = '') {
function media_image_preview_size($image, $rev, $meta = false, $size = 500) {
if (!preg_match("/\.(jpe?g|gif|png)$/", $image)
|| !file_exists($filename = mediaFN($image, $rev))
) return array();
) return [];
$info = getimagesize($filename);
$w = (int) $info[0];
$h = (int) $info[1];
$w = $info[0];
$h = $info[1];
if ($meta && ($w > $size || $h > $size)) {
$ratio = $meta->getResizeRatio($size, $size);
$w = floor($w * $ratio);
$h = floor($h * $ratio);
}
return array($w, $h);
return [$w, $h];
}
/**
@ -1177,14 +1194,14 @@ function media_file_tags($meta) {
}
}
$tags = array();
$tags = [];
foreach ($fields as $key => $tag) {
$t = array();
if (!empty($tag[0])) $t = array($tag[0]);
foreach ($fields as $tag) {
$t = [];
if (!empty($tag[0])) $t = [$tag[0]];
if (isset($tag[3]) && is_array($tag[3])) $t = array_merge($t,$tag[3]);
$value = media_getTag($t, $meta);
$tags[] = array('tag' => $tag, 'value' => $value);
$tags[] = ['tag' => $tag, 'value' => $value];
}
return $tags;
@ -1220,7 +1237,7 @@ function media_details($image, $auth, $rev='', $meta=false) {
echo '<dl>'.NL;
echo '<dt>'.$lang['reference'].':</dt>';
$media_usage = ft_mediause($image,true);
if(count($media_usage) > 0){
if($media_usage !== []){
foreach($media_usage as $path){
echo '<dd>'.html_wikilink($path).'</dd>';
}
@ -1309,7 +1326,7 @@ function media_restore($image, $rev, $auth){
$removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')));
if (!$image || (!file_exists(mediaFN($image)) && !$removed)) return false;
if (!$rev || !file_exists(mediaFN($image, $rev))) return false;
list(,$imime,) = mimetype($image);
[, $imime, ] = mimetype($image);
$res = media_upload_finish(mediaFN($image, $rev),
mediaFN($image),
$image,
@ -1342,18 +1359,18 @@ function media_searchlist($query,$ns,$auth=null,$fullscreen=false,$sort='natural
global $lang;
$ns = cleanID($ns);
$evdata = array(
$evdata = [
'ns' => $ns,
'data' => array(),
'data' => [],
'query' => $query
);
];
if (!blank($query)) {
$evt = new Event('MEDIA_SEARCH', $evdata);
if ($evt->advise_before()) {
$dir = utf8_encodeFN(str_replace(':','/',$evdata['ns']));
$quoted = preg_quote($evdata['query'],'/');
//apply globbing
$quoted = str_replace(array('\*', '\?'), array('.*', '.'), $quoted, $count);
$quoted = str_replace(['\*', '\?'], ['.*', '.'], $quoted, $count);
//if we use globbing file name must match entirely but may be preceded by arbitrary namespace
if ($count > 0) $quoted = '^([^:]*:)*'.$quoted.'$';
@ -1362,7 +1379,7 @@ function media_searchlist($query,$ns,$auth=null,$fullscreen=false,$sort='natural
search($evdata['data'],
$conf['mediadir'],
'search_mediafiles',
array('showmsg'=>false,'pattern'=>$pattern),
['showmsg'=>false, 'pattern'=>$pattern],
$dir,
1,
$sort);
@ -1409,7 +1426,7 @@ function media_searchlist($query,$ns,$auth=null,$fullscreen=false,$sort='natural
* @return string html
*/
function media_printicon($filename, $size=''){
list($ext) = mimetype(mediaFN($filename),false);
[$ext] = mimetype(mediaFN($filename),false);
if (file_exists(DOKU_INC.'lib/images/fileicons/'.$size.'/'.$ext.'.png')) {
$icon = DOKU_BASE.'lib/images/fileicons/'.$size.'/'.$ext.'.png';
@ -1435,8 +1452,8 @@ function media_managerURL($params = false, $amp = '&amp;', $abs = false, $params
global $ID;
global $INPUT;
$gets = array('do' => 'media');
$media_manager_params = array('tab_files', 'tab_details', 'image', 'ns', 'list', 'sort');
$gets = ['do' => 'media'];
$media_manager_params = ['tab_files', 'tab_details', 'image', 'ns', 'list', 'sort'];
foreach ($media_manager_params as $x) {
if ($INPUT->has($x)) $gets[$x] = $INPUT->str($x);
}
@ -1504,7 +1521,7 @@ function media_uploadform($ns, $auth, $fullscreen = false) {
$form->addTagClose('p');
if ($auth >= $auth_ow){
$form->addTagOpen('p');
$attrs = array();
$attrs = [];
if ($update) $attrs['checked'] = 'checked';
$form->addCheckbox('ow', $lang['txt_overwrt'])->id('dw__ow')->val('1')
->addClass('check')->attrs($attrs);
@ -1540,11 +1557,11 @@ function media_uploadform($ns, $auth, $fullscreen = false) {
function media_getuploadsize(){
$okay = 0;
$post = (int) php_to_byte(@ini_get('post_max_size'));
$suho = (int) php_to_byte(@ini_get('suhosin.post.max_value_length'));
$upld = (int) php_to_byte(@ini_get('upload_max_filesize'));
$post = php_to_byte(@ini_get('post_max_size'));
$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($post && ($post < $okay || $okay === 0)) $okay = $post;
if($suho && ($suho < $okay || $okay == 0)) $okay = $suho;
if($upld && ($upld < $okay || $okay == 0)) $okay = $upld;
@ -1606,12 +1623,11 @@ function media_nstree($ns){
$ns_dir = utf8_encodeFN(str_replace(':','/',$ns));
$data = array();
search($data,$conf['mediadir'],'search_index',array('ns' => $ns_dir, 'nofiles' => true));
$data = [];
search($data,$conf['mediadir'],'search_index',['ns' => $ns_dir, 'nofiles' => true]);
// wrap a list with the root level around the other namespaces
array_unshift($data, array('level' => 0, 'id' => '', 'open' =>'true',
'label' => '['.$lang['mediaroot'].']'));
array_unshift($data, ['level' => 0, 'id' => '', 'open' =>'true', 'label' => '['.$lang['mediaroot'].']']);
// insert the current ns into the hierarchy if it isn't already part of it
$ns_parts = explode(':', $ns);
@ -1627,7 +1643,7 @@ function media_nstree($ns){
$pos >= count($data) ||
($data[$pos]['level'] <= $level+1 && Sort::strcmp($data[$pos]['id'], $tmp_ns) > 0)
) {
array_splice($data, $pos, 0, array(array('level' => $level+1, 'id' => $tmp_ns, 'open' => 'true')));
array_splice($data, $pos, 0, [['level' => $level+1, 'id' => $tmp_ns, 'open' => 'true']]);
break;
}
++$pos;
@ -1654,7 +1670,7 @@ function media_nstree_item($item){
if(empty($item['label'])) $item['label'] = $label;
$ret = '';
if (!($INPUT->str('do') == 'media'))
if ($INPUT->str('do') != 'media')
$ret .= '<a href="'.DOKU_BASE.'lib/exe/mediamanager.php?ns='.idfilter($item['id']).'" class="idx_dir">';
else $ret .= '<a href="'.media_managerURL(['ns' => idfilter($item['id'], false), 'tab_files' => 'files'])
.'" class="idx_dir">';
@ -1715,7 +1731,7 @@ function media_mod_image($file, $ext, $w, $h=0, $crop=false)
'imconvert' => $conf['im_convert'],
];
$cache = new \dokuwiki\Cache\CacheImageMod($file, $w, $h, $ext, $crop);
$cache = new CacheImageMod($file, $w, $h, $ext, $crop);
if(!$cache->useCache()) {
try {
Slika::run($file, $options)
@ -1723,7 +1739,7 @@ function media_mod_image($file, $ext, $w, $h=0, $crop=false)
->$operation($w, $h)
->save($cache->cache, $ext);
if($conf['fperm']) @chmod($cache->cache, $conf['fperm']);
} catch (\splitbrain\slika\Exception $e) {
} catch (Exception $e) {
Logger::debug($e->getMessage());
return $file;
}
@ -1783,7 +1799,7 @@ function media_get_token($id,$w,$h){
if ($w) $token .= '.'.$w;
if ($h) $token .= '.'.$h;
return substr(\dokuwiki\PassHash::hmac('md5', $token, auth_cookiesalt()),0,6);
return substr(PassHash::hmac('md5', $token, auth_cookiesalt()),0,6);
}
return '';
@ -1857,7 +1873,7 @@ function media_image_download($url,$file){
if(!$fp) return false;
fwrite($fp,$data);
fclose($fp);
if(!$fileexists and $conf['fperm']) chmod($file, $conf['fperm']);
if(!$fileexists && $conf['fperm']) chmod($file, $conf['fperm']);
// check if it is really an image
$info = @getimagesize($file);
@ -2073,15 +2089,15 @@ function media_resize_imageGD($ext,$from,$from_w,$from_h,$to,$to_w,$to_h,$ofs_x=
*/
function media_alternativefiles($src, $exts){
$files = array();
list($srcExt, /* $srcMime */) = mimetype($src);
$files = [];
[$srcExt, ] = mimetype($src);
$filebase = substr($src, 0, -1 * (strlen($srcExt)+1));
foreach($exts as $ext) {
$fileid = $filebase.'.'.$ext;
$file = mediaFN($fileid);
if(file_exists($file)) {
list(/* $fileExt */, $fileMime) = mimetype($file);
[, $fileMime] = mimetype($file);
$files[$fileMime] = $fileid;
}
}
@ -2098,16 +2114,16 @@ function media_alternativefiles($src, $exts){
* @author Anika Henke <anika@selfthinker.org>
*/
function media_supportedav($mime, $type=NULL){
$supportedAudio = array(
$supportedAudio = [
'ogg' => 'audio/ogg',
'mp3' => 'audio/mpeg',
'wav' => 'audio/wav',
);
$supportedVideo = array(
'wav' => 'audio/wav'
];
$supportedVideo = [
'webm' => 'video/webm',
'ogv' => 'video/ogg',
'mp4' => 'video/mp4',
);
'mp4' => 'video/mp4'
];
if ($type == 'audio') {
$supportedAv = $supportedAudio;
} elseif ($type == 'video') {
@ -2129,25 +2145,22 @@ function media_supportedav($mime, $type=NULL){
* @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
*/
function media_trackfiles($src){
$kinds=array(
$kinds=[
'sub' => 'subtitles',
'cap' => 'captions',
'des' => 'descriptions',
'cha' => 'chapters',
'met' => 'metadata'
);
];
$files = array();
$files = [];
$re='/\\.(sub|cap|des|cha|met)\\.([^.]+)\\.vtt$/';
$baseid=pathinfo($src, PATHINFO_FILENAME);
$pattern=mediaFN($baseid).'.*.*.vtt';
$list=glob($pattern);
foreach($list as $track) {
if(preg_match($re, $track, $matches)){
$files[$baseid.'.'.$matches[1].'.'.$matches[2].'.vtt']=array(
$kinds[$matches[1]],
$matches[2],
);
$files[$baseid.'.'.$matches[1].'.'.$matches[2].'.vtt']=[$kinds[$matches[1]], $matches[2]];
}
}
return $files;

View File

@ -7,7 +7,10 @@
* @author Andreas Gohr <andi@splitbrain.org>
* @todo Combine similar functions like {wiki,media,meta}FN()
*/
use dokuwiki\Utf8\PhpString;
use dokuwiki\Utf8\Clean;
use dokuwiki\File\Resolver;
use dokuwiki\Extension\Event;
use dokuwiki\ChangeLog\MediaChangeLog;
use dokuwiki\ChangeLog\PageChangeLog;
use dokuwiki\File\MediaResolver;
@ -49,7 +52,7 @@ function getID($param = 'id', $clean = true)
$relpath = 'lib/exe/';
}
$script = $conf['basedir'] . $relpath .
\dokuwiki\Utf8\PhpString::basename($INPUT->server->str('SCRIPT_FILENAME'));
PhpString::basename($INPUT->server->str('SCRIPT_FILENAME'));
} elseif ($INPUT->server->str('PATH_INFO')) {
$request = $INPUT->server->str('PATH_INFO');
} elseif ($INPUT->server->str('SCRIPT_NAME')) {
@ -80,16 +83,16 @@ function getID($param = 'id', $clean = true)
if (substr($id, -1) == ':' || ($conf['useslash'] && substr($id, -1) == '/')) {
if (page_exists($id . $conf['start'])) {
// start page inside namespace
$id = $id . $conf['start'];
$id .= $conf['start'];
} elseif (page_exists($id . noNS(cleanID($id)))) {
// page named like the NS inside the NS
$id = $id . noNS(cleanID($id));
$id .= noNS(cleanID($id));
} elseif (page_exists($id)) {
// page like namespace exists
$id = substr($id, 0, -1);
} else {
// fall back to default
$id = $id . $conf['start'];
$id .= $conf['start'];
}
if (isset($ACT) && $ACT === 'show') {
$urlParameters = $_GET;
@ -135,7 +138,7 @@ function cleanID($raw_id, $ascii = false)
$sepcharpat = '#\\' . $sepchar . '+#';
$id = trim((string)$raw_id);
$id = \dokuwiki\Utf8\PhpString::strtolower($id);
$id = PhpString::strtolower($id);
//alternative namespace seperator
if ($conf['useslash']) {
@ -144,13 +147,13 @@ function cleanID($raw_id, $ascii = false)
$id = strtr($id, ';/', ':' . $sepchar);
}
if ($conf['deaccent'] == 2 || $ascii) $id = \dokuwiki\Utf8\Clean::romanize($id);
if ($conf['deaccent'] || $ascii) $id = \dokuwiki\Utf8\Clean::deaccent($id, -1);
if ($conf['deaccent'] == 2 || $ascii) $id = Clean::romanize($id);
if ($conf['deaccent'] || $ascii) $id = Clean::deaccent($id, -1);
//remove specials
$id = \dokuwiki\Utf8\Clean::stripspecials($id, $sepchar, '\*');
$id = Clean::stripspecials($id, $sepchar, '\*');
if ($ascii) $id = \dokuwiki\Utf8\Clean::strip($id);
if ($ascii) $id = Clean::strip($id);
//clean up
$id = preg_replace($sepcharpat, $sepchar, $id);
@ -244,7 +247,7 @@ function noNSorNS($id)
*/
function sectionID($title, &$check)
{
$title = str_replace(array(':','.'), '', cleanID($title));
$title = str_replace([':', '.'], '', cleanID($title));
$new = ltrim($title, '0123456789_-');
if (empty($new)) {
$title = 'section' . preg_replace('/[^0-9]+/', '', $title); //keep numbers from headline
@ -359,7 +362,7 @@ function wikiFN($raw_id, $rev = '', $clean = true)
}
if (!isset($cache[$id])) {
$cache[$id] = array();
$cache[$id] = [];
}
$cache[$id][$rev] = $fn;
return $fn;
@ -394,6 +397,7 @@ function metaFN($id, $ext)
global $conf;
$id = cleanID($id);
$id = str_replace(':', '/', $id);
$fn = $conf['metadir'] . '/' . utf8_encodeFN($id) . $ext;
return $fn;
}
@ -412,6 +416,7 @@ function mediaMetaFN($id, $ext)
global $conf;
$id = cleanID($id);
$id = str_replace(':', '/', $id);
$fn = $conf['mediametadir'] . '/' . utf8_encodeFN($id) . $ext;
return $fn;
}
@ -430,7 +435,7 @@ function metaFiles($id)
$basename = metaFN($id, '');
$files = glob($basename . '.*', GLOB_MARK);
// filter files like foo.bar.meta when $id == 'foo'
return $files ? preg_grep('/^' . preg_quote($basename, '/') . '\.[^.\/]*$/u', $files) : array();
return $files ? preg_grep('/^' . preg_quote($basename, '/') . '\.[^.\/]*$/u', $files) : [];
}
/**
@ -504,7 +509,7 @@ function localeFN($id, $ext = 'txt')
function resolve_id($ns, $id, $clean = true)
{
global $conf;
dbg_deprecated(\dokuwiki\File\Resolver::class . ' and its children');
dbg_deprecated(Resolver::class . ' and its children');
// some pre cleaning for useslash:
if ($conf['useslash']) $id = str_replace('/', ':', $id);
@ -518,10 +523,10 @@ function resolve_id($ns, $id, $clean = true)
$id = $ns . ':' . $id;
// cleanup relatives
$result = array();
$result = [];
$pathA = explode(':', $id);
if (!$pathA[0]) $result[] = '';
foreach ($pathA as $key => $dir) {
foreach ($pathA as $dir) {
if ($dir == '..') {
if (end($result) == '..') {
$result[] = '..';
@ -617,11 +622,8 @@ function getCacheName($data, $ext = '')
*/
function isHiddenPage($id)
{
$data = array(
'id' => $id,
'hidden' => false
);
\dokuwiki\Extension\Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
$data = ['id' => $id, 'hidden' => false];
Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
return $data['hidden'];
}

View File

@ -6,7 +6,7 @@
* @author Harry Fuecks <hfuecks@gmail.com>
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\Extension\PluginInterface;
use dokuwiki\Cache\CacheInstructions;
use dokuwiki\Cache\CacheRenderer;
use dokuwiki\ChangeLog\PageChangeLog;
@ -91,17 +91,15 @@ function p_wiki_xhtml($id, $rev = '', $excuse = true, $date_at = '')
} elseif ($excuse) {
$ret = p_locale_xhtml('norev');
}
} else {
if (file_exists($file)) {
$ret = p_cached_output($file, 'xhtml', $id);
} elseif ($excuse) {
//check if the page once existed
$changelog = new PageChangeLog($id);
if ($changelog->hasRevisions()) {
$ret = p_locale_xhtml('onceexisted');
} else {
$ret = p_locale_xhtml('newpage');
}
} elseif (file_exists($file)) {
$ret = p_cached_output($file, 'xhtml', $id);
} elseif ($excuse) {
//check if the page once existed
$changelog = new PageChangeLog($id);
if ($changelog->hasRevisions()) {
$ret = p_locale_xhtml('onceexisted');
} else {
$ret = p_locale_xhtml('newpage');
}
}
@ -193,7 +191,7 @@ function p_cached_instructions($file, $cacheonly = false, $id = '')
if ($cacheonly || $cache->useCache() || (isset($run[$file]) && !defined('DOKU_UNITTEST'))) {
return $cache->retrieveCache();
} else if (file_exists($file)) {
} elseif (file_exists($file)) {
// no cache - do some work
$ins = p_get_instructions(io_readWikiPage($file, $id));
if ($cache->storeCache($ins)) {
@ -386,14 +384,14 @@ function p_set_metadata($id, $data, $render = false, $persistent = true)
// these keys, must have subkeys - a legitimate value must be an array
if (is_array($value)) {
$meta['current'][$key] = !empty($meta['current'][$key]) ?
array_replace((array)$meta['current'][$key], $value) :
$value;
$meta['current'][$key] = empty($meta['current'][$key]) ?
$value :
array_replace((array)$meta['current'][$key], $value);
if ($persistent) {
$meta['persistent'][$key] = !empty($meta['persistent'][$key]) ?
array_replace((array)$meta['persistent'][$key], $value) :
$value;
$meta['persistent'][$key] = empty($meta['persistent'][$key]) ?
$value :
array_replace((array)$meta['persistent'][$key], $value);
}
}
@ -576,11 +574,11 @@ function p_get_parsermodes()
// add syntax plugins
$pluginlist = plugin_list('syntax');
if (count($pluginlist)) {
if ($pluginlist !== []) {
global $PARSER_MODES;
foreach ($pluginlist as $p) {
/** @var SyntaxPlugin $obj */
if (!$obj = plugin_load('syntax', $p)) continue; //attempt to load plugin into $obj
if (!($obj = plugin_load('syntax', $p)) instanceof PluginInterface) continue; //attempt to load plugin into $obj
$PARSER_MODES[$obj->getType()][] = "plugin_$p"; //register mode type
//add to modes
$modes[] = [
@ -605,11 +603,7 @@ function p_get_parsermodes()
foreach ($std_modes as $m) {
$class = 'dokuwiki\\Parsing\\ParserMode\\' . ucfirst($m);
$obj = new $class();
$modes[] = array(
'sort' => $obj->getSort(),
'mode' => $m,
'obj' => $obj
);
$modes[] = ['sort' => $obj->getSort(), 'mode' => $m, 'obj' => $obj];
}
// add formatting modes
@ -618,11 +612,11 @@ function p_get_parsermodes()
];
foreach ($fmt_modes as $m) {
$obj = new Formatting($m);
$modes[] = array(
$modes[] = [
'sort' => $obj->getSort(),
'mode' => $m,
'obj' => $obj
);
];
}
// add modes which need files
@ -656,8 +650,7 @@ function p_get_parsermodes()
*/
function p_sort_modes($a, $b)
{
if ($a['sort'] == $b['sort']) return 0;
return ($a['sort'] < $b['sort']) ? -1 : 1;
return $a['sort'] <=> $b['sort'];
}
/**
@ -724,7 +717,7 @@ function p_get_renderer($mode)
/** @var PluginController $plugin_controller */
global $conf, $plugin_controller;
$rname = !empty($conf['renderer_' . $mode]) ? $conf['renderer_' . $mode] : $mode;
$rname = empty($conf['renderer_' . $mode]) ? $mode : $conf['renderer_' . $mode];
$rclass = "Doku_Renderer_$rname";
// if requested earlier or a bundled renderer

View File

@ -5,7 +5,8 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\Utf8\PhpString;
use dokuwiki\File\MediaFile;
use dokuwiki\Utf8\Sort;
/**
@ -25,9 +26,9 @@ use dokuwiki\Utf8\Sort;
* @author Andreas Gohr <andi@splitbrain.org>
*/
function search(&$data,$base,$func,$opts,$dir='',$lvl=1,$sort='natural'){
$dirs = array();
$files = array();
$filepaths = array();
$dirs = [];
$files = [];
$filepaths = [];
// safeguard against runaways #1452
if($base == '' || $base == '/') {
@ -58,13 +59,13 @@ function search(&$data,$base,$func,$opts,$dir='',$lvl=1,$sort='natural'){
//give directories to userfunction then recurse
foreach($dirs as $dir){
if (call_user_func_array($func, array(&$data,$base,$dir,'d',$lvl,$opts))){
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){
call_user_func_array($func, array(&$data,$base,$file,'f',$lvl,$opts));
call_user_func_array($func, [&$data, $base, $file, 'f', $lvl, $opts]);
}
}
@ -106,11 +107,11 @@ function search(&$data,$base,$func,$opts,$dir='',$lvl=1,$sort='natural'){
* @return bool
*/
function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){
$opts = array(
'idmatch' => '(^|:)'.preg_quote($opts['query'],'/').'/',
'listfiles' => true,
'pagesonly' => true,
);
$opts = [
'idmatch' => '(^|:)'.preg_quote($opts['query'],'/').'/',
'listfiles' => true,
'pagesonly' => true
];
return search_universal($data,$base,$file,$type,$lvl,$opts);
}
@ -132,15 +133,15 @@ function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){
*/
function search_index(&$data,$base,$file,$type,$lvl,$opts){
global $conf;
$ns = isset($opts['ns']) ? $opts['ns'] : '';
$opts = array(
$ns = $opts['ns'] ?? '';
$opts = [
'pagesonly' => true,
'listdirs' => true,
'listfiles' => empty($opts['nofiles']),
'sneakyacl' => $conf['sneaky_index'],
// Hacky, should rather use recmatch
'depth' => preg_match('#^'.preg_quote($file, '#').'(/|$)#','/'.$ns) ? 0 : -1
);
'depth' => preg_match('#^'.preg_quote($file, '#').'(/|$)#','/'.$ns) ? 0 : -1,
];
return search_universal($data, $base, $file, $type, $lvl, $opts);
}
@ -160,9 +161,7 @@ function search_index(&$data,$base,$file,$type,$lvl,$opts){
* @return bool
*/
function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
$opts = array(
'listdirs' => true,
);
$opts = ['listdirs' => true];
return search_universal($data,$base,$file,$type,$lvl,$opts);
}
@ -195,7 +194,7 @@ function search_media(&$data,$base,$file,$type,$lvl,$opts){
return true;
}
$info = array();
$info = [];
$info['id'] = pathID($file,true);
if($info['id'] != cleanID($info['id'])){
if(!empty($opts['showmsg']))
@ -214,7 +213,7 @@ function search_media(&$data,$base,$file,$type,$lvl,$opts){
return false;
}
$info['file'] = \dokuwiki\Utf8\PhpString::basename($file);
$info['file'] = PhpString::basename($file);
$info['size'] = filesize($base.'/'.$file);
$info['mtime'] = filemtime($base.'/'.$file);
$info['writable'] = is_writable($base.'/'.$file);
@ -280,7 +279,7 @@ function search_mediafiles(&$data,$base,$file,$type,$lvl,$opts){
return false;
}
$data[] = new \dokuwiki\File\MediaFile($id);
$data[] = new MediaFile($id);
return false;
}
@ -338,7 +337,7 @@ function search_pagename(&$data,$base,$file,$type,$lvl,$opts){
//simple stringmatching
if (!empty($opts['query'])){
if(strpos($file,$opts['query']) !== false){
if(strpos($file,(string) $opts['query']) !== false){
//check ACL
$id = pathID($file);
if(auth_quickaclcheck($id) < AUTH_READ){
@ -385,7 +384,7 @@ function search_allpages(&$data,$base,$file,$type,$lvl,$opts){
//only search txt files
if(substr($file,-4) != '.txt') return true;
$item = array();
$item = [];
$item['id'] = pathID($file);
if(empty($opts['skipacl']) && auth_quickaclcheck($item['id']) < AUTH_READ){
return false;
@ -485,7 +484,7 @@ function pathID($path,$keeptxt=false){
* @author Andreas Gohr <gohr@cosmocode.de>
*/
function search_universal(&$data,$base,$file,$type,$lvl,$opts){
$item = array();
$item = [];
$return = true;
// get ID and check if it is a valid one
@ -552,7 +551,7 @@ function search_universal(&$data,$base,$file,$type,$lvl,$opts){
$item['open'] = $return;
if(!empty($opts['meta'])){
$item['file'] = \dokuwiki\Utf8\PhpString::basename($file);
$item['file'] = PhpString::basename($file);
$item['size'] = filesize($base.'/'.$file);
$item['mtime'] = filemtime($base.'/'.$file);
$item['rev'] = $item['mtime'];

View File

@ -5,7 +5,15 @@
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
*/
use dokuwiki\ActionRouter;
use dokuwiki\Action\Exception\FatalException;
use dokuwiki\Extension\PluginInterface;
use dokuwiki\Ui\Admin;
use dokuwiki\StyleUtils;
use dokuwiki\Menu\Item\AbstractItem;
use dokuwiki\Form\Form;
use dokuwiki\Menu\MobileMenu;
use dokuwiki\Ui\Subscribe;
use dokuwiki\Extension\AdminPlugin;
use dokuwiki\Extension\Event;
use dokuwiki\File\PageResolver;
@ -95,10 +103,10 @@ function tpl_content($prependTOC = true) {
* @return bool
*/
function tpl_content_core() {
$router = \dokuwiki\ActionRouter::getInstance();
$router = ActionRouter::getInstance();
try {
$router->getAction()->tplContent();
} catch(\dokuwiki\Action\Exception\FatalException $e) {
} catch(FatalException $e) {
// there was no content for the action
msg(hsc($e->getMessage()), -1);
return false;
@ -125,7 +133,7 @@ function tpl_toc($return = false) {
global $INFO;
global $conf;
global $INPUT;
$toc = array();
$toc = [];
if(is_array($TOC)) {
// if a TOC was prepared in global scope, always use it
@ -138,9 +146,9 @@ function tpl_toc($return = false) {
} else {
$tocok = true;
}
$toc = isset($meta['description']['tableofcontents']) ? $meta['description']['tableofcontents'] : null;
$toc = $meta['description']['tableofcontents'] ?? null;
if(!$tocok || !is_array($toc) || !$conf['tocminheads'] || count($toc) < $conf['tocminheads']) {
$toc = array();
$toc = [];
}
} elseif($ACT == 'admin') {
// try to load admin plugin TOC
@ -182,12 +190,12 @@ function tpl_admin() {
}
}
if($plugin !== null) {
if($plugin instanceof PluginInterface) {
if(!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
if($INFO['prependTOC']) tpl_toc();
$plugin->html();
} else {
$admin = new dokuwiki\Ui\Admin();
$admin = new Admin();
$admin->show();
}
return true;
@ -218,7 +226,7 @@ function tpl_metaheaders($alt = true) {
global $INPUT;
// prepare the head array
$head = array();
$head = [];
// prepare seed for js and css
$tseed = $updateVersion;
@ -228,73 +236,90 @@ function tpl_metaheaders($alt = true) {
$tseed = md5($tseed);
// the usual stuff
$head['meta'][] = array('name'=> 'generator', 'content'=> 'DokuWiki');
$head['meta'][] = ['name'=> 'generator', 'content'=> 'DokuWiki'];
if(actionOK('search')) {
$head['link'][] = array(
'rel' => 'search', 'type'=> 'application/opensearchdescription+xml',
'href'=> DOKU_BASE.'lib/exe/opensearch.php', 'title'=> $conf['title']
);
$head['link'][] = [
'rel' => 'search',
'type'=> 'application/opensearchdescription+xml',
'href'=> DOKU_BASE.'lib/exe/opensearch.php',
'title'=> $conf['title']
];
}
$head['link'][] = array('rel'=> 'start', 'href'=> DOKU_BASE);
$head['link'][] = ['rel'=> 'start', 'href'=> DOKU_BASE];
if(actionOK('index')) {
$head['link'][] = array(
'rel' => 'contents', 'href'=> wl($ID, 'do=index', false, '&'),
$head['link'][] = [
'rel' => 'contents',
'href'=> wl($ID, 'do=index', false, '&'),
'title'=> $lang['btn_index']
);
];
}
if (actionOK('manifest')) {
$head['link'][] = array('rel'=> 'manifest', 'href'=> DOKU_BASE.'lib/exe/manifest.php');
$head['link'][] = [
'rel'=> 'manifest',
'href'=> DOKU_BASE.'lib/exe/manifest.php'
];
}
$styleUtil = new \dokuwiki\StyleUtils();
$styleUtil = new StyleUtils();
$styleIni = $styleUtil->cssStyleini();
$replacements = $styleIni['replacements'];
if (!empty($replacements['__theme_color__'])) {
$head['meta'][] = array('name' => 'theme-color', 'content' => $replacements['__theme_color__']);
$head['meta'][] = [
'name' => 'theme-color',
'content' => $replacements['__theme_color__']
];
}
if($alt) {
if(actionOK('rss')) {
$head['link'][] = array(
'rel' => 'alternate', 'type'=> 'application/rss+xml',
'title'=> $lang['btn_recent'], 'href'=> DOKU_BASE.'feed.php'
);
$head['link'][] = array(
'rel' => 'alternate', 'type'=> 'application/rss+xml',
$head['link'][] = [
'rel' => 'alternate',
'type'=> 'application/rss+xml',
'title'=> $lang['btn_recent'],
'href'=> DOKU_BASE.'feed.php'
];
$head['link'][] = [
'rel' => 'alternate',
'type'=> 'application/rss+xml',
'title'=> $lang['currentns'],
'href' => DOKU_BASE.'feed.php?mode=list&ns='.(isset($INFO) ? $INFO['namespace'] : '')
);
];
}
if(($ACT == 'show' || $ACT == 'search') && $INFO['writable']) {
$head['link'][] = array(
$head['link'][] = [
'rel' => 'edit',
'title'=> $lang['btn_edit'],
'href' => wl($ID, 'do=edit', false, '&')
);
];
}
if(actionOK('rss') && $ACT == 'search') {
$head['link'][] = array(
'rel' => 'alternate', 'type'=> 'application/rss+xml',
$head['link'][] = [
'rel' => 'alternate',
'type'=> 'application/rss+xml',
'title'=> $lang['searchresult'],
'href' => DOKU_BASE.'feed.php?mode=search&q='.$QUERY
);
];
}
if(actionOK('export_xhtml')) {
$head['link'][] = array(
'rel' => 'alternate', 'type'=> 'text/html', 'title'=> $lang['plainhtml'],
$head['link'][] = [
'rel' => 'alternate',
'type'=> 'text/html',
'title'=> $lang['plainhtml'],
'href'=> exportlink($ID, 'xhtml', '', false, '&')
);
];
}
if(actionOK('export_raw')) {
$head['link'][] = array(
'rel' => 'alternate', 'type'=> 'text/plain', 'title'=> $lang['wikimarkup'],
$head['link'][] = [
'rel' => 'alternate',
'type'=> 'text/plain',
'title'=> $lang['wikimarkup'],
'href'=> exportlink($ID, 'raw', '', false, '&')
);
];
}
}
@ -303,62 +328,62 @@ function tpl_metaheaders($alt = true) {
if($INFO['exists']) {
//delay indexing:
if((time() - $INFO['lastmod']) >= $conf['indexdelay'] && !isHiddenPage($ID) ) {
$head['meta'][] = array('name'=> 'robots', 'content'=> 'index,follow');
$head['meta'][] = ['name'=> 'robots', 'content'=> 'index,follow'];
} else {
$head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,nofollow');
$head['meta'][] = ['name'=> 'robots', 'content'=> 'noindex,nofollow'];
}
$canonicalUrl = wl($ID, '', true, '&');
if ($ID == $conf['start']) {
$canonicalUrl = DOKU_URL;
}
$head['link'][] = array('rel'=> 'canonical', 'href'=> $canonicalUrl);
$head['link'][] = ['rel'=> 'canonical', 'href'=> $canonicalUrl];
} else {
$head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,follow');
$head['meta'][] = ['name'=> 'robots', 'content'=> 'noindex,follow'];
}
} elseif(defined('DOKU_MEDIADETAIL')) {
$head['meta'][] = array('name'=> 'robots', 'content'=> 'index,follow');
$head['meta'][] = ['name'=> 'robots', 'content'=> 'index,follow'];
} else {
$head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,nofollow');
$head['meta'][] = ['name'=> 'robots', 'content'=> 'noindex,nofollow'];
}
// set metadata
if($ACT == 'show' || $ACT == 'export_xhtml') {
// keywords (explicit or implicit)
if(!empty($INFO['meta']['subject'])) {
$head['meta'][] = array('name'=> 'keywords', 'content'=> join(',', $INFO['meta']['subject']));
$head['meta'][] = ['name'=> 'keywords', 'content'=> implode(',', $INFO['meta']['subject'])];
} else {
$head['meta'][] = array('name'=> 'keywords', 'content'=> str_replace(':', ',', $ID));
$head['meta'][] = ['name'=> 'keywords', 'content'=> str_replace(':', ',', $ID)];
}
}
// load stylesheets
$head['link'][] = array(
$head['link'][] = [
'rel' => 'stylesheet',
'href'=> DOKU_BASE.'lib/exe/css.php?t='.rawurlencode($conf['template']).'&tseed='.$tseed
);
];
$script = "var NS='".(isset($INFO)?$INFO['namespace']:'')."';";
if($conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
$script .= "var SIG=".toolbar_signature().";";
}
jsinfo();
$script .= 'var JSINFO = ' . json_encode($JSINFO).';';
$head['script'][] = array('_data'=> $script);
$script .= 'var JSINFO = ' . json_encode($JSINFO, JSON_THROW_ON_ERROR).';';
$head['script'][] = ['_data'=> $script];
// load jquery
$jquery = getCdnUrls();
foreach($jquery as $src) {
$head['script'][] = array(
'_data' => '',
'src' => $src,
) + ($conf['defer_js'] ? [ 'defer' => 'defer'] : []);
$head['script'][] = [
'_data' => '',
'src' => $src
] + ($conf['defer_js'] ? [ 'defer' => 'defer'] : []);
}
// load our javascript dispatcher
$head['script'][] = array(
'_data'=> '',
'src' => DOKU_BASE.'lib/exe/js.php'.'?t='.rawurlencode($conf['template']).'&tseed='.$tseed,
) + ($conf['defer_js'] ? [ 'defer' => 'defer'] : []);
$head['script'][] = [
'_data'=> '',
'src' => DOKU_BASE.'lib/exe/js.php'.'?t='.rawurlencode($conf['template']).'&tseed='.$tseed
] + ($conf['defer_js'] ? [ 'defer' => 'defer'] : []);
// trigger event here
Event::createAndTrigger('TPL_METAHEADER_OUTPUT', $head, '_tpl_metaheaders_action', true);
@ -393,7 +418,7 @@ function _tpl_metaheaders_action($data) {
$attr['_data'].
"\n/*!]]>*/";
echo '>', isset($attr['_data']) ? $attr['_data'] : '', '</', $tag, '>';
echo '>', $attr['_data'] ?? '', '</', $tag, '>';
} else {
echo '/>';
}
@ -549,14 +574,15 @@ function tpl_actionlink($type, $pre = '', $suf = '', $inner = '', $return = fals
if(strpos($caption, '%s')){
$caption = sprintf($caption, $replacement);
}
$akey = $addTitle = '';
$akey = '';
$addTitle = '';
if($accesskey) {
$akey = 'accesskey="'.$accesskey.'" ';
$addTitle = ' ['.strtoupper($accesskey).']';
}
$rel = $nofollow ? 'rel="nofollow" ' : '';
$out = tpl_link(
$linktarget, $pre.(($inner) ? $inner : $caption).$suf,
$linktarget, $pre.($inner ?: $caption).$suf,
'class="action '.$type.'" '.
$akey.$rel.
'title="'.hsc($caption).$addTitle.'"', true
@ -587,7 +613,7 @@ function tpl_get_action($type) {
$class = '\\dokuwiki\\Menu\\Item\\' . ucfirst($type);
if(class_exists($class)) {
try {
/** @var \dokuwiki\Menu\Item\AbstractItem $item */
/** @var AbstractItem $item */
$item = new $class;
$data = $item->getLegacyData();
$unknown = false;
@ -596,15 +622,15 @@ function tpl_get_action($type) {
}
} else {
global $ID;
$data = array(
$data = [
'accesskey' => null,
'type' => $type,
'id' => $ID,
'method' => 'get',
'params' => array('do' => $type),
'params' => ['do' => $type],
'nofollow' => true,
'replacement' => '',
);
'replacement' => ''
];
$unknown = true;
}
@ -648,7 +674,7 @@ function tpl_action($type, $link = false, $wrapper = false, $return = false, $pr
if($return) return $out;
print $out;
return $out ? true : false;
return (bool) $out;
}
/**
@ -676,7 +702,7 @@ function tpl_searchform($ajax = true, $autocomplete = true) {
// don't print the search form if search action has been disabled
if(!actionOK('search')) return false;
$searchForm = new dokuwiki\Form\Form([
$searchForm = new Form([
'action' => wl(),
'method' => 'get',
'role' => 'search',
@ -751,7 +777,7 @@ function tpl_breadcrumbs($sep = null, $return = false) {
}
if($return) return $out;
print $out;
return $out ? true : false;
return (bool) $out;
}
/**
@ -821,7 +847,7 @@ function tpl_youarehere($sep = null, $return = false) {
$out .= tpl_pagelink($page, null, true);
if($return) return $out;
print $out;
return $out ? true : false;
return (bool) $out;
}
/**
@ -942,7 +968,7 @@ function tpl_pagetitle($id = null, $ret = false) {
/** @var $plugin AdminPlugin */
if ($plugin = plugin_getRequestAdminPlugin()){
$plugin_title = $plugin->getMenuText($conf['lang']);
$page_title = $plugin_title ? $plugin_title : $plugin->getPluginName();
$page_title = $plugin_title ?: $plugin->getPluginName();
}
break;
@ -1072,20 +1098,18 @@ function tpl_get_img_meta() {
include($config_file);
}
}
/** @var array $fields the included array with metadata */
$tags = array();
$tags = [];
foreach($fields as $tag){
$t = array();
$t = [];
if (!empty($tag[0])) {
$t = array($tag[0]);
$t = [$tag[0]];
}
if(isset($tag[3]) && is_array($tag[3])) {
$t = array_merge($t,$tag[3]);
}
$value = tpl_img_getTag($t);
if ($value) {
$tags[] = array('langkey' => $tag[1], 'type' => $tag[2], 'value' => $value);
$tags[] = ['langkey' => $tag[1], 'type' => $tag[2], 'value' => $value];
}
}
return $tags;
@ -1113,18 +1137,16 @@ function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null) {
//resize to given max values
$ratio = 1;
if($w >= $h) {
if ($w >= $h) {
if($maxwidth && $w >= $maxwidth) {
$ratio = $maxwidth / $w;
} elseif($maxheight && $h > $maxheight) {
$ratio = $maxheight / $h;
}
} else {
if($maxheight && $h >= $maxheight) {
$ratio = $maxheight / $h;
} elseif($maxwidth && $w > $maxwidth) {
$ratio = $maxwidth / $w;
}
} elseif ($maxheight && $h >= $maxheight) {
$ratio = $maxheight / $h;
} elseif($maxwidth && $w > $maxwidth) {
$ratio = $maxwidth / $w;
}
if($ratio) {
$w = floor($ratio * $w);
@ -1132,13 +1154,13 @@ function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null) {
}
//prepare URLs
$url = ml($IMG, array('cache'=> $INPUT->str('cache'),'rev'=>$REV), true, '&');
$src = ml($IMG, array('cache'=> $INPUT->str('cache'),'rev'=>$REV, 'w'=> $w, 'h'=> $h), true, '&');
$url = ml($IMG, ['cache'=> $INPUT->str('cache'), 'rev'=>$REV], true, '&');
$src = ml($IMG, ['cache'=> $INPUT->str('cache'), 'rev'=>$REV, 'w'=> $w, 'h'=> $h], true, '&');
//prepare attributes
$alt = tpl_img_getTag('Simple.Title');
if(is_null($params)) {
$p = array();
$p = [];
} else {
$p = $params;
}
@ -1153,7 +1175,7 @@ function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null) {
}
$p['src'] = $src;
$data = array('url'=> ($link ? $url : null), 'params'=> $p);
$data = ['url'=> ($link ? $url : null), 'params'=> $p];
return Event::createAndTrigger('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
}
@ -1184,7 +1206,7 @@ function _tpl_img_action($data) {
function tpl_indexerWebBug() {
global $ID;
$p = array();
$p = [];
$p['src'] = DOKU_BASE.'lib/exe/taskrunner.php?id='.rawurlencode($ID).
'&'.time();
$p['width'] = 2; //no more 1x1 px image because we live in times of ad blockers...
@ -1221,11 +1243,7 @@ function tpl_getConf($id, $notset=false) {
}
}
if(isset($conf['tpl'][$tpl][$id])){
return $conf['tpl'][$tpl][$id];
}
return $notset;
return $conf['tpl'][$tpl][$id] ?? $notset;
}
/**
@ -1239,7 +1257,7 @@ function tpl_getConf($id, $notset=false) {
function tpl_loadConfig() {
$file = tpl_incdir().'/conf/default.php';
$conf = array();
$conf = [];
if(!file_exists($file)) return false;
@ -1259,14 +1277,14 @@ function tpl_loadConfig() {
* @return string
*/
function tpl_getLang($id) {
static $lang = array();
static $lang = [];
if(count($lang) === 0) {
global $conf, $config_cascade; // definitely don't invoke "global $lang"
$path = tpl_incdir() . 'lang/';
$lang = array();
$lang = [];
// don't include once
@include($path . 'en/lang.php');
@ -1285,7 +1303,7 @@ function tpl_getLang($id) {
}
}
}
return isset($lang[$id]) ? $lang[$id] : '';
return $lang[$id] ?? '';
}
/**
@ -1344,7 +1362,7 @@ function tpl_mediaContent($fromajax = false, $sort='natural') {
global $INPUT;
$do = $INPUT->extract('do')->str('do');
if(in_array($do, array('save', 'cancel'))) $do = '';
if(in_array($do, ['save', 'cancel'])) $do = '';
if(!$do) {
if($INPUT->bool('edit')) {
@ -1358,7 +1376,7 @@ function tpl_mediaContent($fromajax = false, $sort='natural') {
// output the content pane, wrapped in an event.
if(!$fromajax) ptln('<div id="media__content">');
$data = array('do' => $do);
$data = ['do' => $do];
$evt = new Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
if($evt->advise_before()) {
$do = $data['do'];
@ -1394,7 +1412,7 @@ function tpl_mediaFileList() {
global $INPUT;
$opened_tab = $INPUT->str('tab_files');
if(!$opened_tab || !in_array($opened_tab, array('files', 'upload', 'search'))) $opened_tab = 'files';
if(!$opened_tab || !in_array($opened_tab, ['files', 'upload', 'search'])) $opened_tab = 'files';
if($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
echo '<h2 class="a11y">'.$lang['mediaselect'].'</h2>'.NL;
@ -1403,7 +1421,7 @@ function tpl_mediaFileList() {
echo '<div class="panelHeader">'.NL;
echo '<h3>';
$tabTitle = ($NS) ? $NS : '['.$lang['mediaroot'].']';
$tabTitle = $NS ?: '['.$lang['mediaroot'].']';
printf($lang['media_'.$opened_tab], '<strong>'.hsc($tabTitle).'</strong>');
echo '</h3>'.NL;
if($opened_tab === 'search' || $opened_tab === 'files') {
@ -1450,8 +1468,8 @@ function tpl_mediaFileDetails($image, $rev) {
$opened_tab = $INPUT->str('tab_details');
$tab_array = array('view');
list(, $mime) = mimetype($image);
$tab_array = ['view'];
[, $mime] = mimetype($image);
if($mime == 'image/jpeg') {
$tab_array[] = 'edit';
}
@ -1466,9 +1484,10 @@ function tpl_mediaFileDetails($image, $rev) {
media_tabs_details($image, $opened_tab);
echo '<div class="panelHeader"><h3>';
list($ext) = mimetype($image, false);
[$ext] = mimetype($image, false);
$class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
$class = 'select mediafile mf_'.$class;
$attributes = $rev ? ['rev' => $rev] : [];
$tabTitle = '<strong><a href="'.ml($image, $attributes).'" class="'.$class.'" title="'.$lang['mediaview'].'">'.
$image.'</a>'.'</strong>';
@ -1522,7 +1541,7 @@ function tpl_mediaTree() {
*/
function tpl_actiondropdown($empty = '', $button = '&gt;') {
dbg_deprecated('see devel:menus');
$menu = new \dokuwiki\Menu\MobileMenu();
$menu = new MobileMenu();
echo $menu->getDropdown($empty, $button);
}
@ -1603,8 +1622,8 @@ function tpl_include_page($pageid, $print = true, $propagate = false, $useacl =
* @deprecated 2020-07-23
*/
function tpl_subscribe() {
dbg_deprecated(\dokuwiki\Ui\Subscribe::class .'::show()');
(new \dokuwiki\Ui\Subscribe)->show();
dbg_deprecated(Subscribe::class .'::show()');
(new Subscribe)->show();
}
/**
@ -1654,7 +1673,7 @@ function tpl_getMediaFile($search, $abs = false, &$imginfo = null, $fallback = t
// manage non existing target
if (!file_exists($file)) {
// give result for fallback image
if ($fallback === true) {
if ($fallback) {
$file = DOKU_INC . 'lib/images/blank.gif';
// stop process if false result is required (if $fallback is false)
} else {
@ -1698,7 +1717,7 @@ function tpl_getMediaFile($search, $abs = false, &$imginfo = null, $fallback = t
*/
function tpl_includeFile($file) {
global $config_cascade;
foreach(array('protected', 'local', 'default') as $config_group) {
foreach(['protected', 'local', 'default'] as $config_group) {
if(empty($config_cascade['main'][$config_group])) continue;
foreach($config_cascade['main'][$config_group] as $conf_file) {
$dir = dirname($conf_file);
@ -1724,23 +1743,23 @@ function tpl_includeFile($file) {
* @param array $types - list of icon types to display (favicon|mobile|generic)
* @return string
*/
function tpl_favicon($types = array('favicon')) {
function tpl_favicon($types = ['favicon']) {
$return = '';
foreach($types as $type) {
switch($type) {
case 'favicon':
$look = array(':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico');
$look = [':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico'];
$return .= '<link rel="shortcut icon" href="'.tpl_getMediaFile($look).'" />'.NL;
break;
case 'mobile':
$look = array(':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png');
$look = [':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png'];
$return .= '<link rel="apple-touch-icon" href="'.tpl_getMediaFile($look).'" />'.NL;
break;
case 'generic':
// ideal world solution, which doesn't work in any browser yet
$look = array(':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg');
$look = [':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg'];
$return .= '<link rel="icon" href="'.tpl_getMediaFile($look).'" type="image/svg+xml" />'.NL;
break;
}
@ -1804,15 +1823,15 @@ function tpl_classes() {
/** @var Input $INPUT */
global $INPUT;
$classes = array(
$classes = [
'dokuwiki',
'mode_'.$ACT,
'tpl_'.$conf['template'],
$INPUT->server->bool('REMOTE_USER') ? 'loggedIn' : '',
(isset($INFO['exists']) && $INFO['exists']) ? '' : 'notFound',
($ID == $conf['start']) ? 'home' : '',
);
return join(' ', $classes);
($ID == $conf['start']) ? 'home' : ''
];
return implode(' ', $classes);
}
/**
@ -1826,15 +1845,12 @@ function tpl_classes() {
*/
function tpl_toolsevent($toolsname, $items, $view = 'main') {
dbg_deprecated('see devel:menus');
$data = array(
'view' => $view,
'items' => $items
);
$data = ['view' => $view, 'items' => $items];
$hook = 'TEMPLATE_' . strtoupper($toolsname) . '_DISPLAY';
$evt = new Event($hook, $data);
if($evt->advise_before()) {
foreach($evt->data['items'] as $k => $html) echo $html;
foreach($evt->data['items'] as $html) echo $html;
}
$evt->advise_after();
}

View File

@ -16,14 +16,14 @@
function toolbar_JSdefines($varname){
global $lang;
$menu = array();
$menu = [];
$evt = new Event('TOOLBAR_DEFINE', $menu);
if ($evt->advise_before()){
// build button array
$menu = array_merge($menu, array(
array(
$menu = array_merge($menu, [
[
'type' => 'format',
'title' => $lang['qb_bold'],
'icon' => 'bold.png',
@ -31,8 +31,8 @@ function toolbar_JSdefines($varname){
'open' => '**',
'close' => '**',
'block' => false
),
array(
],
[
'type' => 'format',
'title' => $lang['qb_italic'],
'icon' => 'italic.png',
@ -40,8 +40,8 @@ function toolbar_JSdefines($varname){
'open' => '//',
'close' => '//',
'block' => false
),
array(
],
[
'type' => 'format',
'title' => $lang['qb_underl'],
'icon' => 'underline.png',
@ -49,8 +49,8 @@ function toolbar_JSdefines($varname){
'open' => '__',
'close' => '__',
'block' => false
),
array(
],
[
'type' => 'format',
'title' => $lang['qb_code'],
'icon' => 'mono.png',
@ -58,8 +58,8 @@ function toolbar_JSdefines($varname){
'open' => "''",
'close' => "''",
'block' => false
),
array(
],
[
'type' => 'format',
'title' => $lang['qb_strike'],
'icon' => 'strike.png',
@ -67,9 +67,8 @@ function toolbar_JSdefines($varname){
'open' => '<del>',
'close' => '</del>',
'block' => false
),
array(
],
[
'type' => 'autohead',
'title' => $lang['qb_hequal'],
'icon' => 'hequal.png',
@ -77,8 +76,8 @@ function toolbar_JSdefines($varname){
'text' => $lang['qb_h'],
'mod' => 0,
'block' => true
),
array(
],
[
'type' => 'autohead',
'title' => $lang['qb_hminus'],
'icon' => 'hminus.png',
@ -86,8 +85,8 @@ function toolbar_JSdefines($varname){
'text' => $lang['qb_h'],
'mod' => 1,
'block' => true
),
array(
],
[
'type' => 'autohead',
'title' => $lang['qb_hplus'],
'icon' => 'hplus.png',
@ -95,59 +94,57 @@ function toolbar_JSdefines($varname){
'text' => $lang['qb_h'],
'mod' => -1,
'block' => true
),
array(
],
[
'type' => 'picker',
'title' => $lang['qb_hs'],
'icon' => 'h.png',
'class' => 'pk_hl',
'list' => array(
array(
'type' => 'format',
'title' => $lang['qb_h1'],
'icon' => 'h1.png',
'key' => '1',
'open' => '====== ',
'close' => ' ======\n',
),
array(
'type' => 'format',
'title' => $lang['qb_h2'],
'icon' => 'h2.png',
'key' => '2',
'open' => '===== ',
'close' => ' =====\n',
),
array(
'type' => 'format',
'title' => $lang['qb_h3'],
'icon' => 'h3.png',
'key' => '3',
'open' => '==== ',
'close' => ' ====\n',
),
array(
'type' => 'format',
'title' => $lang['qb_h4'],
'icon' => 'h4.png',
'key' => '4',
'open' => '=== ',
'close' => ' ===\n',
),
array(
'type' => 'format',
'title' => $lang['qb_h5'],
'icon' => 'h5.png',
'key' => '5',
'open' => '== ',
'close' => ' ==\n',
),
),
'list' => [
[
'type' => 'format',
'title' => $lang['qb_h1'],
'icon' => 'h1.png',
'key' => '1',
'open' => '====== ',
'close' => ' ======\n'
],
[
'type' => 'format',
'title' => $lang['qb_h2'],
'icon' => 'h2.png',
'key' => '2',
'open' => '===== ',
'close' => ' =====\n'
],
[
'type' => 'format',
'title' => $lang['qb_h3'],
'icon' => 'h3.png',
'key' => '3',
'open' => '==== ',
'close' => ' ====\n'
],
[
'type' => 'format',
'title' => $lang['qb_h4'],
'icon' => 'h4.png',
'key' => '4',
'open' => '=== ',
'close' => ' ===\n'
],
[
'type' => 'format',
'title' => $lang['qb_h5'],
'icon' => 'h5.png',
'key' => '5',
'open' => '== ',
'close' => ' ==\n'
]
],
'block' => true
),
array(
],
[
'type' => 'linkwiz',
'title' => $lang['qb_link'],
'icon' => 'link.png',
@ -155,8 +152,8 @@ function toolbar_JSdefines($varname){
'open' => '[[',
'close' => ']]',
'block' => false
),
array(
],
[
'type' => 'format',
'title' => $lang['qb_extlink'],
'icon' => 'linkextern.png',
@ -164,8 +161,8 @@ function toolbar_JSdefines($varname){
'close' => ']]',
'sample' => 'http://example.com|'.$lang['qb_extlink'],
'block' => false
),
array(
],
[
'type' => 'formatln',
'title' => $lang['qb_ol'],
'icon' => 'ol.png',
@ -173,8 +170,8 @@ function toolbar_JSdefines($varname){
'close' => '',
'key' => '-',
'block' => true
),
array(
],
[
'type' => 'formatln',
'title' => $lang['qb_ul'],
'icon' => 'ul.png',
@ -182,15 +179,15 @@ function toolbar_JSdefines($varname){
'close' => '',
'key' => '.',
'block' => true
),
array(
],
[
'type' => 'insert',
'title' => $lang['qb_hr'],
'icon' => 'hr.png',
'insert' => '\n----\n',
'block' => true
),
array(
],
[
'type' => 'mediapopup',
'title' => $lang['qb_media'],
'icon' => 'image.png',
@ -198,16 +195,16 @@ function toolbar_JSdefines($varname){
'name' => 'mediaselect',
'options'=> 'width=750,height=500,left=20,top=20,scrollbars=yes,resizable=yes',
'block' => false
),
array(
],
[
'type' => 'picker',
'title' => $lang['qb_smileys'],
'icon' => 'smiley.png',
'list' => getSmileys(),
'icobase'=> 'smileys',
'block' => false
),
array(
],
[
'type' => 'picker',
'title' => $lang['qb_chars'],
'icon' => 'chars.png',
@ -236,21 +233,21 @@ function toolbar_JSdefines($varname){
'″', '[', ']', '{', '}', '~', '(', ')', '%', '§', '$', '#', '|', '@'
],
'block' => false
),
array(
],
[
'type' => 'signature',
'title' => $lang['qb_sig'],
'icon' => 'sig.png',
'key' => 'y',
'block' => false
),
));
]
]);
} // end event TOOLBAR_DEFINE default action
$evt->advise_after();
unset($evt);
// use JSON to build the JavaScript array
print "var $varname = ".json_encode($menu).";\n";
print "var $varname = ".json_encode($menu, JSON_THROW_ON_ERROR).";\n";
}
/**
@ -275,7 +272,7 @@ function toolbar_signature(){
}
$sig = str_replace('@DATE@',dformat(),$sig);
$sig = str_replace('\\\\n','\\n',$sig);
return json_encode($sig);
return json_encode($sig, JSON_THROW_ON_ERROR);
}
//Setup VIM: ex: et ts=4 :