You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OC_Helper.php 17KB

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