helper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Ardinis <Ardinis@users.noreply.github.com>
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Christopher Schäpers <kondou@ts.unde.re>
  10. * @author Clark Tomlinson <fallen013@gmail.com>
  11. * @author Fabian Henze <flyser42@gmx.de>
  12. * @author Felix Moeller <mail@felixmoeller.de>
  13. * @author Jakob Sack <mail@jakobsack.de>
  14. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  15. * @author Joas Schilling <coding@schilljs.com>
  16. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  19. * @author Morris Jobke <hey@morrisjobke.de>
  20. * @author Olivier Paroz <github@oparoz.com>
  21. * @author Pellaeon Lin <nfsmwlin@gmail.com>
  22. * @author RealRancor <fisch.666@gmx.de>
  23. * @author Robin Appelman <robin@icewind.nl>
  24. * @author Robin McCorkell <robin@mccorkell.me.uk>
  25. * @author Roeland Jago Douma <roeland@famdouma.nl>
  26. * @author Simon Könnecke <simonkoennecke@gmail.com>
  27. * @author Thomas Müller <thomas.mueller@tmit.eu>
  28. * @author Thomas Tanghus <thomas@tanghus.net>
  29. * @author Vincent Petry <pvince81@owncloud.com>
  30. *
  31. * @license AGPL-3.0
  32. *
  33. * This code is free software: you can redistribute it and/or modify
  34. * it under the terms of the GNU Affero General Public License, version 3,
  35. * as published by the Free Software Foundation.
  36. *
  37. * This program is distributed in the hope that it will be useful,
  38. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  39. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  40. * GNU Affero General Public License for more details.
  41. *
  42. * You should have received a copy of the GNU Affero General Public License, version 3,
  43. * along with this program. If not, see <http://www.gnu.org/licenses/>
  44. *
  45. */
  46. use Symfony\Component\Process\ExecutableFinder;
  47. /**
  48. * Collection of useful functions
  49. */
  50. class OC_Helper {
  51. private static $templateManager;
  52. /**
  53. * Make a human file size
  54. * @param int $bytes file size in bytes
  55. * @return string a human readable file size
  56. *
  57. * Makes 2048 to 2 kB.
  58. */
  59. public static function humanFileSize($bytes) {
  60. if ($bytes < 0) {
  61. return "?";
  62. }
  63. if ($bytes < 1024) {
  64. return "$bytes B";
  65. }
  66. $bytes = round($bytes / 1024, 0);
  67. if ($bytes < 1024) {
  68. return "$bytes KB";
  69. }
  70. $bytes = round($bytes / 1024, 1);
  71. if ($bytes < 1024) {
  72. return "$bytes MB";
  73. }
  74. $bytes = round($bytes / 1024, 1);
  75. if ($bytes < 1024) {
  76. return "$bytes GB";
  77. }
  78. $bytes = round($bytes / 1024, 1);
  79. if ($bytes < 1024) {
  80. return "$bytes TB";
  81. }
  82. $bytes = round($bytes / 1024, 1);
  83. return "$bytes PB";
  84. }
  85. /**
  86. * Make a php file size
  87. * @param int $bytes file size in bytes
  88. * @return string a php parseable file size
  89. *
  90. * Makes 2048 to 2k and 2^41 to 2048G
  91. */
  92. public static function phpFileSize($bytes) {
  93. if ($bytes < 0) {
  94. return "?";
  95. }
  96. if ($bytes < 1024) {
  97. return $bytes . "B";
  98. }
  99. $bytes = round($bytes / 1024, 1);
  100. if ($bytes < 1024) {
  101. return $bytes . "K";
  102. }
  103. $bytes = round($bytes / 1024, 1);
  104. if ($bytes < 1024) {
  105. return $bytes . "M";
  106. }
  107. $bytes = round($bytes / 1024, 1);
  108. return $bytes . "G";
  109. }
  110. /**
  111. * Make a computer file size
  112. * @param string $str file size in human readable format
  113. * @return float|bool a file size in bytes
  114. *
  115. * Makes 2kB to 2048.
  116. *
  117. * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
  118. */
  119. public static function computerFileSize($str) {
  120. $str = strtolower($str);
  121. if (is_numeric($str)) {
  122. return (float)$str;
  123. }
  124. $bytes_array = array(
  125. 'b' => 1,
  126. 'k' => 1024,
  127. 'kb' => 1024,
  128. 'mb' => 1024 * 1024,
  129. 'm' => 1024 * 1024,
  130. 'gb' => 1024 * 1024 * 1024,
  131. 'g' => 1024 * 1024 * 1024,
  132. 'tb' => 1024 * 1024 * 1024 * 1024,
  133. 't' => 1024 * 1024 * 1024 * 1024,
  134. 'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
  135. 'p' => 1024 * 1024 * 1024 * 1024 * 1024,
  136. );
  137. $bytes = (float)$str;
  138. if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
  139. $bytes *= $bytes_array[$matches[1]];
  140. } else {
  141. return false;
  142. }
  143. $bytes = round($bytes);
  144. return $bytes;
  145. }
  146. /**
  147. * Recursive copying of folders
  148. * @param string $src source folder
  149. * @param string $dest target folder
  150. *
  151. */
  152. static function copyr($src, $dest) {
  153. if (is_dir($src)) {
  154. if (!is_dir($dest)) {
  155. mkdir($dest);
  156. }
  157. $files = scandir($src);
  158. foreach ($files as $file) {
  159. if ($file != "." && $file != "..") {
  160. self::copyr("$src/$file", "$dest/$file");
  161. }
  162. }
  163. } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
  164. copy($src, $dest);
  165. }
  166. }
  167. /**
  168. * Recursive deletion of folders
  169. * @param string $dir path to the folder
  170. * @param bool $deleteSelf if set to false only the content of the folder will be deleted
  171. * @return bool
  172. */
  173. static function rmdirr($dir, $deleteSelf = true) {
  174. if (is_dir($dir)) {
  175. $files = new RecursiveIteratorIterator(
  176. new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
  177. RecursiveIteratorIterator::CHILD_FIRST
  178. );
  179. foreach ($files as $fileInfo) {
  180. /** @var SplFileInfo $fileInfo */
  181. if ($fileInfo->isLink()) {
  182. unlink($fileInfo->getPathname());
  183. } else if ($fileInfo->isDir()) {
  184. rmdir($fileInfo->getRealPath());
  185. } else {
  186. unlink($fileInfo->getRealPath());
  187. }
  188. }
  189. if ($deleteSelf) {
  190. rmdir($dir);
  191. }
  192. } elseif (file_exists($dir)) {
  193. if ($deleteSelf) {
  194. unlink($dir);
  195. }
  196. }
  197. if (!$deleteSelf) {
  198. return true;
  199. }
  200. return !file_exists($dir);
  201. }
  202. /**
  203. * @return \OC\Files\Type\TemplateManager
  204. */
  205. static public function getFileTemplateManager() {
  206. if (!self::$templateManager) {
  207. self::$templateManager = new \OC\Files\Type\TemplateManager();
  208. }
  209. return self::$templateManager;
  210. }
  211. /**
  212. * detect if a given program is found in the search PATH
  213. *
  214. * @param string $name
  215. * @param bool $path
  216. * @internal param string $program name
  217. * @internal param string $optional search path, defaults to $PATH
  218. * @return bool true if executable program found in path
  219. */
  220. public static function canExecute($name, $path = false) {
  221. // path defaults to PATH from environment if not set
  222. if ($path === false) {
  223. $path = getenv("PATH");
  224. }
  225. // we look for an executable file of that name
  226. $exts = [""];
  227. $check_fn = "is_executable";
  228. // Default check will be done with $path directories :
  229. $dirs = explode(PATH_SEPARATOR, $path);
  230. // WARNING : We have to check if open_basedir is enabled :
  231. $obd = OC::$server->getIniWrapper()->getString('open_basedir');
  232. if ($obd != "none") {
  233. $obd_values = explode(PATH_SEPARATOR, $obd);
  234. if (count($obd_values) > 0 and $obd_values[0]) {
  235. // open_basedir is in effect !
  236. // We need to check if the program is in one of these dirs :
  237. $dirs = $obd_values;
  238. }
  239. }
  240. foreach ($dirs as $dir) {
  241. foreach ($exts as $ext) {
  242. if ($check_fn("$dir/$name" . $ext))
  243. return true;
  244. }
  245. }
  246. return false;
  247. }
  248. /**
  249. * copy the contents of one stream to another
  250. *
  251. * @param resource $source
  252. * @param resource $target
  253. * @return array the number of bytes copied and result
  254. */
  255. public static function streamCopy($source, $target) {
  256. if (!$source or !$target) {
  257. return array(0, false);
  258. }
  259. $bufSize = 8192;
  260. $result = true;
  261. $count = 0;
  262. while (!feof($source)) {
  263. $buf = fread($source, $bufSize);
  264. $bytesWritten = fwrite($target, $buf);
  265. if ($bytesWritten !== false) {
  266. $count += $bytesWritten;
  267. }
  268. // note: strlen is expensive so only use it when necessary,
  269. // on the last block
  270. if ($bytesWritten === false
  271. || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
  272. ) {
  273. // write error, could be disk full ?
  274. $result = false;
  275. break;
  276. }
  277. }
  278. return array($count, $result);
  279. }
  280. /**
  281. * Adds a suffix to the name in case the file exists
  282. *
  283. * @param string $path
  284. * @param string $filename
  285. * @return string
  286. */
  287. public static function buildNotExistingFileName($path, $filename) {
  288. $view = \OC\Files\Filesystem::getView();
  289. return self::buildNotExistingFileNameForView($path, $filename, $view);
  290. }
  291. /**
  292. * Adds a suffix to the name in case the file exists
  293. *
  294. * @param string $path
  295. * @param string $filename
  296. * @return string
  297. */
  298. public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
  299. if ($path === '/') {
  300. $path = '';
  301. }
  302. if ($pos = strrpos($filename, '.')) {
  303. $name = substr($filename, 0, $pos);
  304. $ext = substr($filename, $pos);
  305. } else {
  306. $name = $filename;
  307. $ext = '';
  308. }
  309. $newpath = $path . '/' . $filename;
  310. if ($view->file_exists($newpath)) {
  311. if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
  312. //Replace the last "(number)" with "(number+1)"
  313. $last_match = count($matches[0]) - 1;
  314. $counter = $matches[1][$last_match][0] + 1;
  315. $offset = $matches[0][$last_match][1];
  316. $match_length = strlen($matches[0][$last_match][0]);
  317. } else {
  318. $counter = 2;
  319. $match_length = 0;
  320. $offset = false;
  321. }
  322. do {
  323. if ($offset) {
  324. //Replace the last "(number)" with "(number+1)"
  325. $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
  326. } else {
  327. $newname = $name . ' (' . $counter . ')';
  328. }
  329. $newpath = $path . '/' . $newname . $ext;
  330. $counter++;
  331. } while ($view->file_exists($newpath));
  332. }
  333. return $newpath;
  334. }
  335. /**
  336. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  337. *
  338. * @param array $input The array to work on
  339. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  340. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  341. * @return array
  342. *
  343. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  344. * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
  345. *
  346. */
  347. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  348. $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
  349. $ret = array();
  350. foreach ($input as $k => $v) {
  351. $ret[mb_convert_case($k, $case, $encoding)] = $v;
  352. }
  353. return $ret;
  354. }
  355. /**
  356. * performs a search in a nested array
  357. * @param array $haystack the array to be searched
  358. * @param string $needle the search string
  359. * @param mixed $index optional, only search this key name
  360. * @return mixed the key of the matching field, otherwise false
  361. *
  362. * performs a search in a nested array
  363. *
  364. * taken from http://www.php.net/manual/en/function.array-search.php#97645
  365. */
  366. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  367. $aIt = new RecursiveArrayIterator($haystack);
  368. $it = new RecursiveIteratorIterator($aIt);
  369. while ($it->valid()) {
  370. if (((isset($index) AND ($it->key() == $index)) OR !isset($index)) AND ($it->current() == $needle)) {
  371. return $aIt->key();
  372. }
  373. $it->next();
  374. }
  375. return false;
  376. }
  377. /**
  378. * calculates the maximum upload size respecting system settings, free space and user quota
  379. *
  380. * @param string $dir the current folder where the user currently operates
  381. * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
  382. * @return int number of bytes representing
  383. */
  384. public static function maxUploadFilesize($dir, $freeSpace = null) {
  385. if (is_null($freeSpace) || $freeSpace < 0){
  386. $freeSpace = self::freeSpace($dir);
  387. }
  388. return min($freeSpace, self::uploadLimit());
  389. }
  390. /**
  391. * Calculate free space left within user quota
  392. *
  393. * @param string $dir the current folder where the user currently operates
  394. * @return int number of bytes representing
  395. */
  396. public static function freeSpace($dir) {
  397. $freeSpace = \OC\Files\Filesystem::free_space($dir);
  398. if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  399. $freeSpace = max($freeSpace, 0);
  400. return $freeSpace;
  401. } else {
  402. return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
  403. }
  404. }
  405. /**
  406. * Calculate PHP upload limit
  407. *
  408. * @return int PHP upload file size limit
  409. */
  410. public static function uploadLimit() {
  411. $ini = \OC::$server->getIniWrapper();
  412. $upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
  413. $post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
  414. if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
  415. return INF;
  416. } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
  417. return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
  418. } else {
  419. return min($upload_max_filesize, $post_max_size);
  420. }
  421. }
  422. /**
  423. * Checks if a function is available
  424. *
  425. * @param string $function_name
  426. * @return bool
  427. */
  428. public static function is_function_enabled($function_name) {
  429. if (!function_exists($function_name)) {
  430. return false;
  431. }
  432. $ini = \OC::$server->getIniWrapper();
  433. $disabled = explode(',', $ini->get('disable_functions') ?: '');
  434. $disabled = array_map('trim', $disabled);
  435. if (in_array($function_name, $disabled)) {
  436. return false;
  437. }
  438. $disabled = explode(',', $ini->get('suhosin.executor.func.blacklist') ?: '');
  439. $disabled = array_map('trim', $disabled);
  440. if (in_array($function_name, $disabled)) {
  441. return false;
  442. }
  443. return true;
  444. }
  445. /**
  446. * Try to find a program
  447. *
  448. * @param string $program
  449. * @return null|string
  450. */
  451. public static function findBinaryPath($program) {
  452. $memcache = \OC::$server->getMemCacheFactory()->createDistributed('findBinaryPath');
  453. if ($memcache->hasKey($program)) {
  454. return $memcache->get($program);
  455. }
  456. $result = null;
  457. if (self::is_function_enabled('exec')) {
  458. $exeSniffer = new ExecutableFinder();
  459. // Returns null if nothing is found
  460. $result = $exeSniffer->find($program, null, ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/opt/bin']);
  461. }
  462. // store the value for 5 minutes
  463. $memcache->set($program, $result, 300);
  464. return $result;
  465. }
  466. /**
  467. * Calculate the disc space for the given path
  468. *
  469. * @param string $path
  470. * @param \OCP\Files\FileInfo $rootInfo (optional)
  471. * @return array
  472. * @throws \OCP\Files\NotFoundException
  473. */
  474. public static function getStorageInfo($path, $rootInfo = null) {
  475. // return storage info without adding mount points
  476. $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
  477. if (!$rootInfo) {
  478. $rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
  479. }
  480. if (!$rootInfo instanceof \OCP\Files\FileInfo) {
  481. throw new \OCP\Files\NotFoundException();
  482. }
  483. $used = $rootInfo->getSize();
  484. if ($used < 0) {
  485. $used = 0;
  486. }
  487. $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
  488. $storage = $rootInfo->getStorage();
  489. $sourceStorage = $storage;
  490. if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
  491. $includeExtStorage = false;
  492. $sourceStorage = $storage->getSourceStorage();
  493. }
  494. if ($includeExtStorage) {
  495. if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
  496. || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
  497. ) {
  498. /** @var \OC\Files\Storage\Home $storage */
  499. $userInstance = $storage->getUser();
  500. $user = ($userInstance === null) ? null : $userInstance->getUID();
  501. } else {
  502. $user = \OC::$server->getUserSession()->getUser()->getUID();
  503. }
  504. if ($user) {
  505. $quota = OC_Util::getUserQuota($user);
  506. } else {
  507. $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
  508. }
  509. if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  510. // always get free space / total space from root + mount points
  511. return self::getGlobalStorageInfo();
  512. }
  513. }
  514. // TODO: need a better way to get total space from storage
  515. if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
  516. /** @var \OC\Files\Storage\Wrapper\Quota $storage */
  517. $quota = $sourceStorage->getQuota();
  518. }
  519. $free = $sourceStorage->free_space($rootInfo->getInternalPath());
  520. if ($free >= 0) {
  521. $total = $free + $used;
  522. } else {
  523. $total = $free; //either unknown or unlimited
  524. }
  525. if ($total > 0) {
  526. if ($quota > 0 && $total > $quota) {
  527. $total = $quota;
  528. }
  529. // prevent division by zero or error codes (negative values)
  530. $relative = round(($used / $total) * 10000) / 100;
  531. } else {
  532. $relative = 0;
  533. }
  534. $ownerId = $storage->getOwner($path);
  535. $ownerDisplayName = '';
  536. $owner = \OC::$server->getUserManager()->get($ownerId);
  537. if($owner) {
  538. $ownerDisplayName = $owner->getDisplayName();
  539. }
  540. return [
  541. 'free' => $free,
  542. 'used' => $used,
  543. 'quota' => $quota,
  544. 'total' => $total,
  545. 'relative' => $relative,
  546. 'owner' => $ownerId,
  547. 'ownerDisplayName' => $ownerDisplayName,
  548. ];
  549. }
  550. /**
  551. * Get storage info including all mount points and quota
  552. *
  553. * @return array
  554. */
  555. private static function getGlobalStorageInfo() {
  556. $quota = OC_Util::getUserQuota(\OCP\User::getUser());
  557. $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
  558. $used = $rootInfo['size'];
  559. if ($used < 0) {
  560. $used = 0;
  561. }
  562. $total = $quota;
  563. $free = $quota - $used;
  564. if ($total > 0) {
  565. if ($quota > 0 && $total > $quota) {
  566. $total = $quota;
  567. }
  568. // prevent division by zero or error codes (negative values)
  569. $relative = round(($used / $total) * 10000) / 100;
  570. } else {
  571. $relative = 0;
  572. }
  573. return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
  574. }
  575. /**
  576. * Returns whether the config file is set manually to read-only
  577. * @return bool
  578. */
  579. public static function isReadOnlyConfigEnabled() {
  580. return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
  581. }
  582. }