1
0

Util.php 19 KB

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