diff options
Diffstat (limited to 'lib/private/legacy')
-rw-r--r-- | lib/private/legacy/OC_App.php | 155 | ||||
-rw-r--r-- | lib/private/legacy/OC_Defaults.php | 6 | ||||
-rw-r--r-- | lib/private/legacy/OC_Helper.php | 249 | ||||
-rw-r--r-- | lib/private/legacy/OC_Response.php | 1 | ||||
-rw-r--r-- | lib/private/legacy/OC_User.php | 34 | ||||
-rw-r--r-- | lib/private/legacy/OC_Util.php | 249 |
6 files changed, 99 insertions, 595 deletions
diff --git a/lib/private/legacy/OC_App.php b/lib/private/legacy/OC_App.php index ecceafa65b3..10b78e2a7ef 100644 --- a/lib/private/legacy/OC_App.php +++ b/lib/private/legacy/OC_App.php @@ -9,6 +9,7 @@ declare(strict_types=1); use OC\App\DependencyAnalyzer; use OC\App\Platform; use OC\AppFramework\Bootstrap\Coordinator; +use OC\Config\ConfigManager; use OC\DB\MigrationService; use OC\Installer; use OC\Repair; @@ -211,7 +212,7 @@ class OC_App { array $groups = []) { // Check if app is already downloaded /** @var Installer $installer */ - $installer = \OCP\Server::get(Installer::class); + $installer = Server::get(Installer::class); $isDownloaded = $installer->isDownloaded($appId); if (!$isDownloaded) { @@ -237,21 +238,6 @@ class OC_App { } /** - * Get the path where to install apps - */ - public static function getInstallPath(): ?string { - foreach (OC::$APPSROOTS as $dir) { - if (isset($dir['writable']) && $dir['writable'] === true) { - return $dir['path']; - } - } - - \OCP\Server::get(LoggerInterface::class)->error('No application directories are marked as writable.', ['app' => 'core']); - return null; - } - - - /** * Find the apps root for an app id. * * If multiple copies are found, the apps root the latest version is returned. @@ -310,12 +296,14 @@ class OC_App { * @param string $appId * @param bool $refreshAppPath should be set to true only during install/upgrade * @return string|false - * @deprecated 11.0.0 use \OCP\Server::get(IAppManager)->getAppPath() + * @deprecated 11.0.0 use Server::get(IAppManager)->getAppPath() */ public static function getAppPath(string $appId, bool $refreshAppPath = false) { $appId = self::cleanAppId($appId); if ($appId === '') { return false; + } elseif ($appId === 'core') { + return __DIR__ . '/../../../core'; } if (($dir = self::findAppInDirectories($appId, $refreshAppPath)) != false) { @@ -347,7 +335,7 @@ class OC_App { */ public static function getAppVersionByPath(string $path): string { $infoFile = $path . '/appinfo/info.xml'; - $appData = \OCP\Server::get(IAppManager::class)->getAppInfoByPath($infoFile); + $appData = Server::get(IAppManager::class)->getAppInfoByPath($infoFile); return $appData['version'] ?? ''; } @@ -389,7 +377,7 @@ class OC_App { * @deprecated 20.0.0 Please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface */ public static function registerLogIn(array $entry) { - \OCP\Server::get(LoggerInterface::class)->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface'); + Server::get(LoggerInterface::class)->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface'); self::$altLogin[] = $entry; } @@ -398,11 +386,11 @@ class OC_App { */ public static function getAlternativeLogIns(): array { /** @var Coordinator $bootstrapCoordinator */ - $bootstrapCoordinator = \OCP\Server::get(Coordinator::class); + $bootstrapCoordinator = Server::get(Coordinator::class); foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) { if (!in_array(IAlternativeLogin::class, class_implements($registration->getService()), true)) { - \OCP\Server::get(LoggerInterface::class)->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [ + Server::get(LoggerInterface::class)->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [ 'option' => $registration->getService(), 'interface' => IAlternativeLogin::class, 'app' => $registration->getAppId(), @@ -412,9 +400,9 @@ class OC_App { try { /** @var IAlternativeLogin $provider */ - $provider = \OCP\Server::get($registration->getService()); + $provider = Server::get($registration->getService()); } catch (ContainerExceptionInterface $e) { - \OCP\Server::get(LoggerInterface::class)->error('Alternative login option {option} can not be initialized.', + Server::get(LoggerInterface::class)->error('Alternative login option {option} can not be initialized.', [ 'exception' => $e, 'option' => $registration->getService(), @@ -431,7 +419,7 @@ class OC_App { 'class' => $provider->getClass(), ]; } catch (Throwable $e) { - \OCP\Server::get(LoggerInterface::class)->error('Alternative login option {option} had an error while loading.', + Server::get(LoggerInterface::class)->error('Alternative login option {option} had an error while loading.', [ 'exception' => $e, 'option' => $registration->getService(), @@ -450,7 +438,7 @@ class OC_App { * @deprecated 31.0.0 Use IAppManager::getAllAppsInAppsFolders instead */ public static function getAllApps(): array { - return \OCP\Server::get(IAppManager::class)->getAllAppsInAppsFolders(); + return Server::get(IAppManager::class)->getAllAppsInAppsFolders(); } /** @@ -459,7 +447,7 @@ class OC_App { * @deprecated 32.0.0 Use \OCP\Support\Subscription\IRegistry::delegateGetSupportedApps instead */ public function getSupportedApps(): array { - $subscriptionRegistry = \OCP\Server::get(\OCP\Support\Subscription\IRegistry::class); + $subscriptionRegistry = Server::get(\OCP\Support\Subscription\IRegistry::class); $supportedApps = $subscriptionRegistry->delegateGetSupportedApps(); return $supportedApps; } @@ -484,12 +472,12 @@ class OC_App { if (!in_array($app, $blacklist)) { $info = $appManager->getAppInfo($app, false, $langCode); if (!is_array($info)) { - \OCP\Server::get(LoggerInterface::class)->error('Could not read app info file for app "' . $app . '"', ['app' => 'core']); + Server::get(LoggerInterface::class)->error('Could not read app info file for app "' . $app . '"', ['app' => 'core']); continue; } if (!isset($info['name'])) { - \OCP\Server::get(LoggerInterface::class)->error('App id "' . $app . '" has no name in appinfo', ['app' => 'core']); + Server::get(LoggerInterface::class)->error('App id "' . $app . '" has no name in appinfo', ['app' => 'core']); continue; } @@ -556,7 +544,7 @@ class OC_App { public static function shouldUpgrade(string $app): bool { $versions = self::getAppVersions(); - $currentVersion = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppVersion($app); + $currentVersion = Server::get(\OCP\App\IAppManager::class)->getAppVersion($app); if ($currentVersion && isset($versions[$app])) { $installedVersion = $versions[$app]; if (!version_compare($currentVersion, $installedVersion, '=')) { @@ -645,7 +633,7 @@ class OC_App { * @deprecated 32.0.0 Use IAppManager::getAppInstalledVersions or IAppConfig::getAppInstalledVersions instead */ public static function getAppVersions(): array { - return \OCP\Server::get(IAppConfig::class)->getAppInstalledVersions(); + return Server::get(IAppConfig::class)->getAppInstalledVersions(); } /** @@ -663,13 +651,13 @@ class OC_App { } if (is_file($appPath . '/appinfo/database.xml')) { - \OCP\Server::get(LoggerInterface::class)->error('The appinfo/database.xml file is not longer supported. Used in ' . $appId); + Server::get(LoggerInterface::class)->error('The appinfo/database.xml file is not longer supported. Used in ' . $appId); return false; } \OC::$server->getAppManager()->clearAppsCache(); $l = \OC::$server->getL10N('core'); - $appData = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppInfo($appId, false, $l->getLanguageCode()); + $appData = Server::get(\OCP\App\IAppManager::class)->getAppInfo($appId, false, $l->getLanguageCode()); $ignoreMaxApps = \OC::$server->getConfig()->getSystemValue('app_install_overwrite', []); $ignoreMax = in_array($appId, $ignoreMaxApps, true); @@ -709,9 +697,13 @@ class OC_App { self::setAppTypes($appId); - $version = \OCP\Server::get(\OCP\App\IAppManager::class)->getAppVersion($appId); + $version = Server::get(\OCP\App\IAppManager::class)->getAppVersion($appId); \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version); + // migrate eventual new config keys in the process + /** @psalm-suppress InternalMethod */ + Server::get(ConfigManager::class)->migrateConfigLexiconKeys($appId); + \OC::$server->get(IEventDispatcher::class)->dispatchTyped(new AppUpdateEvent($appId)); \OC::$server->get(IEventDispatcher::class)->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent( ManagerEvent::EVENT_APP_UPDATE, $appId @@ -769,103 +761,6 @@ class OC_App { } /** - * @param string $appId - * @return \OC\Files\View|false - */ - public static function getStorage(string $appId) { - if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check - if (\OC::$server->getUserSession()->isLoggedIn()) { - $view = new \OC\Files\View('/' . OC_User::getUser()); - if (!$view->file_exists($appId)) { - $view->mkdir($appId); - } - return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId); - } else { - \OCP\Server::get(LoggerInterface::class)->error('Can\'t get app storage, app ' . $appId . ', user not logged in', ['app' => 'core']); - return false; - } - } else { - \OCP\Server::get(LoggerInterface::class)->error('Can\'t get app storage, app ' . $appId . ' not enabled', ['app' => 'core']); - return false; - } - } - - protected static function findBestL10NOption(array $options, string $lang): string { - // only a single option - if (isset($options['@value'])) { - return $options['@value']; - } - - $fallback = $similarLangFallback = $englishFallback = false; - - $lang = strtolower($lang); - $similarLang = $lang; - if (strpos($similarLang, '_')) { - // For "de_DE" we want to find "de" and the other way around - $similarLang = substr($lang, 0, strpos($lang, '_')); - } - - foreach ($options as $option) { - if (is_array($option)) { - if ($fallback === false) { - $fallback = $option['@value']; - } - - if (!isset($option['@attributes']['lang'])) { - continue; - } - - $attributeLang = strtolower($option['@attributes']['lang']); - if ($attributeLang === $lang) { - return $option['@value']; - } - - if ($attributeLang === $similarLang) { - $similarLangFallback = $option['@value']; - } elseif (str_starts_with($attributeLang, $similarLang . '_')) { - if ($similarLangFallback === false) { - $similarLangFallback = $option['@value']; - } - } - } else { - $englishFallback = $option; - } - } - - if ($similarLangFallback !== false) { - return $similarLangFallback; - } elseif ($englishFallback !== false) { - return $englishFallback; - } - return (string)$fallback; - } - - /** - * parses the app data array and enhanced the 'description' value - * - * @param array $data the app data - * @param string $lang - * @return array improved app data - */ - public static function parseAppInfo(array $data, $lang = null): array { - if ($lang && isset($data['name']) && is_array($data['name'])) { - $data['name'] = self::findBestL10NOption($data['name'], $lang); - } - if ($lang && isset($data['summary']) && is_array($data['summary'])) { - $data['summary'] = self::findBestL10NOption($data['summary'], $lang); - } - if ($lang && isset($data['description']) && is_array($data['description'])) { - $data['description'] = trim(self::findBestL10NOption($data['description'], $lang)); - } elseif (isset($data['description']) && is_string($data['description'])) { - $data['description'] = trim($data['description']); - } else { - $data['description'] = ''; - } - - return $data; - } - - /** * @param \OCP\IConfig $config * @param \OCP\IL10N $l * @param array $info diff --git a/lib/private/legacy/OC_Defaults.php b/lib/private/legacy/OC_Defaults.php index f7015a1863a..0d460ff966d 100644 --- a/lib/private/legacy/OC_Defaults.php +++ b/lib/private/legacy/OC_Defaults.php @@ -228,9 +228,9 @@ class OC_Defaults { if ($this->themeExist('getShortFooter')) { $footer = $this->theme->getShortFooter(); } else { - $footer = '<a href="' . $this->getBaseUrl() . '" target="_blank"' . - ' rel="noreferrer noopener">' . $this->getEntity() . '</a>' . - ' – ' . $this->getSlogan(); + $footer = '<a href="' . $this->getBaseUrl() . '" target="_blank"' + . ' rel="noreferrer noopener">' . $this->getEntity() . '</a>' + . ' – ' . $this->getSlogan(); } return $footer; diff --git a/lib/private/legacy/OC_Helper.php b/lib/private/legacy/OC_Helper.php index a89cbe1bb3a..4388f775623 100644 --- a/lib/private/legacy/OC_Helper.php +++ b/lib/private/legacy/OC_Helper.php @@ -12,6 +12,7 @@ use OCP\Files\Mount\IMountPoint; use OCP\IBinaryFinder; use OCP\ICacheFactory; use OCP\IUser; +use OCP\Server; use OCP\Util; use Psr\Log\LoggerInterface; @@ -36,85 +37,11 @@ class OC_Helper { private static ?bool $quotaIncludeExternalStorage = null; /** - * Make a human file size - * @param int|float $bytes file size in bytes - * @return string a human readable file size - * - * Makes 2048 to 2 kB. - */ - public static function humanFileSize(int|float $bytes): string { - if ($bytes < 0) { - return '?'; - } - if ($bytes < 1024) { - return "$bytes B"; - } - $bytes = round($bytes / 1024, 0); - if ($bytes < 1024) { - return "$bytes KB"; - } - $bytes = round($bytes / 1024, 1); - if ($bytes < 1024) { - return "$bytes MB"; - } - $bytes = round($bytes / 1024, 1); - if ($bytes < 1024) { - return "$bytes GB"; - } - $bytes = round($bytes / 1024, 1); - if ($bytes < 1024) { - return "$bytes TB"; - } - - $bytes = round($bytes / 1024, 1); - return "$bytes PB"; - } - - /** - * Make a computer file size - * @param string $str file size in human readable format - * @return false|int|float a file size in bytes - * - * Makes 2kB to 2048. - * - * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418 - */ - public static function computerFileSize(string $str): false|int|float { - $str = strtolower($str); - if (is_numeric($str)) { - return Util::numericToNumber($str); - } - - $bytes_array = [ - 'b' => 1, - 'k' => 1024, - 'kb' => 1024, - 'mb' => 1024 * 1024, - 'm' => 1024 * 1024, - 'gb' => 1024 * 1024 * 1024, - 'g' => 1024 * 1024 * 1024, - 'tb' => 1024 * 1024 * 1024 * 1024, - 't' => 1024 * 1024 * 1024 * 1024, - 'pb' => 1024 * 1024 * 1024 * 1024 * 1024, - 'p' => 1024 * 1024 * 1024 * 1024 * 1024, - ]; - - $bytes = (float)$str; - - if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && isset($bytes_array[$matches[1]])) { - $bytes *= $bytes_array[$matches[1]]; - } else { - return false; - } - - return Util::numericToNumber(round($bytes)); - } - - /** * Recursive copying of folders * @param string $src source folder * @param string $dest target folder * @return void + * @deprecated 32.0.0 - use \OCP\Files\Folder::copy */ public static function copyr($src, $dest) { if (!file_exists($src)) { @@ -140,44 +67,6 @@ class OC_Helper { } /** - * Recursive deletion of folders - * @param string $dir path to the folder - * @param bool $deleteSelf if set to false only the content of the folder will be deleted - * @return bool - */ - public static function rmdirr($dir, $deleteSelf = true) { - if (is_dir($dir)) { - $files = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), - RecursiveIteratorIterator::CHILD_FIRST - ); - - foreach ($files as $fileInfo) { - /** @var SplFileInfo $fileInfo */ - if ($fileInfo->isLink()) { - unlink($fileInfo->getPathname()); - } elseif ($fileInfo->isDir()) { - rmdir($fileInfo->getRealPath()); - } else { - unlink($fileInfo->getRealPath()); - } - } - if ($deleteSelf) { - rmdir($dir); - } - } elseif (file_exists($dir)) { - if ($deleteSelf) { - unlink($dir); - } - } - if (!$deleteSelf) { - return true; - } - - return !file_exists($dir); - } - - /** * @deprecated 18.0.0 * @return \OC\Files\Type\TemplateManager */ @@ -196,6 +85,7 @@ class OC_Helper { * @internal param string $program name * @internal param string $optional search path, defaults to $PATH * @return bool true if executable program found in path + * @deprecated 32.0.0 use the \OCP\IBinaryFinder */ public static function canExecute($name, $path = false) { // path defaults to PATH from environment if not set @@ -206,7 +96,7 @@ class OC_Helper { $exts = ['']; $check_fn = 'is_executable'; // Default check will be done with $path directories : - $dirs = explode(PATH_SEPARATOR, $path); + $dirs = explode(PATH_SEPARATOR, (string)$path); // WARNING : We have to check if open_basedir is enabled : $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir'); if ($obd != 'none') { @@ -233,31 +123,10 @@ class OC_Helper { * @param resource $source * @param resource $target * @return array the number of bytes copied and result + * @deprecated 5.0.0 - Use \OCP\Files::streamCopy */ public static function streamCopy($source, $target) { - if (!$source or !$target) { - return [0, false]; - } - $bufSize = 8192; - $result = true; - $count = 0; - while (!feof($source)) { - $buf = fread($source, $bufSize); - $bytesWritten = fwrite($target, $buf); - if ($bytesWritten !== false) { - $count += $bytesWritten; - } - // note: strlen is expensive so only use it when necessary, - // on the last block - if ($bytesWritten === false - || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf)) - ) { - // write error, could be disk full ? - $result = false; - break; - } - } - return [$count, $result]; + return \OCP\Files::streamCopy($source, $target, true); } /** @@ -320,115 +189,20 @@ class OC_Helper { } /** - * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is. - * - * @param array $input The array to work on - * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default) - * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8 - * @return array - * - * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is. - * based on https://www.php.net/manual/en/function.array-change-key-case.php#107715 - * - */ - public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') { - $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER; - $ret = []; - foreach ($input as $k => $v) { - $ret[mb_convert_case($k, $case, $encoding)] = $v; - } - return $ret; - } - - /** - * performs a search in a nested array - * @param array $haystack the array to be searched - * @param string $needle the search string - * @param mixed $index optional, only search this key name - * @return mixed the key of the matching field, otherwise false - * - * performs a search in a nested array - * - * taken from https://www.php.net/manual/en/function.array-search.php#97645 - */ - public static function recursiveArraySearch($haystack, $needle, $index = null) { - $aIt = new RecursiveArrayIterator($haystack); - $it = new RecursiveIteratorIterator($aIt); - - while ($it->valid()) { - if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) { - return $aIt->key(); - } - - $it->next(); - } - - return false; - } - - /** - * calculates the maximum upload size respecting system settings, free space and user quota - * - * @param string $dir the current folder where the user currently operates - * @param int|float $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly - * @return int|float number of bytes representing - */ - public static function maxUploadFilesize($dir, $freeSpace = null) { - if (is_null($freeSpace) || $freeSpace < 0) { - $freeSpace = self::freeSpace($dir); - } - return min($freeSpace, self::uploadLimit()); - } - - /** - * Calculate free space left within user quota - * - * @param string $dir the current folder where the user currently operates - * @return int|float number of bytes representing - */ - public static function freeSpace($dir) { - $freeSpace = \OC\Files\Filesystem::free_space($dir); - if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) { - $freeSpace = max($freeSpace, 0); - return $freeSpace; - } else { - return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188 - } - } - - /** - * Calculate PHP upload limit - * - * @return int|float PHP upload file size limit - */ - public static function uploadLimit() { - $ini = \OC::$server->get(IniGetWrapper::class); - $upload_max_filesize = Util::computerFileSize($ini->get('upload_max_filesize')) ?: 0; - $post_max_size = Util::computerFileSize($ini->get('post_max_size')) ?: 0; - if ($upload_max_filesize === 0 && $post_max_size === 0) { - return INF; - } elseif ($upload_max_filesize === 0 || $post_max_size === 0) { - return max($upload_max_filesize, $post_max_size); //only the non 0 value counts - } else { - return min($upload_max_filesize, $post_max_size); - } - } - - /** * Checks if a function is available * * @deprecated 25.0.0 use \OCP\Util::isFunctionEnabled instead */ public static function is_function_enabled(string $function_name): bool { - return \OCP\Util::isFunctionEnabled($function_name); + return Util::isFunctionEnabled($function_name); } /** * Try to find a program - * @deprecated 25.0.0 Use \OC\BinaryFinder directly + * @deprecated 25.0.0 Use \OCP\IBinaryFinder directly */ public static function findBinaryPath(string $program): ?string { - $result = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath($program); + $result = Server::get(IBinaryFinder::class)->findBinaryPath($program); return $result !== false ? $result : null; } @@ -448,7 +222,7 @@ class OC_Helper { */ public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) { if (!self::$cacheFactory) { - self::$cacheFactory = \OC::$server->get(ICacheFactory::class); + self::$cacheFactory = Server::get(ICacheFactory::class); } $memcache = self::$cacheFactory->createLocal('storage_info'); @@ -498,7 +272,7 @@ class OC_Helper { } else { $user = \OC::$server->getUserSession()->getUser(); } - $quota = OC_Util::getUserQuota($user); + $quota = $user?->getQuotaBytes() ?? \OCP\Files\FileInfo::SPACE_UNKNOWN; if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) { // always get free space / total space from root + mount points return self::getGlobalStorageInfo($quota, $user, $mount); @@ -641,6 +415,7 @@ class OC_Helper { /** * Returns whether the config file is set manually to read-only * @return bool + * @deprecated 32.0.0 use the `config_is_read_only` system config directly */ public static function isReadOnlyConfigEnabled() { return \OC::$server->getConfig()->getSystemValueBool('config_is_read_only', false); diff --git a/lib/private/legacy/OC_Response.php b/lib/private/legacy/OC_Response.php index 86274f5fcb7..c45852b4b1d 100644 --- a/lib/private/legacy/OC_Response.php +++ b/lib/private/legacy/OC_Response.php @@ -78,7 +78,6 @@ class OC_Response { header('X-Frame-Options: SAMEORIGIN'); // Disallow iFraming from other domains header('X-Permitted-Cross-Domain-Policies: none'); // https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html header('X-Robots-Tag: noindex, nofollow'); // https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag - header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters } } } diff --git a/lib/private/legacy/OC_User.php b/lib/private/legacy/OC_User.php index 4cc102d6672..e5343864c45 100644 --- a/lib/private/legacy/OC_User.php +++ b/lib/private/legacy/OC_User.php @@ -6,7 +6,7 @@ * SPDX-License-Identifier: AGPL-3.0-only */ use OC\Authentication\Token\IProvider; -use OC\User\LoginException; +use OC\User\DisabledUserException; use OCP\Authentication\Exceptions\InvalidTokenException; use OCP\Authentication\Exceptions\WipeTokenException; use OCP\Authentication\Token\IToken; @@ -40,8 +40,6 @@ use Psr\Log\LoggerInterface; * logout() */ class OC_User { - private static $_usedBackends = []; - private static $_setupedBackends = []; // bool, stores if a user want to access a resource anonymously, e.g if they open a public link @@ -52,14 +50,13 @@ class OC_User { * * @param string|\OCP\UserInterface $backend default: database The backend to use for user management * @return bool + * @deprecated 32.0.0 Use IUserManager::registerBackend instead * * Set the User Authentication Module - * @suppress PhanDeprecatedFunction */ public static function useBackend($backend = 'database') { if ($backend instanceof \OCP\UserInterface) { - self::$_usedBackends[get_class($backend)] = $backend; - \OC::$server->getUserManager()->registerBackend($backend); + Server::get(IUserManager::class)->registerBackend($backend); } else { // You'll never know what happens if ($backend === null or !is_string($backend)) { @@ -72,18 +69,15 @@ class OC_User { case 'mysql': case 'sqlite': Server::get(LoggerInterface::class)->debug('Adding user backend ' . $backend . '.', ['app' => 'core']); - self::$_usedBackends[$backend] = new \OC\User\Database(); - \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]); + Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); break; case 'dummy': - self::$_usedBackends[$backend] = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]); + Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy()); break; default: Server::get(LoggerInterface::class)->debug('Adding default user backend ' . $backend . '.', ['app' => 'core']); $className = 'OC_USER_' . strtoupper($backend); - self::$_usedBackends[$backend] = new $className(); - \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]); + Server::get(IUserManager::class)->registerBackend(new $className()); break; } } @@ -92,10 +86,10 @@ class OC_User { /** * remove all used backends + * @deprecated 32.0.0 Use IUserManager::clearBackends instead */ public static function clearBackends() { - self::$_usedBackends = []; - \OC::$server->getUserManager()->clearBackends(); + Server::get(IUserManager::class)->clearBackends(); } /** @@ -157,7 +151,7 @@ class OC_User { if ($userSession->getUser() && !$userSession->getUser()->isEnabled()) { $message = \OC::$server->getL10N('lib')->t('Account disabled'); - throw new LoginException($message); + throw new DisabledUserException($message); } $userSession->setLoginName($uid); $request = OC::$server->getRequest(); @@ -248,7 +242,7 @@ class OC_User { */ public static function setUserId($uid) { $userSession = \OC::$server->getUserSession(); - $userManager = \OC::$server->getUserManager(); + $userManager = Server::get(IUserManager::class); if ($user = $userManager->get($uid)) { $userSession->setUser($user); } else { @@ -348,7 +342,7 @@ class OC_User { * Change the password of a user */ public static function setPassword($uid, $password, $recoveryPassword = null) { - $user = \OC::$server->getUserManager()->get($uid); + $user = Server::get(IUserManager::class)->get($uid); if ($user) { return $user->setPassword($password, $recoveryPassword); } else { @@ -364,7 +358,7 @@ class OC_User { * @deprecated 12.0.0 Use \OC::$server->getUserManager->getHome() */ public static function getHome($uid) { - $user = \OC::$server->getUserManager()->get($uid); + $user = Server::get(IUserManager::class)->get($uid); if ($user) { return $user->getHome(); } else { @@ -385,7 +379,7 @@ class OC_User { */ public static function getDisplayNames($search = '', $limit = null, $offset = null) { $displayNames = []; - $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset); + $users = Server::get(IUserManager::class)->searchDisplayName($search, $limit, $offset); foreach ($users as $user) { $displayNames[$user->getUID()] = $user->getDisplayName(); } @@ -398,7 +392,7 @@ class OC_User { * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend */ private static function findFirstActiveUsedBackend() { - foreach (self::$_usedBackends as $backend) { + foreach (Server::get(IUserManager::class)->getBackends() as $backend) { if ($backend instanceof OCP\Authentication\IApacheBackend) { if ($backend->isSessionActive()) { return $backend; diff --git a/lib/private/legacy/OC_Util.php b/lib/private/legacy/OC_Util.php index 36a121094cc..ebca1105838 100644 --- a/lib/private/legacy/OC_Util.php +++ b/lib/private/legacy/OC_Util.php @@ -9,7 +9,6 @@ use bantu\IniGetWrapper\IniGetWrapper; use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; use OC\Files\SetupManager; use OCP\Files\Template\ITemplateManager; -use OCP\Http\Client\IClientService; use OCP\IConfig; use OCP\IGroupManager; use OCP\IURLGenerator; @@ -19,18 +18,13 @@ use OCP\Security\ISecureRandom; use OCP\Share\IManager; use Psr\Log\LoggerInterface; +/** + * @deprecated 32.0.0 Use \OCP\Util or any appropriate official API instead + */ class OC_Util { - public static $scripts = []; public static $styles = []; public static $headers = []; - /** @var array Local cache of version.php */ - private static $versionCache = null; - - protected static function getAppManager() { - return \OC::$server->getAppManager(); - } - /** * Setup the file system * @@ -63,8 +57,8 @@ class OC_Util { * Check if a password is required for each public link * * @param bool $checkGroupMembership Check group membership exclusion - * @return boolean - * @suppress PhanDeprecatedFunction + * @return bool + * @deprecated 32.0.0 use OCP\Share\IManager's shareApiLinkEnforcePassword directly */ public static function isPublicLinkPasswordRequired(bool $checkGroupMembership = true) { /** @var IManager $shareManager */ @@ -78,6 +72,7 @@ class OC_Util { * @param IGroupManager $groupManager * @param IUser|null $user * @return bool + * @deprecated 32.0.0 use OCP\Share\IManager's sharingDisabledForUser directly */ public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) { /** @var IManager $shareManager */ @@ -90,7 +85,7 @@ class OC_Util { * check if share API enforces a default expire date * * @return bool - * @suppress PhanDeprecatedFunction + * @deprecated 32.0.0 use OCP\Share\IManager's shareApiLinkDefaultExpireDateEnforced directly */ public static function isDefaultExpireDateEnforced() { /** @var IManager $shareManager */ @@ -103,6 +98,7 @@ class OC_Util { * * @param IUser|null $user * @return int|\OCP\Files\FileInfo::SPACE_UNLIMITED|false|float Quota bytes + * @deprecated 9.0.0 - Use \OCP\IUser::getQuota or \OCP\IUser::getQuotaBytes */ public static function getUserQuota(?IUser $user) { if (is_null($user)) { @@ -112,7 +108,7 @@ class OC_Util { if ($userQuota === 'none') { return \OCP\Files\FileInfo::SPACE_UNLIMITED; } - return OC_Helper::computerFileSize($userQuota); + return \OCP\Util::computerFileSize($userQuota); } /** @@ -191,14 +187,13 @@ class OC_Util { $child = $target->newFolder($file); self::copyr($source . '/' . $file, $child); } else { - $child = $target->newFile($file); $sourceStream = fopen($source . '/' . $file, 'r'); if ($sourceStream === false) { $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']); closedir($dir); return; } - $child->putContent($sourceStream); + $target->newFile($file, $sourceStream); } } } @@ -206,12 +201,10 @@ class OC_Util { } /** - * @return void - * @suppress PhanUndeclaredMethod + * @deprecated 32.0.0 Call tearDown directly on SetupManager */ - public static function tearDownFS() { - /** @var SetupManager $setupManager */ - $setupManager = \OC::$server->get(SetupManager::class); + public static function tearDownFS(): void { + $setupManager = \OCP\Server::get(SetupManager::class); $setupManager->tearDown(); } @@ -220,10 +213,9 @@ class OC_Util { * * @param string $application application to get the files from * @param string $directory directory within this application (css, js, vendor, etc) - * @param string $file the file inside of the above folder - * @return string the path + * @param ?string $file the file inside of the above folder */ - private static function generatePath($application, $directory, $file) { + private static function generatePath($application, $directory, $file): string { if (is_null($file)) { $file = $application; $application = ''; @@ -236,68 +228,14 @@ class OC_Util { } /** - * add a javascript file - * - * @deprecated 24.0.0 - Use \OCP\Util::addScript - * - * @param string $application application id - * @param string|null $file filename - * @param bool $prepend prepend the Script to the beginning of the list - * @return void - */ - public static function addScript($application, $file = null, $prepend = false) { - $path = OC_Util::generatePath($application, 'js', $file); - - // core js files need separate handling - if ($application !== 'core' && $file !== null) { - self::addTranslations($application); - } - self::addExternalResource($application, $prepend, $path, 'script'); - } - - /** - * add a javascript file from the vendor sub folder - * - * @param string $application application id - * @param string|null $file filename - * @param bool $prepend prepend the Script to the beginning of the list - * @return void - */ - public static function addVendorScript($application, $file = null, $prepend = false) { - $path = OC_Util::generatePath($application, 'vendor', $file); - self::addExternalResource($application, $prepend, $path, 'script'); - } - - /** - * add a translation JS file - * - * @deprecated 24.0.0 - * - * @param string $application application id - * @param string|null $languageCode language code, defaults to the current language - * @param bool|null $prepend prepend the Script to the beginning of the list - */ - public static function addTranslations($application, $languageCode = null, $prepend = false) { - if (is_null($languageCode)) { - $languageCode = \OC::$server->get(IFactory::class)->findLanguage($application); - } - if (!empty($application)) { - $path = "$application/l10n/$languageCode"; - } else { - $path = "l10n/$languageCode"; - } - self::addExternalResource($application, $prepend, $path, 'script'); - } - - /** * add a css file * * @param string $application application id * @param string|null $file filename * @param bool $prepend prepend the Style to the beginning of the list - * @return void + * @deprecated 32.0.0 Use \OCP\Util::addStyle */ - public static function addStyle($application, $file = null, $prepend = false) { + public static function addStyle($application, $file = null, $prepend = false): void { $path = OC_Util::generatePath($application, 'css', $file); self::addExternalResource($application, $prepend, $path, 'style'); } @@ -308,9 +246,9 @@ class OC_Util { * @param string $application application id * @param string|null $file filename * @param bool $prepend prepend the Style to the beginning of the list - * @return void + * @deprecated 32.0.0 */ - public static function addVendorStyle($application, $file = null, $prepend = false) { + public static function addVendorStyle($application, $file = null, $prepend = false): void { $path = OC_Util::generatePath($application, 'vendor', $file); self::addExternalResource($application, $prepend, $path, 'style'); } @@ -322,9 +260,8 @@ class OC_Util { * @param bool $prepend prepend the file to the beginning of the list * @param string $path * @param string $type (script or style) - * @return void */ - private static function addExternalResource($application, $prepend, $path, $type = 'script') { + private static function addExternalResource($application, $prepend, $path, $type = 'script'): void { if ($type === 'style') { if (!in_array($path, self::$styles)) { if ($prepend === true) { @@ -333,14 +270,6 @@ class OC_Util { self::$styles[] = $path; } } - } elseif ($type === 'script') { - if (!in_array($path, self::$scripts)) { - if ($prepend === true) { - array_unshift(self::$scripts, $path); - } else { - self::$scripts [] = $path; - } - } } } @@ -352,8 +281,9 @@ class OC_Util { * @param array $attributes array of attributes for the element * @param string $text the text content for the element * @param bool $prepend prepend the header to the beginning of the list + * @deprecated 32.0.0 Use \OCP\Util::addHeader instead */ - public static function addHeader($tag, $attributes, $text = null, $prepend = false) { + public static function addHeader($tag, $attributes, $text = null, $prepend = false): void { $header = [ 'tag' => $tag, 'attributes' => $attributes, @@ -369,7 +299,6 @@ class OC_Util { /** * check if the current server configuration is suitable for ownCloud * - * @param \OC\SystemConfig $config * @return array arrays with error messages and hints */ public static function checkServer(\OC\SystemConfig $config) { @@ -402,7 +331,7 @@ class OC_Util { } // Check if config folder is writable. - if (!OC_Helper::isReadOnlyConfigEnabled()) { + if (!(bool)$config->getValue('config_is_read_only', false)) { if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) { $errors[] = [ 'error' => $l->t('Cannot write into "config" directory.'), @@ -414,19 +343,6 @@ class OC_Util { } } - // Check if there is a writable install folder. - if ($config->getValue('appstoreenabled', true)) { - if (OC_App::getInstallPath() === null - || !is_writable(OC_App::getInstallPath()) - || !is_readable(OC_App::getInstallPath()) - ) { - $errors[] = [ - 'error' => $l->t('Cannot write into "apps" directory.'), - 'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory' - . ' or disabling the App Store in the config file.') - ]; - } - } // Create root dir. if ($config->getValue('installed', false)) { if (!is_dir($CONFIG_DATADIRECTORY)) { @@ -550,8 +466,8 @@ class OC_Util { * TODO: Should probably be implemented in the above generic dependency * check somehow in the long-term. */ - if ($iniWrapper->getBool('mbstring.func_overload') !== null && - $iniWrapper->getBool('mbstring.func_overload') === true) { + if ($iniWrapper->getBool('mbstring.func_overload') !== null + && $iniWrapper->getBool('mbstring.func_overload') === true) { $errors[] = [ 'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]), 'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.') @@ -592,6 +508,7 @@ class OC_Util { * * @param string $dataDirectory * @return array arrays with error messages and hints + * @internal */ public static function checkDataDirectoryPermissions($dataDirectory) { if (!\OC::$server->getConfig()->getSystemValueBool('check_data_directory_permissions', true)) { @@ -620,6 +537,7 @@ class OC_Util { * * @param string $dataDirectory data directory path * @return array errors found + * @internal */ public static function checkDataDirectoryValidity($dataDirectory) { $l = \OC::$server->getL10N('lib'); @@ -644,9 +562,9 @@ class OC_Util { * Check if the user is logged in, redirects to home if not. With * redirect URL parameter to the request URI. * - * @return void + * @deprecated 32.0.0 */ - public static function checkLoggedIn() { + public static function checkLoggedIn(): void { // Check if we are a user if (!\OC::$server->getUserSession()->isLoggedIn()) { header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute( @@ -668,10 +586,10 @@ class OC_Util { /** * Check if the user is a admin, redirects to home if not * - * @return void + * @deprecated 32.0.0 */ - public static function checkAdminUser() { - OC_Util::checkLoggedIn(); + public static function checkAdminUser(): void { + self::checkLoggedIn(); if (!OC_User::isAdminUser(OC_User::getUser())) { header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php')); exit(); @@ -684,7 +602,7 @@ class OC_Util { * the apps visible for the current user * * @return string URL - * @suppress PhanDeprecatedFunction + * @deprecated 32.0.0 use IURLGenerator's linkToDefaultPageUrl directly */ public static function getDefaultPageUrl() { /** @var IURLGenerator $urlGenerator */ @@ -695,9 +613,9 @@ class OC_Util { /** * Redirect to the user default page * - * @return void + * @deprecated 32.0.0 */ - public static function redirectToDefaultPage() { + public static function redirectToDefaultPage(): void { $location = self::getDefaultPageUrl(); header('Location: ' . $location); exit(); @@ -708,7 +626,7 @@ class OC_Util { * * @return string */ - public static function getInstanceId() { + public static function getInstanceId(): string { $id = \OC::$server->getSystemConfig()->getValue('instanceid', null); if (is_null($id)) { // We need to guarantee at least one letter in instanceid so it can be used as the session_name @@ -726,6 +644,7 @@ class OC_Util { * * @param string|string[] $value * @return ($value is array ? string[] : string) + * @deprecated 32.0.0 use \OCP\Util::sanitizeHTML instead */ public static function sanitizeHTML($value) { if (is_array($value)) { @@ -748,6 +667,7 @@ class OC_Util { * * @param string $component part of URI to encode * @return string + * @deprecated 32.0.0 use \OCP\Util::encodePath instead */ public static function encodePath($component) { $encoded = rawurlencode($component); @@ -755,86 +675,6 @@ class OC_Util { return $encoded; } - - public function createHtaccessTestFile(\OCP\IConfig $config) { - // php dev server does not support htaccess - if (php_sapi_name() === 'cli-server') { - return false; - } - - // testdata - $fileName = '/htaccesstest.txt'; - $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.'; - - // creating a test file - $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName; - - if (file_exists($testFile)) {// already running this test, possible recursive call - return false; - } - - $fp = @fopen($testFile, 'w'); - if (!$fp) { - throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.', - 'Make sure it is possible for the web server to write to ' . $testFile); - } - fwrite($fp, $testContent); - fclose($fp); - - return $testContent; - } - - /** - * Check if the .htaccess file is working - * - * @param \OCP\IConfig $config - * @return bool - * @throws Exception - * @throws \OCP\HintException If the test file can't get written. - */ - public function isHtaccessWorking(\OCP\IConfig $config) { - if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) { - return true; - } - - $testContent = $this->createHtaccessTestFile($config); - if ($testContent === false) { - return false; - } - - $fileName = '/htaccesstest.txt'; - $testFile = $config->getSystemValueString('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName; - - // accessing the file via http - $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName); - try { - $content = \OC::$server->get(IClientService::class)->newClient()->get($url)->getBody(); - } catch (\Exception $e) { - $content = false; - } - - if (str_starts_with($url, 'https:')) { - $url = 'http:' . substr($url, 6); - } else { - $url = 'https:' . substr($url, 5); - } - - try { - $fallbackContent = \OC::$server->get(IClientService::class)->newClient()->get($url)->getBody(); - } catch (\Exception $e) { - $fallbackContent = false; - } - - // cleanup - @unlink($testFile); - - /* - * If the content is not equal to test content our .htaccess - * is working as required - */ - return $content !== $testContent && $fallbackContent !== $testContent; - } - /** * Check if current locale is non-UTF8 * @@ -854,9 +694,9 @@ class OC_Util { * Check if the setlocale call does not work. This can happen if the right * local packages are not available on the server. * - * @return bool + * @internal */ - public static function isSetLocaleWorking() { + public static function isSetLocaleWorking(): bool { if (self::isNonUTF8Locale()) { // Borrowed from \Patchwork\Utf8\Bootup::initLocale setlocale(LC_ALL, 'C.UTF-8', 'C'); @@ -874,9 +714,9 @@ class OC_Util { /** * Check if it's possible to get the inline annotations * - * @return bool + * @internal */ - public static function isAnnotationsWorking() { + public static function isAnnotationsWorking(): bool { if (PHP_VERSION_ID >= 80300) { /** @psalm-suppress UndefinedMethod */ $reflection = \ReflectionMethod::createFromMethodName(__METHOD__); @@ -891,9 +731,9 @@ class OC_Util { /** * Check if the PHP module fileinfo is loaded. * - * @return bool + * @internal */ - public static function fileInfoLoaded() { + public static function fileInfoLoaded(): bool { return function_exists('finfo_open'); } @@ -963,6 +803,7 @@ class OC_Util { * @param \OC\SystemConfig $config * @return bool whether the core or any app needs an upgrade * @throws \OCP\HintException When the upgrade from the given version is not allowed + * @deprecated 32.0.0 Use \OCP\Util::needUpgrade instead */ public static function needUpgrade(\OC\SystemConfig $config) { if ($config->getValue('installed', false)) { |