PageRenderTime 59ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/helper.php

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