Apply PHP Code Beautifier on source code for linter automatic fixes

This commit is contained in:
ArthurHoaro 2020-09-22 20:25:47 +02:00
parent e09bb93e18
commit 53054b2bf6
87 changed files with 408 additions and 336 deletions

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli;
use DateTime;

View file

@ -76,7 +76,8 @@ class Languages
$this->language = $confLanguage;
}
if (! extension_loaded('gettext')
if (
! extension_loaded('gettext')
|| in_array($this->conf->get('translation.mode', 'auto'), ['auto', 'php'])
) {
$this->initPhpTranslator();

View file

@ -81,7 +81,8 @@ class Thumbnailer
*/
public function get($url)
{
if ($this->conf->get('thumbnails.mode') === self::MODE_COMMON
if (
$this->conf->get('thumbnails.mode') === self::MODE_COMMON
&& ! $this->isCommonMediaOrImage($url)
) {
return false;

View file

@ -1,4 +1,5 @@
<?php
/**
* Generates a list of available timezone continents and cities.
*

View file

@ -1,4 +1,5 @@
<?php
/**
* Shaarli utilities
*/
@ -102,7 +103,7 @@ function escape($input)
}
if (is_array($input)) {
$out = array();
$out = [];
foreach ($input as $key => $value) {
$out[escape($key)] = escape($value);
}
@ -163,7 +164,7 @@ function checkDateFormat($format, $string)
*
* @return string $referer - final referer.
*/
function generateLocation($referer, $host, $loopTerms = array())
function generateLocation($referer, $host, $loopTerms = [])
{
$finalReferer = './?';
@ -196,7 +197,7 @@ function generateLocation($referer, $host, $loopTerms = array())
function autoLocale($headerLocale)
{
// Default if browser does not send HTTP_ACCEPT_LANGUAGE
$locales = array('en_US', 'en_US.utf8', 'en_US.UTF-8');
$locales = ['en_US', 'en_US.utf8', 'en_US.UTF-8'];
if (! empty($headerLocale)) {
if (preg_match_all('/([a-z]{2,3})[-_]?([a-z]{2})?,?/i', $headerLocale, $matches, PREG_SET_ORDER)) {
$attempts = [];
@ -482,7 +483,9 @@ function alphabetical_sort(&$data, $reverse = false, $byKeys = false)
*/
function t($text, $nText = '', $nb = 1, $domain = 'shaarli', $variables = [], $fixCase = false)
{
$postFunction = $fixCase ? 'ucfirst' : function ($input) { return $input; };
$postFunction = $fixCase ? 'ucfirst' : function ($input) {
return $input;
};
return $postFunction(dn__($domain, $text, $nText, $nb, $variables));
}
@ -494,4 +497,3 @@ function exception2text(Throwable $e): string
{
return $e->getMessage() . PHP_EOL . $e->getFile() . $e->getLine() . PHP_EOL . $e->getTraceAsString();
}

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Api;
use malkusch\lock\mutex\FlockMutex;
@ -108,7 +109,8 @@ class ApiMiddleware
*/
protected function checkToken($request)
{
if (!$request->hasHeader('Authorization')
if (
!$request->hasHeader('Authorization')
&& !isset($this->container->environment['REDIRECT_HTTP_AUTHORIZATION'])
) {
throw new ApiAuthorizationException('JWT token not provided');

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Api;
use Shaarli\Api\Exceptions\ApiAuthorizationException;
@ -42,7 +43,8 @@ class ApiUtils
throw new ApiAuthorizationException('Invalid JWT payload');
}
if (empty($payload->iat)
if (
empty($payload->iat)
|| $payload->iat > time()
|| time() - $payload->iat > ApiMiddleware::$TOKEN_DURATION
) {

View file

@ -1,6 +1,5 @@
<?php
namespace Shaarli\Api\Controllers;
use Shaarli\Api\Exceptions\ApiBadParametersException;

View file

@ -29,13 +29,13 @@ class Info extends ApiController
$info = [
'global_counter' => $this->bookmarkService->count(),
'private_counter' => $this->bookmarkService->count(BookmarkFilter::$PRIVATE),
'settings' => array(
'settings' => [
'title' => $this->conf->get('general.title', 'Shaarli'),
'header_link' => $this->conf->get('general.header_link', '?'),
'timezone' => $this->conf->get('general.timezone', 'UTC'),
'enabled_plugins' => $this->conf->get('general.enabled_plugins', []),
'default_private_links' => $this->conf->get('privacy.default_private_links', false),
),
],
];
return $response->withJson($info, 200, $this->jsonStyle);

View file

@ -119,7 +119,8 @@ class Links extends ApiController
$data = (array) ($request->getParsedBody() ?? []);
$bookmark = ApiUtils::buildBookmarkFromRequest($data, $this->conf->get('privacy.default_private_links'));
// duplicate by URL, return 409 Conflict
if (! empty($bookmark->getUrl())
if (
! empty($bookmark->getUrl())
&& ! empty($dup = $this->bookmarkService->findByUrl($bookmark->getUrl()))
) {
return $response->withJson(
@ -159,7 +160,8 @@ class Links extends ApiController
$requestBookmark = ApiUtils::buildBookmarkFromRequest($data, $this->conf->get('privacy.default_private_links'));
// duplicate URL on a different link, return 409 Conflict
if (! empty($requestBookmark->getUrl())
if (
! empty($requestBookmark->getUrl())
&& ! empty($dup = $this->bookmarkService->findByUrl($requestBookmark->getUrl()))
&& $dup->getId() != $id
) {

View file

@ -106,7 +106,8 @@ class Bookmark
*/
public function validate(): void
{
if ($this->id === null
if (
$this->id === null
|| ! is_int($this->id)
|| empty($this->shortUrl)
|| empty($this->created)

View file

@ -72,7 +72,8 @@ class BookmarkArray implements \Iterator, \Countable, \ArrayAccess
*/
public function offsetSet($offset, $value)
{
if (! $value instanceof Bookmark
if (
! $value instanceof Bookmark
|| $value->getId() === null || empty($value->getUrl())
|| ($offset !== null && ! is_int($offset)) || ! is_int($value->getId())
|| $offset !== null && $offset !== $value->getId()
@ -222,7 +223,8 @@ class BookmarkArray implements \Iterator, \Countable, \ArrayAccess
*/
public function getByUrl(string $url): ?Bookmark
{
if (! empty($url)
if (
! empty($url)
&& isset($this->urls[$url])
&& isset($this->bookmarks[$this->urls[$url]])
) {

View file

@ -102,7 +102,8 @@ class BookmarkFileService implements BookmarkServiceInterface
$bookmark = $this->bookmarkFilter->filter(BookmarkFilter::$FILTER_HASH, $hash);
// PHP 7.3 introduced array_key_first() to avoid this hack
$first = reset($bookmark);
if (!$this->isLoggedIn
if (
!$this->isLoggedIn
&& $first->isPrivate()
&& (empty($privateKey) || $privateKey !== $first->getAdditionalContentEntry('private_key'))
) {
@ -165,7 +166,8 @@ class BookmarkFileService implements BookmarkServiceInterface
}
$bookmark = $this->bookmarks[$id];
if (($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
if (
($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
|| (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
) {
throw new Exception('Unauthorized');
@ -265,7 +267,8 @@ class BookmarkFileService implements BookmarkServiceInterface
}
$bookmark = $this->bookmarks[$id];
if (($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
if (
($bookmark->isPrivate() && $visibility != 'all' && $visibility != 'private')
|| (! $bookmark->isPrivate() && $visibility != 'all' && $visibility != 'public')
) {
return false;
@ -307,7 +310,8 @@ class BookmarkFileService implements BookmarkServiceInterface
$caseMapping = [];
foreach ($bookmarks as $bookmark) {
foreach ($bookmark->getTags() as $tag) {
if (empty($tag)
if (
empty($tag)
|| (! $this->isLoggedIn && startsWith($tag, '.'))
|| $tag === BookmarkMarkdownFormatter::NO_MD_TAG
|| in_array($tag, $filteringTags, true)

View file

@ -150,7 +150,7 @@ class BookmarkFilter
return $this->bookmarks;
}
$out = array();
$out = [];
foreach ($this->bookmarks as $key => $value) {
if ($value->isPrivate() && $visibility === 'private') {
$out[$key] = $value;
@ -395,7 +395,7 @@ class BookmarkFilter
$search = $link->getTagsString($tagsSeparator);
if (strlen(trim($link->getDescription())) && strpos($link->getDescription(), '#') !== false) {
// description given and at least one possible tag found
$descTags = array();
$descTags = [];
// find all tags in the form of #tag in the description
preg_match_all(
'/(?<![' . self::$HASHTAG_CHARS . '])#([' . self::$HASHTAG_CHARS . ']+?)\b/sm',

View file

@ -74,7 +74,8 @@ function html_extract_tag($tag, $html)
// New regex to keep this readable... more or less.
$ogRegexReverse = '#<meta[^>]+content=(["\'])([^\1]*?)\1[^>]+(?:' . $properties . ')=(?:' . $orCondition . ').*?>#';
if (preg_match($ogRegex, $html, $matches) > 0
if (
preg_match($ogRegex, $html, $matches) > 0
|| preg_match($ogRegexReverse, $html, $matches) > 0
) {
return $matches[2];

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Bookmark\Exception;
use Exception;

View file

@ -1,7 +1,7 @@
<?php
namespace Shaarli\Bookmark\Exception;
class EmptyDataStoreException extends \Exception {}
class EmptyDataStoreException extends \Exception
{
}

View file

@ -1,9 +1,7 @@
<?php
namespace Shaarli\Bookmark\Exception;
class NotWritableDataStoreException extends \Exception
{
/**

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Config;
/**

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Config;
use Shaarli\Config\Exception\MissingFieldConfigException;
@ -20,7 +21,7 @@ class ConfigManager
*/
protected static $NOT_FOUND = 'NOT_FOUND';
public static $DEFAULT_PLUGINS = array('qrcode');
public static $DEFAULT_PLUGINS = ['qrcode'];
/**
* @var string Config folder.
@ -213,7 +214,7 @@ class ConfigManager
public function write($isLoggedIn)
{
// These fields are required in configuration.
$mandatoryFields = array(
$mandatoryFields = [
'credentials.login',
'credentials.hash',
'credentials.salt',
@ -222,7 +223,7 @@ class ConfigManager
'general.title',
'general.header_link',
'privacy.default_private_links',
);
];
// Only logged in user can alter config.
if (is_file($this->getConfigFileExt()) && !$isLoggedIn) {
@ -392,7 +393,7 @@ class ConfigManager
$this->setEmpty('translation.mode', 'php');
$this->setEmpty('translation.extensions', []);
$this->setEmpty('plugins', array());
$this->setEmpty('plugins', []);
$this->setEmpty('formatter', 'markdown');
}

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Config;
/**
@ -12,7 +13,7 @@ class ConfigPhp implements ConfigIO
/**
* @var array List of config key without group.
*/
public static $ROOT_KEYS = array(
public static $ROOT_KEYS = [
'login',
'hash',
'salt',
@ -22,7 +23,7 @@ class ConfigPhp implements ConfigIO
'redirector',
'disablesessionprotection',
'privateLinkByDefault',
);
];
/**
* Map legacy config keys with the new ones.
@ -31,7 +32,7 @@ class ConfigPhp implements ConfigIO
*
* @var array current key => legacy key.
*/
public static $LEGACY_KEYS_MAPPING = array(
public static $LEGACY_KEYS_MAPPING = [
'credentials.login' => 'login',
'credentials.hash' => 'hash',
'credentials.salt' => 'salt',
@ -68,7 +69,7 @@ class ConfigPhp implements ConfigIO
'privacy.hide_public_links' => 'config.HIDE_PUBLIC_LINKS',
'privacy.hide_timestamps' => 'config.HIDE_TIMESTAMPS',
'security.open_shaarli' => 'config.OPEN_SHAARLI',
);
];
/**
* @inheritdoc
@ -76,12 +77,12 @@ class ConfigPhp implements ConfigIO
public function read($filepath)
{
if (! file_exists($filepath) || ! is_readable($filepath)) {
return array();
return [];
}
include $filepath;
$out = array();
$out = [];
foreach (self::$ROOT_KEYS as $key) {
$out[$key] = isset($GLOBALS[$key]) ? $GLOBALS[$key] : '';
}
@ -121,7 +122,8 @@ class ConfigPhp implements ConfigIO
}
}
if (!file_put_contents($filepath, $configStr)
if (
!file_put_contents($filepath, $configStr)
|| strcmp(file_get_contents($filepath), $configStr) != 0
) {
throw new \Shaarli\Exceptions\IOException(

View file

@ -39,8 +39,8 @@ function save_plugin_config($formData)
throw new PluginConfigOrderException();
}
$plugins = array();
$newEnabledPlugins = array();
$plugins = [];
$newEnabledPlugins = [];
foreach ($formData as $key => $data) {
if (startsWith($key, 'order')) {
continue;
@ -62,7 +62,7 @@ function save_plugin_config($formData)
throw new PluginConfigOrderException();
}
$finalPlugins = array();
$finalPlugins = [];
// Make plugins order continuous.
foreach ($plugins as $plugin) {
$finalPlugins[] = $plugin;
@ -81,7 +81,7 @@ function save_plugin_config($formData)
*/
function validate_plugin_order($formData)
{
$orders = array();
$orders = [];
foreach ($formData as $key => $value) {
// No duplicate order allowed.
if (in_array($value, $orders, true)) {

View file

@ -1,6 +1,5 @@
<?php
namespace Shaarli\Config\Exception;
/**

View file

@ -1,6 +1,5 @@
<?php
namespace Shaarli\Config\Exception;
/**

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Exceptions;
use Exception;

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Feed;
use DateTime;
@ -107,14 +108,14 @@ class FeedBuilder
$nblinksToDisplay = $this->getNbLinks(count($linksToDisplay), $userInput);
// Can't use array_keys() because $link is a LinkDB instance and not a real array.
$keys = array();
$keys = [];
foreach ($linksToDisplay as $key => $value) {
$keys[] = $key;
}
$pageaddr = escape(index_url($this->serverInfo));
$this->formatter->addContextData('index_url', $pageaddr);
$linkDisplayed = array();
$linkDisplayed = [];
for ($i = 0; $i < $nblinksToDisplay && $i < count($keys); $i++) {
$linkDisplayed[$keys[$i]] = $this->buildItem($feedType, $linksToDisplay[$keys[$i]], $pageaddr);
}

View file

@ -178,14 +178,14 @@ class BookmarkMarkdownFormatter extends BookmarkDefaultFormatter
*/
protected function sanitizeHtml($description)
{
$escapeTags = array(
$escapeTags = [
'script',
'style',
'link',
'iframe',
'frameset',
'frame',
);
];
foreach ($escapeTags as $tag) {
$description = preg_replace_callback(
'#<\s*' . $tag . '[^>]*>(.*</\s*' . $tag . '[^>]*>)?#is',

View file

@ -10,4 +10,6 @@ namespace Shaarli\Formatter;
*
* @package Shaarli\Formatter
*/
class BookmarkRawFormatter extends BookmarkFormatter {}
class BookmarkRawFormatter extends BookmarkFormatter
{
}

View file

@ -42,7 +42,8 @@ class ShaarliMiddleware
$this->initBasePath($request);
try {
if (!is_file($this->container->conf->getConfigFileExt())
if (
!is_file($this->container->conf->getConfigFileExt())
&& !in_array($next->getName(), ['displayInstall', 'saveInstall'], true)
) {
return $response->withRedirect($this->container->basePath . '/install');
@ -86,7 +87,8 @@ class ShaarliMiddleware
*/
protected function checkOpenShaarli(Request $request, Response $response, callable $next): bool
{
if (// if the user isn't logged in
if (
// if the user isn't logged in
!$this->container->loginManager->isLoggedIn()
// and Shaarli doesn't have public content...
&& $this->container->conf->get('privacy.hide_public_links')

View file

@ -95,7 +95,8 @@ class ConfigureController extends ShaarliAdminController
}
$thumbnailsMode = extension_loaded('gd') ? $request->getParam('enableThumbnails') : Thumbnailer::MODE_NONE;
if ($thumbnailsMode !== Thumbnailer::MODE_NONE
if (
$thumbnailsMode !== Thumbnailer::MODE_NONE
&& $thumbnailsMode !== $this->container->conf->get('thumbnails.mode', Thumbnailer::MODE_NONE)
) {
$this->saveWarningMessage(

View file

@ -45,6 +45,4 @@ class SessionFilterController extends ShaarliAdminController
return $this->redirectFromReferer($request, $response, ['visibility']);
}
}

View file

@ -118,7 +118,8 @@ class ShaarePublishController extends ShaarliAdminController
$this->container->conf->get('general.tags_separator', ' ')
);
if ($this->container->conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
if (
$this->container->conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
&& true !== $this->container->conf->get('general.enable_async_metadata', true)
&& $bookmark->shouldUpdateThumbnail()
) {
@ -148,7 +149,8 @@ class ShaarePublishController extends ShaarliAdminController
return $this->redirectFromReferer(
$request,
$response,
['/admin/add-shaare', '/admin/shaare'], ['addlink', 'post', 'edit_link'],
['/admin/add-shaare', '/admin/shaare'],
['addlink', 'post', 'edit_link'],
$bookmark->getShortUrl()
);
}
@ -194,7 +196,8 @@ class ShaarePublishController extends ShaarliAdminController
// If this is an HTTP(S) link, we try go get the page to extract
// the title (otherwise we will to straight to the edit form.)
if (true !== $this->container->conf->get('general.enable_async_metadata', true)
if (
true !== $this->container->conf->get('general.enable_async_metadata', true)
&& empty($title)
&& strpos(get_url_scheme($url) ?: '', 'http') !== false
) {

View file

@ -35,7 +35,8 @@ class BookmarkListController extends ShaarliVisitorController
$formatter->addContextData('base_path', $this->container->basePath);
$searchTags = normalize_spaces($request->getParam('searchtags') ?? '');
$searchTerm = escape(normalize_spaces($request->getParam('searchterm') ?? ''));;
$searchTerm = escape(normalize_spaces($request->getParam('searchterm') ?? ''));
;
// Filter bookmarks according search parameters.
$visibility = $this->container->sessionManager->getSessionParameter('visibility');
@ -185,7 +186,8 @@ class BookmarkListController extends ShaarliVisitorController
$bookmark->setThumbnail(null);
// Requires an update, not async retrieval, thumbnails enabled
if ($bookmark->shouldUpdateThumbnail()
if (
$bookmark->shouldUpdateThumbnail()
&& true !== $this->container->conf->get('general.enable_async_metadata', true)
&& $this->container->conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
) {

View file

@ -39,7 +39,8 @@ class InstallController extends ShaarliVisitorController
// Before installation, we'll make sure that permissions are set properly, and sessions are working.
$this->checkPermissions();
if (static::SESSION_TEST_VALUE
if (
static::SESSION_TEST_VALUE
!== $this->container->sessionManager->getSessionParameter(static::SESSION_TEST_KEY)
) {
$this->container->sessionManager->setSessionParameter(static::SESSION_TEST_KEY, static::SESSION_TEST_VALUE);
@ -75,7 +76,8 @@ class InstallController extends ShaarliVisitorController
// This part makes sure sessions works correctly.
// (Because on some hosts, session.save_path may not be set correctly,
// or we may not have write access to it.)
if (static::SESSION_TEST_VALUE
if (
static::SESSION_TEST_VALUE
!== $this->container->sessionManager->getSessionParameter(static::SESSION_TEST_KEY)
) {
// Step 2: Check if data in session is correct.
@ -104,7 +106,8 @@ class InstallController extends ShaarliVisitorController
public function save(Request $request, Response $response): Response
{
$timezone = 'UTC';
if (!empty($request->getParam('continent'))
if (
!empty($request->getParam('continent'))
&& !empty($request->getParam('city'))
&& isTimeZoneValid($request->getParam('continent'), $request->getParam('city'))
) {

View file

@ -64,7 +64,8 @@ class LoginController extends ShaarliVisitorController
return $this->redirect($response, '/');
}
if (!$this->container->loginManager->checkCredentials(
if (
!$this->container->loginManager->checkCredentials(
client_ip_id($this->container->environment),
$request->getParam('login'),
$request->getParam('password')
@ -101,7 +102,8 @@ class LoginController extends ShaarliVisitorController
*/
protected function checkLoginState(): bool
{
if ($this->container->loginManager->isLoggedIn()
if (
$this->container->loginManager->isLoggedIn()
|| $this->container->conf->get('security.open_shaarli', false)
) {
throw new CantLoginException();

View file

@ -144,7 +144,8 @@ abstract class ShaarliVisitorController
if (null !== $referer) {
$currentUrl = parse_url($referer);
// If the referer is not related to Shaarli instance, redirect to default
if (isset($currentUrl['host'])
if (
isset($currentUrl['host'])
&& strpos(index_url($this->container->environment), $currentUrl['host']) === false
) {
return $response->withRedirect($defaultPath);

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Helper;
use Exception;
@ -16,7 +17,7 @@ class ApplicationUtils
public static $GITHUB_URL = 'https://github.com/shaarli/Shaarli';
public static $GIT_RAW_URL = 'https://raw.githubusercontent.com/shaarli/Shaarli';
public static $GIT_BRANCHES = array('latest', 'stable');
public static $GIT_BRANCHES = ['latest', 'stable'];
private static $VERSION_START_TAG = '<?php /* ';
private static $VERSION_END_TAG = ' */ ?>';
@ -64,8 +65,8 @@ class ApplicationUtils
}
return str_replace(
array(self::$VERSION_START_TAG, self::$VERSION_END_TAG, PHP_EOL),
array('', '', ''),
[self::$VERSION_START_TAG, self::$VERSION_END_TAG, PHP_EOL],
['', '', ''],
$data
);
}
@ -184,13 +185,15 @@ class ApplicationUtils
$rainTplDir = rtrim($conf->get('resource.raintpl_tpl'), '/');
// Check script and template directories are readable
foreach ([
foreach (
[
'application',
'inc',
'plugins',
$rainTplDir,
$rainTplDir . '/' . $conf->get('resource.theme'),
] as $path) {
] as $path
) {
if (!is_readable(realpath($path))) {
$errors[] = '"' . $path . '" ' . t('directory is not readable');
}
@ -224,13 +227,15 @@ class ApplicationUtils
}
// Check configuration files are readable and writable
foreach (array(
foreach (
[
$conf->getConfigFileExt(),
$conf->get('resource.datastore'),
$conf->get('resource.ban_file'),
$conf->get('resource.log'),
$conf->get('resource.update_check'),
) as $path) {
] as $path
) {
if (!is_file(realpath($path))) {
# the file may not exist yet
continue;

View file

@ -48,7 +48,7 @@ function get_http_response(
$cleanUrl = $urlObj->idnToAscii();
if (!filter_var($cleanUrl, FILTER_VALIDATE_URL) || !$urlObj->isHttp()) {
return array(array(0 => 'Invalid HTTP UrlUtils'), false);
return [[0 => 'Invalid HTTP UrlUtils'], false];
}
$userAgent =
@ -71,7 +71,7 @@ function get_http_response(
$ch = curl_init($cleanUrl);
if ($ch === false) {
return array(array(0 => 'curl_init() error'), false);
return [[0 => 'curl_init() error'], false];
}
// General cURL settings
@ -82,7 +82,7 @@ function get_http_response(
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array('Accept-Language: ' . $acceptLanguage)
['Accept-Language: ' . $acceptLanguage]
);
curl_setopt($ch, CURLOPT_MAXREDIRS, $maxRedirs);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@ -122,9 +122,9 @@ function get_http_response(
* Removing this would require updating
* GetHttpUrlTest::testGetInvalidRemoteUrl()
*/
return array(false, false);
return [false, false];
}
return array(array(0 => 'curl_exec() error: ' . $errorStr), false);
return [[0 => 'curl_exec() error: ' . $errorStr], false];
}
// Formatting output like the fallback method
@ -135,7 +135,7 @@ function get_http_response(
$rawHeadersLastRedir = end($rawHeadersArrayRedirs);
$content = substr($response, $headSize);
$headers = array();
$headers = [];
foreach (preg_split('~[\r\n]+~', $rawHeadersLastRedir) as $line) {
if (empty($line) || ctype_space($line)) {
continue;
@ -146,7 +146,7 @@ function get_http_response(
$value = $splitLine[1];
if (array_key_exists($key, $headers)) {
if (!is_array($headers[$key])) {
$headers[$key] = array(0 => $headers[$key]);
$headers[$key] = [0 => $headers[$key]];
}
$headers[$key][] = $value;
} else {
@ -157,7 +157,7 @@ function get_http_response(
}
}
return array($headers, $content);
return [$headers, $content];
}
/**
@ -188,15 +188,15 @@ function get_http_response_fallback(
$acceptLanguage,
$maxRedr
) {
$options = array(
'http' => array(
$options = [
'http' => [
'method' => 'GET',
'timeout' => $timeout,
'user_agent' => $userAgent,
'header' => "Accept: */*\r\n"
. 'Accept-Language: ' . $acceptLanguage
)
);
]
];
stream_context_set_default($options);
list($headers, $finalUrl) = get_redirected_headers($cleanUrl, $maxRedr);
@ -207,7 +207,7 @@ function get_http_response_fallback(
}
if (! $headers) {
return array($headers, false);
return [$headers, false];
}
try {
@ -215,10 +215,10 @@ function get_http_response_fallback(
$context = stream_context_create($options);
$content = file_get_contents($finalUrl, false, $context, -1, $maxBytes);
} catch (Exception $exc) {
return array(array(0 => 'HTTP Error'), $exc->getMessage());
return [[0 => 'HTTP Error'], $exc->getMessage()];
}
return array($headers, $content);
return [$headers, $content];
}
/**
@ -237,10 +237,12 @@ function get_redirected_headers($url, $redirectionLimit = 3)
}
// Headers found, redirection found, and limit not reached.
if ($redirectionLimit-- > 0
if (
$redirectionLimit-- > 0
&& !empty($headers)
&& (strpos($headers[0], '301') !== false || strpos($headers[0], '302') !== false)
&& !empty($headers['Location'])) {
&& !empty($headers['Location'])
) {
$redirection = is_array($headers['Location']) ? end($headers['Location']) : $headers['Location'];
if ($redirection != $url) {
$redirection = getAbsoluteUrl($url, $redirection);
@ -248,7 +250,7 @@ function get_redirected_headers($url, $redirectionLimit = 3)
}
}
return array($headers, $url);
return [$headers, $url];
}
/**
@ -323,7 +325,8 @@ function server_url($server)
$scheme = 'https';
}
if (($scheme == 'http' && $port != '80')
if (
($scheme == 'http' && $port != '80')
|| ($scheme == 'https' && $port != '443')
) {
$port = ':' . $port;
@ -348,14 +351,18 @@ function server_url($server)
}
// SSL detection
if ((! empty($server['HTTPS']) && strtolower($server['HTTPS']) == 'on')
|| (isset($server['SERVER_PORT']) && $server['SERVER_PORT'] == '443')) {
if (
(! empty($server['HTTPS']) && strtolower($server['HTTPS']) == 'on')
|| (isset($server['SERVER_PORT']) && $server['SERVER_PORT'] == '443')
) {
$scheme = 'https';
}
// Do not append standard port values
if (($scheme == 'http' && $server['SERVER_PORT'] != '80')
|| ($scheme == 'https' && $server['SERVER_PORT'] != '443')) {
if (
($scheme == 'http' && $server['SERVER_PORT'] != '80')
|| ($scheme == 'https' && $server['SERVER_PORT'] != '443')
) {
$port = ':' . $server['SERVER_PORT'];
}
@ -567,7 +574,10 @@ function get_curl_download_callback(
*
* @return int|bool length of $data or false if we need to stop the download
*/
return function ($ch, $data) use (
return function (
$ch,
$data
) use (
$retrieveDescription,
$tagsSeparator,
&$charset,
@ -611,7 +621,8 @@ function get_curl_download_callback(
// If we already found either the title, description or keywords,
// it's highly unlikely that we'll found the other metas further than
// in the same chunk of data or the next one. So we also stop the download after that.
if ((!empty($responseCode) && !empty($contentType) && !empty($charset)) && $foundChunk !== null
if (
(!empty($responseCode) && !empty($contentType) && !empty($charset)) && $foundChunk !== null
&& (! $retrieveDescription
|| $foundChunk < $currentChunk
|| (!empty($title) && !empty($description) && !empty($keywords))

View file

@ -17,7 +17,7 @@ namespace Shaarli\Http;
*/
class Url
{
private static $annoyingQueryParams = array(
private static $annoyingQueryParams = [
// Facebook
'action_object_map=',
'action_ref_map=',
@ -37,15 +37,15 @@ class Url
// Other
'campaign_'
);
];
private static $annoyingFragments = array(
private static $annoyingFragments = [
// ATInternet
'xtor=RSS-',
// Misc.
'tk.rss_all'
);
];
/*
* URL parts represented as an array
@ -120,7 +120,7 @@ class Url
foreach (self::$annoyingQueryParams as $annoying) {
foreach ($queryParams as $param) {
if (startsWith($param, $annoying)) {
$queryParams = array_diff($queryParams, array($param));
$queryParams = array_diff($queryParams, [$param]);
continue;
}
}

View file

@ -1,4 +1,5 @@
<?php
/**
* Converts an array-represented URL to a string
*

View file

@ -240,8 +240,8 @@ class LegacyLinkDB implements Iterator, Countable, ArrayAccess
}
// Create a dummy database for example
$this->links = array();
$link = array(
$this->links = [];
$link = [
'id' => 1,
'title' => t('The personal, minimalist, super-fast, database free, bookmarking service'),
'url' => 'https://shaarli.readthedocs.io',
@ -257,11 +257,11 @@ You use the community supported version of the original Shaarli project, by Seba
'created' => new DateTime(),
'tags' => 'opensource software',
'sticky' => false,
);
];
$link['shorturl'] = link_small_hash($link['created'], $link['id']);
$this->links[1] = $link;
$link = array(
$link = [
'id' => 0,
'title' => t('My secret stuff... - Pastebin.com'),
'url' => 'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=',
@ -270,7 +270,7 @@ You use the community supported version of the original Shaarli project, by Seba
'created' => new DateTime('1 minute ago'),
'tags' => 'secretstuff',
'sticky' => false,
);
];
$link['shorturl'] = link_small_hash($link['created'], $link['id']);
$this->links[0] = $link;
@ -285,7 +285,7 @@ You use the community supported version of the original Shaarli project, by Seba
{
// Public bookmarks are hidden and user not logged in => nothing to show
if ($this->hidePublicLinks && !$this->loggedIn) {
$this->links = array();
$this->links = [];
return;
}
@ -293,7 +293,7 @@ You use the community supported version of the original Shaarli project, by Seba
$this->ids = [];
$this->links = FileUtils::readFlatDB($this->datastore, []);
$toremove = array();
$toremove = [];
foreach ($this->links as $key => &$link) {
if (!$this->loggedIn && $link['private'] != 0) {
// Transition for not upgraded databases.
@ -414,7 +414,7 @@ You use the community supported version of the original Shaarli project, by Seba
* @return array filtered bookmarks, all bookmarks if no suitable filter was provided.
*/
public function filterSearch(
$filterRequest = array(),
$filterRequest = [],
$casesensitive = false,
$visibility = 'all',
$untaggedonly = false
@ -512,7 +512,7 @@ You use the community supported version of the original Shaarli project, by Seba
*/
public function days()
{
$linkDays = array();
$linkDays = [];
foreach ($this->links as $link) {
$linkDays[$link['created']->format('Ymd')] = 0;
}

View file

@ -120,7 +120,7 @@ class LegacyLinkFilter
return $this->links;
}
$out = array();
$out = [];
foreach ($this->links as $key => $value) {
if ($value['private'] && $visibility === 'private') {
$out[$key] = $value;
@ -143,7 +143,7 @@ class LegacyLinkFilter
*/
private function filterSmallHash($smallHash)
{
$filtered = array();
$filtered = [];
foreach ($this->links as $key => $l) {
if ($smallHash == $l['shorturl']) {
// Yes, this is ugly and slow
@ -186,7 +186,7 @@ class LegacyLinkFilter
return $this->noFilter($visibility);
}
$filtered = array();
$filtered = [];
$search = mb_convert_case(html_entity_decode($searchterms), MB_CASE_LOWER, 'UTF-8');
$exactRegex = '/"([^"]+)"/';
// Retrieve exact search terms.
@ -198,8 +198,8 @@ class LegacyLinkFilter
$explodedSearchAnd = array_values(array_filter($explodedSearchAnd));
// Filter excluding terms and update andSearch.
$excludeSearch = array();
$andSearch = array();
$excludeSearch = [];
$andSearch = [];
foreach ($explodedSearchAnd as $needle) {
if ($needle[0] == '-' && strlen($needle) > 1) {
$excludeSearch[] = substr($needle, 1);
@ -208,7 +208,7 @@ class LegacyLinkFilter
}
}
$keys = array('title', 'description', 'url', 'tags');
$keys = ['title', 'description', 'url', 'tags'];
// Iterate over every stored link.
foreach ($this->links as $id => $link) {
@ -336,7 +336,7 @@ class LegacyLinkFilter
}
// create resulting array
$filtered = array();
$filtered = [];
// iterate over each link
foreach ($this->links as $key => $link) {
@ -352,7 +352,7 @@ class LegacyLinkFilter
$search = $link['tags']; // build search string, start with tags of current link
if (strlen(trim($link['description'])) && strpos($link['description'], '#') !== false) {
// description given and at least one possible tag found
$descTags = array();
$descTags = [];
// find all tags in the form of #tag in the description
preg_match_all(
'/(?<![' . self::$HASHTAG_CHARS . '])#([' . self::$HASHTAG_CHARS . ']+?)\b/sm',
@ -419,7 +419,7 @@ class LegacyLinkFilter
throw new Exception('Invalid date format');
}
$filtered = array();
$filtered = [];
foreach ($this->links as $key => $l) {
if ($l['created']->format('Ymd') == $day) {
$filtered[$key] = $l;

View file

@ -93,7 +93,7 @@ class LegacyUpdater
*/
public function update()
{
$updatesRan = array();
$updatesRan = [];
// If the user isn't logged in, exit without updating.
if ($this->isLoggedIn !== true) {
@ -106,7 +106,8 @@ class LegacyUpdater
foreach ($this->methods as $method) {
// Not an update method or already done, pass.
if (!startsWith($method->getName(), 'updateMethod')
if (
!startsWith($method->getName(), 'updateMethod')
|| in_array($method->getName(), $this->doneUpdates)
) {
continue;
@ -189,7 +190,7 @@ class LegacyUpdater
}
// Set sub config keys (config and plugins)
$subConfig = array('config', 'plugins');
$subConfig = ['config', 'plugins'];
foreach ($subConfig as $sub) {
foreach ($oldConfig[$sub] as $key => $value) {
if (isset($legacyMap[$sub . '.' . $key])) {
@ -259,7 +260,7 @@ class LegacyUpdater
$save = $this->conf->get('resource.data_dir') . '/datastore.' . date('YmdHis') . '.php';
copy($this->conf->get('resource.datastore'), $save);
$links = array();
$links = [];
foreach ($this->linkDB as $offset => $value) {
$links[] = $value;
unset($this->linkDB[$offset]);
@ -498,7 +499,8 @@ class LegacyUpdater
*/
public function updateMethodDownloadSizeAndTimeoutConf()
{
if ($this->conf->exists('general.download_max_size')
if (
$this->conf->exists('general.download_max_size')
&& $this->conf->exists('general.download_timeout')
) {
return true;

View file

@ -59,11 +59,11 @@ class NetscapeBookmarkUtils
$indexUrl
) {
// see tpl/export.html for possible values
if (!in_array($selection, array('all', 'public', 'private'))) {
if (!in_array($selection, ['all', 'public', 'private'])) {
throw new Exception(t('Invalid export selection:') . ' "' . $selection . '"');
}
$bookmarkLinks = array();
$bookmarkLinks = [];
foreach ($this->bookmarkService->search([], $selection) as $bookmark) {
$link = $formatter->format($bookmark);
$link['taglist'] = implode(',', $bookmark->getTags());

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Plugin;
use Shaarli\Config\ConfigManager;
@ -23,7 +24,7 @@ class PluginManager
*
* @var array $loadedPlugins
*/
private $loadedPlugins = array();
private $loadedPlugins = [];
/**
* @var ConfigManager Configuration Manager instance.
@ -57,7 +58,7 @@ class PluginManager
public function __construct(&$conf)
{
$this->conf = $conf;
$this->errors = array();
$this->errors = [];
}
/**
@ -98,7 +99,7 @@ class PluginManager
*
* @return void
*/
public function executeHooks($hook, &$data, $params = array())
public function executeHooks($hook, &$data, $params = [])
{
$metadataParameters = [
'target' => '_PAGE_',
@ -196,7 +197,7 @@ class PluginManager
*/
public function getPluginsMeta()
{
$metaData = array();
$metaData = [];
$dirs = glob(self::$PLUGINS_PATH . '/*', GLOB_ONLYDIR | GLOB_MARK);
// Browse all plugin directories.
@ -217,9 +218,9 @@ class PluginManager
if (isset($metaData[$plugin]['parameters'])) {
$params = explode(';', $metaData[$plugin]['parameters']);
} else {
$params = array();
$params = [];
}
$metaData[$plugin]['parameters'] = array();
$metaData[$plugin]['parameters'] = [];
foreach ($params as $param) {
if (empty($param)) {
continue;

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Plugin\Exception;
use Exception;

View file

@ -1,6 +1,5 @@
<?php
namespace Shaarli\Security;
use Psr\Log\LoggerInterface;
@ -47,7 +46,8 @@ class BanManager
* @param string $banFile Path to the file containing IP bans and failures
* @param LoggerInterface $logger PSR-3 logger to save login attempts in log directory
*/
public function __construct($trustedProxies, $nbAttempts, $banDuration, $banFile, LoggerInterface $logger) {
public function __construct($trustedProxies, $nbAttempts, $banDuration, $banFile, LoggerInterface $logger)
{
$this->trustedProxies = $trustedProxies;
$this->nbAttempts = $nbAttempts;
$this->banDuration = $banDuration;

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Security;
use Exception;
@ -106,7 +107,8 @@ class LoginManager
// The user client has a valid stay-signed-in cookie
// Session information is updated with the current client information
$this->sessionManager->storeLoginInfo($clientIpId);
} elseif ($this->sessionManager->hasSessionExpired()
} elseif (
$this->sessionManager->hasSessionExpired()
|| $this->sessionManager->hasClientIpChanged($clientIpId)
) {
$this->sessionManager->logout();
@ -145,7 +147,8 @@ class LoginManager
// Check credentials
try {
$useLdapLogin = !empty($this->configManager->get('ldap.host'));
if ($login === $this->configManager->get('credentials.login')
if (
$login === $this->configManager->get('credentials.login')
&& (
(false === $useLdapLogin && $this->checkCredentialsFromLocalConfig($login, $password))
|| (true === $useLdapLogin && $this->checkCredentialsFromLdap($login, $password))
@ -174,7 +177,8 @@ class LoginManager
*
* @return bool true if the provided credentials are valid, false otherwise
*/
public function checkCredentialsFromLocalConfig($login, $password) {
public function checkCredentialsFromLocalConfig($login, $password)
{
$hash = sha1($password . $login . $this->configManager->get('credentials.salt'));
return $login == $this->configManager->get('credentials.login')

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Security;
use Shaarli\Config\ConfigManager;

View file

@ -88,7 +88,8 @@ class Updater
foreach ($this->methods as $method) {
// Not an update method or already done, pass.
if (! startsWith($method->getName(), 'updateMethod')
if (
! startsWith($method->getName(), 'updateMethod')
|| in_array($method->getName(), $this->doneUpdates)
) {
continue;
@ -152,7 +153,8 @@ class Updater
$updated = false;
foreach ($this->bookmarkService->search() as $bookmark) {
if ($bookmark->isNote()
if (
$bookmark->isNote()
&& startsWith($bookmark->getUrl(), '?')
&& 1 === preg_match('/^\?([a-zA-Z0-9-_@]{6})($|&|#)/', $bookmark->getUrl(), $match)
) {

View file

@ -19,7 +19,7 @@ class UpdaterUtils
return explode(';', $content);
}
}
return array();
return [];
}
/**

View file

@ -1,4 +1,5 @@
<?php
/**
* Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
*

View file

@ -17,26 +17,26 @@ use Shaarli\Render\TemplatePage;
function hook_addlink_toolbar_render_header($data)
{
if ($data['_PAGE_'] == TemplatePage::LINKLIST && $data['_LOGGEDIN_'] === true) {
$form = array(
'attr' => array(
$form = [
'attr' => [
'method' => 'GET',
'action' => $data['_BASE_PATH_'] . '/admin/shaare',
'name' => 'addform',
'class' => 'addform',
),
'inputs' => array(
array(
],
'inputs' => [
[
'type' => 'text',
'name' => 'post',
'placeholder' => t('URI'),
),
array(
],
[
'type' => 'submit',
'value' => t('Add link'),
'class' => 'bigbutton',
),
),
);
],
],
];
$data['fields_toolbar'][] = $form;
}

View file

@ -1,4 +1,5 @@
<?php
/**
* Plugin Archive.org.
*

View file

@ -1,4 +1,5 @@
<?php
/**
* Demo Plugin.
*
@ -82,14 +83,14 @@ function hook_demo_plugin_render_header($data)
* A link is an array of its attributes (key="value"),
* and a mandatory `html` key, which contains its value.
*/
$button = array(
'attr' => array (
$button = [
'attr' => [
'href' => '#',
'class' => 'mybutton',
'title' => 'hover me',
),
],
'html' => 'DEMO buttons toolbar',
);
];
$data['buttons_toolbar'][] = $button;
}
@ -115,29 +116,29 @@ function hook_demo_plugin_render_header($data)
* <input input-2-attribute-1="input 2 attribute 1 value">
* </form>
*/
$form = array(
'attr' => array(
$form = [
'attr' => [
'method' => 'GET',
'action' => $data['_BASE_PATH_'] . '/',
'class' => 'addform',
),
'inputs' => array(
array(
],
'inputs' => [
[
'type' => 'text',
'name' => 'demo',
'placeholder' => 'demo',
)
)
);
]
]
];
$data['fields_toolbar'][] = $form;
}
// Another button always displayed
$button = array(
'attr' => array(
$button = [
'attr' => [
'href' => '#',
),
],
'html' => 'Demo',
);
];
$data['buttons_toolbar'][] = $button;
return $data;
@ -229,13 +230,13 @@ function hook_demo_plugin_render_linklist($data)
* and a mandatory `html` key, which contains its value.
* It's also recommended to add key 'on' or 'off' for theme rendering.
*/
$action = array(
'attr' => array(
$action = [
'attr' => [
'href' => '?up',
'title' => 'Uppercase!',
),
],
'html' => '←',
);
];
if (isset($_GET['up'])) {
// Manipulate link data

View file

@ -21,7 +21,7 @@ function isso_init($conf)
if (empty($issoUrl)) {
$error = t('Isso plugin error: ' .
'Please define the "ISSO_SERVER" setting in the plugin administration page.');
return array($error);
return [$error];
}
}

View file

@ -1,4 +1,5 @@
<?php
/**
* Piwik plugin.
* Adds tracking code on each page.
@ -22,7 +23,7 @@ function piwik_init($conf)
if (empty($piwikUrl) || empty($piwikSiteid)) {
$error = t('Piwik plugin error: ' .
'Please define PIWIK_URL and PIWIK_SITEID in the plugin administration page.');
return array($error);
return [$error];
}
}

View file

@ -1,4 +1,5 @@
<?php
/**
* Plugin PlayVideos
*
@ -19,14 +20,14 @@ use Shaarli\Render\TemplatePage;
function hook_playvideos_render_header($data)
{
if ($data['_PAGE_'] == TemplatePage::LINKLIST) {
$playvideo = array(
'attr' => array(
$playvideo = [
'attr' => [
'href' => '#',
'title' => t('Video player'),
'id' => 'playvideos',
),
],
'html' => '► ' . t('Play Videos')
);
];
$data['buttons_toolbar'][] = $playvideo;
}

View file

@ -59,10 +59,10 @@ function hook_pubsubhubbub_render_feed($data, $conf)
*/
function hook_pubsubhubbub_save_link($data, $conf)
{
$feeds = array(
$feeds = [
index_url($_SERVER) . 'feed/atom',
index_url($_SERVER) . 'feed/rss',
);
];
$httpPost = function_exists('curl_version') ? false : 'nocurl_http_post';
try {
@ -87,11 +87,11 @@ function hook_pubsubhubbub_save_link($data, $conf)
*/
function nocurl_http_post($url, $postString)
{
$params = array('http' => array(
$params = ['http' => [
'method' => 'POST',
'content' => $postString,
'user_agent' => 'PubSubHubbub-Publisher-PHP/1.0',
));
]];
$context = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $context);

View file

@ -1,4 +1,5 @@
<?php
/**
* Plugin qrcode
* Add QRCode containing URL for each links.

View file

@ -1,4 +1,5 @@
<?php
namespace Shaarli\Plugin\Wallabag;
/**
@ -11,20 +12,20 @@ class WallabagInstance
* - key: version ID, must match plugin settings.
* - value: version name.
*/
private static $wallabagVersions = array(
private static $wallabagVersions = [
1 => '1.x',
2 => '2.x',
);
];
/**
* @var array Static reference to WB endpoint according to the API version.
* - key: version name.
* - value: endpoint.
*/
private static $wallabagEndpoints = array(
private static $wallabagEndpoints = [
'1.x' => '?plainurl=',
'2.x' => 'bookmarklet?url=',
);
];
/**
* @var string Wallabag user instance URL.

View file

@ -1,4 +1,5 @@
<?php
/**
* Wallabag plugin
*/
@ -20,7 +21,7 @@ function wallabag_init($conf)
if (empty($wallabagUrl)) {
$error = t('Wallabag plugin error: ' .
'Please define the "WALLABAG_URL" setting in the plugin administration page.');
return array($error);
return [$error];
}
$conf->setEmpty('plugins.WALLABAG_URL', '2');
}