Util.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 Frank Karlitschek <frank@karlitschek.de>
  9. * @author Georg Ehrke <oc.list@georgehrke.com>
  10. * @author Individual IT Services <info@individual-it.net>
  11. * @author Jens-Christian Fischer <jens-christian.fischer@switch.ch>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author Julius Härtl <jus@bitgrid.net>
  14. * @author Lukas Reschke <lukas@statuscode.ch>
  15. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  16. * @author Morris Jobke <hey@morrisjobke.de>
  17. * @author Nicolas Grekas <nicolas.grekas@gmail.com>
  18. * @author Pellaeon Lin <nfsmwlin@gmail.com>
  19. * @author Randolph Carter <RandolphCarter@fantasymail.de>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Robin McCorkell <robin@mccorkell.me.uk>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. * @author Stefan Herbrechtsmeier <stefan@herbrechtsmeier.net>
  24. * @author Thomas Müller <thomas.mueller@tmit.eu>
  25. * @author Thomas Tanghus <thomas@tanghus.net>
  26. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  27. * @author Vincent Petry <pvince81@owncloud.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. * @since 4.0.0
  55. */
  56. class Util {
  57. /**
  58. * @deprecated 14.0.0 use \OCP\ILogger::DEBUG
  59. */
  60. const DEBUG=0;
  61. /**
  62. * @deprecated 14.0.0 use \OCP\ILogger::INFO
  63. */
  64. const INFO=1;
  65. /**
  66. * @deprecated 14.0.0 use \OCP\ILogger::WARN
  67. */
  68. const WARN=2;
  69. /**
  70. * @deprecated 14.0.0 use \OCP\ILogger::ERROR
  71. */
  72. const ERROR=3;
  73. /**
  74. * @deprecated 14.0.0 use \OCP\ILogger::FATAL
  75. */
  76. const FATAL=4;
  77. /** \OCP\Share\IManager */
  78. private static $shareManager;
  79. /**
  80. * get the current installed version of Nextcloud
  81. * @return array
  82. * @since 4.0.0
  83. */
  84. public static function getVersion() {
  85. return \OC_Util::getVersion();
  86. }
  87. /**
  88. * Set current update channel
  89. * @param string $channel
  90. * @since 8.1.0
  91. */
  92. public static function setChannel($channel) {
  93. \OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
  94. }
  95. /**
  96. * Get current update channel
  97. * @return string
  98. * @since 8.1.0
  99. */
  100. public static function getChannel() {
  101. return \OC_Util::getChannel();
  102. }
  103. /**
  104. * write a message in the log
  105. * @param string $app
  106. * @param string $message
  107. * @param int $level
  108. * @since 4.0.0
  109. * @deprecated 13.0.0 use log of \OCP\ILogger
  110. */
  111. public static function writeLog( $app, $message, $level ) {
  112. $context = ['app' => $app];
  113. \OC::$server->getLogger()->log($level, $message, $context);
  114. }
  115. /**
  116. * write exception into the log
  117. * @param string $app app name
  118. * @param \Exception $ex exception to log
  119. * @param int $level log level, defaults to \OCP\Util::FATAL
  120. * @since ....0.0 - parameter $level was added in 7.0.0
  121. * @deprecated 8.2.0 use logException of \OCP\ILogger
  122. */
  123. public static function logException( $app, \Exception $ex, $level = ILogger::FATAL) {
  124. \OC::$server->getLogger()->logException($ex, ['app' => $app]);
  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 = array() ) {
  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. */
  226. public static function linkToPublic($service) {
  227. return \OC_Helper::linkToPublic($service);
  228. }
  229. /**
  230. * Returns the server host name without an eventual port number
  231. * @return string the server hostname
  232. * @since 5.0.0
  233. */
  234. public static function getServerHostName() {
  235. $host_name = \OC::$server->getRequest()->getServerHost();
  236. // strip away port number (if existing)
  237. $colon_pos = strpos($host_name, ':');
  238. if ($colon_pos != FALSE) {
  239. $host_name = substr($host_name, 0, $colon_pos);
  240. }
  241. return $host_name;
  242. }
  243. /**
  244. * Returns the default email address
  245. * @param string $user_part the user part of the address
  246. * @return string the default email address
  247. *
  248. * Assembles a default email address (using the server hostname
  249. * and the given user part, and returns it
  250. * Example: when given lostpassword-noreply as $user_part param,
  251. * and is currently accessed via http(s)://example.com/,
  252. * it would return 'lostpassword-noreply@example.com'
  253. *
  254. * If the configuration value 'mail_from_address' is set in
  255. * config.php, this value will override the $user_part that
  256. * is passed to this function
  257. * @since 5.0.0
  258. */
  259. public static function getDefaultEmailAddress($user_part) {
  260. $config = \OC::$server->getConfig();
  261. $user_part = $config->getSystemValue('mail_from_address', $user_part);
  262. $host_name = self::getServerHostName();
  263. $host_name = $config->getSystemValue('mail_domain', $host_name);
  264. $defaultEmailAddress = $user_part.'@'.$host_name;
  265. $mailer = \OC::$server->getMailer();
  266. if ($mailer->validateMailAddress($defaultEmailAddress)) {
  267. return $defaultEmailAddress;
  268. }
  269. // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
  270. return $user_part.'@localhost.localdomain';
  271. }
  272. /**
  273. * Make a human file size (2048 to 2 kB)
  274. * @param int $bytes file size in bytes
  275. * @return string a human readable file size
  276. * @since 4.0.0
  277. */
  278. public static function humanFileSize($bytes) {
  279. return \OC_Helper::humanFileSize($bytes);
  280. }
  281. /**
  282. * Make a computer file size (2 kB to 2048)
  283. * @param string $str file size in a fancy format
  284. * @return float a file size in bytes
  285. *
  286. * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
  287. * @since 4.0.0
  288. */
  289. public static function computerFileSize($str) {
  290. return \OC_Helper::computerFileSize($str);
  291. }
  292. /**
  293. * connects a function to a hook
  294. *
  295. * @param string $signalClass class name of emitter
  296. * @param string $signalName name of signal
  297. * @param string|object $slotClass class name of slot
  298. * @param string $slotName name of slot
  299. * @return bool
  300. *
  301. * This function makes it very easy to connect to use hooks.
  302. *
  303. * TODO: write example
  304. * @since 4.0.0
  305. */
  306. static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
  307. return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
  308. }
  309. /**
  310. * Emits a signal. To get data from the slot use references!
  311. * @param string $signalclass class name of emitter
  312. * @param string $signalname name of signal
  313. * @param array $params default: array() array with additional data
  314. * @return bool true if slots exists or false if not
  315. *
  316. * TODO: write example
  317. * @since 4.0.0
  318. */
  319. static public function emitHook($signalclass, $signalname, $params = array()) {
  320. return \OC_Hook::emit($signalclass, $signalname, $params);
  321. }
  322. /**
  323. * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
  324. * multiple OC_Template elements which invoke `callRegister`. If the value
  325. * would not be cached these unit-tests would fail.
  326. * @var string
  327. */
  328. private static $token = '';
  329. /**
  330. * Register an get/post call. This is important to prevent CSRF attacks
  331. * @since 4.5.0
  332. */
  333. public static function callRegister() {
  334. if(self::$token === '') {
  335. self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
  336. }
  337. return self::$token;
  338. }
  339. /**
  340. * Check an ajax get/post call if the request token is valid. exit if not.
  341. * @since 4.5.0
  342. * @deprecated 9.0.0 Use annotations based on the app framework.
  343. */
  344. public static function callCheck() {
  345. if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
  346. header('Location: '.\OC::$WEBROOT);
  347. exit();
  348. }
  349. if (!\OC::$server->getRequest()->passesCSRFCheck()) {
  350. exit();
  351. }
  352. }
  353. /**
  354. * Used to sanitize HTML
  355. *
  356. * This function is used to sanitize HTML and should be applied on any
  357. * string or array of strings before displaying it on a web page.
  358. *
  359. * @param string|array $value
  360. * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
  361. * @since 4.5.0
  362. */
  363. public static function sanitizeHTML($value) {
  364. return \OC_Util::sanitizeHTML($value);
  365. }
  366. /**
  367. * Public function to encode url parameters
  368. *
  369. * This function is used to encode path to file before output.
  370. * Encoding is done according to RFC 3986 with one exception:
  371. * Character '/' is preserved as is.
  372. *
  373. * @param string $component part of URI to encode
  374. * @return string
  375. * @since 6.0.0
  376. */
  377. public static function encodePath($component) {
  378. return \OC_Util::encodePath($component);
  379. }
  380. /**
  381. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  382. *
  383. * @param array $input The array to work on
  384. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  385. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  386. * @return array
  387. * @since 4.5.0
  388. */
  389. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  390. return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
  391. }
  392. /**
  393. * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
  394. *
  395. * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
  396. * @param string $replacement The replacement string.
  397. * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
  398. * @param int $length Length of the part to be replaced
  399. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  400. * @return string
  401. * @since 4.5.0
  402. * @deprecated 8.2.0 Use substr_replace() instead.
  403. */
  404. public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
  405. return substr_replace($string, $replacement, $start, $length);
  406. }
  407. /**
  408. * Replace all occurrences of the search string with the replacement string
  409. *
  410. * @param string $search The value being searched for, otherwise known as the needle. String.
  411. * @param string $replace The replacement string.
  412. * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
  413. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  414. * @param int $count If passed, this will be set to the number of replacements performed.
  415. * @return string
  416. * @since 4.5.0
  417. * @deprecated 8.2.0 Use str_replace() instead.
  418. */
  419. public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
  420. return str_replace($search, $replace, $subject, $count);
  421. }
  422. /**
  423. * performs a search in a nested array
  424. *
  425. * @param array $haystack the array to be searched
  426. * @param string $needle the search string
  427. * @param mixed $index optional, only search this key name
  428. * @return mixed the key of the matching field, otherwise false
  429. * @since 4.5.0
  430. */
  431. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  432. return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
  433. }
  434. /**
  435. * calculates the maximum upload size respecting system settings, free space and user quota
  436. *
  437. * @param string $dir the current folder where the user currently operates
  438. * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
  439. * @return int number of bytes representing
  440. * @since 5.0.0
  441. */
  442. public static function maxUploadFilesize($dir, $free = null) {
  443. return \OC_Helper::maxUploadFilesize($dir, $free);
  444. }
  445. /**
  446. * Calculate free space left within user quota
  447. * @param string $dir the current folder where the user currently operates
  448. * @return int number of bytes representing
  449. * @since 7.0.0
  450. */
  451. public static function freeSpace($dir) {
  452. return \OC_Helper::freeSpace($dir);
  453. }
  454. /**
  455. * Calculate PHP upload limit
  456. *
  457. * @return int number of bytes representing
  458. * @since 7.0.0
  459. */
  460. public static function uploadLimit() {
  461. return \OC_Helper::uploadLimit();
  462. }
  463. /**
  464. * Returns whether the given file name is valid
  465. * @param string $file file name to check
  466. * @return bool true if the file name is valid, false otherwise
  467. * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
  468. * @since 7.0.0
  469. * @suppress PhanDeprecatedFunction
  470. */
  471. public static function isValidFileName($file) {
  472. return \OC_Util::isValidFileName($file);
  473. }
  474. /**
  475. * Compare two strings to provide a natural sort
  476. * @param string $a first string to compare
  477. * @param string $b second string to compare
  478. * @return int -1 if $b comes before $a, 1 if $a comes before $b
  479. * or 0 if the strings are identical
  480. * @since 7.0.0
  481. */
  482. public static function naturalSortCompare($a, $b) {
  483. return \OC\NaturalSort::getInstance()->compare($a, $b);
  484. }
  485. /**
  486. * check if a password is required for each public link
  487. * @return boolean
  488. * @since 7.0.0
  489. */
  490. public static function isPublicLinkPasswordRequired() {
  491. return \OC_Util::isPublicLinkPasswordRequired();
  492. }
  493. /**
  494. * check if share API enforces a default expire date
  495. * @return boolean
  496. * @since 8.0.0
  497. */
  498. public static function isDefaultExpireDateEnforced() {
  499. return \OC_Util::isDefaultExpireDateEnforced();
  500. }
  501. protected static $needUpgradeCache = null;
  502. /**
  503. * Checks whether the current version needs upgrade.
  504. *
  505. * @return bool true if upgrade is needed, false otherwise
  506. * @since 7.0.0
  507. */
  508. public static function needUpgrade() {
  509. if (!isset(self::$needUpgradeCache)) {
  510. self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
  511. }
  512. return self::$needUpgradeCache;
  513. }
  514. }