選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

helper.php 24KB

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