PageRenderTime 60ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/system/CKfinder/core/connector/php/php5/Utils/FileSystem.php

https://bitbucket.org/llxff/orgupframework
PHP | 551 lines | 319 code | 57 blank | 175 comment | 105 complexity | 35f99115e2baa95bf446a148026227c2 MD5 | raw file
  1. <?php
  2. /*
  3. * CKFinder
  4. * ========
  5. * http://ckfinder.com
  6. * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
  7. *
  8. * The software, this file and its contents are subject to the CKFinder
  9. * License. Please read the license.txt file before using, installing, copying,
  10. * modifying or distribute this file or part of its contents. The contents of
  11. * this file is part of the Source Code of CKFinder.
  12. */
  13. if (!defined('IN_CKFINDER')) exit;
  14. /**
  15. * @package CKFinder
  16. * @subpackage Utils
  17. * @copyright CKSource - Frederico Knabben
  18. */
  19. /**
  20. * @package CKFinder
  21. * @subpackage Utils
  22. * @copyright CKSource - Frederico Knabben
  23. */
  24. class CKFinder_Connector_Utils_FileSystem
  25. {
  26. /**
  27. * This function behaves similar to System.IO.Path.Combine in C#, the only diffrenece is that it also accepts null values and treat them as empty string
  28. *
  29. * @static
  30. * @access public
  31. * @param string $path1 first path
  32. * @param string $path2 scecond path
  33. * @return string
  34. */
  35. public static function combinePaths($path1, $path2)
  36. {
  37. if (is_null($path1)) {
  38. $path1 = "";
  39. }
  40. if (is_null($path2)) {
  41. $path2 = "";
  42. }
  43. if (!strlen($path2)) {
  44. if (strlen($path1)) {
  45. $_lastCharP1 = substr($path1, -1, 1);
  46. if ($_lastCharP1 != "/" && $_lastCharP1 != "\\") {
  47. $path1 .= DIRECTORY_SEPARATOR;
  48. }
  49. }
  50. }
  51. else {
  52. $_firstCharP2 = substr($path2, 0, 1);
  53. if (strlen($path1)) {
  54. if (strpos($path2, $path1)===0) {
  55. return $path2;
  56. }
  57. $_lastCharP1 = substr($path1, -1, 1);
  58. if ($_lastCharP1 != "/" && $_lastCharP1 != "\\" && $_firstCharP2 != "/" && $_firstCharP2 != "\\") {
  59. $path1 .= DIRECTORY_SEPARATOR;
  60. }
  61. }
  62. else {
  63. return $path2;
  64. }
  65. }
  66. return $path1 . $path2;
  67. }
  68. /**
  69. * Check whether $fileName is a valid file name, return true on success
  70. *
  71. * @static
  72. * @access public
  73. * @param string $fileName
  74. * @return boolean
  75. */
  76. public static function checkFileName($fileName)
  77. {
  78. if (is_null($fileName) || !strlen($fileName) || substr($fileName,-1,1)=="." || false!==strpos($fileName, "..")) {
  79. return false;
  80. }
  81. if (preg_match(CKFINDER_REGEX_INVALID_FILE, $fileName)) {
  82. return false;
  83. }
  84. return true;
  85. }
  86. /**
  87. * Unlink file/folder
  88. *
  89. * @static
  90. * @access public
  91. * @param string $path
  92. * @return boolean
  93. */
  94. public static function unlink($path)
  95. {
  96. /* make sure the path exists */
  97. if(!file_exists($path)) {
  98. return false;
  99. }
  100. /* If it is a file or link, just delete it */
  101. if(is_file($path) || is_link($path)) {
  102. return @unlink($path);
  103. }
  104. /* Scan the dir and recursively unlink */
  105. $files = scandir($path);
  106. if ($files) {
  107. foreach($files as $filename)
  108. {
  109. if ($filename == '.' || $filename == '..') {
  110. continue;
  111. }
  112. $file = str_replace('//','/',$path.'/'.$filename);
  113. CKFinder_Connector_Utils_FileSystem::unlink($file);
  114. }
  115. }
  116. /* Remove the parent dir */
  117. if(!@rmdir($path)) {
  118. return false;
  119. }
  120. return true;
  121. }
  122. /**
  123. * Return file name without extension (without dot & last part after dot)
  124. *
  125. * @static
  126. * @access public
  127. * @param string $fileName
  128. * @return string
  129. */
  130. public static function getFileNameWithoutExtension($fileName)
  131. {
  132. $dotPos = strrpos( $fileName, '.' );
  133. if (false === $dotPos) {
  134. return $fileName;
  135. }
  136. return substr($fileName, 0, $dotPos);
  137. }
  138. /**
  139. * Get file extension (only last part - e.g. extension of file.foo.bar.jpg = jpg)
  140. *
  141. * @static
  142. * @access public
  143. * @param string $fileName
  144. * @return string
  145. */
  146. public static function getExtension( $fileName )
  147. {
  148. $dotPos = strrpos( $fileName, '.' );
  149. if (false === $dotPos) {
  150. return "";
  151. }
  152. return substr( $fileName, strrpos( $fileName, '.' ) +1 ) ;
  153. }
  154. /**
  155. * Read file, split it into small chunks and send it to the browser
  156. *
  157. * @static
  158. * @access public
  159. * @param string $filename
  160. * @return boolean
  161. */
  162. public static function readfileChunked($filename)
  163. {
  164. $chunksize = 1024 * 10; // how many bytes per chunk
  165. $handle = fopen($filename, 'rb');
  166. if ($handle === false) {
  167. return false;
  168. }
  169. while (!feof($handle)) {
  170. echo fread($handle, $chunksize);
  171. @ob_flush();
  172. flush();
  173. @set_time_limit(8);
  174. }
  175. fclose($handle);
  176. return true;
  177. }
  178. /**
  179. * Replace accented UTF-8 characters by unaccented ASCII-7 "equivalents".
  180. * The purpose of this function is to replace characters commonly found in Latin
  181. * alphabets with something more or less equivalent from the ASCII range. This can
  182. * be useful for converting a UTF-8 to something ready for a filename, for example.
  183. * Following the use of this function, you would probably also pass the string
  184. * through utf8_strip_non_ascii to clean out any other non-ASCII chars
  185. *
  186. * For a more complete implementation of transliteration, see the utf8_to_ascii package
  187. * available from the phputf8 project downloads:
  188. * http://prdownloads.sourceforge.net/phputf8
  189. *
  190. * @param string UTF-8 string
  191. * @param string UTF-8 with accented characters replaced by ASCII chars
  192. * @return string accented chars replaced with ascii equivalents
  193. * @author Andreas Gohr <andi@splitbrain.org>
  194. * @see http://sourceforge.net/projects/phputf8/
  195. */
  196. public static function convertToAscii($str)
  197. {
  198. static $UTF8_LOWER_ACCENTS = NULL;
  199. static $UTF8_UPPER_ACCENTS = NULL;
  200. if ( is_null($UTF8_LOWER_ACCENTS) ) {
  201. $UTF8_LOWER_ACCENTS = array(
  202. 'à' => 'a', 'ô' => 'o', 'ď' => 'd', 'ḟ' => 'f', 'ë' => 'e', 'š' => 's', 'ơ' => 'o',
  203. 'ß' => 'ss', 'ă' => 'a', 'ř' => 'r', 'ț' => 't', 'ň' => 'n', 'ā' => 'a', 'ķ' => 'k',
  204. 'ŝ' => 's', 'ỳ' => 'y', 'ņ' => 'n', 'ĺ' => 'l', 'ħ' => 'h', 'ṗ' => 'p', 'ó' => 'o',
  205. 'ú' => 'u', 'ě' => 'e', 'é' => 'e', 'ç' => 'c', 'ẁ' => 'w', 'ċ' => 'c', 'õ' => 'o',
  206. 'ṡ' => 's', 'ø' => 'o', 'ģ' => 'g', 'ŧ' => 't', 'ș' => 's', 'ė' => 'e', 'ĉ' => 'c',
  207. 'ś' => 's', 'î' => 'i', 'ű' => 'u', 'ć' => 'c', 'ę' => 'e', 'ŵ' => 'w', 'ṫ' => 't',
  208. 'ū' => 'u', 'č' => 'c', 'ö' => 'oe', 'è' => 'e', 'ŷ' => 'y', 'ą' => 'a', 'ł' => 'l',
  209. 'ų' => 'u', 'ů' => 'u', 'ş' => 's', 'ğ' => 'g', 'ļ' => 'l', 'ƒ' => 'f', 'ž' => 'z',
  210. 'ẃ' => 'w', 'ḃ' => 'b', 'å' => 'a', 'ì' => 'i', 'ï' => 'i', 'ḋ' => 'd', 'ť' => 't',
  211. 'ŗ' => 'r', 'ä' => 'ae', 'í' => 'i', 'ŕ' => 'r', 'ê' => 'e', 'ü' => 'ue', 'ò' => 'o',
  212. 'ē' => 'e', 'ñ' => 'n', 'ń' => 'n', 'ĥ' => 'h', 'ĝ' => 'g', 'đ' => 'd', 'ĵ' => 'j',
  213. 'ÿ' => 'y', 'ũ' => 'u', 'ŭ' => 'u', 'ư' => 'u', 'ţ' => 't', 'ý' => 'y', 'ő' => 'o',
  214. 'â' => 'a', 'ľ' => 'l', 'ẅ' => 'w', 'ż' => 'z', 'ī' => 'i', 'ã' => 'a', 'ġ' => 'g',
  215. 'ṁ' => 'm', 'ō' => 'o', 'ĩ' => 'i', 'ù' => 'u', 'į' => 'i', 'ź' => 'z', 'á' => 'a',
  216. 'û' => 'u', 'þ' => 'th', 'ð' => 'dh', 'æ' => 'ae', 'µ' => 'u', 'ĕ' => 'e',
  217. );
  218. }
  219. $str = str_replace(
  220. array_keys($UTF8_LOWER_ACCENTS),
  221. array_values($UTF8_LOWER_ACCENTS),
  222. $str
  223. );
  224. if ( is_null($UTF8_UPPER_ACCENTS) ) {
  225. $UTF8_UPPER_ACCENTS = array(
  226. 'À' => 'A', 'Ô' => 'O', 'Ď' => 'D', 'Ḟ' => 'F', 'Ë' => 'E', 'Š' => 'S', 'Ơ' => 'O',
  227. 'Ă' => 'A', 'Ř' => 'R', 'Ț' => 'T', 'Ň' => 'N', 'Ā' => 'A', 'Ķ' => 'K',
  228. 'Ŝ' => 'S', 'Ỳ' => 'Y', 'Ņ' => 'N', 'Ĺ' => 'L', 'Ħ' => 'H', 'Ṗ' => 'P', 'Ó' => 'O',
  229. 'Ú' => 'U', 'Ě' => 'E', 'É' => 'E', 'Ç' => 'C', 'Ẁ' => 'W', 'Ċ' => 'C', 'Õ' => 'O',
  230. 'Ṡ' => 'S', 'Ø' => 'O', 'Ģ' => 'G', 'Ŧ' => 'T', 'Ș' => 'S', 'Ė' => 'E', 'Ĉ' => 'C',
  231. 'Ś' => 'S', 'Î' => 'I', 'Ű' => 'U', 'Ć' => 'C', 'Ę' => 'E', 'Ŵ' => 'W', 'Ṫ' => 'T',
  232. 'Ū' => 'U', 'Č' => 'C', 'Ö' => 'Oe', 'È' => 'E', 'Ŷ' => 'Y', 'Ą' => 'A', 'Ł' => 'L',
  233. 'Ų' => 'U', 'Ů' => 'U', 'Ş' => 'S', 'Ğ' => 'G', 'Ļ' => 'L', 'Ƒ' => 'F', 'Ž' => 'Z',
  234. 'Ẃ' => 'W', 'Ḃ' => 'B', 'Å' => 'A', 'Ì' => 'I', 'Ï' => 'I', 'Ḋ' => 'D', 'Ť' => 'T',
  235. 'Ŗ' => 'R', 'Ä' => 'Ae', 'Í' => 'I', 'Ŕ' => 'R', 'Ê' => 'E', 'Ü' => 'Ue', 'Ò' => 'O',
  236. 'Ē' => 'E', 'Ñ' => 'N', 'Ń' => 'N', 'Ĥ' => 'H', 'Ĝ' => 'G', 'Đ' => 'D', 'Ĵ' => 'J',
  237. 'Ÿ' => 'Y', 'Ũ' => 'U', 'Ŭ' => 'U', 'Ư' => 'U', 'Ţ' => 'T', 'Ý' => 'Y', 'Ő' => 'O',
  238. 'Â' => 'A', 'Ľ' => 'L', 'Ẅ' => 'W', 'Ż' => 'Z', 'Ī' => 'I', 'Ã' => 'A', 'Ġ' => 'G',
  239. 'Ṁ' => 'M', 'Ō' => 'O', 'Ĩ' => 'I', 'Ù' => 'U', 'Į' => 'I', 'Ź' => 'Z', 'Á' => 'A',
  240. 'Û' => 'U', 'Þ' => 'Th', 'Ð' => 'Dh', 'Æ' => 'Ae', 'Ĕ' => 'E',
  241. );
  242. }
  243. $str = str_replace(
  244. array_keys($UTF8_UPPER_ACCENTS),
  245. array_values($UTF8_UPPER_ACCENTS),
  246. $str
  247. );
  248. return $str;
  249. }
  250. /**
  251. * Convert file name from UTF-8 to system encoding
  252. *
  253. * @static
  254. * @access public
  255. * @param string $fileName
  256. * @return string
  257. */
  258. public static function convertToFilesystemEncoding($fileName)
  259. {
  260. $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
  261. $encoding = $_config->getFilesystemEncoding();
  262. if (is_null($encoding) || strcasecmp($encoding, "UTF-8") == 0 || strcasecmp($encoding, "UTF8") == 0) {
  263. return $fileName;
  264. }
  265. if (!function_exists("iconv")) {
  266. if (strcasecmp($encoding, "ISO-8859-1") == 0 || strcasecmp($encoding, "ISO8859-1") == 0 || strcasecmp($encoding, "Latin1") == 0) {
  267. return str_replace("\0", "_", utf8_decode($fileName));
  268. } else if (function_exists('mb_convert_encoding')) {
  269. /**
  270. * @todo check whether charset is supported - mb_list_encodings
  271. */
  272. $encoded = @mb_convert_encoding($fileName, $encoding, 'UTF-8');
  273. if (@mb_strlen($fileName, "UTF-8") != @mb_strlen($encoded, $encoding)) {
  274. return str_replace("\0", "_", preg_replace("/[^[:ascii:]]/u","_",$fileName));
  275. }
  276. else {
  277. return str_replace("\0", "_", $encoded);
  278. }
  279. } else {
  280. return str_replace("\0", "_", preg_replace("/[^[:ascii:]]/u","_",$fileName));
  281. }
  282. }
  283. $converted = @iconv("UTF-8", $encoding . "//IGNORE//TRANSLIT", $fileName);
  284. if ($converted === false) {
  285. return str_replace("\0", "_", preg_replace("/[^[:ascii:]]/u","_",$fileName));
  286. }
  287. return $converted;
  288. }
  289. /**
  290. * Convert file name from system encoding into UTF-8
  291. *
  292. * @static
  293. * @access public
  294. * @param string $fileName
  295. * @return string
  296. */
  297. public static function convertToConnectorEncoding($fileName)
  298. {
  299. $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
  300. $encoding = $_config->getFilesystemEncoding();
  301. if (is_null($encoding) || strcasecmp($encoding, "UTF-8") == 0 || strcasecmp($encoding, "UTF8") == 0) {
  302. return $fileName;
  303. }
  304. if (!function_exists("iconv")) {
  305. if (strcasecmp($encoding, "ISO-8859-1") == 0 || strcasecmp($encoding, "ISO8859-1") == 0 || strcasecmp($encoding, "Latin1") == 0) {
  306. return utf8_encode($fileName);
  307. } else {
  308. return $fileName;
  309. }
  310. }
  311. $converted = @iconv($encoding, "UTF-8", $fileName);
  312. if ($converted === false) {
  313. return $fileName;
  314. }
  315. return $converted;
  316. }
  317. /**
  318. * Find document root
  319. *
  320. * @return string
  321. * @access public
  322. */
  323. public function getDocumentRootPath()
  324. {
  325. /**
  326. * The absolute pathname of the currently executing script.
  327. * Notatka: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php,
  328. * $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
  329. */
  330. if (isset($_SERVER['SCRIPT_FILENAME'])) {
  331. $sRealPath = dirname($_SERVER['SCRIPT_FILENAME']);
  332. }
  333. else {
  334. /**
  335. * realpath — Returns canonicalized absolute pathname
  336. */
  337. $sRealPath = realpath( './' ) ;
  338. }
  339. /**
  340. * The filename of the currently executing script, relative to the document root.
  341. * For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar
  342. * would be /test.php/foo.bar.
  343. */
  344. $sSelfPath = dirname($_SERVER['PHP_SELF']);
  345. return substr($sRealPath, 0, strlen($sRealPath) - strlen($sSelfPath));
  346. }
  347. /**
  348. * Create directory recursively
  349. *
  350. * @access public
  351. * @static
  352. * @param string $dir
  353. * @return boolean
  354. */
  355. public static function createDirectoryRecursively($dir)
  356. {
  357. if (DIRECTORY_SEPARATOR === "\\") {
  358. $dir = str_replace("/", "\\", $dir);
  359. }
  360. else if (DIRECTORY_SEPARATOR === "/") {
  361. $dir = str_replace("\\", "/", $dir);
  362. }
  363. $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
  364. if ($perms = $_config->getChmodFolders()) {
  365. $oldUmask = umask(0);
  366. $bCreated = @mkdir($dir, $perms, true);
  367. umask($oldUmask);
  368. }
  369. else {
  370. $bCreated = @mkdir($dir, 0777, true);
  371. }
  372. return $bCreated;
  373. }
  374. /**
  375. * Detect HTML in the first KB to prevent against potential security issue with
  376. * IE/Safari/Opera file type auto detection bug.
  377. * Returns true if file contain insecure HTML code at the beginning.
  378. *
  379. * @static
  380. * @access public
  381. * @param string $filePath absolute path to file
  382. * @return boolean
  383. */
  384. public static function detectHtml($filePath)
  385. {
  386. $fp = @fopen($filePath, 'rb');
  387. if ( $fp === false || !flock( $fp, LOCK_SH ) ) {
  388. return -1 ;
  389. }
  390. $chunk = fread($fp, 1024);
  391. flock( $fp, LOCK_UN ) ;
  392. fclose($fp);
  393. $chunk = strtolower($chunk);
  394. if (!$chunk) {
  395. return false;
  396. }
  397. $chunk = trim($chunk);
  398. if (preg_match("/<!DOCTYPE\W*X?HTML/sim", $chunk)) {
  399. return true;
  400. }
  401. $tags = array('<body', '<head', '<html', '<img', '<pre', '<script', '<table', '<title');
  402. foreach( $tags as $tag ) {
  403. if(false !== strpos($chunk, $tag)) {
  404. return true ;
  405. }
  406. }
  407. //type = javascript
  408. if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk)) {
  409. return true ;
  410. }
  411. //href = javascript
  412. //src = javascript
  413. //data = javascript
  414. if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) {
  415. return true ;
  416. }
  417. //url(javascript
  418. if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk)) {
  419. return true ;
  420. }
  421. return false ;
  422. }
  423. /**
  424. * Check file content.
  425. * Currently this function validates only image files.
  426. * Returns false if file is invalid.
  427. *
  428. * @static
  429. * @access public
  430. * @param string $filePath absolute path to file
  431. * @param string $extension file extension
  432. * @param integer $detectionLevel 0 = none, 1 = use getimagesize for images, 2 = use DetectHtml for images
  433. * @return boolean
  434. */
  435. public static function isImageValid($filePath, $extension)
  436. {
  437. if (!@is_readable($filePath)) {
  438. return -1;
  439. }
  440. $imageCheckExtensions = array('gif', 'jpeg', 'jpg', 'png', 'psd', 'bmp', 'tiff');
  441. // version_compare is available since PHP4 >= 4.0.7
  442. if ( function_exists( 'version_compare' ) ) {
  443. $sCurrentVersion = phpversion();
  444. if ( version_compare( $sCurrentVersion, "4.2.0" ) >= 0 ) {
  445. $imageCheckExtensions[] = "tiff";
  446. $imageCheckExtensions[] = "tif";
  447. }
  448. if ( version_compare( $sCurrentVersion, "4.3.0" ) >= 0 ) {
  449. $imageCheckExtensions[] = "swc";
  450. }
  451. if ( version_compare( $sCurrentVersion, "4.3.2" ) >= 0 ) {
  452. $imageCheckExtensions[] = "jpc";
  453. $imageCheckExtensions[] = "jp2";
  454. $imageCheckExtensions[] = "jpx";
  455. $imageCheckExtensions[] = "jb2";
  456. $imageCheckExtensions[] = "xbm";
  457. $imageCheckExtensions[] = "wbmp";
  458. }
  459. }
  460. if ( !in_array( $extension, $imageCheckExtensions ) ) {
  461. return true;
  462. }
  463. if ( @getimagesize( $filePath ) === false ) {
  464. return false ;
  465. }
  466. return true;
  467. }
  468. /**
  469. * Returns true if directory is not empty
  470. *
  471. * @access public
  472. * @static
  473. * @param string $serverPath
  474. * @return boolean
  475. */
  476. public static function hasChildren($serverPath)
  477. {
  478. if (!is_dir($serverPath) || (false === $fh = @opendir($serverPath))) {
  479. return false;
  480. }
  481. $hasChildren = false;
  482. while (false !== ($filename = readdir($fh))) {
  483. if ($filename == '.' || $filename == '..') {
  484. continue;
  485. } else if (is_dir($serverPath . DIRECTORY_SEPARATOR . $filename)) {
  486. //we have found valid directory
  487. $hasChildren = true;
  488. break;
  489. }
  490. }
  491. closedir($fh);
  492. return $hasChildren;
  493. }
  494. }