OC_Helper.php 18 KB

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