1
0

Util.php 17 KB

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