helper.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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 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 = 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. 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. 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. } else if ($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. * @return \OC\Files\Type\TemplateManager
  179. */
  180. static public function getFileTemplateManager() {
  181. if (!self::$templateManager) {
  182. self::$templateManager = new \OC\Files\Type\TemplateManager();
  183. }
  184. return self::$templateManager;
  185. }
  186. /**
  187. * detect if a given program is found in the search PATH
  188. *
  189. * @param string $name
  190. * @param bool $path
  191. * @internal param string $program name
  192. * @internal param string $optional search path, defaults to $PATH
  193. * @return bool true if executable program found in path
  194. */
  195. public static function canExecute($name, $path = false) {
  196. // path defaults to PATH from environment if not set
  197. if ($path === false) {
  198. $path = getenv("PATH");
  199. }
  200. // we look for an executable file of that name
  201. $exts = [""];
  202. $check_fn = "is_executable";
  203. // Default check will be done with $path directories :
  204. $dirs = explode(PATH_SEPARATOR, $path);
  205. // WARNING : We have to check if open_basedir is enabled :
  206. $obd = OC::$server->getIniWrapper()->getString('open_basedir');
  207. if ($obd != "none") {
  208. $obd_values = explode(PATH_SEPARATOR, $obd);
  209. if (count($obd_values) > 0 and $obd_values[0]) {
  210. // open_basedir is in effect !
  211. // We need to check if the program is in one of these dirs :
  212. $dirs = $obd_values;
  213. }
  214. }
  215. foreach ($dirs as $dir) {
  216. foreach ($exts as $ext) {
  217. if ($check_fn("$dir/$name" . $ext))
  218. return true;
  219. }
  220. }
  221. return false;
  222. }
  223. /**
  224. * copy the contents of one stream to another
  225. *
  226. * @param resource $source
  227. * @param resource $target
  228. * @return array the number of bytes copied and result
  229. */
  230. public static function streamCopy($source, $target) {
  231. if (!$source or !$target) {
  232. return array(0, false);
  233. }
  234. $bufSize = 8192;
  235. $result = true;
  236. $count = 0;
  237. while (!feof($source)) {
  238. $buf = fread($source, $bufSize);
  239. $bytesWritten = fwrite($target, $buf);
  240. if ($bytesWritten !== false) {
  241. $count += $bytesWritten;
  242. }
  243. // note: strlen is expensive so only use it when necessary,
  244. // on the last block
  245. if ($bytesWritten === false
  246. || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
  247. ) {
  248. // write error, could be disk full ?
  249. $result = false;
  250. break;
  251. }
  252. }
  253. return array($count, $result);
  254. }
  255. /**
  256. * Adds a suffix to the name in case the file exists
  257. *
  258. * @param string $path
  259. * @param string $filename
  260. * @return string
  261. */
  262. public static function buildNotExistingFileName($path, $filename) {
  263. $view = \OC\Files\Filesystem::getView();
  264. return self::buildNotExistingFileNameForView($path, $filename, $view);
  265. }
  266. /**
  267. * Adds a suffix to the name in case the file exists
  268. *
  269. * @param string $path
  270. * @param string $filename
  271. * @return string
  272. */
  273. public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
  274. if ($path === '/') {
  275. $path = '';
  276. }
  277. if ($pos = strrpos($filename, '.')) {
  278. $name = substr($filename, 0, $pos);
  279. $ext = substr($filename, $pos);
  280. } else {
  281. $name = $filename;
  282. $ext = '';
  283. }
  284. $newpath = $path . '/' . $filename;
  285. if ($view->file_exists($newpath)) {
  286. if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
  287. //Replace the last "(number)" with "(number+1)"
  288. $last_match = count($matches[0]) - 1;
  289. $counter = $matches[1][$last_match][0] + 1;
  290. $offset = $matches[0][$last_match][1];
  291. $match_length = strlen($matches[0][$last_match][0]);
  292. } else {
  293. $counter = 2;
  294. $match_length = 0;
  295. $offset = false;
  296. }
  297. do {
  298. if ($offset) {
  299. //Replace the last "(number)" with "(number+1)"
  300. $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
  301. } else {
  302. $newname = $name . ' (' . $counter . ')';
  303. }
  304. $newpath = $path . '/' . $newname . $ext;
  305. $counter++;
  306. } while ($view->file_exists($newpath));
  307. }
  308. return $newpath;
  309. }
  310. /**
  311. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  312. *
  313. * @param array $input The array to work on
  314. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  315. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  316. * @return array
  317. *
  318. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  319. * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
  320. *
  321. */
  322. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  323. $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
  324. $ret = array();
  325. foreach ($input as $k => $v) {
  326. $ret[mb_convert_case($k, $case, $encoding)] = $v;
  327. }
  328. return $ret;
  329. }
  330. /**
  331. * performs a search in a nested array
  332. * @param array $haystack the array to be searched
  333. * @param string $needle the search string
  334. * @param mixed $index optional, only search this key name
  335. * @return mixed the key of the matching field, otherwise false
  336. *
  337. * performs a search in a nested array
  338. *
  339. * taken from http://www.php.net/manual/en/function.array-search.php#97645
  340. */
  341. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  342. $aIt = new RecursiveArrayIterator($haystack);
  343. $it = new RecursiveIteratorIterator($aIt);
  344. while ($it->valid()) {
  345. if (((isset($index) AND ($it->key() == $index)) OR !isset($index)) AND ($it->current() == $needle)) {
  346. return $aIt->key();
  347. }
  348. $it->next();
  349. }
  350. return false;
  351. }
  352. /**
  353. * calculates the maximum upload size respecting system settings, free space and user quota
  354. *
  355. * @param string $dir the current folder where the user currently operates
  356. * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
  357. * @return int number of bytes representing
  358. */
  359. public static function maxUploadFilesize($dir, $freeSpace = null) {
  360. if (is_null($freeSpace) || $freeSpace < 0){
  361. $freeSpace = self::freeSpace($dir);
  362. }
  363. return min($freeSpace, self::uploadLimit());
  364. }
  365. /**
  366. * Calculate free space left within user quota
  367. *
  368. * @param string $dir the current folder where the user currently operates
  369. * @return int number of bytes representing
  370. */
  371. public static function freeSpace($dir) {
  372. $freeSpace = \OC\Files\Filesystem::free_space($dir);
  373. if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  374. $freeSpace = max($freeSpace, 0);
  375. return $freeSpace;
  376. } else {
  377. return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
  378. }
  379. }
  380. /**
  381. * Calculate PHP upload limit
  382. *
  383. * @return int PHP upload file size limit
  384. */
  385. public static function uploadLimit() {
  386. $ini = \OC::$server->getIniWrapper();
  387. $upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
  388. $post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
  389. if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
  390. return INF;
  391. } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
  392. return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
  393. } else {
  394. return min($upload_max_filesize, $post_max_size);
  395. }
  396. }
  397. /**
  398. * Checks if a function is available
  399. *
  400. * @param string $function_name
  401. * @return bool
  402. */
  403. public static function is_function_enabled($function_name) {
  404. if (!function_exists($function_name)) {
  405. return false;
  406. }
  407. $ini = \OC::$server->getIniWrapper();
  408. $disabled = explode(',', $ini->get('disable_functions') ?: '');
  409. $disabled = array_map('trim', $disabled);
  410. if (in_array($function_name, $disabled)) {
  411. return false;
  412. }
  413. $disabled = explode(',', $ini->get('suhosin.executor.func.blacklist') ?: '');
  414. $disabled = array_map('trim', $disabled);
  415. if (in_array($function_name, $disabled)) {
  416. return false;
  417. }
  418. return true;
  419. }
  420. /**
  421. * Try to find a program
  422. *
  423. * @param string $program
  424. * @return null|string
  425. */
  426. public static function findBinaryPath($program) {
  427. $memcache = \OC::$server->getMemCacheFactory()->createDistributed('findBinaryPath');
  428. if ($memcache->hasKey($program)) {
  429. return $memcache->get($program);
  430. }
  431. $result = null;
  432. if (self::is_function_enabled('exec')) {
  433. $exeSniffer = new ExecutableFinder();
  434. // Returns null if nothing is found
  435. $result = $exeSniffer->find($program, null, ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/opt/bin']);
  436. }
  437. // store the value for 5 minutes
  438. $memcache->set($program, $result, 300);
  439. return $result;
  440. }
  441. /**
  442. * Calculate the disc space for the given path
  443. *
  444. * @param string $path
  445. * @param \OCP\Files\FileInfo $rootInfo (optional)
  446. * @return array
  447. * @throws \OCP\Files\NotFoundException
  448. */
  449. public static function getStorageInfo($path, $rootInfo = null) {
  450. // return storage info without adding mount points
  451. $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
  452. if (!$rootInfo) {
  453. $rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
  454. }
  455. if (!$rootInfo instanceof \OCP\Files\FileInfo) {
  456. throw new \OCP\Files\NotFoundException();
  457. }
  458. $used = $rootInfo->getSize();
  459. if ($used < 0) {
  460. $used = 0;
  461. }
  462. $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
  463. $storage = $rootInfo->getStorage();
  464. $sourceStorage = $storage;
  465. if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
  466. $includeExtStorage = false;
  467. $sourceStorage = $storage->getSourceStorage();
  468. }
  469. if ($includeExtStorage) {
  470. if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
  471. || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
  472. ) {
  473. /** @var \OC\Files\Storage\Home $storage */
  474. $userInstance = $storage->getUser();
  475. $user = ($userInstance === null) ? null : $userInstance->getUID();
  476. } else {
  477. $user = \OC::$server->getUserSession()->getUser()->getUID();
  478. }
  479. if ($user) {
  480. $quota = OC_Util::getUserQuota($user);
  481. } else {
  482. $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
  483. }
  484. if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  485. // always get free space / total space from root + mount points
  486. return self::getGlobalStorageInfo();
  487. }
  488. }
  489. // TODO: need a better way to get total space from storage
  490. if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
  491. /** @var \OC\Files\Storage\Wrapper\Quota $storage */
  492. $quota = $sourceStorage->getQuota();
  493. }
  494. $free = $sourceStorage->free_space($rootInfo->getInternalPath());
  495. if ($free >= 0) {
  496. $total = $free + $used;
  497. } else {
  498. $total = $free; //either unknown or unlimited
  499. }
  500. if ($total > 0) {
  501. if ($quota > 0 && $total > $quota) {
  502. $total = $quota;
  503. }
  504. // prevent division by zero or error codes (negative values)
  505. $relative = round(($used / $total) * 10000) / 100;
  506. } else {
  507. $relative = 0;
  508. }
  509. $ownerId = $storage->getOwner($path);
  510. $ownerDisplayName = '';
  511. $owner = \OC::$server->getUserManager()->get($ownerId);
  512. if($owner) {
  513. $ownerDisplayName = $owner->getDisplayName();
  514. }
  515. return [
  516. 'free' => $free,
  517. 'used' => $used,
  518. 'quota' => $quota,
  519. 'total' => $total,
  520. 'relative' => $relative,
  521. 'owner' => $ownerId,
  522. 'ownerDisplayName' => $ownerDisplayName,
  523. ];
  524. }
  525. /**
  526. * Get storage info including all mount points and quota
  527. *
  528. * @return array
  529. */
  530. private static function getGlobalStorageInfo() {
  531. $quota = OC_Util::getUserQuota(\OCP\User::getUser());
  532. $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
  533. $used = $rootInfo['size'];
  534. if ($used < 0) {
  535. $used = 0;
  536. }
  537. $total = $quota;
  538. $free = $quota - $used;
  539. if ($total > 0) {
  540. if ($quota > 0 && $total > $quota) {
  541. $total = $quota;
  542. }
  543. // prevent division by zero or error codes (negative values)
  544. $relative = round(($used / $total) * 10000) / 100;
  545. } else {
  546. $relative = 0;
  547. }
  548. return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
  549. }
  550. /**
  551. * Returns whether the config file is set manually to read-only
  552. * @return bool
  553. */
  554. public static function isReadOnlyConfigEnabled() {
  555. return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
  556. }
  557. }