helper.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Frank Karlitschek
  6. * @author Jakob Sack
  7. * @copyright 2012 Frank Karlitschek frank@owncloud.org
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  11. * License as published by the Free Software Foundation; either
  12. * version 3 of the License, or any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public
  20. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. */
  23. /**
  24. * Collection of useful functions
  25. */
  26. class OC_Helper {
  27. private static $mimetypes=array();
  28. private static $tmpFiles=array();
  29. /**
  30. * @brief Creates an url using a defined route
  31. * @param $route
  32. * @param array $parameters
  33. * @return
  34. * @internal param array $args with param=>value, will be appended to the returned url
  35. * @returns the url
  36. *
  37. * Returns a url to the given app and file.
  38. */
  39. public static function linkToRoute( $route, $parameters = array() ) {
  40. $urlLinkTo = OC::getRouter()->generate($route, $parameters);
  41. return $urlLinkTo;
  42. }
  43. /**
  44. * @brief Creates an url
  45. * @param string $app app
  46. * @param string $file file
  47. * @param array $args array with param=>value, will be appended to the returned url
  48. * The value of $args will be urlencoded
  49. * @return string the url
  50. *
  51. * Returns a url to the given app and file.
  52. */
  53. public static function linkTo( $app, $file, $args = array() ) {
  54. if( $app != '' ) {
  55. $app_path = OC_App::getAppPath($app);
  56. // Check if the app is in the app folder
  57. if( $app_path && file_exists( $app_path.'/'.$file )) {
  58. if(substr($file, -3) == 'php' || substr($file, -3) == 'css') {
  59. $urlLinkTo = OC::$WEBROOT . '/index.php/apps/' . $app;
  60. $urlLinkTo .= ($file!='index.php') ? '/' . $file : '';
  61. }else{
  62. $urlLinkTo = OC_App::getAppWebPath($app) . '/' . $file;
  63. }
  64. }
  65. else{
  66. $urlLinkTo = OC::$WEBROOT . '/' . $app . '/' . $file;
  67. }
  68. }
  69. else{
  70. if( file_exists( OC::$SERVERROOT . '/core/'. $file )) {
  71. $urlLinkTo = OC::$WEBROOT . '/core/'.$file;
  72. }
  73. else{
  74. $urlLinkTo = OC::$WEBROOT . '/'.$file;
  75. }
  76. }
  77. if ($args && $query = http_build_query($args, '', '&')) {
  78. $urlLinkTo .= '?'.$query;
  79. }
  80. return $urlLinkTo;
  81. }
  82. /**
  83. * @brief Creates an absolute url
  84. * @param string $app app
  85. * @param string $file file
  86. * @param array $args array with param=>value, will be appended to the returned url
  87. * The value of $args will be urlencoded
  88. * @return string the url
  89. *
  90. * Returns a absolute url to the given app and file.
  91. */
  92. public static function linkToAbsolute( $app, $file, $args = array() ) {
  93. $urlLinkTo = self::linkTo( $app, $file, $args );
  94. return self::makeURLAbsolute($urlLinkTo);
  95. }
  96. /**
  97. * @brief Makes an $url absolute
  98. * @param string $url the url
  99. * @return string the absolute url
  100. *
  101. * Returns a absolute url to the given app and file.
  102. */
  103. public static function makeURLAbsolute( $url )
  104. {
  105. return OC_Request::serverProtocol(). '://' . OC_Request::serverHost() . $url;
  106. }
  107. /**
  108. * @brief Creates an url for remote use
  109. * @param string $service id
  110. * @return string the url
  111. *
  112. * Returns a url to the given service.
  113. */
  114. public static function linkToRemoteBase( $service ) {
  115. return self::linkTo( '', 'remote.php') . '/' . $service;
  116. }
  117. /**
  118. * @brief Creates an absolute url for remote use
  119. * @param string $service id
  120. * @param bool $add_slash
  121. * @return string the url
  122. *
  123. * Returns a absolute url to the given service.
  124. */
  125. public static function linkToRemote( $service, $add_slash = true ) {
  126. return self::makeURLAbsolute(self::linkToRemoteBase($service)) . (($add_slash && $service[strlen($service)-1]!='/')?'/':'');
  127. }
  128. /**
  129. * @brief Creates an absolute url for public use
  130. * @param string $service id
  131. * @param bool $add_slash
  132. * @return string the url
  133. *
  134. * Returns a absolute url to the given service.
  135. */
  136. public static function linkToPublic($service, $add_slash = false) {
  137. return self::linkToAbsolute( '', 'public.php') . '?service=' . $service . (($add_slash && $service[strlen($service)-1]!='/')?'/':'');
  138. }
  139. /**
  140. * @brief Creates path to an image
  141. * @param string $app app
  142. * @param string $image image name
  143. * @return string the url
  144. *
  145. * Returns the path to the image.
  146. */
  147. public static function imagePath( $app, $image ) {
  148. // Read the selected theme from the config file
  149. $theme=OC_Config::getValue( "theme" );
  150. // Check if the app is in the app folder
  151. if( file_exists( OC::$SERVERROOT."/themes/$theme/apps/$app/img/$image" )) {
  152. return OC::$WEBROOT."/themes/$theme/apps/$app/img/$image";
  153. }elseif( file_exists(OC_App::getAppPath($app)."/img/$image" )) {
  154. return OC_App::getAppWebPath($app)."/img/$image";
  155. }elseif( !empty( $app ) and file_exists( OC::$SERVERROOT."/themes/$theme/$app/img/$image" )) {
  156. return OC::$WEBROOT."/themes/$theme/$app/img/$image";
  157. }elseif( !empty( $app ) and file_exists( OC::$SERVERROOT."/$app/img/$image" )) {
  158. return OC::$WEBROOT."/$app/img/$image";
  159. }elseif( file_exists( OC::$SERVERROOT."/themes/$theme/core/img/$image" )) {
  160. return OC::$WEBROOT."/themes/$theme/core/img/$image";
  161. }elseif( file_exists( OC::$SERVERROOT."/core/img/$image" )) {
  162. return OC::$WEBROOT."/core/img/$image";
  163. }else{
  164. echo('image not found: image:'.$image.' webroot:'.OC::$WEBROOT.' serverroot:'.OC::$SERVERROOT);
  165. die();
  166. }
  167. }
  168. /**
  169. * @brief get path to icon of file type
  170. * @param string $mimetype mimetype
  171. * @return string the url
  172. *
  173. * Returns the path to the image of this file type.
  174. */
  175. public static function mimetypeIcon( $mimetype ) {
  176. $alias=array('application/xml'=>'code/xml');
  177. if(isset($alias[$mimetype])) {
  178. $mimetype=$alias[$mimetype];
  179. }
  180. // Replace slash and backslash with a minus
  181. $mimetype = str_replace( "/", "-", $mimetype );
  182. $mimetype = str_replace( "\\", "-", $mimetype );
  183. // Is it a dir?
  184. if( $mimetype == "dir" ) {
  185. return OC::$WEBROOT."/core/img/filetypes/folder.png";
  186. }
  187. // Icon exists?
  188. if( file_exists( OC::$SERVERROOT."/core/img/filetypes/$mimetype.png" )) {
  189. return OC::$WEBROOT."/core/img/filetypes/$mimetype.png";
  190. }
  191. //try only the first part of the filetype
  192. $mimetype=substr($mimetype, 0, strpos($mimetype, '-'));
  193. if( file_exists( OC::$SERVERROOT."/core/img/filetypes/$mimetype.png" )) {
  194. return OC::$WEBROOT."/core/img/filetypes/$mimetype.png";
  195. }
  196. else{
  197. return OC::$WEBROOT."/core/img/filetypes/file.png";
  198. }
  199. }
  200. /**
  201. * @brief Make a human file size
  202. * @param int $bytes file size in bytes
  203. * @return string a human readable file size
  204. *
  205. * Makes 2048 to 2 kB.
  206. */
  207. public static function humanFileSize( $bytes ) {
  208. if( $bytes < 0 ) {
  209. $l = OC_L10N::get('lib');
  210. return $l->t("couldn't be determined");
  211. }
  212. if( $bytes < 1024 ) {
  213. return "$bytes B";
  214. }
  215. $bytes = round( $bytes / 1024, 1 );
  216. if( $bytes < 1024 ) {
  217. return "$bytes kB";
  218. }
  219. $bytes = round( $bytes / 1024, 1 );
  220. if( $bytes < 1024 ) {
  221. return "$bytes MB";
  222. }
  223. // Wow, heavy duty for owncloud
  224. $bytes = round( $bytes / 1024, 1 );
  225. return "$bytes GB";
  226. }
  227. /**
  228. * @brief Make a computer file size
  229. * @param string $str file size in a fancy format
  230. * @return int a file size in bytes
  231. *
  232. * Makes 2kB to 2048.
  233. *
  234. * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
  235. */
  236. public static function computerFileSize( $str ) {
  237. $str=strtolower($str);
  238. $bytes_array = array(
  239. 'b' => 1,
  240. 'k' => 1024,
  241. 'kb' => 1024,
  242. 'mb' => 1024 * 1024,
  243. 'm' => 1024 * 1024,
  244. 'gb' => 1024 * 1024 * 1024,
  245. 'g' => 1024 * 1024 * 1024,
  246. 'tb' => 1024 * 1024 * 1024 * 1024,
  247. 't' => 1024 * 1024 * 1024 * 1024,
  248. 'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
  249. 'p' => 1024 * 1024 * 1024 * 1024 * 1024,
  250. );
  251. $bytes = floatval($str);
  252. if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
  253. $bytes *= $bytes_array[$matches[1]];
  254. }
  255. $bytes = round($bytes, 2);
  256. return $bytes;
  257. }
  258. /**
  259. * @brief Recursive editing of file permissions
  260. * @param string $path path to file or folder
  261. * @param int $filemode unix style file permissions
  262. * @return bool
  263. */
  264. static function chmodr($path, $filemode) {
  265. if (!is_dir($path))
  266. return chmod($path, $filemode);
  267. $dh = opendir($path);
  268. while (($file = readdir($dh)) !== false) {
  269. if($file != '.' && $file != '..') {
  270. $fullpath = $path.'/'.$file;
  271. if(is_link($fullpath))
  272. return false;
  273. elseif(!is_dir($fullpath) && !@chmod($fullpath, $filemode))
  274. return false;
  275. elseif(!self::chmodr($fullpath, $filemode))
  276. return false;
  277. }
  278. }
  279. closedir($dh);
  280. if(@chmod($path, $filemode))
  281. return true;
  282. else
  283. return false;
  284. }
  285. /**
  286. * @brief Recursive copying of folders
  287. * @param string $src source folder
  288. * @param string $dest target folder
  289. *
  290. */
  291. static function copyr($src, $dest) {
  292. if(is_dir($src)) {
  293. if(!is_dir($dest)) {
  294. mkdir($dest);
  295. }
  296. $files = scandir($src);
  297. foreach ($files as $file) {
  298. if ($file != "." && $file != "..") {
  299. self::copyr("$src/$file", "$dest/$file");
  300. }
  301. }
  302. }elseif(file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
  303. copy($src, $dest);
  304. }
  305. }
  306. /**
  307. * @brief Recursive deletion of folders
  308. * @param string $dir path to the folder
  309. * @return bool
  310. */
  311. static function rmdirr($dir) {
  312. if(is_dir($dir)) {
  313. $files=scandir($dir);
  314. foreach($files as $file) {
  315. if ($file != "." && $file != "..") {
  316. self::rmdirr("$dir/$file");
  317. }
  318. }
  319. rmdir($dir);
  320. }elseif(file_exists($dir)) {
  321. unlink($dir);
  322. }
  323. if(file_exists($dir)) {
  324. return false;
  325. }else{
  326. return true;
  327. }
  328. }
  329. /**
  330. * get the mimetype form a local file
  331. * @param string $path
  332. * @return string
  333. * does NOT work for ownClouds filesystem, use OC_FileSystem::getMimeType instead
  334. */
  335. static function getMimeType($path) {
  336. $isWrapped=(strpos($path, '://')!==false) and (substr($path, 0, 7)=='file://');
  337. if (@is_dir($path)) {
  338. // directories are easy
  339. return "httpd/unix-directory";
  340. }
  341. if(strpos($path, '.')) {
  342. //try to guess the type by the file extension
  343. if(!self::$mimetypes || self::$mimetypes != include 'mimetypes.list.php') {
  344. self::$mimetypes=include 'mimetypes.list.php';
  345. }
  346. $extension=strtolower(strrchr(basename($path), "."));
  347. $extension=substr($extension, 1);//remove leading .
  348. $mimeType=(isset(self::$mimetypes[$extension]))?self::$mimetypes[$extension]:'application/octet-stream';
  349. }else{
  350. $mimeType='application/octet-stream';
  351. }
  352. if($mimeType=='application/octet-stream' and function_exists('finfo_open') and function_exists('finfo_file') and $finfo=finfo_open(FILEINFO_MIME)) {
  353. $info = @strtolower(finfo_file($finfo, $path));
  354. if($info) {
  355. $mimeType=substr($info, 0, strpos($info, ';'));
  356. }
  357. finfo_close($finfo);
  358. }
  359. if (!$isWrapped and $mimeType=='application/octet-stream' && function_exists("mime_content_type")) {
  360. // use mime magic extension if available
  361. $mimeType = mime_content_type($path);
  362. }
  363. if (!$isWrapped and $mimeType=='application/octet-stream' && OC_Helper::canExecute("file")) {
  364. // it looks like we have a 'file' command,
  365. // lets see if it does have mime support
  366. $path=escapeshellarg($path);
  367. $fp = popen("file -i -b $path 2>/dev/null", "r");
  368. $reply = fgets($fp);
  369. pclose($fp);
  370. // we have smth like 'text/x-c++; charset=us-ascii\n'
  371. // and need to eliminate everything starting with semicolon including trailing LF
  372. $mimeType = preg_replace('/;.*/ms', '', trim($reply));
  373. }
  374. return $mimeType;
  375. }
  376. /**
  377. * get the mimetype form a data string
  378. * @param string $data
  379. * @return string
  380. */
  381. static function getStringMimeType($data) {
  382. if(function_exists('finfo_open') and function_exists('finfo_file')) {
  383. $finfo=finfo_open(FILEINFO_MIME);
  384. return finfo_buffer($finfo, $data);
  385. }else{
  386. $tmpFile=OC_Helper::tmpFile();
  387. $fh=fopen($tmpFile, 'wb');
  388. fwrite($fh, $data, 8024);
  389. fclose($fh);
  390. $mime=self::getMimeType($tmpFile);
  391. unset($tmpFile);
  392. return $mime;
  393. }
  394. }
  395. /**
  396. * @brief Checks $_REQUEST contains a var for the $s key. If so, returns the html-escaped value of this var; otherwise returns the default value provided by $d.
  397. * @param string $s name of the var to escape, if set.
  398. * @param string $d default value.
  399. * @return string the print-safe value.
  400. *
  401. */
  402. //FIXME: should also check for value validation (i.e. the email is an email).
  403. public static function init_var($s, $d="") {
  404. $r = $d;
  405. if(isset($_REQUEST[$s]) && !empty($_REQUEST[$s]))
  406. $r = stripslashes(htmlspecialchars($_REQUEST[$s]));
  407. return $r;
  408. }
  409. /**
  410. * returns "checked"-attribute if request contains selected radio element OR if radio element is the default one -- maybe?
  411. * @param string $s Name of radio-button element name
  412. * @param string $v Value of current radio-button element
  413. * @param string $d Value of default radio-button element
  414. */
  415. public static function init_radio($s, $v, $d) {
  416. if((isset($_REQUEST[$s]) && $_REQUEST[$s]==$v) || (!isset($_REQUEST[$s]) && $v == $d))
  417. print "checked=\"checked\" ";
  418. }
  419. /**
  420. * detect if a given program is found in the search PATH
  421. *
  422. * @param $name
  423. * @param bool $path
  424. * @internal param string $program name
  425. * @internal param string $optional search path, defaults to $PATH
  426. * @return bool true if executable program found in path
  427. */
  428. public static function canExecute($name, $path = false) {
  429. // path defaults to PATH from environment if not set
  430. if ($path === false) {
  431. $path = getenv("PATH");
  432. }
  433. // check method depends on operating system
  434. if (!strncmp(PHP_OS, "WIN", 3)) {
  435. // on Windows an appropriate COM or EXE file needs to exist
  436. $exts = array(".exe", ".com");
  437. $check_fn = "file_exists";
  438. } else {
  439. // anywhere else we look for an executable file of that name
  440. $exts = array("");
  441. $check_fn = "is_executable";
  442. }
  443. // Default check will be done with $path directories :
  444. $dirs = explode(PATH_SEPARATOR, $path);
  445. // WARNING : We have to check if open_basedir is enabled :
  446. $obd = ini_get('open_basedir');
  447. if($obd != "none") {
  448. $obd_values = explode(PATH_SEPARATOR, $obd);
  449. if(count($obd_values) > 0 and $obd_values[0]) {
  450. // open_basedir is in effect !
  451. // We need to check if the program is in one of these dirs :
  452. $dirs = $obd_values;
  453. }
  454. }
  455. foreach($dirs as $dir) {
  456. foreach($exts as $ext) {
  457. if($check_fn("$dir/$name".$ext))
  458. return true;
  459. }
  460. }
  461. return false;
  462. }
  463. /**
  464. * copy the contents of one stream to another
  465. * @param resource $source
  466. * @param resource $target
  467. * @return int the number of bytes copied
  468. */
  469. public static function streamCopy($source, $target) {
  470. if(!$source or !$target) {
  471. return false;
  472. }
  473. $count=0;
  474. while(!feof($source)) {
  475. $count+=fwrite($target, fread($source, 8192));
  476. }
  477. return $count;
  478. }
  479. /**
  480. * create a temporary file with an unique filename
  481. * @param string $postfix
  482. * @return string
  483. *
  484. * temporary files are automatically cleaned up after the script is finished
  485. */
  486. public static function tmpFile($postfix='') {
  487. $file=get_temp_dir().'/'.md5(time().rand()).$postfix;
  488. $fh=fopen($file, 'w');
  489. fclose($fh);
  490. self::$tmpFiles[]=$file;
  491. return $file;
  492. }
  493. /**
  494. * create a temporary file with an unique filename. It will not be deleted
  495. * automatically
  496. * @param string $postfix
  497. * @return string
  498. *
  499. */
  500. public static function tmpFileNoClean($postfix='') {
  501. $tmpDirNoClean=get_temp_dir().'/oc-noclean/';
  502. if (!file_exists($tmpDirNoClean) || !is_dir($tmpDirNoClean)) {
  503. if (file_exists($tmpDirNoClean)) {
  504. unlink($tmpDirNoClean);
  505. }
  506. mkdir($tmpDirNoClean);
  507. }
  508. $file=$tmpDirNoClean.md5(time().rand()).$postfix;
  509. $fh=fopen($file, 'w');
  510. fclose($fh);
  511. return $file;
  512. }
  513. /**
  514. * create a temporary folder with an unique filename
  515. * @return string
  516. *
  517. * temporary files are automatically cleaned up after the script is finished
  518. */
  519. public static function tmpFolder() {
  520. $path=get_temp_dir().'/'.md5(time().rand());
  521. mkdir($path);
  522. self::$tmpFiles[]=$path;
  523. return $path.'/';
  524. }
  525. /**
  526. * remove all files created by self::tmpFile
  527. */
  528. public static function cleanTmp() {
  529. $leftoversFile=get_temp_dir().'/oc-not-deleted';
  530. if(file_exists($leftoversFile)) {
  531. $leftovers=file($leftoversFile);
  532. foreach($leftovers as $file) {
  533. self::rmdirr($file);
  534. }
  535. unlink($leftoversFile);
  536. }
  537. foreach(self::$tmpFiles as $file) {
  538. if(file_exists($file)) {
  539. if(!self::rmdirr($file)) {
  540. file_put_contents($leftoversFile, $file."\n", FILE_APPEND);
  541. }
  542. }
  543. }
  544. }
  545. /**
  546. * remove all files created by self::tmpFileNoClean
  547. */
  548. public static function cleanTmpNoClean() {
  549. $tmpDirNoCleanFile=get_temp_dir().'/oc-noclean/';
  550. if(file_exists($tmpDirNoCleanFile)) {
  551. self::rmdirr($tmpDirNoCleanFile);
  552. }
  553. }
  554. /**
  555. * Adds a suffix to the name in case the file exists
  556. *
  557. * @param $path
  558. * @param $filename
  559. * @return string
  560. */
  561. public static function buildNotExistingFileName($path, $filename) {
  562. if($path==='/') {
  563. $path='';
  564. }
  565. if ($pos = strrpos($filename, '.')) {
  566. $name = substr($filename, 0, $pos);
  567. $ext = substr($filename, $pos);
  568. } else {
  569. $name = $filename;
  570. $ext = '';
  571. }
  572. $newpath = $path . '/' . $filename;
  573. $counter = 2;
  574. while (\OC\Files\Filesystem::file_exists($newpath)) {
  575. $newname = $name . ' (' . $counter . ')' . $ext;
  576. $newpath = $path . '/' . $newname;
  577. $counter++;
  578. }
  579. return $newpath;
  580. }
  581. /**
  582. * @brief Checks if $sub is a subdirectory of $parent
  583. *
  584. * @param string $sub
  585. * @param string $parent
  586. * @return bool
  587. */
  588. public static function issubdirectory($sub, $parent) {
  589. if (strpos(realpath($sub), realpath($parent)) === 0) {
  590. return true;
  591. }
  592. return false;
  593. }
  594. /**
  595. * @brief Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  596. *
  597. * @param array $input The array to work on
  598. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  599. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  600. * @return array
  601. *
  602. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  603. * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
  604. *
  605. */
  606. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  607. $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
  608. $ret = array();
  609. foreach ($input as $k => $v) {
  610. $ret[mb_convert_case($k, $case, $encoding)] = $v;
  611. }
  612. return $ret;
  613. }
  614. /**
  615. * @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
  616. *
  617. * @param $string
  618. * @param string $replacement The replacement string.
  619. * @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.
  620. * @param int $length Length of the part to be replaced
  621. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  622. * @internal param string $input The input string. .Opposite to the PHP build-in function does not accept an array.
  623. * @return string
  624. */
  625. public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
  626. $start = intval($start);
  627. $length = intval($length);
  628. $string = mb_substr($string, 0, $start, $encoding) .
  629. $replacement .
  630. mb_substr($string, $start+$length, mb_strlen($string, 'UTF-8')-$start, $encoding);
  631. return $string;
  632. }
  633. /**
  634. * @brief Replace all occurrences of the search string with the replacement string
  635. *
  636. * @param string $search The value being searched for, otherwise known as the needle.
  637. * @param string $replace The replacement
  638. * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
  639. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  640. * @param int $count If passed, this will be set to the number of replacements performed.
  641. * @return string
  642. *
  643. */
  644. public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
  645. $offset = -1;
  646. $length = mb_strlen($search, $encoding);
  647. while(($i = mb_strrpos($subject, $search, $offset, $encoding)) !== false ) {
  648. $subject = OC_Helper::mb_substr_replace($subject, $replace, $i, $length);
  649. $offset = $i - mb_strlen($subject, $encoding);
  650. $count++;
  651. }
  652. return $subject;
  653. }
  654. /**
  655. * @brief performs a search in a nested array
  656. * @param array $haystack the array to be searched
  657. * @param string $needle the search string
  658. * @param string $index optional, only search this key name
  659. * @return mixed the key of the matching field, otherwise false
  660. *
  661. * performs a search in a nested array
  662. *
  663. * taken from http://www.php.net/manual/en/function.array-search.php#97645
  664. */
  665. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  666. $aIt = new RecursiveArrayIterator($haystack);
  667. $it = new RecursiveIteratorIterator($aIt);
  668. while($it->valid()) {
  669. if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
  670. return $aIt->key();
  671. }
  672. $it->next();
  673. }
  674. return false;
  675. }
  676. /**
  677. * Shortens str to maxlen by replacing characters in the middle with '...', eg.
  678. * ellipsis('a very long string with lots of useless info to make a better example', 14) becomes 'a very ...example'
  679. * @param string $str the string
  680. * @param string $maxlen the maximum length of the result
  681. * @return string with at most maxlen characters
  682. */
  683. public static function ellipsis($str, $maxlen) {
  684. if (strlen($str) > $maxlen) {
  685. $characters = floor($maxlen / 2);
  686. return substr($str, 0, $characters) . '...' . substr($str, -1 * $characters);
  687. }
  688. return $str;
  689. }
  690. /**
  691. * @brief calculates the maximum upload size respecting system settings, free space and user quota
  692. *
  693. * @param $dir the current folder where the user currently operates
  694. * @return number of bytes representing
  695. */
  696. public static function maxUploadFilesize($dir) {
  697. $upload_max_filesize = OCP\Util::computerFileSize(ini_get('upload_max_filesize'));
  698. $post_max_size = OCP\Util::computerFileSize(ini_get('post_max_size'));
  699. $maxUploadFilesize = min($upload_max_filesize, $post_max_size);
  700. $freeSpace = \OC\Files\Filesystem::free_space($dir);
  701. $freeSpace = max($freeSpace, 0);
  702. return min($maxUploadFilesize, $freeSpace);
  703. }
  704. /**
  705. * Checks if a function is available
  706. * @param string $function_name
  707. * @return bool
  708. */
  709. public static function is_function_enabled($function_name) {
  710. if (!function_exists($function_name)) {
  711. return false;
  712. }
  713. $disabled = explode(', ', ini_get('disable_functions'));
  714. if (in_array($function_name, $disabled)) {
  715. return false;
  716. }
  717. $disabled = explode(', ', ini_get('suhosin.executor.func.blacklist'));
  718. if (in_array($function_name, $disabled)) {
  719. return false;
  720. }
  721. return true;
  722. }
  723. /**
  724. * Calculate the disc space
  725. */
  726. public static function getStorageInfo() {
  727. $rootInfo = \OC\Files\Filesystem::getFileInfo('/');
  728. $used = $rootInfo['size'];
  729. if ($used < 0) {
  730. $used = 0;
  731. }
  732. $free = \OC\Files\Filesystem::free_space();
  733. $total = $free + $used;
  734. if ($total == 0) {
  735. $total = 1; // prevent division by zero
  736. }
  737. $relative = round(($used / $total) * 10000) / 100;
  738. return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
  739. }
  740. }