Util.php 20 KB

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