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.

530 lines
16 KiB

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