Util.php 15 KB

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