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

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