You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Util.php 18KB

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