1
0

Util.php 15 KB

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