util.php 18 KB

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