helper.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Frank Karlitschek
  6. * @author Jakob Sack
  7. * @copyright 2012 Frank Karlitschek frank@owncloud.org
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  11. * License as published by the Free Software Foundation; either
  12. * version 3 of the License, or any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public
  20. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. */
  23. /**
  24. * Collection of useful functions
  25. */
  26. class OC_Helper {
  27. private static $tmpFiles = array();
  28. private static $mimetypeIcons = array();
  29. private static $mimetypeDetector;
  30. private static $templateManager;
  31. /**
  32. * @brief Creates an url using a defined route
  33. * @param $route
  34. * @param array $parameters
  35. * @return
  36. * @internal param array $args with param=>value, will be appended to the returned url
  37. * @returns the url
  38. *
  39. * Returns a url to the given app and file.
  40. */
  41. public static function linkToRoute($route, $parameters = array()) {
  42. return OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
  43. }
  44. /**
  45. * @brief Creates an url
  46. * @param string $app app
  47. * @param string $file file
  48. * @param array $args array with param=>value, will be appended to the returned url
  49. * The value of $args will be urlencoded
  50. * @return string the url
  51. *
  52. * Returns a url to the given app and file.
  53. */
  54. public static function linkTo( $app, $file, $args = array() ) {
  55. return OC::$server->getURLGenerator()->linkTo($app, $file, $args);
  56. }
  57. /**
  58. * @param $key
  59. * @return string url to the online documentation
  60. */
  61. public static function linkToDocs($key) {
  62. $theme = new OC_Defaults();
  63. return $theme->getDocBaseUrl() . '/server/6.0/go.php?to=' . $key;
  64. }
  65. /**
  66. * @brief Creates an absolute url
  67. * @param string $app app
  68. * @param string $file file
  69. * @param array $args array with param=>value, will be appended to the returned url
  70. * The value of $args will be urlencoded
  71. * @return string the url
  72. *
  73. * Returns a absolute url to the given app and file.
  74. */
  75. public static function linkToAbsolute($app, $file, $args = array()) {
  76. $urlLinkTo = self::linkTo($app, $file, $args);
  77. return self::makeURLAbsolute($urlLinkTo);
  78. }
  79. /**
  80. * @brief Makes an $url absolute
  81. * @param string $url the url
  82. * @return string the absolute url
  83. *
  84. * Returns a absolute url to the given app and file.
  85. */
  86. public static function makeURLAbsolute($url) {
  87. return OC::$server->getURLGenerator()->getAbsoluteURL($url);
  88. }
  89. /**
  90. * @brief Creates an url for remote use
  91. * @param string $service id
  92. * @return string the url
  93. *
  94. * Returns a url to the given service.
  95. */
  96. public static function linkToRemoteBase($service) {
  97. return self::linkTo('', 'remote.php') . '/' . $service;
  98. }
  99. /**
  100. * @brief Creates an absolute url for remote use
  101. * @param string $service id
  102. * @param bool $add_slash
  103. * @return string the url
  104. *
  105. * Returns a absolute url to the given service.
  106. */
  107. public static function linkToRemote($service, $add_slash = true) {
  108. return self::makeURLAbsolute(self::linkToRemoteBase($service))
  109. . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
  110. }
  111. /**
  112. * @brief Creates an absolute url for public use
  113. * @param string $service id
  114. * @param bool $add_slash
  115. * @return string the url
  116. *
  117. * Returns a absolute url to the given service.
  118. */
  119. public static function linkToPublic($service, $add_slash = false) {
  120. return self::linkToAbsolute('', 'public.php') . '?service=' . $service
  121. . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
  122. }
  123. /**
  124. * @brief Creates path to an image
  125. * @param string $app app
  126. * @param string $image image name
  127. * @return string the url
  128. *
  129. * Returns the path to the image.
  130. */
  131. public static function imagePath($app, $image) {
  132. return OC::$server->getURLGenerator()->imagePath($app, $image);
  133. }
  134. /**
  135. * @brief get path to icon of file type
  136. * @param string $mimetype mimetype
  137. * @return string the url
  138. *
  139. * Returns the path to the image of this file type.
  140. */
  141. public static function mimetypeIcon($mimetype) {
  142. $alias = array(
  143. 'application/xml' => 'code/xml',
  144. 'application/msword' => 'x-office/document',
  145. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'x-office/document',
  146. 'application/vnd.openxmlformats-officedocument.wordprocessingml.template' => 'x-office/document',
  147. 'application/vnd.ms-word.document.macroEnabled.12' => 'x-office/document',
  148. 'application/vnd.ms-word.template.macroEnabled.12' => 'x-office/document',
  149. 'application/vnd.oasis.opendocument.text' => 'x-office/document',
  150. 'application/vnd.oasis.opendocument.text-template' => 'x-office/document',
  151. 'application/vnd.oasis.opendocument.text-web' => 'x-office/document',
  152. 'application/vnd.oasis.opendocument.text-master' => 'x-office/document',
  153. 'application/vnd.ms-powerpoint' => 'x-office/presentation',
  154. 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'x-office/presentation',
  155. 'application/vnd.openxmlformats-officedocument.presentationml.template' => 'x-office/presentation',
  156. 'application/vnd.openxmlformats-officedocument.presentationml.slideshow' => 'x-office/presentation',
  157. 'application/vnd.ms-powerpoint.addin.macroEnabled.12' => 'x-office/presentation',
  158. 'application/vnd.ms-powerpoint.presentation.macroEnabled.12' => 'x-office/presentation',
  159. 'application/vnd.ms-powerpoint.template.macroEnabled.12' => 'x-office/presentation',
  160. 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12' => 'x-office/presentation',
  161. 'application/vnd.oasis.opendocument.presentation' => 'x-office/presentation',
  162. 'application/vnd.oasis.opendocument.presentation-template' => 'x-office/presentation',
  163. 'application/vnd.ms-excel' => 'x-office/spreadsheet',
  164. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'x-office/spreadsheet',
  165. 'application/vnd.openxmlformats-officedocument.spreadsheetml.template' => 'x-office/spreadsheet',
  166. 'application/vnd.ms-excel.sheet.macroEnabled.12' => 'x-office/spreadsheet',
  167. 'application/vnd.ms-excel.template.macroEnabled.12' => 'x-office/spreadsheet',
  168. 'application/vnd.ms-excel.addin.macroEnabled.12' => 'x-office/spreadsheet',
  169. 'application/vnd.ms-excel.sheet.binary.macroEnabled.12' => 'x-office/spreadsheet',
  170. 'application/vnd.oasis.opendocument.spreadsheet' => 'x-office/spreadsheet',
  171. 'application/vnd.oasis.opendocument.spreadsheet-template' => 'x-office/spreadsheet',
  172. );
  173. if (isset($alias[$mimetype])) {
  174. $mimetype = $alias[$mimetype];
  175. }
  176. if (isset(self::$mimetypeIcons[$mimetype])) {
  177. return self::$mimetypeIcons[$mimetype];
  178. }
  179. // Replace slash and backslash with a minus
  180. $icon = str_replace('/', '-', $mimetype);
  181. $icon = str_replace('\\', '-', $icon);
  182. // Is it a dir?
  183. if ($mimetype === 'dir') {
  184. self::$mimetypeIcons[$mimetype] = OC::$WEBROOT . '/core/img/filetypes/folder.png';
  185. return OC::$WEBROOT . '/core/img/filetypes/folder.png';
  186. }
  187. if ($mimetype === 'dir-shared') {
  188. self::$mimetypeIcons[$mimetype] = OC::$WEBROOT . '/core/img/filetypes/folder-shared.png';
  189. return OC::$WEBROOT . '/core/img/filetypes/folder-shared.png';
  190. }
  191. if ($mimetype === 'dir-external') {
  192. self::$mimetypeIcons[$mimetype] = OC::$WEBROOT . '/core/img/filetypes/folder-external.png';
  193. return OC::$WEBROOT . '/core/img/filetypes/folder-external.png';
  194. }
  195. // Icon exists?
  196. if (file_exists(OC::$SERVERROOT . '/core/img/filetypes/' . $icon . '.png')) {
  197. self::$mimetypeIcons[$mimetype] = OC::$WEBROOT . '/core/img/filetypes/' . $icon . '.png';
  198. return OC::$WEBROOT . '/core/img/filetypes/' . $icon . '.png';
  199. }
  200. // Try only the first part of the filetype
  201. $mimePart = substr($icon, 0, strpos($icon, '-'));
  202. if (file_exists(OC::$SERVERROOT . '/core/img/filetypes/' . $mimePart . '.png')) {
  203. self::$mimetypeIcons[$mimetype] = OC::$WEBROOT . '/core/img/filetypes/' . $mimePart . '.png';
  204. return OC::$WEBROOT . '/core/img/filetypes/' . $mimePart . '.png';
  205. } else {
  206. self::$mimetypeIcons[$mimetype] = OC::$WEBROOT . '/core/img/filetypes/file.png';
  207. return OC::$WEBROOT . '/core/img/filetypes/file.png';
  208. }
  209. }
  210. /**
  211. * @brief get path to preview of file
  212. * @param string $path path
  213. * @return string the url
  214. *
  215. * Returns the path to the preview of the file.
  216. */
  217. public static function previewIcon($path) {
  218. return self::linkToRoute( 'core_ajax_preview', array('x' => 36, 'y' => 36, 'file' => $path ));
  219. }
  220. public static function publicPreviewIcon( $path, $token ) {
  221. return self::linkToRoute( 'core_ajax_public_preview', array('x' => 36, 'y' => 36, 'file' => $path, 't' => $token));
  222. }
  223. /**
  224. * @brief Make a human file size
  225. * @param int $bytes file size in bytes
  226. * @return string a human readable file size
  227. *
  228. * Makes 2048 to 2 kB.
  229. */
  230. public static function humanFileSize($bytes) {
  231. if ($bytes < 0) {
  232. return "?";
  233. }
  234. if ($bytes < 1024) {
  235. return "$bytes B";
  236. }
  237. $bytes = round($bytes / 1024, 1);
  238. if ($bytes < 1024) {
  239. return "$bytes kB";
  240. }
  241. $bytes = round($bytes / 1024, 1);
  242. if ($bytes < 1024) {
  243. return "$bytes MB";
  244. }
  245. $bytes = round($bytes / 1024, 1);
  246. if ($bytes < 1024) {
  247. return "$bytes GB";
  248. }
  249. $bytes = round($bytes / 1024, 1);
  250. if ($bytes < 1024) {
  251. return "$bytes TB";
  252. }
  253. $bytes = round($bytes / 1024, 1);
  254. return "$bytes PB";
  255. }
  256. /**
  257. * @brief Make a computer file size
  258. * @param string $str file size in a fancy format
  259. * @return int a file size in bytes
  260. *
  261. * Makes 2kB to 2048.
  262. *
  263. * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
  264. */
  265. public static function computerFileSize($str) {
  266. $str = strtolower($str);
  267. $bytes_array = array(
  268. 'b' => 1,
  269. 'k' => 1024,
  270. 'kb' => 1024,
  271. 'mb' => 1024 * 1024,
  272. 'm' => 1024 * 1024,
  273. 'gb' => 1024 * 1024 * 1024,
  274. 'g' => 1024 * 1024 * 1024,
  275. 'tb' => 1024 * 1024 * 1024 * 1024,
  276. 't' => 1024 * 1024 * 1024 * 1024,
  277. 'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
  278. 'p' => 1024 * 1024 * 1024 * 1024 * 1024,
  279. );
  280. $bytes = floatval($str);
  281. if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
  282. $bytes *= $bytes_array[$matches[1]];
  283. }
  284. $bytes = round($bytes, 2);
  285. return $bytes;
  286. }
  287. /**
  288. * @brief Recursive editing of file permissions
  289. * @param string $path path to file or folder
  290. * @param int $filemode unix style file permissions
  291. * @return bool
  292. */
  293. static function chmodr($path, $filemode) {
  294. if (!is_dir($path))
  295. return chmod($path, $filemode);
  296. $dh = opendir($path);
  297. if(is_resource($dh)) {
  298. while (($file = readdir($dh)) !== false) {
  299. if ($file != '.' && $file != '..') {
  300. $fullpath = $path . '/' . $file;
  301. if (is_link($fullpath))
  302. return false;
  303. elseif (!is_dir($fullpath) && !@chmod($fullpath, $filemode))
  304. return false; elseif (!self::chmodr($fullpath, $filemode))
  305. return false;
  306. }
  307. }
  308. closedir($dh);
  309. }
  310. if (@chmod($path, $filemode))
  311. return true;
  312. else
  313. return false;
  314. }
  315. /**
  316. * @brief Recursive copying of folders
  317. * @param string $src source folder
  318. * @param string $dest target folder
  319. *
  320. */
  321. static function copyr($src, $dest) {
  322. if (is_dir($src)) {
  323. if (!is_dir($dest)) {
  324. mkdir($dest);
  325. }
  326. $files = scandir($src);
  327. foreach ($files as $file) {
  328. if ($file != "." && $file != "..") {
  329. self::copyr("$src/$file", "$dest/$file");
  330. }
  331. }
  332. } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
  333. copy($src, $dest);
  334. }
  335. }
  336. /**
  337. * @brief Recursive deletion of folders
  338. * @param string $dir path to the folder
  339. * @return bool
  340. */
  341. static function rmdirr($dir) {
  342. if (is_dir($dir)) {
  343. $files = scandir($dir);
  344. foreach ($files as $file) {
  345. if ($file != "." && $file != "..") {
  346. self::rmdirr("$dir/$file");
  347. }
  348. }
  349. rmdir($dir);
  350. } elseif (file_exists($dir)) {
  351. unlink($dir);
  352. }
  353. if (file_exists($dir)) {
  354. return false;
  355. } else {
  356. return true;
  357. }
  358. }
  359. /**
  360. * @return \OC\Files\Type\Detection
  361. */
  362. static public function getMimetypeDetector() {
  363. if (!self::$mimetypeDetector) {
  364. self::$mimetypeDetector = new \OC\Files\Type\Detection();
  365. self::$mimetypeDetector->registerTypeArray(include 'mimetypes.list.php');
  366. }
  367. return self::$mimetypeDetector;
  368. }
  369. /**
  370. * @return \OC\Files\Type\TemplateManager
  371. */
  372. static public function getFileTemplateManager() {
  373. if (!self::$templateManager) {
  374. self::$templateManager = new \OC\Files\Type\TemplateManager();
  375. }
  376. return self::$templateManager;
  377. }
  378. /**
  379. * Try to guess the mimetype based on filename
  380. *
  381. * @param string $path
  382. * @return string
  383. */
  384. static public function getFileNameMimeType($path) {
  385. return self::getMimetypeDetector()->detectPath($path);
  386. }
  387. /**
  388. * get the mimetype form a local file
  389. *
  390. * @param string $path
  391. * @return string
  392. * does NOT work for ownClouds filesystem, use OC_FileSystem::getMimeType instead
  393. */
  394. static function getMimeType($path) {
  395. return self::getMimetypeDetector()->detect($path);
  396. }
  397. /**
  398. * get the mimetype form a data string
  399. *
  400. * @param string $data
  401. * @return string
  402. */
  403. static function getStringMimeType($data) {
  404. return self::getMimetypeDetector()->detectString($data);
  405. }
  406. /**
  407. * @brief Checks $_REQUEST contains a var for the $s key. If so, returns the html-escaped value of this var; otherwise returns the default value provided by $d.
  408. * @param string $s name of the var to escape, if set.
  409. * @param string $d default value.
  410. * @return string the print-safe value.
  411. *
  412. */
  413. //FIXME: should also check for value validation (i.e. the email is an email).
  414. public static function init_var($s, $d = "") {
  415. $r = $d;
  416. if (isset($_REQUEST[$s]) && !empty($_REQUEST[$s])) {
  417. $r = OC_Util::sanitizeHTML($_REQUEST[$s]);
  418. }
  419. return $r;
  420. }
  421. /**
  422. * returns "checked"-attribute if request contains selected radio element
  423. * OR if radio element is the default one -- maybe?
  424. *
  425. * @param string $s Name of radio-button element name
  426. * @param string $v Value of current radio-button element
  427. * @param string $d Value of default radio-button element
  428. */
  429. public static function init_radio($s, $v, $d) {
  430. if ((isset($_REQUEST[$s]) && $_REQUEST[$s] == $v) || (!isset($_REQUEST[$s]) && $v == $d))
  431. print "checked=\"checked\" ";
  432. }
  433. /**
  434. * detect if a given program is found in the search PATH
  435. *
  436. * @param $name
  437. * @param bool $path
  438. * @internal param string $program name
  439. * @internal param string $optional search path, defaults to $PATH
  440. * @return bool true if executable program found in path
  441. */
  442. public static function canExecute($name, $path = false) {
  443. // path defaults to PATH from environment if not set
  444. if ($path === false) {
  445. $path = getenv("PATH");
  446. }
  447. // check method depends on operating system
  448. if (!strncmp(PHP_OS, "WIN", 3)) {
  449. // on Windows an appropriate COM or EXE file needs to exist
  450. $exts = array(".exe", ".com");
  451. $check_fn = "file_exists";
  452. } else {
  453. // anywhere else we look for an executable file of that name
  454. $exts = array("");
  455. $check_fn = "is_executable";
  456. }
  457. // Default check will be done with $path directories :
  458. $dirs = explode(PATH_SEPARATOR, $path);
  459. // WARNING : We have to check if open_basedir is enabled :
  460. $obd = ini_get('open_basedir');
  461. if ($obd != "none") {
  462. $obd_values = explode(PATH_SEPARATOR, $obd);
  463. if (count($obd_values) > 0 and $obd_values[0]) {
  464. // open_basedir is in effect !
  465. // We need to check if the program is in one of these dirs :
  466. $dirs = $obd_values;
  467. }
  468. }
  469. foreach ($dirs as $dir) {
  470. foreach ($exts as $ext) {
  471. if ($check_fn("$dir/$name" . $ext))
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477. /**
  478. * copy the contents of one stream to another
  479. *
  480. * @param resource $source
  481. * @param resource $target
  482. * @return array the number of bytes copied and result
  483. */
  484. public static function streamCopy($source, $target) {
  485. if (!$source or !$target) {
  486. return array(0, false);
  487. }
  488. $result = true;
  489. $count = 0;
  490. while (!feof($source)) {
  491. if (($c = fwrite($target, fread($source, 8192))) === false) {
  492. $result = false;
  493. } else {
  494. $count += $c;
  495. }
  496. }
  497. return array($count, $result);
  498. }
  499. /**
  500. * create a temporary file with an unique filename
  501. *
  502. * @param string $postfix
  503. * @return string
  504. *
  505. * temporary files are automatically cleaned up after the script is finished
  506. */
  507. public static function tmpFile($postfix = '') {
  508. $file = get_temp_dir() . '/' . md5(time() . rand()) . $postfix;
  509. $fh = fopen($file, 'w');
  510. fclose($fh);
  511. self::$tmpFiles[] = $file;
  512. return $file;
  513. }
  514. /**
  515. * move a file to oc-noclean temp dir
  516. *
  517. * @param string $filename
  518. * @return mixed
  519. *
  520. */
  521. public static function moveToNoClean($filename = '') {
  522. if ($filename == '') {
  523. return false;
  524. }
  525. $tmpDirNoClean = get_temp_dir() . '/oc-noclean/';
  526. if (!file_exists($tmpDirNoClean) || !is_dir($tmpDirNoClean)) {
  527. if (file_exists($tmpDirNoClean)) {
  528. unlink($tmpDirNoClean);
  529. }
  530. mkdir($tmpDirNoClean);
  531. }
  532. $newname = $tmpDirNoClean . basename($filename);
  533. if (rename($filename, $newname)) {
  534. return $newname;
  535. } else {
  536. return false;
  537. }
  538. }
  539. /**
  540. * create a temporary folder with an unique filename
  541. *
  542. * @return string
  543. *
  544. * temporary files are automatically cleaned up after the script is finished
  545. */
  546. public static function tmpFolder() {
  547. $path = get_temp_dir() . '/' . md5(time() . rand());
  548. mkdir($path);
  549. self::$tmpFiles[] = $path;
  550. return $path . '/';
  551. }
  552. /**
  553. * remove all files created by self::tmpFile
  554. */
  555. public static function cleanTmp() {
  556. $leftoversFile = get_temp_dir() . '/oc-not-deleted';
  557. if (file_exists($leftoversFile)) {
  558. $leftovers = file($leftoversFile);
  559. foreach ($leftovers as $file) {
  560. self::rmdirr($file);
  561. }
  562. unlink($leftoversFile);
  563. }
  564. foreach (self::$tmpFiles as $file) {
  565. if (file_exists($file)) {
  566. if (!self::rmdirr($file)) {
  567. file_put_contents($leftoversFile, $file . "\n", FILE_APPEND);
  568. }
  569. }
  570. }
  571. }
  572. /**
  573. * remove all files in PHP /oc-noclean temp dir
  574. */
  575. public static function cleanTmpNoClean() {
  576. $tmpDirNoCleanName=get_temp_dir() . '/oc-noclean/';
  577. if(file_exists($tmpDirNoCleanName) && is_dir($tmpDirNoCleanName)) {
  578. $files=scandir($tmpDirNoCleanName);
  579. foreach($files as $file) {
  580. $fileName = $tmpDirNoCleanName . $file;
  581. if (!\OC\Files\Filesystem::isIgnoredDir($file) && filemtime($fileName) + 600 < time()) {
  582. unlink($fileName);
  583. }
  584. }
  585. // if oc-noclean is empty delete it
  586. $isTmpDirNoCleanEmpty = true;
  587. $tmpDirNoClean = opendir($tmpDirNoCleanName);
  588. if(is_resource($tmpDirNoClean)) {
  589. while (false !== ($file = readdir($tmpDirNoClean))) {
  590. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  591. $isTmpDirNoCleanEmpty = false;
  592. }
  593. }
  594. }
  595. if ($isTmpDirNoCleanEmpty) {
  596. rmdir($tmpDirNoCleanName);
  597. }
  598. }
  599. }
  600. /**
  601. * Adds a suffix to the name in case the file exists
  602. *
  603. * @param $path
  604. * @param $filename
  605. * @return string
  606. */
  607. public static function buildNotExistingFileName($path, $filename) {
  608. $view = \OC\Files\Filesystem::getView();
  609. return self::buildNotExistingFileNameForView($path, $filename, $view);
  610. }
  611. /**
  612. * Adds a suffix to the name in case the file exists
  613. *
  614. * @param $path
  615. * @param $filename
  616. * @return string
  617. */
  618. public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
  619. if ($path === '/') {
  620. $path = '';
  621. }
  622. if ($pos = strrpos($filename, '.')) {
  623. $name = substr($filename, 0, $pos);
  624. $ext = substr($filename, $pos);
  625. } else {
  626. $name = $filename;
  627. $ext = '';
  628. }
  629. $newpath = $path . '/' . $filename;
  630. if ($view->file_exists($newpath)) {
  631. if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
  632. //Replace the last "(number)" with "(number+1)"
  633. $last_match = count($matches[0]) - 1;
  634. $counter = $matches[1][$last_match][0] + 1;
  635. $offset = $matches[0][$last_match][1];
  636. $match_length = strlen($matches[0][$last_match][0]);
  637. } else {
  638. $counter = 2;
  639. $offset = false;
  640. }
  641. do {
  642. if ($offset) {
  643. //Replace the last "(number)" with "(number+1)"
  644. $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
  645. } else {
  646. $newname = $name . ' (' . $counter . ')';
  647. }
  648. $newpath = $path . '/' . $newname . $ext;
  649. $counter++;
  650. } while ($view->file_exists($newpath));
  651. }
  652. return $newpath;
  653. }
  654. /**
  655. * @brief Checks if $sub is a subdirectory of $parent
  656. *
  657. * @param string $sub
  658. * @param string $parent
  659. * @return bool
  660. */
  661. public static function issubdirectory($sub, $parent) {
  662. if (strpos(realpath($sub), realpath($parent)) === 0) {
  663. return true;
  664. }
  665. return false;
  666. }
  667. /**
  668. * @brief Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  669. *
  670. * @param array $input The array to work on
  671. * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
  672. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  673. * @return array
  674. *
  675. * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
  676. * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
  677. *
  678. */
  679. public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
  680. $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
  681. $ret = array();
  682. foreach ($input as $k => $v) {
  683. $ret[mb_convert_case($k, $case, $encoding)] = $v;
  684. }
  685. return $ret;
  686. }
  687. /**
  688. * @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
  689. *
  690. * @param $string
  691. * @param string $replacement The replacement string.
  692. * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
  693. * @param int $length Length of the part to be replaced
  694. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  695. * @internal param string $input The input string. .Opposite to the PHP build-in function does not accept an array.
  696. * @return string
  697. */
  698. public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
  699. $start = intval($start);
  700. $length = intval($length);
  701. $string = mb_substr($string, 0, $start, $encoding) .
  702. $replacement .
  703. mb_substr($string, $start + $length, mb_strlen($string, 'UTF-8') - $start, $encoding);
  704. return $string;
  705. }
  706. /**
  707. * @brief Replace all occurrences of the search string with the replacement string
  708. *
  709. * @param string $search The value being searched for, otherwise known as the needle.
  710. * @param string $replace The replacement
  711. * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
  712. * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
  713. * @param int $count If passed, this will be set to the number of replacements performed.
  714. * @return string
  715. *
  716. */
  717. public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
  718. $offset = -1;
  719. $length = mb_strlen($search, $encoding);
  720. while (($i = mb_strrpos($subject, $search, $offset, $encoding)) !== false) {
  721. $subject = OC_Helper::mb_substr_replace($subject, $replace, $i, $length);
  722. $offset = $i - mb_strlen($subject, $encoding);
  723. $count++;
  724. }
  725. return $subject;
  726. }
  727. /**
  728. * @brief performs a search in a nested array
  729. * @param array $haystack the array to be searched
  730. * @param string $needle the search string
  731. * @param string $index optional, only search this key name
  732. * @return mixed the key of the matching field, otherwise false
  733. *
  734. * performs a search in a nested array
  735. *
  736. * taken from http://www.php.net/manual/en/function.array-search.php#97645
  737. */
  738. public static function recursiveArraySearch($haystack, $needle, $index = null) {
  739. $aIt = new RecursiveArrayIterator($haystack);
  740. $it = new RecursiveIteratorIterator($aIt);
  741. while ($it->valid()) {
  742. if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
  743. return $aIt->key();
  744. }
  745. $it->next();
  746. }
  747. return false;
  748. }
  749. /**
  750. * Shortens str to maxlen by replacing characters in the middle with '...', eg.
  751. * ellipsis('a very long string with lots of useless info to make a better example', 14) becomes 'a very ...example'
  752. *
  753. * @param string $str the string
  754. * @param string $maxlen the maximum length of the result
  755. * @return string with at most maxlen characters
  756. */
  757. public static function ellipsis($str, $maxlen) {
  758. if (strlen($str) > $maxlen) {
  759. $characters = floor($maxlen / 2);
  760. return substr($str, 0, $characters) . '...' . substr($str, -1 * $characters);
  761. }
  762. return $str;
  763. }
  764. /**
  765. * @brief calculates the maximum upload size respecting system settings, free space and user quota
  766. *
  767. * @param $dir the current folder where the user currently operates
  768. * @return number of bytes representing
  769. */
  770. public static function maxUploadFilesize($dir) {
  771. $upload_max_filesize = OCP\Util::computerFileSize(ini_get('upload_max_filesize'));
  772. $post_max_size = OCP\Util::computerFileSize(ini_get('post_max_size'));
  773. $freeSpace = \OC\Files\Filesystem::free_space($dir);
  774. if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
  775. $maxUploadFilesize = \OC\Files\SPACE_UNLIMITED;
  776. } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
  777. $maxUploadFilesize = max($upload_max_filesize, $post_max_size); //only the non 0 value counts
  778. } else {
  779. $maxUploadFilesize = min($upload_max_filesize, $post_max_size);
  780. }
  781. if ($freeSpace !== \OC\Files\SPACE_UNKNOWN) {
  782. $freeSpace = max($freeSpace, 0);
  783. return min($maxUploadFilesize, $freeSpace);
  784. } else {
  785. return $maxUploadFilesize;
  786. }
  787. }
  788. /**
  789. * Checks if a function is available
  790. *
  791. * @param string $function_name
  792. * @return bool
  793. */
  794. public static function is_function_enabled($function_name) {
  795. if (!function_exists($function_name)) {
  796. return false;
  797. }
  798. $disabled = explode(', ', ini_get('disable_functions'));
  799. if (in_array($function_name, $disabled)) {
  800. return false;
  801. }
  802. $disabled = explode(', ', ini_get('suhosin.executor.func.blacklist'));
  803. if (in_array($function_name, $disabled)) {
  804. return false;
  805. }
  806. return true;
  807. }
  808. /**
  809. * Calculate the disc space for the given path
  810. *
  811. * @param string $path
  812. * @return array
  813. */
  814. public static function getStorageInfo($path) {
  815. // return storage info without adding mount points
  816. $rootInfo = \OC\Files\Filesystem::getFileInfo($path, false);
  817. $used = $rootInfo['size'];
  818. if ($used < 0) {
  819. $used = 0;
  820. }
  821. $free = \OC\Files\Filesystem::free_space($path);
  822. if ($free >= 0) {
  823. $total = $free + $used;
  824. } else {
  825. $total = $free; //either unknown or unlimited
  826. }
  827. if ($total > 0) {
  828. // prevent division by zero or error codes (negative values)
  829. $relative = round(($used / $total) * 10000) / 100;
  830. } else {
  831. $relative = 0;
  832. }
  833. return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
  834. }
  835. }