Refactors "strpos" calls in lib/private to improve code readability.

Signed-off-by: Faraz Samapoor <fsamapoor@gmail.com>
pull/38261/head
Faraz Samapoor 1 year ago
parent 8bdb50fd50
commit e7cc7653b8

@ -176,7 +176,7 @@ class AccountManager implements IAccountManager {
if ($defaultRegion === '') {
// When no default region is set, only +49… numbers are valid
if (strpos($input, '+') !== 0) {
if (!str_starts_with($input, '+')) {
throw new InvalidArgumentException(self::PROPERTY_PHONE);
}

@ -145,7 +145,7 @@ class AccountProperty implements IAccountProperty {
}
public static function mapScopeToV2(string $scope): string {
if (strpos($scope, 'v2-') === 0) {
if (str_starts_with($scope, 'v2-')) {
return $scope;
}

@ -99,7 +99,7 @@ class AppFetcher extends Fetcher {
foreach ($app['releases'] as $release) {
// Exclude all nightly and pre-releases if required
if (($allowNightly || $release['isNightly'] === false)
&& ($allowPreReleases || strpos($release['version'], '-') === false)) {
&& ($allowPreReleases || !str_contains($release['version'], '-'))) {
// Exclude all versions not compatible with the current version
try {
$versionParser = new VersionParser();

@ -64,7 +64,7 @@ class VersionParser {
if (!$this->isValidVersionString($firstVersionNumber)) {
break;
}
if (strpos($firstVersion, '>') === 0) {
if (str_starts_with($firstVersion, '>')) {
return new Version($firstVersionNumber, '');
}
return new Version('', $firstVersionNumber);

@ -383,7 +383,7 @@ class DependencyAnalyzer {
case '9.1':
return '10';
default:
if (strpos($version, '9.1.') === 0) {
if (str_starts_with($version, '9.1.')) {
$version = '10.0.' . substr($version, 4);
}
return $version;

@ -91,12 +91,12 @@ class App {
}
public static function getAppIdForClass(string $className, string $topNamespace = 'OCA\\'): ?string {
if (strpos($className, $topNamespace) !== 0) {
if (!str_starts_with($className, $topNamespace)) {
return null;
}
foreach (self::$nameSpaceCache as $appId => $namespace) {
if (strpos($className, $topNamespace . $namespace . '\\') === 0) {
if (str_starts_with($className, $topNamespace . $namespace . '\\')) {
return $appId;
}
}
@ -147,7 +147,7 @@ class App {
try {
$controller = $container->get($controllerName);
} catch (QueryException $e) {
if (strpos($controllerName, '\\Controller\\') !== false) {
if (str_contains($controllerName, '\\Controller\\')) {
// This is from a global registered app route that is not enabled.
[/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3);
throw new HintException('App ' . strtolower($app) . ' is not enabled');

@ -212,8 +212,8 @@ class Dispatcher {
$value === 'false' &&
(
$this->request->method === 'GET' ||
strpos($this->request->getHeader('Content-Type'),
'application/x-www-form-urlencoded') !== false
str_contains($this->request->getHeader('Content-Type'),
'application/x-www-form-urlencoded')
)
) {
$value = false;

@ -413,8 +413,8 @@ class Request implements \ArrayAccess, \Countable, IRequest {
return $this->method === 'PUT'
&& $this->getHeader('Content-Length') !== '0'
&& $this->getHeader('Content-Length') !== ''
&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
&& strpos($this->getHeader('Content-Type'), 'application/json') === false;
&& !str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')
&& !str_contains($this->getHeader('Content-Type'), 'application/json');
}
/**
@ -439,7 +439,7 @@ class Request implements \ArrayAccess, \Countable, IRequest {
// or post correctly
} elseif ($this->method !== 'GET'
&& $this->method !== 'POST'
&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
&& str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')) {
parse_str(file_get_contents($this->inputStream), $params);
if (\is_array($params)) {
$this->items['params'] = $params;
@ -603,7 +603,7 @@ class Request implements \ArrayAccess, \Countable, IRequest {
$IP = trim($IP);
// remove brackets from IPv6 addresses
if (strpos($IP, '[') === 0 && substr($IP, -1) === ']') {
if (str_starts_with($IP, '[') && str_ends_with($IP, ']')) {
$IP = substr($IP, 1, -1);
}
@ -642,7 +642,7 @@ class Request implements \ArrayAccess, \Countable, IRequest {
}
if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
if (str_contains($this->server['HTTP_X_FORWARDED_PROTO'], ',')) {
$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
$proto = strtolower(trim($parts[0]));
} else {
@ -724,7 +724,7 @@ class Request implements \ArrayAccess, \Countable, IRequest {
// FIXME: Sabre does not really belong here
[$path, $name] = \Sabre\Uri\split($scriptName);
if (!empty($path)) {
if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
if ($path === $pathInfo || str_starts_with($pathInfo, $path . '/')) {
$pathInfo = substr($pathInfo, \strlen($path));
} else {
throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
@ -734,10 +734,10 @@ class Request implements \ArrayAccess, \Countable, IRequest {
$name = '';
}
if (strpos($pathInfo, '/'.$name) === 0) {
if (str_starts_with($pathInfo, '/' . $name)) {
$pathInfo = substr($pathInfo, \strlen($name) + 1);
}
if ($name !== '' && strpos($pathInfo, $name) === 0) {
if ($name !== '' && str_starts_with($pathInfo, $name)) {
$pathInfo = substr($pathInfo, \strlen($name));
}
if ($pathInfo === false || $pathInfo === '/') {
@ -803,7 +803,7 @@ class Request implements \ArrayAccess, \Countable, IRequest {
$host = 'localhost';
if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
if (str_contains($this->server['HTTP_X_FORWARDED_HOST'], ',')) {
$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
$host = trim(current($parts));
} else {

@ -57,7 +57,7 @@ class CompressionMiddleware extends Middleware {
// Check if we are even asked for gzip
$header = $this->request->getHeader('Accept-Encoding');
if (strpos($header, 'gzip') === false) {
if (!str_contains($header, 'gzip')) {
return $response;
}

@ -218,7 +218,7 @@ class SecurityMiddleware extends Middleware {
if (!$this->request->passesCSRFCheck() && !(
$controller instanceof OCSController && (
$this->request->getHeader('OCS-APIREQUEST') === 'true' ||
strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
str_starts_with($this->request->getHeader('Authorization'), 'Bearer ')
)
)) {
throw new CrossSiteRequestForgeryException();

@ -134,7 +134,7 @@ abstract class BaseResponse extends Response {
continue;
}
if (\is_string($k) && strpos($k, '@') === 0) {
if (\is_string($k) && str_starts_with($k, '@')) {
$writer->writeAttribute(substr($k, 1), $v);
continue;
}

@ -160,7 +160,7 @@ class File implements ICache {
$dh = $storage->opendir('/');
if (is_resource($dh)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
if ($file != '.' and $file != '..' and ($prefix === '' || str_starts_with($file, $prefix))) {
$storage->unlink('/' . $file);
}
}

@ -97,7 +97,7 @@ class Search implements ISearch {
// if we have an exact local user match with an email-a-like query,
// there is no need to show the remote and email matches.
$userType = new SearchResultType('users');
if (strpos($search, '@') !== false && $searchResult->hasExactIdMatch($userType)) {
if (str_contains($search, '@') && $searchResult->hasExactIdMatch($userType)) {
$searchResult->unsetResult($remoteType);
$searchResult->unsetResult($emailType);
}

@ -240,9 +240,9 @@ class Comment implements IComment {
$result = [];
foreach ($mentionIds as $mentionId) {
$cleanId = trim(substr($mentionId, 1), '"');
if (strpos($cleanId, 'guest/') === 0) {
if (str_starts_with($cleanId, 'guest/')) {
$result[] = ['type' => 'guest', 'id' => $cleanId];
} elseif (strpos($cleanId, 'group/') === 0) {
} elseif (str_starts_with($cleanId, 'group/')) {
$result[] = ['type' => 'group', 'id' => substr($cleanId, 6)];
} else {
$result[] = ['type' => 'user', 'id' => $cleanId];

@ -302,7 +302,7 @@ class ContactsStore implements IContactsStore {
}
$avatarPrefix = "VALUE=uri:";
if (isset($contact['PHOTO']) && strpos($contact['PHOTO'], $avatarPrefix) === 0) {
if (isset($contact['PHOTO']) && str_starts_with($contact['PHOTO'], $avatarPrefix)) {
$entry->setAvatar(substr($contact['PHOTO'], strlen($avatarPrefix)));
}

@ -63,7 +63,7 @@ class MySqlTools {
return false;
}
return strpos($row, 'maria') && version_compare($row, '10.3', '>=') ||
strpos($row, 'maria') === false && version_compare($row, '8.0', '>=');
return str_contains($row, 'maria') && version_compare($row, '10.3', '>=') ||
!str_contains($row, 'maria') && version_compare($row, '8.0', '>=');
}
}

@ -1321,7 +1321,7 @@ class QueryBuilder implements IQueryBuilder {
* @return string
*/
protected function prefixTableName($table) {
if ($this->automaticTablePrefix === false || strpos($table, '*PREFIX*') === 0) {
if ($this->automaticTablePrefix === false || str_starts_with($table, '*PREFIX*')) {
return $table;
}

@ -62,7 +62,7 @@ class SchemaWrapper implements ISchemaWrapper {
public function getTableNamesWithoutPrefix() {
$tableNames = $this->schema->getTableNames();
return array_map(function ($tableName) {
if (strpos($tableName, $this->connection->getPrefix()) === 0) {
if (str_starts_with($tableName, $this->connection->getPrefix())) {
return substr($tableName, strlen($this->connection->getPrefix()));
}

@ -311,10 +311,7 @@ class Util {
// detect alternative key storage root
$rootDir = $this->getKeyStorageRoot();
if ($rootDir !== '' &&
0 === strpos(
Filesystem::normalizePath($path),
Filesystem::normalizePath($rootDir)
)
str_starts_with(Filesystem::normalizePath($path), Filesystem::normalizePath($rootDir))
) {
return true;
}

@ -81,7 +81,7 @@ class CloudIdManager implements ICloudIdManager {
if ($event instanceof CardUpdatedEvent) {
$data = $event->getCardData()['carddata'];
foreach (explode("\r\n", $data) as $line) {
if (strpos($line, "CLOUD;") === 0) {
if (str_starts_with($line, "CLOUD;")) {
$parts = explode(':', $line, 2);
if (isset($parts[1])) {
$key = $parts[1];
@ -210,9 +210,9 @@ class CloudIdManager implements ICloudIdManager {
* @return string
*/
private function removeProtocolFromUrl($url) {
if (strpos($url, 'https://') === 0) {
if (str_starts_with($url, 'https://')) {
return substr($url, strlen('https://'));
} elseif (strpos($url, 'http://') === 0) {
} elseif (str_starts_with($url, 'http://')) {
return substr($url, strlen('http://'));
}
@ -246,6 +246,6 @@ class CloudIdManager implements ICloudIdManager {
* @return bool
*/
public function isValidCloudId(string $cloudId): bool {
return strpos($cloudId, '@') !== false;
return str_contains($cloudId, '@');
}
}

@ -836,7 +836,7 @@ class Cache implements ICache {
* @return ICacheEntry[] an array of cache entries where the mimetype matches the search
*/
public function searchByMime($mimetype) {
if (strpos($mimetype, '/') === false) {
if (!str_contains($mimetype, '/')) {
$operator = new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%');
} else {
$operator = new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype);

@ -44,6 +44,6 @@ class LocalRootScanner extends Scanner {
private function shouldScanPath(string $path): bool {
$path = trim($path, '/');
return $path === '' || strpos($path, 'appdata_') === 0 || strpos($path, '__groupfolders') === 0;
return $path === '' || str_starts_with($path, 'appdata_') || str_starts_with($path, '__groupfolders');
}
}

@ -71,7 +71,7 @@ class Propagator implements IPropagator {
public function propagateChange($internalPath, $time, $sizeDifference = 0) {
// Do not propagate changes in ignored paths
foreach ($this->ignore as $ignore) {
if (strpos($internalPath, $ignore) === 0) {
if (str_starts_with($internalPath, $ignore)) {
return;
}
}

@ -521,7 +521,7 @@ class Scanner extends BasicEmitter implements IScanner {
if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
return true;
}
if (strpos($file, '.part/') !== false) {
if (str_contains($file, '.part/')) {
return true;
}

@ -152,7 +152,7 @@ class SearchBuilder {
$field = 'mimepart';
$value = (int)$this->mimetypeLoader->getId($matches[1]);
$type = ISearchComparison::COMPARE_EQUAL;
} elseif (strpos($value, '%') !== false) {
} elseif (str_contains($value, '%')) {
throw new \InvalidArgumentException('Unsupported query value for mimetype: ' . $value . ', only values in the format "mime/type" or "mime/%" are supported');
} else {
$field = 'mimetype';

@ -328,7 +328,7 @@ class CacheJail extends CacheWrapper {
}
public function getCacheEntryFromSearchResult(ICacheEntry $rawEntry): ?ICacheEntry {
if ($this->getGetUnjailedRoot() === '' || strpos($rawEntry->getPath(), $this->getGetUnjailedRoot()) === 0) {
if ($this->getGetUnjailedRoot() === '' || str_starts_with($rawEntry->getPath(), $this->getGetUnjailedRoot())) {
$rawEntry = $this->getCache()->getCacheEntryFromSearchResult($rawEntry);
if ($rawEntry) {
$jailedPath = $this->getJailedPath($rawEntry->getPath());

@ -487,7 +487,7 @@ class UserMountCache implements IUserMountCache {
$path = rtrim($path, '/') . '/';
$mounts = $this->getMountsForUser($user);
return array_filter($mounts, function (ICachedMountInfo $mount) use ($path) {
return $mount->getMountPoint() !== $path && strpos($mount->getMountPoint(), $path) === 0;
return $mount->getMountPoint() !== $path && str_starts_with($mount->getMountPoint(), $path);
});
}
}

@ -451,7 +451,7 @@ class Filesystem {
if (!$path || $path[0] !== '/') {
$path = '/' . $path;
}
if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
if (str_contains($path, '/../') || strrchr($path, '/') === '/..') {
return false;
}
return true;

@ -121,7 +121,7 @@ class MountPoint implements IMountPoint {
$this->storage = $this->loader->wrap($this, $storage);
} else {
// Update old classes to new namespace
if (strpos($storage, 'OC_Filestorage_') !== false) {
if (str_contains($storage, 'OC_Filestorage_')) {
$storage = '\OC\Files\Storage\\' . substr($storage, 15);
}
$this->class = $storage;

@ -64,7 +64,7 @@ class RootMountProvider implements IRootMountProvider {
// instantiate object store implementation
$name = $config['class'];
if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
if (str_starts_with($name, 'OCA\\') && substr_count($name, '\\') >= 2) {
$segments = explode('\\', $name);
OC_App::loadApp(strtolower($segments[1]));
}

@ -88,7 +88,7 @@ class Folder extends Node implements \OCP\Files\Folder {
* @return bool
*/
public function isSubNode($node) {
return strpos($node->getPath(), $this->path . '/') === 0;
return str_starts_with($node->getPath(), $this->path . '/');
}
/**
@ -284,7 +284,7 @@ class Folder extends Node implements \OCP\Files\Folder {
* @return Node[]
*/
public function searchByMime($mimetype) {
if (strpos($mimetype, '/') === false) {
if (!str_contains($mimetype, '/')) {
$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%'));
} else {
$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype));
@ -339,7 +339,7 @@ class Folder extends Node implements \OCP\Files\Folder {
$absolutePath = '/' . ltrim($cacheEntry->getPath(), '/');
$currentPath = rtrim($this->path, '/') . '/';
if (strpos($absolutePath, $currentPath) !== 0) {
if (!str_starts_with($absolutePath, $currentPath)) {
return [];
}

@ -107,7 +107,7 @@ class S3Signature implements SignatureInterface {
// Move X-Amz-* headers to the query string
foreach ($request->getHeaders() as $name => $header) {
$name = strtolower($name);
if (strpos($name, 'x-amz-') === 0) {
if (str_starts_with($name, 'x-amz-')) {
$query[$name] = implode(',', $header);
}
}
@ -169,7 +169,7 @@ class S3Signature implements SignatureInterface {
$headers = [];
foreach ($request->getHeaders() as $name => $header) {
$name = strtolower($name);
if (strpos($name, 'x-amz-') === 0) {
if (str_starts_with($name, 'x-amz-')) {
$value = implode(',', $header);
if (strlen($value) > 0) {
$headers[$name] = $name . ':' . $value;

@ -294,7 +294,7 @@ class SetupManager {
$userRoot = '/' . $user->getUID() . '/';
$mounts = $this->mountManager->getAll();
$mounts = array_filter($mounts, function (IMountPoint $mount) use ($userRoot) {
return strpos($mount->getMountPoint(), $userRoot) === 0;
return str_starts_with($mount->getMountPoint(), $userRoot);
});
$allProviders = array_map(function (IMountProvider $provider) {
return get_class($provider);
@ -365,7 +365,7 @@ class SetupManager {
* @return IUser|null
*/
private function getUserForPath(string $path) {
if (strpos($path, '/__groupfolders') === 0) {
if (str_starts_with($path, '/__groupfolders')) {
return null;
} elseif (substr_count($path, '/') < 2) {
if ($user = $this->userSession->getUser()) {
@ -373,7 +373,7 @@ class SetupManager {
} else {
return null;
}
} elseif (strpos($path, '/appdata_' . \OC_Util::getInstanceId()) === 0 || strpos($path, '/files_external/') === 0) {
} elseif (str_starts_with($path, '/appdata_' . \OC_Util::getInstanceId()) || str_starts_with($path, '/files_external/')) {
return null;
} else {
[, $userId] = explode('/', $path);

@ -577,7 +577,7 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage {
*/
private function scanForInvalidCharacters($fileName, $invalidChars) {
foreach (str_split($invalidChars) as $char) {
if (strpos($fileName, $char) !== false) {
if (str_contains($fileName, $char)) {
throw new InvalidCharacterInPathException();
}
}

@ -769,16 +769,16 @@ class DAV extends Common {
*/
protected function parsePermissions($permissionsString) {
$permissions = Constants::PERMISSION_READ;
if (strpos($permissionsString, 'R') !== false) {
if (str_contains($permissionsString, 'R')) {
$permissions |= Constants::PERMISSION_SHARE;
}
if (strpos($permissionsString, 'D') !== false) {
if (str_contains($permissionsString, 'D')) {
$permissions |= Constants::PERMISSION_DELETE;
}
if (strpos($permissionsString, 'W') !== false) {
if (str_contains($permissionsString, 'W')) {
$permissions |= Constants::PERMISSION_UPDATE;
}
if (strpos($permissionsString, 'CK') !== false) {
if (str_contains($permissionsString, 'CK')) {
$permissions |= Constants::PERMISSION_CREATE;
$permissions |= Constants::PERMISSION_UPDATE;
}

@ -922,7 +922,7 @@ class Encryption extends Wrapper {
}
$firstBlock = $this->readFirstBlock($path);
if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
if (str_starts_with($firstBlock, Util::HEADER_START)) {
$headerSize = $this->util->getHeaderSize();
}
@ -937,7 +937,7 @@ class Encryption extends Wrapper {
*/
protected function parseRawHeader($rawHeader) {
$result = [];
if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
if (str_starts_with($rawHeader, Util::HEADER_START)) {
$header = $rawHeader;
$endAt = strpos($header, Util::HEADER_END);
if ($endAt !== false) {

@ -72,7 +72,7 @@ class Jail extends Wrapper {
public function getJailedPath($path) {
$root = rtrim($this->rootPath, '/') . '/';
if ($path !== $this->rootPath && strpos($path, $root) !== 0) {
if ($path !== $this->rootPath && !str_starts_with($path, $root)) {
return null;
} else {
$path = substr($path, strlen($this->rootPath));

@ -109,7 +109,7 @@ class Quota extends Wrapper {
if (!$this->hasQuota()) {
return $this->storage->free_space($path);
}
if ($this->getQuota() < 0 || strpos($path, 'cache') === 0 || strpos($path, 'uploads') === 0) {
if ($this->getQuota() < 0 || str_starts_with($path, 'cache') || str_starts_with($path, 'uploads')) {
return $this->storage->free_space($path);
} else {
$used = $this->getSize($this->sizeRoot);
@ -207,7 +207,7 @@ class Quota extends Wrapper {
* Only apply quota for files, not metadata, trash or others
*/
private function shouldApplyQuota(string $path): bool {
return strpos(ltrim($path, '/'), 'files/') === 0;
return str_starts_with(ltrim($path, '/'), 'files/');
}
/**

@ -116,7 +116,7 @@ class Detection implements IMimeTypeDetector {
// Update the alternative mimetypes to avoid having to look them up each time.
foreach ($this->mimetypes as $extension => $mimeType) {
if (strpos($extension, '_comment') === 0) {
if (str_starts_with($extension, '_comment')) {
continue;
}
$this->secureMimeTypes[$mimeType[0]] = $mimeType[1] ?? $mimeType[0];
@ -238,7 +238,7 @@ class Detection implements IMimeTypeDetector {
finfo_close($finfo);
if ($info) {
$info = strtolower($info);
$mimeType = strpos($info, ';') !== false ? substr($info, 0, strpos($info, ';')) : $info;
$mimeType = str_contains($info, ';') ? substr($info, 0, strpos($info, ';')) : $info;
$mimeType = $this->getSecureMimeType($mimeType);
if ($mimeType !== 'application/octet-stream') {
return $mimeType;
@ -246,7 +246,7 @@ class Detection implements IMimeTypeDetector {
}
}
if (strpos($path, '://') !== false && strpos($path, 'file://') === 0) {
if (str_contains($path, '://') && str_starts_with($path, 'file://')) {
// Is the file wrapped in a stream?
return 'application/octet-stream';
}
@ -308,7 +308,7 @@ class Detection implements IMimeTypeDetector {
if (function_exists('finfo_open') && function_exists('finfo_file')) {
$finfo = finfo_open(FILEINFO_MIME);
$info = finfo_buffer($finfo, $data);
return strpos($info, ';') !== false ? substr($info, 0, strpos($info, ';')) : $info;
return str_contains($info, ';') ? substr($info, 0, strpos($info, ';')) : $info;
}
$tmpFile = \OC::$server->getTempManager()->getTemporaryFile();

@ -37,7 +37,7 @@ class PathHelper {
}
if ($path === $root) {
return '/';
} elseif (strpos($path, $root . '/') !== 0) {
} elseif (!str_starts_with($path, $root . '/')) {
return null;
} else {
$path = substr($path, strlen($root));
@ -60,7 +60,7 @@ class PathHelper {
$path = '/' . $path;
}
//remove duplicate slashes
while (strpos($path, '//') !== false) {
while (str_contains($path, '//')) {
$path = str_replace('//', '/', $path);
}
//remove trailing slash

@ -168,7 +168,7 @@ class View {
// missing slashes can cause wrong matches!
$root = rtrim($this->fakeRoot, '/') . '/';
if (strpos($path, $root) !== 0) {
if (!str_starts_with($path, $root)) {
return null;
} else {
$path = substr($path, strlen($this->fakeRoot));
@ -2079,7 +2079,7 @@ class View {
return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
}
return strpos($path, '/appdata_') !== 0;
return !str_starts_with($path, '/appdata_');
}
/**

@ -379,7 +379,7 @@ class Checker {
// integrity check.
if ($basePath === $this->environmentHelper->getServerRoot()) {
foreach ($expectedHashes as $fileName => $hash) {
if (strpos($fileName, 'updater/') === 0) {
if (str_starts_with($fileName, 'updater/')) {
unset($expectedHashes[$fileName]);
}
}

@ -539,12 +539,12 @@ class Factory implements IFactory {
*/
private function isSubDirectory($sub, $parent) {
// Check whether $sub contains no ".."
if (strpos($sub, '..') !== false) {
if (str_contains($sub, '..')) {
return false;
}
// Check whether $sub is a subdirectory of $parent
if (strpos($sub, $parent) === 0) {
if (str_starts_with($sub, $parent)) {
return true;
}

@ -65,12 +65,12 @@ class L10NString implements \JsonSerializable {
if (is_array($identity)) {
$pipeCheck = implode('', $identity);
if (strpos($pipeCheck, '|') !== false) {
if (str_contains($pipeCheck, '|')) {
return 'Can not use pipe character in translations';
}
$identity = implode('|', $identity);
} elseif (strpos($identity, '|') !== false) {
} elseif (str_contains($identity, '|')) {
return 'Can not use pipe character in translations';
}

@ -150,9 +150,9 @@ class LargeFileHelper {
$os = strtolower(php_uname('s'));
$arg = escapeshellarg($filename);
$result = null;
if (strpos($os, 'linux') !== false) {
if (str_contains($os, 'linux')) {
$result = $this->exec("stat -c %s $arg");
} elseif (strpos($os, 'bsd') !== false || strpos($os, 'darwin') !== false) {
} elseif (str_contains($os, 'bsd') || str_contains($os, 'darwin')) {
$result = $this->exec("stat -f %z $arg");
}
return $result;
@ -193,7 +193,7 @@ class LargeFileHelper {
if ($result < 0) {
if (\OCP\Util::isFunctionEnabled('exec')) {
$os = strtolower(php_uname('s'));
if (strpos($os, 'linux') !== false) {
if (str_contains($os, 'linux')) {
return (int)($this->exec('stat -c %Y ' . escapeshellarg($fullPath)) ?? -1);
}
}

@ -242,8 +242,8 @@ class Log implements ILogger, IDataLogger {
$request = \OC::$server->getRequest();
if ($request->getMethod() === 'PUT' &&
strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false &&
strpos($request->getHeader('Content-Type'), 'application/json') === false) {
!str_contains($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') &&
!str_contains($request->getHeader('Content-Type'), 'application/json')) {
$logSecretRequest = '';
} else {
$logSecretRequest = $request->getParam('log_secret', '');
@ -391,7 +391,7 @@ class Log implements ILogger, IDataLogger {
foreach ($context as $key => $val) {
$fullKey = '{' . $key . '}';
$replace[$fullKey] = $val;
if (strpos($message, $fullKey) !== false) {
if (str_contains($message, $fullKey)) {
$usedContextKeys[$key] = true;
}
}

@ -205,7 +205,7 @@ class ExceptionSerializer {
return $this->editTrace($sensitiveValues, $traceLine);
}
foreach (self::methodsWithSensitiveParameters as $sensitiveMethod) {
if (strpos($traceLine['function'], $sensitiveMethod) !== false) {
if (str_contains($traceLine['function'], $sensitiveMethod)) {
return $this->editTrace($sensitiveValues, $traceLine);
}
}

@ -75,7 +75,7 @@ class ArrayCache extends Cache implements IMemcache {
}
foreach ($this->cachedData as $key => $value) {
if (strpos($key, $prefix) === 0) {
if (str_starts_with($key, $prefix)) {
$this->remove($key);
}
}

@ -358,7 +358,7 @@ class Generator {
// It might have been generated with a higher resolution than the current value.
foreach ($previewFiles as $node) {
$name = $node->getName();
if (($prefix === '' || strpos($name, $prefix) === 0) && strpos($name, 'max')) {
if (($prefix === '' || str_starts_with($name, $prefix)) && strpos($name, 'max')) {
return $node;
}
}

@ -66,7 +66,7 @@ class FileProfilerStorage {
[$csvToken, $csvMethod, $csvUrl, $csvTime, $csvParent, $csvStatusCode] = $values;
$csvTime = (int) $csvTime;
if ($url && false === strpos($csvUrl, $url) || $method && false === strpos($csvMethod, $method) || $statusCode && false === strpos($csvStatusCode, $statusCode)) {
if ($url && !str_contains($csvUrl, $url) || $method && !str_contains($csvMethod, $method) || $statusCode && !str_contains($csvStatusCode, $statusCode)) {
continue;
}

@ -361,7 +361,7 @@ class Router implements IRouter {
$referenceType = UrlGenerator::ABSOLUTE_PATH;
}
$name = $this->fixLegacyRootName($name);
if (strpos($name, '.') !== false) {
if (str_contains($name, '.')) {
[$appName, $other] = explode('.', $name, 3);
// OCS routes are prefixed with "ocs."
if ($appName === 'ocs') {

@ -157,7 +157,7 @@ class Throttler implements IThrottler {
$keys = $this->config->getAppKeys('bruteForce');
$keys = array_filter($keys, function ($key) {
return 0 === strpos($key, 'whitelist_');
return str_starts_with($key, 'whitelist_');
});
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {

@ -30,7 +30,6 @@ use OC\Net\IpAddressClassifier;
use OCP\IConfig;
use OCP\Security\IRemoteHostValidator;
use Psr\Log\LoggerInterface;
use function strpos;
use function strtolower;
use function substr;
use function urldecode;
@ -61,7 +60,7 @@ final class RemoteHostValidator implements IRemoteHostValidator {
$host = idn_to_utf8(strtolower(urldecode($host)));
// Remove brackets from IPv6 addresses
if (strpos($host, '[') === 0 && substr($host, -1) === ']') {
if (str_starts_with($host, '[') && str_ends_with($host, ']')) {
$host = substr($host, 1, -1);
}

@ -98,7 +98,7 @@ class TrustedDomainHelper implements ITrustedDomainHelper {
return true;
}
// Reject malformed domains in any case
if (strpos($domain, '-') === 0 || strpos($domain, '..') !== false) {
if (str_starts_with($domain, '-') || str_contains($domain, '..')) {
return false;
}
// Match, allowing for * wildcards

@ -157,7 +157,7 @@ class ServerContainer extends SimpleContainer {
// Didn't find the service or the respective app container,
// ignore it and fall back to the core container.
}
} elseif (strpos($name, 'OC\\Settings\\') === 0 && substr_count($name, '\\') >= 3) {
} elseif (str_starts_with($name, 'OC\\Settings\\') && substr_count($name, '\\') >= 3) {
$segments = explode('\\', $name);
try {
$appContainer = $this->getAppContainer(strtolower($segments[1]), $segments[1]);
@ -177,7 +177,7 @@ class ServerContainer extends SimpleContainer {
* @return DIContainer|null
*/
public function getAppContainerForService(string $id): ?DIContainer {
if (strpos($id, 'OCA\\') !== 0 || substr_count($id, '\\') < 2) {
if (!str_starts_with($id, 'OCA\\') || substr_count($id, '\\') < 2) {
return null;
}

@ -942,9 +942,9 @@ class Share extends Constants {
* @return string
*/
public static function removeProtocolFromUrl($url) {
if (strpos($url, 'https://') === 0) {
if (str_starts_with($url, 'https://')) {
return substr($url, strlen('https://'));
} elseif (strpos($url, 'http://') === 0) {
} elseif (str_starts_with($url, 'http://')) {
return substr($url, strlen('http://'));
}

@ -884,7 +884,7 @@ class DefaultShareProvider implements IShareProvider {
$pathSections = explode('/', $data['path'], 2);
// FIXME: would not detect rare md5'd home storage case properly
if ($pathSections[0] !== 'files'
&& (strpos($data['storage_string_id'], 'home::') === 0 || strpos($data['storage_string_id'], 'object::user') === 0)) {
&& (str_starts_with($data['storage_string_id'], 'home::') || str_starts_with($data['storage_string_id'], 'object::user'))) {
return false;
} elseif ($pathSections[0] === '__groupfolders'
&& str_starts_with($pathSections[1], 'trash/')

@ -52,7 +52,7 @@ class JSResourceLocator extends ResourceLocator {
$app = substr($script, 0, strpos($script, '/'));
$scriptName = basename($script);
if (strpos($script, '/l10n/') !== false) {
if (str_contains($script, '/l10n/')) {
// For language files we try to load them all, so themes can overwrite
// single l10n strings without having to translate all of them.
$found = 0;
@ -113,7 +113,7 @@ class JSResourceLocator extends ResourceLocator {
}
// missing translations files will be ignored
if (strpos($script, 'l10n/') === 0) {
if (str_starts_with($script, 'l10n/')) {
return;
}

@ -284,7 +284,7 @@ class TemplateLayout extends \OC_Template {
} else {
$suffix = $this->getVersionHashSuffix($web, $file);
if (strpos($file, '?v=') == false) {
if (!strpos($file, '?v=')) {
$this->append('cssfiles', $web.'/'.$file . $suffix);
} else {
$this->append('cssfiles', $web.'/'.$file . '-' . substr($suffix, 3));

@ -272,13 +272,13 @@ class URLGenerator implements IURLGenerator {
* @return string the absolute version of the url
*/
public function getAbsoluteURL(string $url): string {
$separator = strpos($url, '/') === 0 ? '' : '/';
$separator = str_starts_with($url, '/') ? '' : '/';
if (\OC::$CLI && !\defined('PHPUNIT_RUN')) {
return rtrim($this->config->getSystemValueString('overwrite.cli.url'), '/') . '/' . ltrim($url, '/');
}
// The ownCloud web root can already be prepended.
if (\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) {
if (\OC::$WEBROOT !== '' && str_starts_with($url, \OC::$WEBROOT)) {
$url = substr($url, \strlen(\OC::$WEBROOT));
}
@ -302,7 +302,7 @@ class URLGenerator implements IURLGenerator {
public function linkToDefaultPageUrl(): string {
// Deny the redirect if the URL contains a @
// This prevents unvalidated redirects like ?redirect_url=:user@domain.com
if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
if (isset($_REQUEST['redirect_url']) && !str_contains($_REQUEST['redirect_url'], '@')) {
return $this->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
}

@ -818,7 +818,7 @@ class Session implements IUserSession, Emitter {
*/
public function tryTokenLogin(IRequest $request) {
$authHeader = $request->getHeader('Authorization');
if (strpos($authHeader, 'Bearer ') === 0) {
if (str_starts_with($authHeader, 'Bearer ')) {
$token = substr($authHeader, 7);
} else {
// No auth header, let's try session id

@ -596,7 +596,7 @@ class User implements IUser {
}
private function removeProtocolFromUrl(string $url): string {
if (strpos($url, 'https://') === 0) {
if (str_starts_with($url, 'https://')) {
return substr($url, strlen('https://'));
}

@ -979,7 +979,7 @@ class OC_App {
if ($attributeLang === $similarLang) {
$similarLangFallback = $option['@value'];
} elseif (strpos($attributeLang, $similarLang . '_') === 0) {
} elseif (str_starts_with($attributeLang, $similarLang . '_')) {
if ($similarLangFallback === false) {
$similarLangFallback = $option['@value'];
}

@ -179,7 +179,7 @@ class OC_Files {
$streamer->sendHeaders($name);
$executionTime = (int)OC::$server->get(IniGetWrapper::class)->getNumeric('max_execution_time');
if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
if (!str_contains(@ini_get('disable_functions'), 'set_time_limit')) {
@set_time_limit(0);
}
ignore_user_abort(true);

@ -987,7 +987,7 @@ class OC_Util {
$content = false;
}
if (strpos($url, 'https:') === 0) {
if (str_starts_with($url, 'https:')) {
$url = 'http:' . substr($url, 6);
} else {
$url = 'https:' . substr($url, 5);
@ -1160,7 +1160,7 @@ class OC_Util {
}
foreach (str_split($trimmed) as $char) {
if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
if (str_contains(\OCP\Constants::FILENAME_INVALID_CHARS, $char)) {
return false;
}
}

Loading…
Cancel
Save