Util.php 19 KB

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