util.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. <?php
  2. /**
  3. * @author Arthur Schiwon <blizzz@owncloud.com>
  4. * @author Bart Visscher <bartv@thisnet.nl>
  5. * @author Björn Schießle <schiessle@owncloud.com>
  6. * @author Frank Karlitschek <frank@owncloud.org>
  7. * @author Georg Ehrke <georg@owncloud.com>
  8. * @author itheiss <ingo.theiss@i-matrixx.de>
  9. * @author Jens-Christian Fischer <jens-christian.fischer@switch.ch>
  10. * @author Joas Schilling <nickvergessen@owncloud.com>
  11. * @author Lukas Reschke <lukas@owncloud.com>
  12. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Pellaeon Lin <nfsmwlin@gmail.com>
  15. * @author Randolph Carter <RandolphCarter@fantasymail.de>
  16. * @author Robin Appelman <icewind@owncloud.com>
  17. * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
  18. * @author Stefan Herbrechtsmeier <stefan@herbrechtsmeier.net>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Thomas Tanghus <thomas@tanghus.net>
  21. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  22. * @author Vincent Petry <pvince81@owncloud.com>
  23. *
  24. * @copyright Copyright (c) 2015, ownCloud, Inc.
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. /**
  41. * Public interface of ownCloud for apps to use.
  42. * Utility Class.
  43. *
  44. */
  45. // use OCP namespace for all classes that are considered public.
  46. // This means that they should be used by apps instead of the internal ownCloud classes
  47. namespace OCP;
  48. use DateTimeZone;
  49. /**
  50. * This class provides different helper functions to make the life of a developer easier
  51. */
  52. class Util {
  53. // consts for Logging
  54. const DEBUG=0;
  55. const INFO=1;
  56. const WARN=2;
  57. const ERROR=3;
  58. const FATAL=4;
  59. /**
  60. * get the current installed version of ownCloud
  61. * @return array
  62. */
  63. public static function getVersion() {
  64. return(\OC_Util::getVersion());
  65. }
  66. /**
  67. * send an email
  68. * @param string $toaddress
  69. * @param string $toname
  70. * @param string $subject
  71. * @param string $mailtext
  72. * @param string $fromaddress
  73. * @param string $fromname
  74. * @param int $html
  75. * @param string $altbody
  76. * @param string $ccaddress
  77. * @param string $ccname
  78. * @param string $bcc
  79. * @deprecated Use \OCP\Mail\IMailer instead
  80. */
  81. public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
  82. $html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
  83. $mailer = \OC::$server->getMailer();
  84. $message = $mailer->createMessage();
  85. $message->setTo([$toaddress => $toname]);
  86. $message->setSubject($subject);
  87. $message->setPlainBody($mailtext);
  88. $message->setFrom([$fromaddress => $fromname]);
  89. if($html === 1) {
  90. $message->setHTMLBody($altbody);
  91. }
  92. if($altbody === '') {
  93. $message->setHTMLBody($mailtext);
  94. $message->setPlainBody('');
  95. } else {
  96. $message->setHtmlBody($mailtext);
  97. $message->setPlainBody($altbody);
  98. }
  99. if(!empty($ccaddress)) {
  100. if(!empty($ccname)) {
  101. $message->setCc([$ccaddress => $ccname]);
  102. } else {
  103. $message->setCc([$ccaddress]);
  104. }
  105. }
  106. if(!empty($bcc)) {
  107. $message->setBcc([$bcc]);
  108. }
  109. $mailer->send($message);
  110. }
  111. /**
  112. * write a message in the log
  113. * @param string $app
  114. * @param string $message
  115. * @param int $level
  116. */
  117. public static function writeLog( $app, $message, $level ) {
  118. // call the internal log class
  119. \OC_LOG::write( $app, $message, $level );
  120. }
  121. /**
  122. * write exception into the log
  123. * @param string $app app name
  124. * @param \Exception $ex exception to log
  125. * @param int $level log level, defaults to \OCP\Util::FATAL
  126. */
  127. public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
  128. $exception = array(
  129. 'Message' => $ex->getMessage(),
  130. 'Code' => $ex->getCode(),
  131. 'Trace' => $ex->getTraceAsString(),
  132. 'File' => $ex->getFile(),
  133. 'Line' => $ex->getLine(),
  134. );
  135. \OCP\Util::writeLog($app, 'Exception: ' . json_encode($exception), $level);
  136. }
  137. /**
  138. * check if sharing is disabled for the current user
  139. *
  140. * @return boolean
  141. */
  142. public static function isSharingDisabledForUser() {
  143. return \OC_Util::isSharingDisabledForUser();
  144. }
  145. /**
  146. * get l10n object
  147. * @param string $application
  148. * @param string|null $language
  149. * @return \OC_L10N
  150. */
  151. public static function getL10N($application, $language = null) {
  152. return \OC::$server->getL10N($application, $language);
  153. }
  154. /**
  155. * add a css file
  156. * @param string $application
  157. * @param string $file
  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. */
  167. public static function addScript( $application, $file = null ) {
  168. \OC_Util::addScript( $application, $file );
  169. }
  170. /**
  171. * Add a translation JS file
  172. * @param string $application application id
  173. * @param string $languageCode language code, defaults to the current locale
  174. */
  175. public static function addTranslations($application, $languageCode = null) {
  176. \OC_Util::addTranslations($application, $languageCode);
  177. }
  178. /**
  179. * Add a custom element to the header
  180. * If $text is null then the element will be written as empty element.
  181. * So use "" to get a closing tag.
  182. * @param string $tag tag name of the element
  183. * @param array $attributes array of attributes for the element
  184. * @param string $text the text content for the element
  185. */
  186. public static function addHeader($tag, $attributes, $text=null) {
  187. \OC_Util::addHeader($tag, $attributes, $text);
  188. }
  189. /**
  190. * formats a timestamp in the "right" way
  191. * @param int $timestamp $timestamp
  192. * @param bool $dateOnly option to omit time from the result
  193. * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
  194. * @return string timestamp
  195. *
  196. * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
  197. */
  198. public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
  199. return(\OC_Util::formatDate($timestamp, $dateOnly, $timeZone));
  200. }
  201. /**
  202. * check if some encrypted files are stored
  203. * @return bool
  204. *
  205. * @deprecated No longer required
  206. */
  207. public static function encryptedFiles() {
  208. return false;
  209. }
  210. /**
  211. * Creates an absolute url to the given app and file.
  212. * @param string $app app
  213. * @param string $file file
  214. * @param array $args array with param=>value, will be appended to the returned url
  215. * The value of $args will be urlencoded
  216. * @return string the url
  217. */
  218. public static function linkToAbsolute( $app, $file, $args = array() ) {
  219. return(\OC_Helper::linkToAbsolute( $app, $file, $args ));
  220. }
  221. /**
  222. * Creates an absolute url for remote use.
  223. * @param string $service id
  224. * @return string the url
  225. */
  226. public static function linkToRemote( $service ) {
  227. return(\OC_Helper::linkToRemote( $service ));
  228. }
  229. /**
  230. * Creates an absolute url for public use
  231. * @param string $service id
  232. * @return string the url
  233. */
  234. public static function linkToPublic($service) {
  235. return \OC_Helper::linkToPublic($service);
  236. }
  237. /**
  238. * Creates an url using a defined route
  239. * @param string $route
  240. * @param array $parameters
  241. * @internal param array $args with param=>value, will be appended to the returned url
  242. * @return string the url
  243. * @deprecated Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
  244. */
  245. public static function linkToRoute( $route, $parameters = array() ) {
  246. return \OC_Helper::linkToRoute($route, $parameters);
  247. }
  248. /**
  249. * Creates an url to the given app and file
  250. * @param string $app app
  251. * @param string $file file
  252. * @param array $args array with param=>value, will be appended to the returned url
  253. * The value of $args will be urlencoded
  254. * @return string the url
  255. * @deprecated Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
  256. */
  257. public static function linkTo( $app, $file, $args = array() ) {
  258. return(\OC_Helper::linkTo( $app, $file, $args ));
  259. }
  260. /**
  261. * Returns the server host, even if the website uses one or more reverse proxy
  262. * @return string the server host
  263. * @deprecated Use \OCP\IRequest::getServerHost
  264. */
  265. public static function getServerHost() {
  266. return \OC::$server->getRequest()->getServerHost();
  267. }
  268. /**
  269. * Returns the server host name without an eventual port number
  270. * @return string the server hostname
  271. */
  272. public static function getServerHostName() {
  273. $host_name = self::getServerHost();
  274. // strip away port number (if existing)
  275. $colon_pos = strpos($host_name, ':');
  276. if ($colon_pos != FALSE) {
  277. $host_name = substr($host_name, 0, $colon_pos);
  278. }
  279. return $host_name;
  280. }
  281. /**
  282. * Returns the default email address
  283. * @param string $user_part the user part of the address
  284. * @return string the default email address
  285. *
  286. * Assembles a default email address (using the server hostname
  287. * and the given user part, and returns it
  288. * Example: when given lostpassword-noreply as $user_part param,
  289. * and is currently accessed via http(s)://example.com/,
  290. * it would return 'lostpassword-noreply@example.com'
  291. *
  292. * If the configuration value 'mail_from_address' is set in
  293. * config.php, this value will override the $user_part that
  294. * is passed to this function
  295. */
  296. public static function getDefaultEmailAddress($user_part) {
  297. $user_part = \OC_Config::getValue('mail_from_address', $user_part);
  298. $host_name = self::getServerHostName();
  299. $host_name = \OC_Config::getValue('mail_domain', $host_name);
  300. $defaultEmailAddress = $user_part.'@'.$host_name;
  301. $mailer = \OC::$server->getMailer();
  302. if ($mailer->validateMailAddress($defaultEmailAddress)) {
  303. return $defaultEmailAddress;
  304. }
  305. // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
  306. return $user_part.'@localhost.localdomain';
  307. }
  308. /**
  309. * Returns the server protocol. It respects reverse proxy servers and load balancers
  310. * @return string the server protocol
  311. * @deprecated Use \OCP\IRequest::getServerProtocol
  312. */
  313. public static function getServerProtocol() {
  314. return \OC::$server->getRequest()->getServerProtocol();
  315. }
  316. /**
  317. * Returns the request uri, even if the website uses one or more reverse proxies
  318. * @return string the request uri
  319. * @deprecated Use \OCP\IRequest::getRequestUri
  320. */
  321. public static function getRequestUri() {
  322. return \OC::$server->getRequest()->getRequestUri();
  323. }
  324. /**
  325. * Returns the script name, even if the website uses one or more reverse proxies
  326. * @return string the script name
  327. * @deprecated Use \OCP\IRequest::getScriptName
  328. */
  329. public static function getScriptName() {
  330. return \OC::$server->getRequest()->getScriptName();
  331. }
  332. /**
  333. * Creates path to an image
  334. * @param string $app app
  335. * @param string $image image name
  336. * @return string the url
  337. * @deprecated Use \OC::$server->getURLGenerator()->imagePath($app, $image)
  338. */
  339. public static function imagePath( $app, $image ) {
  340. return(\OC_Helper::imagePath( $app, $image ));
  341. }
  342. /**
  343. * Make a human file size (2048 to 2 kB)
  344. * @param int $bytes file size in bytes
  345. * @return string a human readable file size
  346. */
  347. public static function humanFileSize( $bytes ) {
  348. return(\OC_Helper::humanFileSize( $bytes ));
  349. }
  350. /**
  351. * Make a computer file size (2 kB to 2048)
  352. * @param string $str file size in a fancy format
  353. * @return int a file size in bytes
  354. *
  355. * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
  356. */
  357. public static function computerFileSize( $str ) {
  358. return(\OC_Helper::computerFileSize( $str ));
  359. }
  360. /**
  361. * connects a function to a hook
  362. *
  363. * @param string $signalClass class name of emitter
  364. * @param string $signalName name of signal
  365. * @param string|object $slotClass class name of slot
  366. * @param string $slotName name of slot
  367. * @return bool
  368. *
  369. * This function makes it very easy to connect to use hooks.
  370. *
  371. * TODO: write example
  372. */
  373. static public function connectHook($signalClass, $signalName, $slotClass, $slotName ) {
  374. return(\OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName ));
  375. }
  376. /**
  377. * Emits a signal. To get data from the slot use references!
  378. * @param string $signalclass class name of emitter
  379. * @param string $signalname name of signal
  380. * @param array $params default: array() array with additional data
  381. * @return bool true if slots exists or false if not
  382. *
  383. * TODO: write example
  384. */
  385. static public function emitHook( $signalclass, $signalname, $params = array()) {
  386. return(\OC_Hook::emit( $signalclass, $signalname, $params ));
  387. }
  388. /**
  389. * Register an get/post call. This is important to prevent CSRF attacks
  390. * TODO: write example
  391. */
  392. public static function callRegister() {
  393. return(\OC_Util::callRegister());
  394. }
  395. /**
  396. * Check an ajax get/post call if the request token is valid. exit if not.
  397. * Todo: Write howto
  398. */
  399. public static function callCheck() {
  400. \OC_Util::callCheck();
  401. }
  402. /**
  403. * Used to sanitize HTML
  404. *
  405. * This function is used to sanitize HTML and should be applied on any
  406. * string or array of strings before displaying it on a web page.
  407. *
  408. * @param string|array $value
  409. * @return string|array an array of sanitized strings or a single sinitized string, depends on the input parameter.
  410. */
  411. public static function sanitizeHTML( $value ) {
  412. return(\OC_Util::sanitizeHTML($value));
  413. }
  414. /**
  415. * Public function to encode url parameters
  416. *
  417. * This function is used to encode path to file before output.
  418. * Encoding is done according to RFC 3986 with one exception:
  419. * Character '/' is preserved as is.
  420. *
  421. * @param string $component part of URI to encode
  422. * @return string
  423. */
  424. public static function encodePath($component) {
  425. return(\OC_Util::encodePath($component));
  426. }
  427. /**
  428. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  429. *
  430. * @param array $input The array to work on
  431. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  432. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  433. * @return array
  434. */
  435. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  436. return(\OC_Helper::mb_array_change_key_case($input, $case, $encoding));
  437. }
  438. /**
  439. * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
  440. *
  441. * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
  442. * @param string $replacement The replacement string.
  443. * @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.
  444. * @param int $length Length of the part to be replaced
  445. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  446. * @return string
  447. */
  448. public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
  449. return(\OC_Helper::mb_substr_replace($string, $replacement, $start, $length, $encoding));
  450. }
  451. /**
  452. * Replace all occurrences of the search string with the replacement string
  453. *
  454. * @param string $search The value being searched for, otherwise known as the needle. String.
  455. * @param string $replace The replacement string.
  456. * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
  457. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  458. * @param int $count If passed, this will be set to the number of replacements performed.
  459. * @return string
  460. */
  461. public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
  462. return(\OC_Helper::mb_str_replace($search, $replace, $subject, $encoding, $count));
  463. }
  464. /**
  465. * performs a search in a nested array
  466. *
  467. * @param array $haystack the array to be searched
  468. * @param string $needle the search string
  469. * @param int $index optional, only search this key name
  470. * @return mixed the key of the matching field, otherwise false
  471. */
  472. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  473. return(\OC_Helper::recursiveArraySearch($haystack, $needle, $index));
  474. }
  475. /**
  476. * calculates the maximum upload size respecting system settings, free space and user quota
  477. *
  478. * @param string $dir the current folder where the user currently operates
  479. * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
  480. * @return int number of bytes representing
  481. */
  482. public static function maxUploadFilesize($dir, $free = null) {
  483. return \OC_Helper::maxUploadFilesize($dir, $free);
  484. }
  485. /**
  486. * Calculate free space left within user quota
  487. * @param string $dir the current folder where the user currently operates
  488. * @return int number of bytes representing
  489. */
  490. public static function freeSpace($dir) {
  491. return \OC_Helper::freeSpace($dir);
  492. }
  493. /**
  494. * Calculate PHP upload limit
  495. *
  496. * @return int number of bytes representing
  497. */
  498. public static function uploadLimit() {
  499. return \OC_Helper::uploadLimit();
  500. }
  501. /**
  502. * Returns whether the given file name is valid
  503. * @param string $file file name to check
  504. * @return bool true if the file name is valid, false otherwise
  505. * @deprecated use \OC\Files\View::verifyPath()
  506. */
  507. public static function isValidFileName($file) {
  508. return \OC_Util::isValidFileName($file);
  509. }
  510. /**
  511. * Generates a cryptographic secure pseudo-random string
  512. * @param int $length of the random string
  513. * @return string
  514. * @deprecated Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
  515. */
  516. public static function generateRandomBytes($length = 30) {
  517. return \OC_Util::generateRandomBytes($length);
  518. }
  519. /**
  520. * Compare two strings to provide a natural sort
  521. * @param string $a first string to compare
  522. * @param string $b second string to compare
  523. * @return -1 if $b comes before $a, 1 if $a comes before $b
  524. * or 0 if the strings are identical
  525. */
  526. public static function naturalSortCompare($a, $b) {
  527. return \OC\NaturalSort::getInstance()->compare($a, $b);
  528. }
  529. /**
  530. * check if a password is required for each public link
  531. * @return boolean
  532. */
  533. public static function isPublicLinkPasswordRequired() {
  534. return \OC_Util::isPublicLinkPasswordRequired();
  535. }
  536. /**
  537. * check if share API enforces a default expire date
  538. * @return boolean
  539. */
  540. public static function isDefaultExpireDateEnforced() {
  541. return \OC_Util::isDefaultExpireDateEnforced();
  542. }
  543. /**
  544. * Checks whether the current version needs upgrade.
  545. *
  546. * @return bool true if upgrade is needed, false otherwise
  547. */
  548. public static function needUpgrade() {
  549. return \OC_Util::needUpgrade(\OC::$server->getConfig());
  550. }
  551. }