diff --git a/application/History.php b/application/History.php
index bd5c1bf7..1be955c5 100644
--- a/application/History.php
+++ b/application/History.php
@@ -1,4 +1,5 @@
language = $confLanguage;
}
- if (! extension_loaded('gettext')
+ if (
+ ! extension_loaded('gettext')
|| in_array($this->conf->get('translation.mode', 'auto'), ['auto', 'php'])
) {
$this->initPhpTranslator();
@@ -98,7 +99,7 @@ class Languages
$this->translator->loadDomain(self::DEFAULT_DOMAIN, 'inc/languages');
// Default extension translation from the current theme
- $themeTransFolder = rtrim($this->conf->get('raintpl_tpl'), '/') .'/'. $this->conf->get('theme') .'/language';
+ $themeTransFolder = rtrim($this->conf->get('raintpl_tpl'), '/') . '/' . $this->conf->get('theme') . '/language';
if (is_dir($themeTransFolder)) {
$this->translator->loadDomain($this->conf->get('theme'), $themeTransFolder, false);
}
@@ -121,7 +122,7 @@ class Languages
$translations = new Translations();
// Core translations
try {
- $translations = $translations->addFromPoFile('inc/languages/'. $this->language .'/LC_MESSAGES/shaarli.po');
+ $translations = $translations->addFromPoFile('inc/languages/' . $this->language . '/LC_MESSAGES/shaarli.po');
$translations->setDomain('shaarli');
$this->translator->loadTranslations($translations);
} catch (\InvalidArgumentException $e) {
@@ -129,11 +130,11 @@ class Languages
// Default extension translation from the current theme
$theme = $this->conf->get('theme');
- $themeTransFolder = rtrim($this->conf->get('raintpl_tpl'), '/') .'/'. $theme .'/language';
+ $themeTransFolder = rtrim($this->conf->get('raintpl_tpl'), '/') . '/' . $theme . '/language';
if (is_dir($themeTransFolder)) {
try {
$translations = Translations::fromPoFile(
- $themeTransFolder .'/'. $this->language .'/LC_MESSAGES/'. $theme .'.po'
+ $themeTransFolder . '/' . $this->language . '/LC_MESSAGES/' . $theme . '.po'
);
$translations->setDomain($theme);
$this->translator->loadTranslations($translations);
@@ -149,7 +150,7 @@ class Languages
try {
$extension = Translations::fromPoFile(
- $translationPath . $this->language .'/LC_MESSAGES/'. $domain .'.po'
+ $translationPath . $this->language . '/LC_MESSAGES/' . $domain . '.po'
);
$extension->setDomain($domain);
$this->translator->loadTranslations($extension);
diff --git a/application/Thumbnailer.php b/application/Thumbnailer.php
index 5aec23c8..30354310 100644
--- a/application/Thumbnailer.php
+++ b/application/Thumbnailer.php
@@ -60,7 +60,7 @@ class Thumbnailer
// TODO: create a proper error handling system able to catch exceptions...
die(t(
'php-gd extension must be loaded to use thumbnails. '
- .'Thumbnails are now disabled. Please reload the page.'
+ . 'Thumbnails are now disabled. Please reload the page.'
));
}
@@ -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;
diff --git a/application/TimeZone.php b/application/TimeZone.php
index c1869ef8..a420eb96 100644
--- a/application/TimeZone.php
+++ b/application/TimeZone.php
@@ -1,4 +1,5 @@
$continent, 'city' => $city];
$continents[$continent] = true;
}
@@ -85,7 +86,7 @@ function generateTimeZoneData($installedTimeZones, $preselectedTimezone = '')
function isTimeZoneValid($continent, $city)
{
return in_array(
- $continent.'/'.$city,
+ $continent . '/' . $city,
timezone_identifiers_list()
);
}
diff --git a/application/Utils.php b/application/Utils.php
index db046893..4c2d6701 100644
--- a/application/Utils.php
+++ b/application/Utils.php
@@ -1,4 +1,5 @@
$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 = [];
@@ -376,7 +377,7 @@ function return_bytes($val)
return $val;
}
$val = trim($val);
- $last = strtolower($val[strlen($val)-1]);
+ $last = strtolower($val[strlen($val) - 1]);
$val = intval(substr($val, 0, -1));
switch ($last) {
case 'g':
@@ -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();
}
-
diff --git a/application/api/ApiMiddleware.php b/application/api/ApiMiddleware.php
index adc8b266..9fb88358 100644
--- a/application/api/ApiMiddleware.php
+++ b/application/api/ApiMiddleware.php
@@ -1,4 +1,5 @@
hasHeader('Authorization')
+ if (
+ !$request->hasHeader('Authorization')
&& !isset($this->container->environment['REDIRECT_HTTP_AUTHORIZATION'])
) {
throw new ApiAuthorizationException('JWT token not provided');
diff --git a/application/api/ApiUtils.php b/application/api/ApiUtils.php
index eb1ca9bc..05a2840a 100644
--- a/application/api/ApiUtils.php
+++ b/application/api/ApiUtils.php
@@ -1,4 +1,5 @@
iat)
+ if (
+ empty($payload->iat)
|| $payload->iat > time()
|| time() - $payload->iat > ApiMiddleware::$TOKEN_DURATION
) {
diff --git a/application/api/controllers/HistoryController.php b/application/api/controllers/HistoryController.php
index 505647a9..d83a3a25 100644
--- a/application/api/controllers/HistoryController.php
+++ b/application/api/controllers/HistoryController.php
@@ -1,6 +1,5 @@
$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);
diff --git a/application/api/controllers/Links.php b/application/api/controllers/Links.php
index 6bf529e4..c379b962 100644
--- a/application/api/controllers/Links.php
+++ b/application/api/controllers/Links.php
@@ -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
) {
diff --git a/application/api/exceptions/ApiAuthorizationException.php b/application/api/exceptions/ApiAuthorizationException.php
index 0e3f4776..c77e9eea 100644
--- a/application/api/exceptions/ApiAuthorizationException.php
+++ b/application/api/exceptions/ApiAuthorizationException.php
@@ -28,7 +28,7 @@ class ApiAuthorizationException extends ApiException
*/
public function setMessage($message)
{
- $original = $this->debug === true ? ': '. $this->getMessage() : '';
+ $original = $this->debug === true ? ': ' . $this->getMessage() : '';
$this->message = $message . $original;
}
}
diff --git a/application/api/exceptions/ApiException.php b/application/api/exceptions/ApiException.php
index d6b66323..7deafb96 100644
--- a/application/api/exceptions/ApiException.php
+++ b/application/api/exceptions/ApiException.php
@@ -44,7 +44,7 @@ abstract class ApiException extends \Exception
}
return [
'message' => $this->getMessage(),
- 'stacktrace' => get_class($this) .': '. $this->getTraceAsString()
+ 'stacktrace' => get_class($this) . ': ' . $this->getTraceAsString()
];
}
diff --git a/application/bookmark/Bookmark.php b/application/bookmark/Bookmark.php
index 8aaeb9d8..b592722f 100644
--- a/application/bookmark/Bookmark.php
+++ b/application/bookmark/Bookmark.php
@@ -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)
@@ -114,7 +115,7 @@ class Bookmark
throw new InvalidBookmarkException($this);
}
if (empty($this->url)) {
- $this->url = '/shaare/'. $this->shortUrl;
+ $this->url = '/shaare/' . $this->shortUrl;
}
if (empty($this->title)) {
$this->title = $this->url;
diff --git a/application/bookmark/BookmarkArray.php b/application/bookmark/BookmarkArray.php
index 67bb3b73..b9328116 100644
--- a/application/bookmark/BookmarkArray.php
+++ b/application/bookmark/BookmarkArray.php
@@ -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]])
) {
diff --git a/application/bookmark/BookmarkFileService.php b/application/bookmark/BookmarkFileService.php
index 85efeea6..66248cc2 100644
--- a/application/bookmark/BookmarkFileService.php
+++ b/application/bookmark/BookmarkFileService.php
@@ -69,7 +69,7 @@ class BookmarkFileService implements BookmarkServiceInterface
} else {
try {
$this->bookmarks = $this->bookmarksIO->read();
- } catch (EmptyDataStoreException|DatastoreNotInitializedException $e) {
+ } catch (EmptyDataStoreException | DatastoreNotInitializedException $e) {
$this->bookmarks = new BookmarkArray();
if ($this->isLoggedIn) {
@@ -85,7 +85,7 @@ class BookmarkFileService implements BookmarkServiceInterface
if (! $this->bookmarks instanceof BookmarkArray) {
$this->migrate();
exit(
- 'Your data store has been migrated, please reload the page.'. PHP_EOL .
+ 'Your data store has been migrated, please reload the page.' . PHP_EOL .
'If this message keeps showing up, please delete data/updates.txt 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)
@@ -356,7 +360,7 @@ class BookmarkFileService implements BookmarkServiceInterface
foreach ($this->search([], null, false, false, true) as $bookmark) {
if ($to < $bookmark->getCreated()) {
$next = $bookmark->getCreated();
- } else if ($from < $bookmark->getCreated() && $to > $bookmark->getCreated()) {
+ } elseif ($from < $bookmark->getCreated() && $to > $bookmark->getCreated()) {
$out[] = $bookmark;
} else {
if ($previous !== null) {
diff --git a/application/bookmark/BookmarkFilter.php b/application/bookmark/BookmarkFilter.php
index 5d8733dc..db83c51c 100644
--- a/application/bookmark/BookmarkFilter.php
+++ b/application/bookmark/BookmarkFilter.php
@@ -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(
'/(?getTagsString($this->conf->get('general.tags_separator', ' '));
- $content = mb_convert_case($link->getTitle(), MB_CASE_LOWER, 'UTF-8') .'\\';
- $content .= mb_convert_case($link->getDescription(), MB_CASE_LOWER, 'UTF-8') .'\\';
- $content .= mb_convert_case($link->getUrl(), MB_CASE_LOWER, 'UTF-8') .'\\';
- $content .= mb_convert_case($tagString, MB_CASE_LOWER, 'UTF-8') .'\\';
+ $content = mb_convert_case($link->getTitle(), MB_CASE_LOWER, 'UTF-8') . '\\';
+ $content .= mb_convert_case($link->getDescription(), MB_CASE_LOWER, 'UTF-8') . '\\';
+ $content .= mb_convert_case($link->getUrl(), MB_CASE_LOWER, 'UTF-8') . '\\';
+ $content .= mb_convert_case($tagString, MB_CASE_LOWER, 'UTF-8') . '\\';
$lengths['title'] = ['start' => 0, 'end' => mb_strlen($link->getTitle())];
$nextField = $lengths['title']['end'] + 1;
diff --git a/application/bookmark/BookmarkIO.php b/application/bookmark/BookmarkIO.php
index f40fa476..c78dbe41 100644
--- a/application/bookmark/BookmarkIO.php
+++ b/application/bookmark/BookmarkIO.php
@@ -112,12 +112,12 @@ class BookmarkIO
if (is_file($this->datastore) && !is_writeable($this->datastore)) {
// The datastore exists but is not writeable
throw new NotWritableDataStoreException($this->datastore);
- } else if (!is_file($this->datastore) && !is_writeable(dirname($this->datastore))) {
+ } elseif (!is_file($this->datastore) && !is_writeable(dirname($this->datastore))) {
// The datastore does not exist and its parent directory is not writeable
throw new NotWritableDataStoreException(dirname($this->datastore));
}
- $data = self::$phpPrefix.base64_encode(gzdeflate(serialize($links))).self::$phpSuffix;
+ $data = self::$phpPrefix . base64_encode(gzdeflate(serialize($links))) . self::$phpSuffix;
$this->mutex->synchronized(function () use ($data) {
file_put_contents(
diff --git a/application/bookmark/BookmarkInitializer.php b/application/bookmark/BookmarkInitializer.php
index 98dd3f1c..2240f58c 100644
--- a/application/bookmark/BookmarkInitializer.php
+++ b/application/bookmark/BookmarkInitializer.php
@@ -39,7 +39,7 @@ class BookmarkInitializer
$bookmark->setTitle('Calm Jazz Music - YouTube ' . t('(private bookmark with thumbnail demo)'));
$bookmark->setUrl('https://www.youtube.com/watch?v=DVEUcbPkb-c');
$bookmark->setDescription(t(
-'Shaarli will automatically pick up the thumbnail for links to a variety of websites.
+ 'Shaarli will automatically pick up the thumbnail for links to a variety of websites.
Explore your new Shaarli instance by trying out controls and menus.
Visit the project on [Github](https://github.com/shaarli/Shaarli) or [the documentation](https://shaarli.readthedocs.io/en/master/) to learn more about Shaarli.
@@ -54,7 +54,7 @@ Now you can edit or delete the default shaares.
$bookmark = new Bookmark();
$bookmark->setTitle(t('Note: Shaare descriptions'));
$bookmark->setDescription(t(
-'Adding a shaare without entering a URL creates a text-only "note" post such as this one.
+ 'Adding a shaare without entering a URL creates a text-only "note" post such as this one.
This note is private, so you are the only one able to see it while logged in.
You can use this to keep notes, post articles, code snippets, and much more.
@@ -91,7 +91,7 @@ Markdown also supports tables:
'Shaarli - ' . t('The personal, minimalist, super-fast, database free, bookmarking service')
);
$bookmark->setDescription(t(
-'Welcome to Shaarli!
+ 'Welcome to Shaarli!
Shaarli allows you to bookmark your favorite pages, and share them with others or store them privately.
You can add a description to your bookmarks, such as this one, and tag them.
diff --git a/application/bookmark/LinkUtils.php b/application/bookmark/LinkUtils.php
index cf97e3b0..d65e97ed 100644
--- a/application/bookmark/LinkUtils.php
+++ b/application/bookmark/LinkUtils.php
@@ -67,14 +67,15 @@ function html_extract_tag($tag, $html)
$propertiesKey = ['property', 'name', 'itemprop'];
$properties = implode('|', $propertiesKey);
// We need a OR here to accept either 'property=og:noquote' or 'property="og:unrelated og:my-tag"'
- $orCondition = '["\']?(?:og:)?'. $tag .'["\']?|["\'][^\'"]*?(?:og:)?' . $tag . '[^\'"]*?[\'"]';
+ $orCondition = '["\']?(?:og:)?' . $tag . '["\']?|["\'][^\'"]*?(?:og:)?' . $tag . '[^\'"]*?[\'"]';
// Try to retrieve OpenGraph tag.
- $ogRegex = '#]+(?:'. $properties .')=(?:'. $orCondition .')[^>]*content=(["\'])([^\1]*?)\1.*?>#';
+ $ogRegex = '#]+(?:' . $properties . ')=(?:' . $orCondition . ')[^>]*content=(["\'])([^\1]*?)\1.*?>#';
// If the attributes are not in the order property => content (e.g. Github)
// New regex to keep this readable... more or less.
- $ogRegexReverse = '#]+content=(["\'])([^\1]*?)\1[^>]+(?:'. $properties .')=(?:'. $orCondition .').*?>#';
+ $ogRegexReverse = '#]+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];
@@ -116,7 +117,7 @@ function hashtag_autolink($description, $indexUrl = '')
* \p{Mn} - any non marking space (accents, umlauts, etc)
*/
$regex = '/(^|\s)#([\p{Pc}\p{N}\p{L}\p{Mn}]+)/mui';
- $replacement = '$1#$2';
+ $replacement = '$1#$2';
return preg_replace($regex, $replacement, $description);
}
diff --git a/application/bookmark/exception/BookmarkNotFoundException.php b/application/bookmark/exception/BookmarkNotFoundException.php
index 827a3d35..a91d1efa 100644
--- a/application/bookmark/exception/BookmarkNotFoundException.php
+++ b/application/bookmark/exception/BookmarkNotFoundException.php
@@ -1,4 +1,5 @@
message = 'This bookmark is not valid'. PHP_EOL;
- $this->message .= ' - ID: '. $bookmark->getId() . PHP_EOL;
- $this->message .= ' - Title: '. $bookmark->getTitle() . PHP_EOL;
- $this->message .= ' - Url: '. $bookmark->getUrl() . PHP_EOL;
- $this->message .= ' - ShortUrl: '. $bookmark->getShortUrl() . PHP_EOL;
- $this->message .= ' - Created: '. $created . PHP_EOL;
+ $this->message = 'This bookmark is not valid' . PHP_EOL;
+ $this->message .= ' - ID: ' . $bookmark->getId() . PHP_EOL;
+ $this->message .= ' - Title: ' . $bookmark->getTitle() . PHP_EOL;
+ $this->message .= ' - Url: ' . $bookmark->getUrl() . PHP_EOL;
+ $this->message .= ' - ShortUrl: ' . $bookmark->getShortUrl() . PHP_EOL;
+ $this->message .= ' - Created: ' . $created . PHP_EOL;
} else {
- $this->message = 'The provided data is not a bookmark'. PHP_EOL;
+ $this->message = 'The provided data is not a bookmark' . PHP_EOL;
$this->message .= var_export($bookmark, true);
}
}
diff --git a/application/bookmark/exception/NotWritableDataStoreException.php b/application/bookmark/exception/NotWritableDataStoreException.php
index 95f34b50..df91f3bc 100644
--- a/application/bookmark/exception/NotWritableDataStoreException.php
+++ b/application/bookmark/exception/NotWritableDataStoreException.php
@@ -1,9 +1,7 @@
message = 'Couldn\'t load data from the data store file "'. $dataStore .'". '.
+ $this->message = 'Couldn\'t load data from the data store file "' . $dataStore . '". ' .
'Your data might be corrupted, or your file isn\'t readable.';
}
}
diff --git a/application/config/ConfigIO.php b/application/config/ConfigIO.php
index 3efe5b6f..a623bc8b 100644
--- a/application/config/ConfigIO.php
+++ b/application/config/ConfigIO.php
@@ -1,4 +1,5 @@
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');
}
diff --git a/application/config/ConfigPhp.php b/application/config/ConfigPhp.php
index cad34594..53d6a7a3 100644
--- a/application/config/ConfigPhp.php
+++ b/application/config/ConfigPhp.php
@@ -1,4 +1,5 @@
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] : '';
}
@@ -95,7 +96,7 @@ class ConfigPhp implements ConfigIO
*/
public function write($filepath, $conf)
{
- $configStr = ' $value) {
$configStr .= '$GLOBALS[\'config\'][\''
. $key
- .'\'] = '
- .var_export($conf['config'][$key], true).';'
+ . '\'] = '
+ . var_export($conf['config'][$key], true) . ';'
. PHP_EOL;
}
@@ -115,18 +116,19 @@ class ConfigPhp implements ConfigIO
foreach ($conf['plugins'] as $key => $value) {
$configStr .= '$GLOBALS[\'plugins\'][\''
. $key
- .'\'] = '
- .var_export($conf['plugins'][$key], true).';'
+ . '\'] = '
+ . var_export($conf['plugins'][$key], true) . ';'
. PHP_EOL;
}
}
- if (!file_put_contents($filepath, $configStr)
+ if (
+ !file_put_contents($filepath, $configStr)
|| strcmp(file_get_contents($filepath), $configStr) != 0
) {
throw new \Shaarli\Exceptions\IOException(
$filepath,
- t('Shaarli could not create the config file. '.
+ t('Shaarli could not create the config file. ' .
'Please make sure Shaarli has the right to write in the folder is it installed in.')
);
}
diff --git a/application/config/ConfigPlugin.php b/application/config/ConfigPlugin.php
index ea8dfbda..6cadef12 100644
--- a/application/config/ConfigPlugin.php
+++ b/application/config/ConfigPlugin.php
@@ -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)) {
diff --git a/application/config/exception/MissingFieldConfigException.php b/application/config/exception/MissingFieldConfigException.php
index 9e0a9359..a5f4356a 100644
--- a/application/config/exception/MissingFieldConfigException.php
+++ b/application/config/exception/MissingFieldConfigException.php
@@ -1,6 +1,5 @@
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);
}
@@ -176,9 +177,9 @@ class FeedBuilder
$data = $this->formatter->format($link);
$data['guid'] = rtrim($pageaddr, '/') . '/shaare/' . $data['shorturl'];
if ($this->usePermalinks === true) {
- $permalink = ''. t('Direct link') .'';
+ $permalink = '' . t('Direct link') . '';
} else {
- $permalink = ''. t('Permalink') .'';
+ $permalink = '' . t('Permalink') . '';
}
$data['description'] .= PHP_EOL . PHP_EOL . '
— ' . $permalink;
diff --git a/application/formatter/BookmarkMarkdownFormatter.php b/application/formatter/BookmarkMarkdownFormatter.php
index f7714be9..052333ca 100644
--- a/application/formatter/BookmarkMarkdownFormatter.php
+++ b/application/formatter/BookmarkMarkdownFormatter.php
@@ -71,7 +71,7 @@ class BookmarkMarkdownFormatter extends BookmarkDefaultFormatter
$processedDescription = $this->replaceTokens($processedDescription);
if (!empty($processedDescription)) {
- $processedDescription = '
Sessions do not seem to work correctly on your server.
'. - 'Make sure the variable "session.save_path" is set correctly in your PHP config, '. - 'and that you have write access to it.
'. - 'It currently points to %s.
'. - 'On some browsers, accessing your server via a hostname like \'localhost\' '. - 'or any custom hostname without a dot causes cookie storage to fail. '. + 'Sessions do not seem to work correctly on your server.
' . + 'Make sure the variable "session.save_path" is set correctly in your PHP config, ' . + 'and that you have write access to it.
' . + 'It currently points to %s.
' . + 'On some browsers, accessing your server via a hostname like \'localhost\' ' . + 'or any custom hostname without a dot causes cookie storage to fail. ' . 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.
' ); $msg = sprintf($msg, $this->container->sessionManager->getSavePath()); @@ -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')) ) { @@ -114,7 +117,7 @@ class InstallController extends ShaarliVisitorController $login = $request->getParam('setlogin'); $this->container->conf->set('credentials.login', $login); - $salt = sha1(uniqid('', true) .'_'. mt_rand()); + $salt = sha1(uniqid('', true) . '_' . mt_rand()); $this->container->conf->set('credentials.salt', $salt); $this->container->conf->set('credentials.hash', sha1($request->getParam('setpassword') . $login . $salt)); @@ -123,7 +126,7 @@ class InstallController extends ShaarliVisitorController } else { $this->container->conf->set( 'general.title', - 'Shared bookmarks on '.escape(index_url($this->container->environment)) + 'Shared bookmarks on ' . escape(index_url($this->container->environment)) ); } diff --git a/application/front/controller/visitor/LoginController.php b/application/front/controller/visitor/LoginController.php index f5038fe3..4b881535 100644 --- a/application/front/controller/visitor/LoginController.php +++ b/application/front/controller/visitor/LoginController.php @@ -43,7 +43,7 @@ class LoginController extends ShaarliVisitorController $this ->assignView('returnurl', escape($returnUrl)) ->assignView('remember_user_default', $this->container->conf->get('privacy.remember_user_default', true)) - ->assignView('pagetitle', t('Login') .' - '. $this->container->conf->get('general.title', 'Shaarli')) + ->assignView('pagetitle', t('Login') . ' - ' . $this->container->conf->get('general.title', 'Shaarli')) ; return $response->write($this->render(TemplatePage::LOGIN)); @@ -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(); diff --git a/application/front/controller/visitor/PictureWallController.php b/application/front/controller/visitor/PictureWallController.php index 3c57f8dd..23553ee6 100644 --- a/application/front/controller/visitor/PictureWallController.php +++ b/application/front/controller/visitor/PictureWallController.php @@ -26,7 +26,7 @@ class PictureWallController extends ShaarliVisitorController $this->assignView( 'pagetitle', - t('Picture wall') .' - '. $this->container->conf->get('general.title', 'Shaarli') + t('Picture wall') . ' - ' . $this->container->conf->get('general.title', 'Shaarli') ); // Optionally filter the results: diff --git a/application/front/controller/visitor/ShaarliVisitorController.php b/application/front/controller/visitor/ShaarliVisitorController.php index 54f9fe03..ae946c59 100644 --- a/application/front/controller/visitor/ShaarliVisitorController.php +++ b/application/front/controller/visitor/ShaarliVisitorController.php @@ -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); @@ -173,7 +174,7 @@ abstract class ShaarliVisitorController } } - $queryString = count($params) > 0 ? '?'. http_build_query($params) : ''; + $queryString = count($params) > 0 ? '?' . http_build_query($params) : ''; $anchor = $anchor ? '#' . $anchor : ''; return $response->withRedirect($path . $queryString . $anchor); diff --git a/application/front/controller/visitor/TagCloudController.php b/application/front/controller/visitor/TagCloudController.php index 560cad08..46d62779 100644 --- a/application/front/controller/visitor/TagCloudController.php +++ b/application/front/controller/visitor/TagCloudController.php @@ -84,10 +84,10 @@ class TagCloudController extends ShaarliVisitorController $this->executePageHooks('render_tag' . $type, $data, 'tag.' . $type); $this->assignAllView($data); - $searchTags = !empty($searchTags) ? trim(str_replace($tagsSeparator, ' ', $searchTags)) .' - ' : ''; + $searchTags = !empty($searchTags) ? trim(str_replace($tagsSeparator, ' ', $searchTags)) . ' - ' : ''; $this->assignView( 'pagetitle', - $searchTags . t('Tag '. $type) .' - '. $this->container->conf->get('general.title', 'Shaarli') + $searchTags . t('Tag ' . $type) . ' - ' . $this->container->conf->get('general.title', 'Shaarli') ); return $response->write($this->render('tag.' . $type)); diff --git a/application/front/controller/visitor/TagController.php b/application/front/controller/visitor/TagController.php index 7a3377a7..3aa58542 100644 --- a/application/front/controller/visitor/TagController.php +++ b/application/front/controller/visitor/TagController.php @@ -27,7 +27,7 @@ class TagController extends ShaarliVisitorController // In case browser does not send HTTP_REFERER, we search a single tag if (null === $referer) { if (null !== $newTag) { - return $this->redirect($response, '/?searchtags='. urlencode($newTag)); + return $this->redirect($response, '/?searchtags=' . urlencode($newTag)); } return $this->redirect($response, '/'); @@ -37,7 +37,7 @@ class TagController extends ShaarliVisitorController parse_str($currentUrl['query'] ?? '', $params); if (null === $newTag) { - return $response->withRedirect(($currentUrl['path'] ?? './') .'?'. http_build_query($params)); + return $response->withRedirect(($currentUrl['path'] ?? './') . '?' . http_build_query($params)); } // Prevent redirection loop @@ -68,7 +68,7 @@ class TagController extends ShaarliVisitorController // We also remove page (keeping the same page has no sense, since the results are different) unset($params['page']); - return $response->withRedirect(($currentUrl['path'] ?? './') .'?'. http_build_query($params)); + return $response->withRedirect(($currentUrl['path'] ?? './') . '?' . http_build_query($params)); } /** @@ -90,7 +90,7 @@ class TagController extends ShaarliVisitorController parse_str($currentUrl['query'] ?? '', $params); if (null === $tagToRemove) { - return $response->withRedirect(($currentUrl['path'] ?? './') .'?'. http_build_query($params)); + return $response->withRedirect(($currentUrl['path'] ?? './') . '?' . http_build_query($params)); } // Prevent redirection loop diff --git a/application/helper/ApplicationUtils.php b/application/helper/ApplicationUtils.php index 4b34e114..212dd8e2 100644 --- a/application/helper/ApplicationUtils.php +++ b/application/helper/ApplicationUtils.php @@ -1,4 +1,5 @@ '; @@ -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 ([ - 'application', - 'inc', - 'plugins', - $rainTplDir, - $rainTplDir . '/' . $conf->get('resource.theme'), - ] as $path) { + foreach ( + [ + 'application', + 'inc', + 'plugins', + $rainTplDir, + $rainTplDir . '/' . $conf->get('resource.theme'), + ] as $path + ) { if (!is_readable(realpath($path))) { $errors[] = '"' . $path . '" ' . t('directory is not readable'); } @@ -203,10 +206,10 @@ class ApplicationUtils ]; } else { $folders = [ - $conf->get('resource.thumbnails_cache'), - $conf->get('resource.data_dir'), - $conf->get('resource.page_cache'), - $conf->get('resource.raintpl_tmp'), + $conf->get('resource.thumbnails_cache'), + $conf->get('resource.data_dir'), + $conf->get('resource.page_cache'), + $conf->get('resource.raintpl_tmp'), ]; } @@ -224,13 +227,15 @@ class ApplicationUtils } // Check configuration files are readable and writable - foreach (array( - $conf->getConfigFileExt(), - $conf->get('resource.datastore'), - $conf->get('resource.ban_file'), - $conf->get('resource.log'), - $conf->get('resource.update_check'), - ) as $path) { + foreach ( + [ + $conf->getConfigFileExt(), + $conf->get('resource.datastore'), + $conf->get('resource.ban_file'), + $conf->get('resource.log'), + $conf->get('resource.update_check'), + ] as $path + ) { if (!is_file(realpath($path))) { # the file may not exist yet continue; diff --git a/application/helper/FileUtils.php b/application/helper/FileUtils.php index 2eac0793..e8a2168c 100644 --- a/application/helper/FileUtils.php +++ b/application/helper/FileUtils.php @@ -105,7 +105,7 @@ class FileUtils } foreach (new \DirectoryIterator($path) as $file) { - if($file->isDot()) { + if ($file->isDot()) { continue; } @@ -116,7 +116,7 @@ class FileUtils if ($file->isFile()) { unlink($file->getPathname()); - } elseif($file->isDir()) { + } elseif ($file->isDir()) { $skipped = static::clearFolder($file->getRealPath(), true, $exclude) || $skipped; } } diff --git a/application/http/HttpUtils.php b/application/http/HttpUtils.php index ed1002b0..4bde1d5b 100644 --- a/application/http/HttpUtils.php +++ b/application/http/HttpUtils.php @@ -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); @@ -90,7 +90,7 @@ function get_http_response( curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); // Max download size management - curl_setopt($ch, CURLOPT_BUFFERSIZE, 1024*16); + curl_setopt($ch, CURLOPT_BUFFERSIZE, 1024 * 16); curl_setopt($ch, CURLOPT_NOPROGRESS, false); if (is_callable($curlHeaderFunction)) { curl_setopt($ch, CURLOPT_HEADERFUNCTION, $curlHeaderFunction); @@ -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]; } /** @@ -270,7 +272,7 @@ function getAbsoluteUrl($originalUrl, $newUrl) } $parts = parse_url($originalUrl); - $final = $parts['scheme'] .'://'. $parts['host']; + $final = $parts['scheme'] . '://' . $parts['host']; $final .= (!empty($parts['port'])) ? $parts['port'] : ''; $final .= '/'; if ($newUrl[0] != '/') { @@ -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; @@ -344,22 +347,26 @@ function server_url($server) $host = $server['SERVER_NAME']; } - return $scheme.'://'.$host.$port; + return $scheme . '://' . $host . $port; } // 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')) { - $port = ':'.$server['SERVER_PORT']; + if ( + ($scheme == 'http' && $server['SERVER_PORT'] != '80') + || ($scheme == 'https' && $server['SERVER_PORT'] != '443') + ) { + $port = ':' . $server['SERVER_PORT']; } - return $scheme.'://'.$server['SERVER_NAME'].$port; + return $scheme . '://' . $server['SERVER_NAME'] . $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, @@ -601,7 +611,7 @@ function get_curl_download_callback( $foundChunk = $currentChunk; // Keywords use the format tag1, tag2 multiple words, tag // So we split the result with `,`, then if a tag contains the separator we replace it by `-`. - $keywords = tags_array2str(array_map(function(string $keyword) use ($tagsSeparator): string { + $keywords = tags_array2str(array_map(function (string $keyword) use ($tagsSeparator): string { return tags_array2str(tags_str2array($keyword, $tagsSeparator), '-'); }, tags_str2array($keywords, ',')), $tagsSeparator); } @@ -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)) diff --git a/application/http/Url.php b/application/http/Url.php index 90444a2f..fe87088f 100644 --- a/application/http/Url.php +++ b/application/http/Url.php @@ -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; } } diff --git a/application/http/UrlUtils.php b/application/http/UrlUtils.php index e8d1a283..de5b7db1 100644 --- a/application/http/UrlUtils.php +++ b/application/http/UrlUtils.php @@ -1,4 +1,5 @@ container->loginManager->isLoggedIn()) { $parameters = $buildParameters($request->getQueryParams(), true); - return $this->redirect($response, '/login?returnurl='. $this->getBasePath() . $route . $parameters); + return $this->redirect($response, '/login?returnurl=' . $this->getBasePath() . $route . $parameters); } $parameters = $buildParameters($request->getQueryParams(), false); diff --git a/application/legacy/LegacyLinkDB.php b/application/legacy/LegacyLinkDB.php index 5c02a21b..442b833c 100644 --- a/application/legacy/LegacyLinkDB.php +++ b/application/legacy/LegacyLinkDB.php @@ -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; } diff --git a/application/legacy/LegacyLinkFilter.php b/application/legacy/LegacyLinkFilter.php index 7cf93d60..e6d186c4 100644 --- a/application/legacy/LegacyLinkFilter.php +++ b/application/legacy/LegacyLinkFilter.php @@ -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( '/(?links as $key => $l) { if ($l['created']->format('Ymd') == $day) { $filtered[$key] = $l; diff --git a/application/legacy/LegacyUpdater.php b/application/legacy/LegacyUpdater.php index ed949b1e..9bda54b8 100644 --- a/application/legacy/LegacyUpdater.php +++ b/application/legacy/LegacyUpdater.php @@ -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; diff --git a/application/netscape/NetscapeBookmarkUtils.php b/application/netscape/NetscapeBookmarkUtils.php index 6ca728b7..2d97b4c8 100644 --- a/application/netscape/NetscapeBookmarkUtils.php +++ b/application/netscape/NetscapeBookmarkUtils.php @@ -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()); diff --git a/application/plugin/PluginManager.php b/application/plugin/PluginManager.php index da66dea3..3ea55728 100644 --- a/application/plugin/PluginManager.php +++ b/application/plugin/PluginManager.php @@ -1,4 +1,5 @@ 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; diff --git a/application/plugin/exception/PluginFileNotFoundException.php b/application/plugin/exception/PluginFileNotFoundException.php index e5386f02..21ac6604 100644 --- a/application/plugin/exception/PluginFileNotFoundException.php +++ b/application/plugin/exception/PluginFileNotFoundException.php @@ -1,4 +1,5 @@ trustedProxies = $trustedProxies; $this->nbAttempts = $nbAttempts; $this->banDuration = $banDuration; @@ -80,7 +80,7 @@ class BanManager if ($this->failures[$ip] >= $this->nbAttempts) { $this->bans[$ip] = time() + $this->banDuration; - $this->logger->info(format_log('IP address banned from login: '. $ip, $ip)); + $this->logger->info(format_log('IP address banned from login: ' . $ip, $ip)); } $this->writeBanFile(); } @@ -136,7 +136,7 @@ class BanManager unset($this->failures[$ip]); } unset($this->bans[$ip]); - $this->logger->info(format_log('Ban lifted for: '. $ip, $ip)); + $this->logger->info(format_log('Ban lifted for: ' . $ip, $ip)); $this->writeBanFile(); return false; diff --git a/application/security/LoginManager.php b/application/security/LoginManager.php index 426e785e..b795b80e 100644 --- a/application/security/LoginManager.php +++ b/application/security/LoginManager.php @@ -1,4 +1,5 @@ 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)) @@ -156,7 +159,7 @@ class LoginManager return true; } - } catch(Exception $exception) { + } catch (Exception $exception) { $this->logger->info(format_log('Exception while checking credentials: ' . $exception, $clientIpId)); } @@ -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') @@ -193,14 +197,14 @@ class LoginManager */ public function checkCredentialsFromLdap($login, $password, $connect = null, $bind = null) { - $connect = $connect ?? function($host) { + $connect = $connect ?? function ($host) { $resource = ldap_connect($host); ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3); return $resource; }; - $bind = $bind ?? function($handle, $dn, $password) { + $bind = $bind ?? function ($handle, $dn, $password) { return ldap_bind($handle, $dn, $password); }; diff --git a/application/security/SessionManager.php b/application/security/SessionManager.php index 96bf193c..f957b91a 100644 --- a/application/security/SessionManager.php +++ b/application/security/SessionManager.php @@ -1,4 +1,5 @@ conf->get('credentials.salt')); + $token = sha1(uniqid('', true) . '_' . mt_rand() . $this->conf->get('credentials.salt')); $this->session['tokens'][$token] = 1; return $token; } diff --git a/application/updater/Updater.php b/application/updater/Updater.php index 88a7bc7b..3451cf36 100644 --- a/application/updater/Updater.php +++ b/application/updater/Updater.php @@ -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) ) { diff --git a/application/updater/UpdaterUtils.php b/application/updater/UpdaterUtils.php index 828a49fc..908bdc39 100644 --- a/application/updater/UpdaterUtils.php +++ b/application/updater/UpdaterUtils.php @@ -19,7 +19,7 @@ class UpdaterUtils return explode(';', $content); } } - return array(); + return []; } /** @@ -38,7 +38,7 @@ class UpdaterUtils $res = file_put_contents($updatesFilepath, implode(';', $updates)); if ($res === false) { - throw new \Exception('Unable to write updates in '. $updatesFilepath . '.'); + throw new \Exception('Unable to write updates in ' . $updatesFilepath . '.'); } } } diff --git a/index.php b/index.php index 8fe86236..1eb7659a 100644 --- a/index.php +++ b/index.php @@ -1,4 +1,5 @@ setEmpty('general.timezone', date_default_timezone_get()); -$conf->setEmpty('general.title', t('Shared bookmarks on '). escape(index_url($_SERVER))); +$conf->setEmpty('general.title', t('Shared bookmarks on ') . escape(index_url($_SERVER))); -RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory +RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl') . '/' . $conf->get('resource.theme') . '/'; // template directory RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory date_default_timezone_set($conf->get('general.timezone', 'UTC')); @@ -177,6 +178,6 @@ try { } catch (Throwable $e) { die(nl2br( 'An unexpected error happened, and the error template could not be displayed.' . PHP_EOL . PHP_EOL . - exception2text($e) + exception2text($e) )); } diff --git a/plugins/addlink_toolbar/addlink_toolbar.php b/plugins/addlink_toolbar/addlink_toolbar.php index ab6ed6de..80b1dd95 100644 --- a/plugins/addlink_toolbar/addlink_toolbar.php +++ b/plugins/addlink_toolbar/addlink_toolbar.php @@ -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; } diff --git a/plugins/archiveorg/archiveorg.php b/plugins/archiveorg/archiveorg.php index ed271532..88f2b653 100644 --- a/plugins/archiveorg/archiveorg.php +++ b/plugins/archiveorg/archiveorg.php @@ -1,4 +1,5 @@ get('plugins.'. $placeholder, '')); + $value = trim($conf->get('plugins.' . $placeholder, '')); if (strlen($value) > 0) { $params[$placeholder] = $value; } } if (empty($params)) { - $error = t('Default colors plugin error: '. + $error = t('Default colors plugin error: ' . 'This plugin is active and no custom color is configured.'); return [$error]; } @@ -56,7 +56,7 @@ function default_colors_init($conf) function hook_default_colors_render_includes($data) { $file = PluginManager::$PLUGINS_PATH . '/default_colors/default_colors.css'; - if (file_exists($file )) { + if (file_exists($file)) { $data['css_files'][] = $file ; } @@ -75,7 +75,7 @@ function default_colors_generate_css_file($params): void $content = ''; foreach (DEFAULT_COLORS_PLACEHOLDERS as $rule) { $content .= !empty($params[$rule]) - ? default_colors_format_css_rule($params, $rule) .';'. PHP_EOL + ? default_colors_format_css_rule($params, $rule) . ';' . PHP_EOL : ''; } @@ -99,8 +99,8 @@ function default_colors_format_css_rule($data, $parameter) } $key = str_replace('DEFAULT_COLORS_', '', $parameter); - $key = str_replace('_', '-', strtolower($key)) .'-color'; - return ' --'. $key .': '. $data[$parameter]; + $key = str_replace('_', '-', strtolower($key)) . '-color'; + return ' --' . $key . ': ' . $data[$parameter]; } diff --git a/plugins/demo_plugin/demo_plugin.php b/plugins/demo_plugin/demo_plugin.php index defb01f7..22d27b68 100644 --- a/plugins/demo_plugin/demo_plugin.php +++ b/plugins/demo_plugin/demo_plugin.php @@ -1,4 +1,5 @@ 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) * * */ - $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; @@ -187,7 +188,7 @@ function hook_demo_plugin_render_includes($data) function hook_demo_plugin_render_footer($data) { // Footer text - $data['text'][] = '
'. demo_plugin_t('Shaarli is now enhanced by the awesome demo_plugin.'); + $data['text'][] = '
' . demo_plugin_t('Shaarli is now enhanced by the awesome demo_plugin.'); // Free elements at the end of the page. $data['endofpage'][] = '