Util.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. // use OCP namespace for all classes that are considered public.
  8. // This means that they should be used by apps instead of the internal Nextcloud classes
  9. namespace OCP;
  10. use bantu\IniGetWrapper\IniGetWrapper;
  11. use OC\AppScriptDependency;
  12. use OC\AppScriptSort;
  13. use OC\Security\CSRF\CsrfTokenManager;
  14. use OCP\L10N\IFactory;
  15. use OCP\Mail\IMailer;
  16. use OCP\Share\IManager;
  17. use Psr\Container\ContainerExceptionInterface;
  18. use Psr\Log\LoggerInterface;
  19. /**
  20. * This class provides different helper functions to make the life of a developer easier
  21. *
  22. * @since 4.0.0
  23. */
  24. class Util {
  25. private static ?IManager $shareManager = null;
  26. private static array $scriptsInit = [];
  27. private static array $scripts = [];
  28. private static array $scriptDeps = [];
  29. /**
  30. * get the current installed version of Nextcloud
  31. * @return array
  32. * @since 4.0.0
  33. */
  34. public static function getVersion() {
  35. return \OC_Util::getVersion();
  36. }
  37. /**
  38. * @since 17.0.0
  39. */
  40. public static function hasExtendedSupport(): bool {
  41. try {
  42. /** @var \OCP\Support\Subscription\IRegistry */
  43. $subscriptionRegistry = \OCP\Server::get(\OCP\Support\Subscription\IRegistry::class);
  44. return $subscriptionRegistry->delegateHasExtendedSupport();
  45. } catch (ContainerExceptionInterface $e) {
  46. }
  47. return \OC::$server->getConfig()->getSystemValueBool('extendedSupport', false);
  48. }
  49. /**
  50. * Set current update channel
  51. * @param string $channel
  52. * @since 8.1.0
  53. */
  54. public static function setChannel($channel) {
  55. \OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
  56. }
  57. /**
  58. * Get current update channel
  59. * @return string
  60. * @since 8.1.0
  61. */
  62. public static function getChannel() {
  63. return \OC_Util::getChannel();
  64. }
  65. /**
  66. * check if sharing is disabled for the current user
  67. *
  68. * @return boolean
  69. * @since 7.0.0
  70. * @deprecated 9.1.0 Use \OC::$server->get(\OCP\Share\IManager::class)->sharingDisabledForUser
  71. */
  72. public static function isSharingDisabledForUser() {
  73. if (self::$shareManager === null) {
  74. self::$shareManager = \OC::$server->get(IManager::class);
  75. }
  76. $user = \OC::$server->getUserSession()->getUser();
  77. if ($user !== null) {
  78. $user = $user->getUID();
  79. }
  80. return self::$shareManager->sharingDisabledForUser($user);
  81. }
  82. /**
  83. * get l10n object
  84. * @since 6.0.0 - parameter $language was added in 8.0.0
  85. */
  86. public static function getL10N(string $application, ?string $language = null): IL10N {
  87. return Server::get(\OCP\L10N\IFactory::class)->get($application, $language);
  88. }
  89. /**
  90. * add a css file
  91. * @param string $application
  92. * @param string $file
  93. * @since 4.0.0
  94. */
  95. public static function addStyle($application, $file = null) {
  96. \OC_Util::addStyle($application, $file);
  97. }
  98. /**
  99. * Add a standalone init js file that is loaded for initialization
  100. *
  101. * Be careful loading scripts using this method as they are loaded early
  102. * and block the initial page rendering. They should not have dependencies
  103. * on any other scripts than core-common and core-main.
  104. *
  105. * @since 28.0.0
  106. */
  107. public static function addInitScript(string $application, string $file): void {
  108. if (!empty($application)) {
  109. $path = "$application/js/$file";
  110. } else {
  111. $path = "js/$file";
  112. }
  113. // We need to handle the translation BEFORE the init script
  114. // is loaded, as the init script might use translations
  115. if ($application !== 'core' && !str_contains($file, 'l10n')) {
  116. self::addTranslations($application, null, true);
  117. }
  118. self::$scriptsInit[] = $path;
  119. }
  120. /**
  121. * add a javascript file
  122. *
  123. * @param string $application
  124. * @param string|null $file
  125. * @param string $afterAppId
  126. * @param bool $prepend
  127. * @since 4.0.0
  128. */
  129. public static function addScript(string $application, ?string $file = null, string $afterAppId = 'core', bool $prepend = false): void {
  130. if (!empty($application)) {
  131. $path = "$application/js/$file";
  132. } else {
  133. $path = "js/$file";
  134. }
  135. // Inject js translations if we load a script for
  136. // a specific app that is not core, as those js files
  137. // need separate handling
  138. if ($application !== 'core'
  139. && $file !== null
  140. && !str_contains($file, 'l10n')) {
  141. self::addTranslations($application);
  142. }
  143. // store app in dependency list
  144. if (!array_key_exists($application, self::$scriptDeps)) {
  145. self::$scriptDeps[$application] = new AppScriptDependency($application, [$afterAppId]);
  146. } else {
  147. self::$scriptDeps[$application]->addDep($afterAppId);
  148. }
  149. if ($prepend) {
  150. array_unshift(self::$scripts[$application], $path);
  151. } else {
  152. self::$scripts[$application][] = $path;
  153. }
  154. }
  155. /**
  156. * Return the list of scripts injected to the page
  157. *
  158. * @return array
  159. * @since 24.0.0
  160. */
  161. public static function getScripts(): array {
  162. // Sort scriptDeps into sortedScriptDeps
  163. $scriptSort = \OC::$server->get(AppScriptSort::class);
  164. $sortedScripts = $scriptSort->sort(self::$scripts, self::$scriptDeps);
  165. // Flatten array and remove duplicates
  166. $sortedScripts = array_merge([self::$scriptsInit], $sortedScripts);
  167. $sortedScripts = array_merge(...array_values($sortedScripts));
  168. // Override core-common and core-main order
  169. if (in_array('core/js/main', $sortedScripts)) {
  170. array_unshift($sortedScripts, 'core/js/main');
  171. }
  172. if (in_array('core/js/common', $sortedScripts)) {
  173. array_unshift($sortedScripts, 'core/js/common');
  174. }
  175. return array_unique($sortedScripts);
  176. }
  177. /**
  178. * Add a translation JS file
  179. * @param string $application application id
  180. * @param string $languageCode language code, defaults to the current locale
  181. * @param bool $init whether the translations should be loaded early or not
  182. * @since 8.0.0
  183. */
  184. public static function addTranslations($application, $languageCode = null, $init = false) {
  185. if (is_null($languageCode)) {
  186. $languageCode = \OC::$server->get(IFactory::class)->findLanguage($application);
  187. }
  188. if (!empty($application)) {
  189. $path = "$application/l10n/$languageCode";
  190. } else {
  191. $path = "l10n/$languageCode";
  192. }
  193. if ($init) {
  194. self::$scriptsInit[] = $path;
  195. } else {
  196. self::$scripts[$application][] = $path;
  197. }
  198. }
  199. /**
  200. * Add a custom element to the header
  201. * If $text is null then the element will be written as empty element.
  202. * So use "" to get a closing tag.
  203. * @param string $tag tag name of the element
  204. * @param array $attributes array of attributes for the element
  205. * @param string $text the text content for the element
  206. * @since 4.0.0
  207. */
  208. public static function addHeader($tag, $attributes, $text = null) {
  209. \OC_Util::addHeader($tag, $attributes, $text);
  210. }
  211. /**
  212. * Creates an absolute url to the given app and file.
  213. * @param string $app app
  214. * @param string $file file
  215. * @param array $args array with param=>value, will be appended to the returned url
  216. * The value of $args will be urlencoded
  217. * @return string the url
  218. * @since 4.0.0 - parameter $args was added in 4.5.0
  219. */
  220. public static function linkToAbsolute($app, $file, $args = []) {
  221. $urlGenerator = \OC::$server->getURLGenerator();
  222. return $urlGenerator->getAbsoluteURL(
  223. $urlGenerator->linkTo($app, $file, $args)
  224. );
  225. }
  226. /**
  227. * Creates an absolute url for remote use.
  228. * @param string $service id
  229. * @return string the url
  230. * @since 4.0.0
  231. */
  232. public static function linkToRemote($service) {
  233. $urlGenerator = \OC::$server->getURLGenerator();
  234. $remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
  235. return $urlGenerator->getAbsoluteURL(
  236. $remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
  237. );
  238. }
  239. /**
  240. * Returns the server host name without an eventual port number
  241. * @return string the server hostname
  242. * @since 5.0.0
  243. */
  244. public static function getServerHostName() {
  245. $host_name = \OC::$server->getRequest()->getServerHost();
  246. // strip away port number (if existing)
  247. $colon_pos = strpos($host_name, ':');
  248. if ($colon_pos != false) {
  249. $host_name = substr($host_name, 0, $colon_pos);
  250. }
  251. return $host_name;
  252. }
  253. /**
  254. * Returns the default email address
  255. * @param string $user_part the user part of the address
  256. * @return string the default email address
  257. *
  258. * Assembles a default email address (using the server hostname
  259. * and the given user part, and returns it
  260. * Example: when given lostpassword-noreply as $user_part param,
  261. * and is currently accessed via http(s)://example.com/,
  262. * it would return 'lostpassword-noreply@example.com'
  263. *
  264. * If the configuration value 'mail_from_address' is set in
  265. * config.php, this value will override the $user_part that
  266. * is passed to this function
  267. * @since 5.0.0
  268. */
  269. public static function getDefaultEmailAddress(string $user_part): string {
  270. $config = \OC::$server->getConfig();
  271. $user_part = $config->getSystemValueString('mail_from_address', $user_part);
  272. $host_name = self::getServerHostName();
  273. $host_name = $config->getSystemValueString('mail_domain', $host_name);
  274. $defaultEmailAddress = $user_part.'@'.$host_name;
  275. $mailer = \OC::$server->get(IMailer::class);
  276. if ($mailer->validateMailAddress($defaultEmailAddress)) {
  277. return $defaultEmailAddress;
  278. }
  279. // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
  280. return $user_part.'@localhost.localdomain';
  281. }
  282. /**
  283. * Converts string to int of float depending if it fits an int
  284. * @param numeric-string|float|int $number numeric string
  285. * @return int|float int if it fits, float if it is too big
  286. * @since 26.0.0
  287. */
  288. public static function numericToNumber(string|float|int $number): int|float {
  289. /* This is a hack to cast to (int|float) */
  290. return 0 + (string)$number;
  291. }
  292. /**
  293. * Make a human file size (2048 to 2 kB)
  294. * @param int|float $bytes file size in bytes
  295. * @return string a human readable file size
  296. * @since 4.0.0
  297. */
  298. public static function humanFileSize(int|float $bytes): string {
  299. return \OC_Helper::humanFileSize($bytes);
  300. }
  301. /**
  302. * Make a computer file size (2 kB to 2048)
  303. * @param string $str file size in a fancy format
  304. * @return false|int|float a file size in bytes
  305. *
  306. * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418
  307. * @since 4.0.0
  308. */
  309. public static function computerFileSize(string $str): false|int|float {
  310. return \OC_Helper::computerFileSize($str);
  311. }
  312. /**
  313. * connects a function to a hook
  314. *
  315. * @param string $signalClass class name of emitter
  316. * @param string $signalName name of signal
  317. * @param string|object $slotClass class name of slot
  318. * @param string $slotName name of slot
  319. * @return bool
  320. *
  321. * This function makes it very easy to connect to use hooks.
  322. *
  323. * TODO: write example
  324. * @since 4.0.0
  325. * @deprecated 21.0.0 use \OCP\EventDispatcher\IEventDispatcher::addListener
  326. */
  327. public static function connectHook($signalClass, $signalName, $slotClass, $slotName) {
  328. return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
  329. }
  330. /**
  331. * Emits a signal. To get data from the slot use references!
  332. * @param string $signalclass class name of emitter
  333. * @param string $signalname name of signal
  334. * @param array $params default: array() array with additional data
  335. * @return bool true if slots exists or false if not
  336. *
  337. * TODO: write example
  338. * @since 4.0.0
  339. * @deprecated 21.0.0 use \OCP\EventDispatcher\IEventDispatcher::dispatchTypedEvent
  340. */
  341. public static function emitHook($signalclass, $signalname, $params = []) {
  342. return \OC_Hook::emit($signalclass, $signalname, $params);
  343. }
  344. /**
  345. * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
  346. * multiple OC_Template elements which invoke `callRegister`. If the value
  347. * would not be cached these unit-tests would fail.
  348. * @var string
  349. */
  350. private static $token = '';
  351. /**
  352. * Register an get/post call. This is important to prevent CSRF attacks
  353. * @since 4.5.0
  354. */
  355. public static function callRegister() {
  356. if (self::$token === '') {
  357. self::$token = \OC::$server->get(CsrfTokenManager::class)->getToken()->getEncryptedValue();
  358. }
  359. return self::$token;
  360. }
  361. /**
  362. * Used to sanitize HTML
  363. *
  364. * This function is used to sanitize HTML and should be applied on any
  365. * string or array of strings before displaying it on a web page.
  366. *
  367. * @param string|string[] $value
  368. * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
  369. * @since 4.5.0
  370. */
  371. public static function sanitizeHTML($value) {
  372. return \OC_Util::sanitizeHTML($value);
  373. }
  374. /**
  375. * Public function to encode url parameters
  376. *
  377. * This function is used to encode path to file before output.
  378. * Encoding is done according to RFC 3986 with one exception:
  379. * Character '/' is preserved as is.
  380. *
  381. * @param string $component part of URI to encode
  382. * @return string
  383. * @since 6.0.0
  384. */
  385. public static function encodePath($component) {
  386. return \OC_Util::encodePath($component);
  387. }
  388. /**
  389. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  390. *
  391. * @param array $input The array to work on
  392. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  393. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  394. * @return array
  395. * @since 4.5.0
  396. */
  397. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  398. return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
  399. }
  400. /**
  401. * performs a search in a nested array
  402. *
  403. * @param array $haystack the array to be searched
  404. * @param string $needle the search string
  405. * @param mixed $index optional, only search this key name
  406. * @return mixed the key of the matching field, otherwise false
  407. * @since 4.5.0
  408. * @deprecated 15.0.0
  409. */
  410. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  411. return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
  412. }
  413. /**
  414. * calculates the maximum upload size respecting system settings, free space and user quota
  415. *
  416. * @param string $dir the current folder where the user currently operates
  417. * @param int|float|null $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
  418. * @return int|float number of bytes representing
  419. * @since 5.0.0
  420. */
  421. public static function maxUploadFilesize(string $dir, int|float|null $free = null): int|float {
  422. return \OC_Helper::maxUploadFilesize($dir, $free);
  423. }
  424. /**
  425. * Calculate free space left within user quota
  426. * @param string $dir the current folder where the user currently operates
  427. * @return int|float number of bytes representing
  428. * @since 7.0.0
  429. */
  430. public static function freeSpace(string $dir): int|float {
  431. return \OC_Helper::freeSpace($dir);
  432. }
  433. /**
  434. * Calculate PHP upload limit
  435. *
  436. * @return int|float number of bytes representing
  437. * @since 7.0.0
  438. */
  439. public static function uploadLimit(): int|float {
  440. return \OC_Helper::uploadLimit();
  441. }
  442. /**
  443. * Get a list of characters forbidden in file names
  444. * @return string[]
  445. * @since 29.0.0
  446. */
  447. public static function getForbiddenFileNameChars(): array {
  448. // Get always forbidden characters
  449. $invalidChars = str_split(\OCP\Constants::FILENAME_INVALID_CHARS);
  450. if ($invalidChars === false) {
  451. $invalidChars = [];
  452. }
  453. // Get admin defined invalid characters
  454. $additionalChars = \OCP\Server::get(IConfig::class)->getSystemValue('forbidden_chars', []);
  455. if (!is_array($additionalChars)) {
  456. \OCP\Server::get(LoggerInterface::class)->error('Invalid system config value for "forbidden_chars" is ignored.');
  457. $additionalChars = [];
  458. }
  459. return array_merge($invalidChars, $additionalChars);
  460. }
  461. /**
  462. * Returns whether the given file name is valid
  463. * @param string $file file name to check
  464. * @return bool true if the file name is valid, false otherwise
  465. * @deprecated 8.1.0 use OCP\Files\Storage\IStorage::verifyPath()
  466. * @since 7.0.0
  467. * @suppress PhanDeprecatedFunction
  468. */
  469. public static function isValidFileName($file) {
  470. return \OC_Util::isValidFileName($file);
  471. }
  472. /**
  473. * Compare two strings to provide a natural sort
  474. * @param string $a first string to compare
  475. * @param string $b second string to compare
  476. * @return int -1 if $b comes before $a, 1 if $a comes before $b
  477. * or 0 if the strings are identical
  478. * @since 7.0.0
  479. */
  480. public static function naturalSortCompare($a, $b) {
  481. return \OC\NaturalSort::getInstance()->compare($a, $b);
  482. }
  483. /**
  484. * Check if a password is required for each public link
  485. *
  486. * @param bool $checkGroupMembership Check group membership exclusion
  487. * @return boolean
  488. * @since 7.0.0
  489. */
  490. public static function isPublicLinkPasswordRequired(bool $checkGroupMembership = true) {
  491. return \OC_Util::isPublicLinkPasswordRequired($checkGroupMembership);
  492. }
  493. /**
  494. * check if share API enforces a default expire date
  495. * @return boolean
  496. * @since 8.0.0
  497. */
  498. public static function isDefaultExpireDateEnforced() {
  499. return \OC_Util::isDefaultExpireDateEnforced();
  500. }
  501. protected static $needUpgradeCache = null;
  502. /**
  503. * Checks whether the current version needs upgrade.
  504. *
  505. * @return bool true if upgrade is needed, false otherwise
  506. * @since 7.0.0
  507. */
  508. public static function needUpgrade() {
  509. if (!isset(self::$needUpgradeCache)) {
  510. self::$needUpgradeCache = \OC_Util::needUpgrade(\OC::$server->getSystemConfig());
  511. }
  512. return self::$needUpgradeCache;
  513. }
  514. /**
  515. * Sometimes a string has to be shortened to fit within a certain maximum
  516. * data length in bytes. substr() you may break multibyte characters,
  517. * because it operates on single byte level. mb_substr() operates on
  518. * characters, so does not ensure that the shortened string satisfies the
  519. * max length in bytes.
  520. *
  521. * For example, json_encode is messing with multibyte characters a lot,
  522. * replacing them with something along "\u1234".
  523. *
  524. * This function shortens the string with by $accuracy (-5) from
  525. * $dataLength characters, until it fits within $dataLength bytes.
  526. *
  527. * @since 23.0.0
  528. */
  529. public static function shortenMultibyteString(string $subject, int $dataLength, int $accuracy = 5): string {
  530. $temp = mb_substr($subject, 0, $dataLength);
  531. // json encodes encapsulates the string in double quotes, they need to be substracted
  532. while ((strlen(json_encode($temp)) - 2) > $dataLength) {
  533. $temp = mb_substr($temp, 0, -$accuracy);
  534. }
  535. return $temp;
  536. }
  537. /**
  538. * Check if a function is enabled in the php configuration
  539. *
  540. * @since 25.0.0
  541. */
  542. public static function isFunctionEnabled(string $functionName): bool {
  543. if (!function_exists($functionName)) {
  544. return false;
  545. }
  546. $ini = \OCP\Server::get(IniGetWrapper::class);
  547. $disabled = explode(',', $ini->get('disable_functions') ?: '');
  548. $disabled = array_map('trim', $disabled);
  549. if (in_array($functionName, $disabled)) {
  550. return false;
  551. }
  552. return true;
  553. }
  554. }