OC_Helper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Felix Moeller <mail@felixmoeller.de>
  12. * @author J0WI <J0WI@users.noreply.github.com>
  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 Julius Härtl <jus@bitgrid.net>
  18. * @author Lukas Reschke <lukas@statuscode.ch>
  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 <vincent@nextcloud.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 bantu\IniGetWrapper\IniGetWrapper;
  47. use OC\Files\Filesystem;
  48. use OCP\Files\Mount\IMountPoint;
  49. use OCP\ICacheFactory;
  50. use OCP\IBinaryFinder;
  51. use OCP\IUser;
  52. use Psr\Log\LoggerInterface;
  53. /**
  54. * Collection of useful functions
  55. */
  56. class OC_Helper {
  57. private static $templateManager;
  58. /**
  59. * Make a human file size
  60. * @param int $bytes file size in bytes
  61. * @return string a human readable file size
  62. *
  63. * Makes 2048 to 2 kB.
  64. */
  65. public static function humanFileSize($bytes) {
  66. if ($bytes < 0) {
  67. return "?";
  68. }
  69. if ($bytes < 1024) {
  70. return "$bytes B";
  71. }
  72. $bytes = round($bytes / 1024, 0);
  73. if ($bytes < 1024) {
  74. return "$bytes KB";
  75. }
  76. $bytes = round($bytes / 1024, 1);
  77. if ($bytes < 1024) {
  78. return "$bytes MB";
  79. }
  80. $bytes = round($bytes / 1024, 1);
  81. if ($bytes < 1024) {
  82. return "$bytes GB";
  83. }
  84. $bytes = round($bytes / 1024, 1);
  85. if ($bytes < 1024) {
  86. return "$bytes TB";
  87. }
  88. $bytes = round($bytes / 1024, 1);
  89. return "$bytes PB";
  90. }
  91. /**
  92. * Make a computer file size
  93. * @param string $str file size in human readable format
  94. * @return int|false a file size in bytes
  95. *
  96. * Makes 2kB to 2048.
  97. *
  98. * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418
  99. */
  100. public static function computerFileSize($str) {
  101. $str = strtolower($str);
  102. if (is_numeric($str)) {
  103. return (int)$str;
  104. }
  105. $bytes_array = [
  106. 'b' => 1,
  107. 'k' => 1024,
  108. 'kb' => 1024,
  109. 'mb' => 1024 * 1024,
  110. 'm' => 1024 * 1024,
  111. 'gb' => 1024 * 1024 * 1024,
  112. 'g' => 1024 * 1024 * 1024,
  113. 'tb' => 1024 * 1024 * 1024 * 1024,
  114. 't' => 1024 * 1024 * 1024 * 1024,
  115. 'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
  116. 'p' => 1024 * 1024 * 1024 * 1024 * 1024,
  117. ];
  118. $bytes = (float)$str;
  119. if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
  120. $bytes *= $bytes_array[$matches[1]];
  121. } else {
  122. return false;
  123. }
  124. $bytes = round($bytes);
  125. return (int)$bytes;
  126. }
  127. /**
  128. * Recursive copying of folders
  129. * @param string $src source folder
  130. * @param string $dest target folder
  131. *
  132. */
  133. public static function copyr($src, $dest) {
  134. if (is_dir($src)) {
  135. if (!is_dir($dest)) {
  136. mkdir($dest);
  137. }
  138. $files = scandir($src);
  139. foreach ($files as $file) {
  140. if ($file != "." && $file != "..") {
  141. self::copyr("$src/$file", "$dest/$file");
  142. }
  143. }
  144. } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
  145. copy($src, $dest);
  146. }
  147. }
  148. /**
  149. * Recursive deletion of folders
  150. * @param string $dir path to the folder
  151. * @param bool $deleteSelf if set to false only the content of the folder will be deleted
  152. * @return bool
  153. */
  154. public static function rmdirr($dir, $deleteSelf = true) {
  155. if (is_dir($dir)) {
  156. $files = new RecursiveIteratorIterator(
  157. new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
  158. RecursiveIteratorIterator::CHILD_FIRST
  159. );
  160. foreach ($files as $fileInfo) {
  161. /** @var SplFileInfo $fileInfo */
  162. if ($fileInfo->isLink()) {
  163. unlink($fileInfo->getPathname());
  164. } elseif ($fileInfo->isDir()) {
  165. rmdir($fileInfo->getRealPath());
  166. } else {
  167. unlink($fileInfo->getRealPath());
  168. }
  169. }
  170. if ($deleteSelf) {
  171. rmdir($dir);
  172. }
  173. } elseif (file_exists($dir)) {
  174. if ($deleteSelf) {
  175. unlink($dir);
  176. }
  177. }
  178. if (!$deleteSelf) {
  179. return true;
  180. }
  181. return !file_exists($dir);
  182. }
  183. /**
  184. * @deprecated 18.0.0
  185. * @return \OC\Files\Type\TemplateManager
  186. */
  187. public static function getFileTemplateManager() {
  188. if (!self::$templateManager) {
  189. self::$templateManager = new \OC\Files\Type\TemplateManager();
  190. }
  191. return self::$templateManager;
  192. }
  193. /**
  194. * detect if a given program is found in the search PATH
  195. *
  196. * @param string $name
  197. * @param bool $path
  198. * @internal param string $program name
  199. * @internal param string $optional search path, defaults to $PATH
  200. * @return bool true if executable program found in path
  201. */
  202. public static function canExecute($name, $path = false) {
  203. // path defaults to PATH from environment if not set
  204. if ($path === false) {
  205. $path = getenv("PATH");
  206. }
  207. // we look for an executable file of that name
  208. $exts = [""];
  209. $check_fn = "is_executable";
  210. // Default check will be done with $path directories :
  211. $dirs = explode(PATH_SEPARATOR, $path);
  212. // WARNING : We have to check if open_basedir is enabled :
  213. $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
  214. if ($obd != "none") {
  215. $obd_values = explode(PATH_SEPARATOR, $obd);
  216. if (count($obd_values) > 0 and $obd_values[0]) {
  217. // open_basedir is in effect !
  218. // We need to check if the program is in one of these dirs :
  219. $dirs = $obd_values;
  220. }
  221. }
  222. foreach ($dirs as $dir) {
  223. foreach ($exts as $ext) {
  224. if ($check_fn("$dir/$name" . $ext)) {
  225. return true;
  226. }
  227. }
  228. }
  229. return false;
  230. }
  231. /**
  232. * copy the contents of one stream to another
  233. *
  234. * @param resource $source
  235. * @param resource $target
  236. * @return array the number of bytes copied and result
  237. */
  238. public static function streamCopy($source, $target) {
  239. if (!$source or !$target) {
  240. return [0, false];
  241. }
  242. $bufSize = 8192;
  243. $result = true;
  244. $count = 0;
  245. while (!feof($source)) {
  246. $buf = fread($source, $bufSize);
  247. $bytesWritten = fwrite($target, $buf);
  248. if ($bytesWritten !== false) {
  249. $count += $bytesWritten;
  250. }
  251. // note: strlen is expensive so only use it when necessary,
  252. // on the last block
  253. if ($bytesWritten === false
  254. || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
  255. ) {
  256. // write error, could be disk full ?
  257. $result = false;
  258. break;
  259. }
  260. }
  261. return [$count, $result];
  262. }
  263. /**
  264. * Adds a suffix to the name in case the file exists
  265. *
  266. * @param string $path
  267. * @param string $filename
  268. * @return string
  269. */
  270. public static function buildNotExistingFileName($path, $filename) {
  271. $view = \OC\Files\Filesystem::getView();
  272. return self::buildNotExistingFileNameForView($path, $filename, $view);
  273. }
  274. /**
  275. * Adds a suffix to the name in case the file exists
  276. *
  277. * @param string $path
  278. * @param string $filename
  279. * @return string
  280. */
  281. public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
  282. if ($path === '/') {
  283. $path = '';
  284. }
  285. if ($pos = strrpos($filename, '.')) {
  286. $name = substr($filename, 0, $pos);
  287. $ext = substr($filename, $pos);
  288. } else {
  289. $name = $filename;
  290. $ext = '';
  291. }
  292. $newpath = $path . '/' . $filename;
  293. if ($view->file_exists($newpath)) {
  294. if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
  295. //Replace the last "(number)" with "(number+1)"
  296. $last_match = count($matches[0]) - 1;
  297. $counter = $matches[1][$last_match][0] + 1;
  298. $offset = $matches[0][$last_match][1];
  299. $match_length = strlen($matches[0][$last_match][0]);
  300. } else {
  301. $counter = 2;
  302. $match_length = 0;
  303. $offset = false;
  304. }
  305. do {
  306. if ($offset) {
  307. //Replace the last "(number)" with "(number+1)"
  308. $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
  309. } else {
  310. $newname = $name . ' (' . $counter . ')';
  311. }
  312. $newpath = $path . '/' . $newname . $ext;
  313. $counter++;
  314. } while ($view->file_exists($newpath));
  315. }
  316. return $newpath;
  317. }
  318. /**
  319. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  320. *
  321. * @param array $input The array to work on
  322. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  323. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  324. * @return array
  325. *
  326. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  327. * based on https://www.php.net/manual/en/function.array-change-key-case.php#107715
  328. *
  329. */
  330. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  331. $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
  332. $ret = [];
  333. foreach ($input as $k => $v) {
  334. $ret[mb_convert_case($k, $case, $encoding)] = $v;
  335. }
  336. return $ret;
  337. }
  338. /**
  339. * performs a search in a nested array
  340. * @param array $haystack the array to be searched
  341. * @param string $needle the search string
  342. * @param mixed $index optional, only search this key name
  343. * @return mixed the key of the matching field, otherwise false
  344. *
  345. * performs a search in a nested array
  346. *
  347. * taken from https://www.php.net/manual/en/function.array-search.php#97645
  348. */
  349. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  350. $aIt = new RecursiveArrayIterator($haystack);
  351. $it = new RecursiveIteratorIterator($aIt);
  352. while ($it->valid()) {
  353. if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
  354. return $aIt->key();
  355. }
  356. $it->next();
  357. }
  358. return false;
  359. }
  360. /**
  361. * calculates the maximum upload size respecting system settings, free space and user quota
  362. *
  363. * @param string $dir the current folder where the user currently operates
  364. * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
  365. * @return int number of bytes representing
  366. */
  367. public static function maxUploadFilesize($dir, $freeSpace = null) {
  368. if (is_null($freeSpace) || $freeSpace < 0) {
  369. $freeSpace = self::freeSpace($dir);
  370. }
  371. return min($freeSpace, self::uploadLimit());
  372. }
  373. /**
  374. * Calculate free space left within user quota
  375. *
  376. * @param string $dir the current folder where the user currently operates
  377. * @return int number of bytes representing
  378. */
  379. public static function freeSpace($dir) {
  380. $freeSpace = \OC\Files\Filesystem::free_space($dir);
  381. if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  382. $freeSpace = max($freeSpace, 0);
  383. return $freeSpace;
  384. } else {
  385. return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
  386. }
  387. }
  388. /**
  389. * Calculate PHP upload limit
  390. *
  391. * @return int PHP upload file size limit
  392. */
  393. public static function uploadLimit() {
  394. $ini = \OC::$server->get(IniGetWrapper::class);
  395. $upload_max_filesize = (int)OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
  396. $post_max_size = (int)OCP\Util::computerFileSize($ini->get('post_max_size'));
  397. if ($upload_max_filesize === 0 && $post_max_size === 0) {
  398. return INF;
  399. } elseif ($upload_max_filesize === 0 || $post_max_size === 0) {
  400. return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
  401. } else {
  402. return min($upload_max_filesize, $post_max_size);
  403. }
  404. }
  405. /**
  406. * Checks if a function is available
  407. *
  408. * @deprecated Since 25.0.0 use \OCP\Util::isFunctionEnabled instead
  409. */
  410. public static function is_function_enabled(string $function_name): bool {
  411. return \OCP\Util::isFunctionEnabled($function_name);
  412. }
  413. /**
  414. * Try to find a program
  415. * @deprecated Since 25.0.0 Use \OC\BinaryFinder directly
  416. */
  417. public static function findBinaryPath(string $program): ?string {
  418. $result = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath($program);
  419. return $result !== false ? $result : null;
  420. }
  421. /**
  422. * Calculate the disc space for the given path
  423. *
  424. * BEWARE: this requires that Util::setupFS() was called
  425. * already !
  426. *
  427. * @param string $path
  428. * @param \OCP\Files\FileInfo $rootInfo (optional)
  429. * @param bool $includeMountPoints whether to include mount points in the size calculation
  430. * @param bool $useCache whether to use the cached quota values
  431. * @return array
  432. * @throws \OCP\Files\NotFoundException
  433. */
  434. public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) {
  435. /** @var ICacheFactory $cacheFactory */
  436. $cacheFactory = \OC::$server->get(ICacheFactory::class);
  437. $memcache = $cacheFactory->createLocal('storage_info');
  438. // return storage info without adding mount points
  439. $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
  440. $fullPath = Filesystem::getView()->getAbsolutePath($path);
  441. $cacheKey = $fullPath. '::' . ($includeMountPoints ? 'include' : 'exclude');
  442. if ($useCache) {
  443. $cached = $memcache->get($cacheKey);
  444. if ($cached) {
  445. return $cached;
  446. }
  447. }
  448. if (!$rootInfo) {
  449. $rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
  450. }
  451. if (!$rootInfo instanceof \OCP\Files\FileInfo) {
  452. throw new \OCP\Files\NotFoundException();
  453. }
  454. $used = $rootInfo->getSize($includeMountPoints);
  455. if ($used < 0) {
  456. $used = 0;
  457. }
  458. $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
  459. $mount = $rootInfo->getMountPoint();
  460. $storage = $mount->getStorage();
  461. $sourceStorage = $storage;
  462. if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
  463. $includeExtStorage = false;
  464. }
  465. if ($includeExtStorage) {
  466. if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
  467. || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
  468. ) {
  469. /** @var \OC\Files\Storage\Home $storage */
  470. $user = $storage->getUser();
  471. } else {
  472. $user = \OC::$server->getUserSession()->getUser();
  473. }
  474. $quota = OC_Util::getUserQuota($user);
  475. if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  476. // always get free space / total space from root + mount points
  477. return self::getGlobalStorageInfo($quota, $user, $mount);
  478. }
  479. }
  480. // TODO: need a better way to get total space from storage
  481. if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
  482. /** @var \OC\Files\Storage\Wrapper\Quota $storage */
  483. $quota = $sourceStorage->getQuota();
  484. }
  485. try {
  486. $free = $sourceStorage->free_space($rootInfo->getInternalPath());
  487. } catch (\Exception $e) {
  488. if ($path === "") {
  489. throw $e;
  490. }
  491. /** @var LoggerInterface $logger */
  492. $logger = \OC::$server->get(LoggerInterface::class);
  493. $logger->warning("Error while getting quota info, using root quota", ['exception' => $e]);
  494. $rootInfo = self::getStorageInfo("");
  495. $memcache->set($cacheKey, $rootInfo, 5 * 60);
  496. return $rootInfo;
  497. }
  498. if ($free >= 0) {
  499. $total = $free + $used;
  500. } else {
  501. $total = $free; //either unknown or unlimited
  502. }
  503. if ($total > 0) {
  504. if ($quota > 0 && $total > $quota) {
  505. $total = $quota;
  506. }
  507. // prevent division by zero or error codes (negative values)
  508. $relative = round(($used / $total) * 10000) / 100;
  509. } else {
  510. $relative = 0;
  511. }
  512. $ownerId = $storage->getOwner($path);
  513. $ownerDisplayName = '';
  514. if ($ownerId) {
  515. $ownerDisplayName = \OC::$server->getUserManager()->getDisplayName($ownerId) ?? '';
  516. }
  517. if (substr_count($mount->getMountPoint(), '/') < 3) {
  518. $mountPoint = '';
  519. } else {
  520. [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
  521. }
  522. $info = [
  523. 'free' => $free,
  524. 'used' => $used,
  525. 'quota' => $quota,
  526. 'total' => $total,
  527. 'relative' => $relative,
  528. 'owner' => $ownerId,
  529. 'ownerDisplayName' => $ownerDisplayName,
  530. 'mountType' => $mount->getMountType(),
  531. 'mountPoint' => trim($mountPoint, '/'),
  532. ];
  533. $memcache->set($cacheKey, $info, 5 * 60);
  534. return $info;
  535. }
  536. /**
  537. * Get storage info including all mount points and quota
  538. */
  539. private static function getGlobalStorageInfo(int $quota, IUser $user, IMountPoint $mount): array {
  540. $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
  541. $used = $rootInfo['size'];
  542. if ($used < 0) {
  543. $used = 0;
  544. }
  545. $total = $quota;
  546. $free = $quota - $used;
  547. if ($total > 0) {
  548. if ($quota > 0 && $total > $quota) {
  549. $total = $quota;
  550. }
  551. // prevent division by zero or error codes (negative values)
  552. $relative = round(($used / $total) * 10000) / 100;
  553. } else {
  554. $relative = 0;
  555. }
  556. if (substr_count($mount->getMountPoint(), '/') < 3) {
  557. $mountPoint = '';
  558. } else {
  559. [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
  560. }
  561. return [
  562. 'free' => $free,
  563. 'used' => $used,
  564. 'total' => $total,
  565. 'relative' => $relative,
  566. 'quota' => $quota,
  567. 'owner' => $user->getUID(),
  568. 'ownerDisplayName' => $user->getDisplayName(),
  569. 'mountType' => $mount->getMountType(),
  570. 'mountPoint' => trim($mountPoint, '/'),
  571. ];
  572. }
  573. /**
  574. * Returns whether the config file is set manually to read-only
  575. * @return bool
  576. */
  577. public static function isReadOnlyConfigEnabled() {
  578. return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
  579. }
  580. }