helper.php 28 KB

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