Util.php 18 KB

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