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 16KB

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