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.

605 lines
17 KiB

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