1
0

Util.php 18 KB

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