PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/wysiwyg/shared/kcfinder/core/uploader.php

http://github.com/limb-php-framework/limb
PHP | 495 lines | 406 code | 55 blank | 34 comment | 87 complexity | 0780f16c86ad7ee021259ab033448509 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, MPL-2.0-no-copyleft-exception, GPL-2.0
  1. <?php
  2. /** This file is part of KCFinder project
  3. *
  4. * @desc Uploader class
  5. * @package KCFinder
  6. * @version {version}
  7. * @author Pavel Tzonkov <pavelc@users.sourceforge.net>
  8. * @copyright 2010 KCFinder Project
  9. * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
  10. * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
  11. * @link http://kcfinder.sunhater.com
  12. */
  13. class uploader {
  14. protected $config = array();
  15. protected $opener = array();
  16. protected $type;
  17. protected $typeDir;
  18. protected $typeURL;
  19. protected $types = array();
  20. protected $typeSettings = array('disabled', 'theme', 'dirPerms', 'filePerms', 'denyZipDownload', 'maxImageWidth', 'maxImageHeight', 'thumbWidth', 'thumbHeight', 'jpegQuality');
  21. protected $charset;
  22. protected $lang = 'en';
  23. protected $langInputNames = array('lang', 'langCode', 'lng', 'language', 'lang_code');
  24. protected $file;
  25. protected $dateTimeFull; // Currently not used
  26. protected $dateTimeMid; // Currently not used
  27. protected $dateTimeSmall;
  28. protected $labels = array();
  29. protected $get;
  30. protected $post;
  31. protected $cookie;
  32. protected $session;
  33. public function __get($property) {
  34. return property_exists($this, $property) ? $this->$property : null;
  35. }
  36. public function __construct() {
  37. // DISABLE MAGIC QUOTES
  38. if (function_exists('set_magic_quotes_runtime'))
  39. @set_magic_quotes_runtime(false);
  40. // INPUT INIT
  41. $input = new input();
  42. $this->get = &$input->get;
  43. $this->post = &$input->post;
  44. $this->cookie = &$input->cookie;
  45. // LINKING UPLOADED FILE
  46. if (count($_FILES))
  47. $this->file = &$_FILES[key($_FILES)];
  48. // LOAD DEFAULT CONFIGURATION
  49. require "config.php";
  50. // SETTING UP SESSION
  51. if (isset($_CONFIG['_sessionLifetime']))
  52. ini_set('session.gc_maxlifetime', $_CONFIG['_sessionLifetime'] * 60);
  53. if (isset($_CONFIG['_sessionDir']))
  54. ini_set('session.save_path', $_CONFIG['_sessionDir']);
  55. if (isset($_CONFIG['_sessionDomain']))
  56. ini_set('session.cookie_domain', $_CONFIG['_sessionDomain']);
  57. session_start();
  58. // RELOAD DEFAULT CONFIGURATION
  59. require "config.php";
  60. $this->config = $_CONFIG;
  61. // LOAD SESSION CONFIGURATION IF EXISTS
  62. if (isset($_CONFIG['_sessionVar']) &&
  63. is_array($_CONFIG['_sessionVar'])
  64. ) {
  65. foreach ($_CONFIG['_sessionVar'] as $key => $val)
  66. if ((substr($key, 0, 1) != "_") && isset($_CONFIG[$key]))
  67. $this->config[$key] = $val;
  68. if (!isset($this->config['_sessionVar']['self']))
  69. $this->config['_sessionVar']['self'] = array();
  70. $this->session = &$this->config['_sessionVar']['self'];
  71. } else
  72. $this->session = &$_SESSION;
  73. // GET TYPE DIRECTORY
  74. $this->types = &$this->config['types'];
  75. $firstType = array_keys($this->types);
  76. $firstType = $firstType[0];
  77. $this->type = (
  78. isset($this->get['type']) &&
  79. isset($this->types[$this->get['type']])
  80. )
  81. ? $this->get['type'] : $firstType;
  82. // LOAD DIRECTORY TYPE SPECIFIC CONFIGURATION IF EXISTS
  83. if (is_array($this->types[$this->type])) {
  84. foreach ($this->types[$this->type] as $key => $val)
  85. if (in_array($key, $this->typeSettings))
  86. $this->config[$key] = $val;
  87. $this->types[$this->type] = isset($this->types[$this->type]['type'])
  88. ? $this->types[$this->type]['type'] : "";
  89. }
  90. // COOKIES INIT
  91. if (!strlen($this->config['cookieDomain']))
  92. $this->config['cookieDomain'] = $_SERVER['HTTP_HOST'];
  93. if (!strlen($this->config['cookiePath']))
  94. $this->config['cookiePath'] = "/";
  95. // UPLOAD FOLDER INIT
  96. if ($this->config['uploadURL'] == "/") {
  97. $this->config['uploadDir'] = strlen($this->config['uploadDir'])
  98. ? path::normalize($this->config['uploadDir'])
  99. : path::normalize($_SERVER['DOCUMENT_ROOT']);
  100. $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
  101. $this->typeURL = "/{$this->type}";
  102. } else {
  103. $this->config['uploadURL'] = (substr($this->config['uploadURL'], 0, 1) === "/")
  104. ? path::normalize($this->config['uploadURL'])
  105. : path::rel2abs_url($this->config['uploadURL']);
  106. $this->config['uploadDir'] = strlen($this->config['uploadDir'])
  107. ? path::normalize($this->config['uploadDir'])
  108. : path::url2fullPath($this->config['uploadURL']);
  109. $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
  110. $this->typeURL = "{$this->config['uploadURL']}/{$this->type}";
  111. }
  112. if (!is_dir($this->config['uploadDir']))
  113. @mkdir($this->config['uploadDir'], $this->config['dirPerms']);
  114. // HOST APPLICATIONS INIT
  115. if (isset($this->get['CKEditorFuncNum']))
  116. $this->opener['CKEditor']['funcNum'] = $this->get['CKEditorFuncNum'];
  117. if (isset($this->get['opener']) &&
  118. (strtolower($this->get['opener']) == "tinymce") &&
  119. isset($this->config['_tinyMCEPath']) &&
  120. strlen($this->config['_tinyMCEPath'])
  121. )
  122. $this->opener['TinyMCE'] = true;
  123. // LOCALIZATION
  124. foreach ($this->langInputNames as $key)
  125. if (isset($this->get[$key]) &&
  126. preg_match('/^[a-z][a-z\._\-]*$/i', $this->get[$key]) &&
  127. file_exists("lang/" . strtolower($this->get[$key]) . ".php")
  128. ) {
  129. $this->lang = $this->get[$key];
  130. break;
  131. }
  132. $this->localize($this->lang);
  133. // CHECK & MAKE DEFAULT .htaccess
  134. $htaccess = "{$this->config['uploadDir']}/.htaccess";
  135. if (isset($this->config['_check4htaccess']) &&
  136. $this->config['_check4htaccess'] &&
  137. !file_exists($htaccess)
  138. ) {
  139. if (!@file_put_contents($htaccess, $this->get_htaccess()))
  140. $this->backMsg("Cannot write to upload folder.");
  141. } else {
  142. if (false === ($data = @file_get_contents($htaccess)))
  143. $this->backMsg("Cannot read .htaccess");
  144. if (($data != $this->get_htaccess()) && !@file_put_contents($htaccess, $data))
  145. $this->backMsg("Incorrect .htaccess file. Cannot rewrite it!");
  146. }
  147. // CHECK & CREATE UPLOAD FOLDER
  148. if (!is_dir($this->typeDir)) {
  149. if (!mkdir($this->typeDir, $this->config['dirPerms']))
  150. $this->backMsg("Cannot create {dir} folder.", array('dir' => $this->type));
  151. } elseif (!is_readable($this->typeDir))
  152. $this->backMsg("Cannot read upload folder.");
  153. }
  154. public function upload() {
  155. $config = &$this->config;
  156. $file = &$this->file;
  157. $url = $message = "";
  158. if ($config['disabled'] || $config['readonly']) {
  159. if (isset($file['tmp_name'])) @unlink($file['tmp_name']);
  160. $message = $this->label("You don't have permissions to upload files.");
  161. } elseif (true === ($message = $this->checkUploadedFile())) {
  162. $message = "";
  163. $dir = "{$this->typeDir}/";
  164. if (isset($this->get['dir']) &&
  165. (false !== ($gdir = $this->checkInputDir($this->get['dir'])))
  166. ) {
  167. $udir = path::normalize("$dir$gdir");
  168. if (substr($udir, 0, strlen($dir)) !== $dir)
  169. $message = $this->label("Unknown error.");
  170. else {
  171. $l = strlen($dir);
  172. $dir = "$udir/";
  173. $udir = substr($udir, $l);
  174. }
  175. }
  176. if (!strlen($message)) {
  177. if (!is_dir(path::normalize($dir)))
  178. @mkdir(path::normalize($dir), $this->config['dirPerms'], true);
  179. $target = file::getInexistantFilename("$dir{$file['name']}");
  180. if (!move_uploaded_file($file['tmp_name'], $target))
  181. $message = $this->label("Cannot move uploaded file to target folder.");
  182. else {
  183. if (function_exists('chmod'))
  184. @chmod($target, $this->config['filePerms']);
  185. $this->makeThumb($target);
  186. $url = $this->typeURL;
  187. if (isset($udir)) $url .= "/$udir";
  188. $url .= "/" . basename($target);
  189. $url = path::urlPathEncode($url);
  190. }
  191. }
  192. }
  193. if (strlen($message) &&
  194. isset($this->file['tmp_name']) &&
  195. file_exists($this->file['tmp_name'])
  196. )
  197. @unlink($this->file['tmp_name']);
  198. if (strlen($message) && method_exists($this, 'errorMsg'))
  199. $this->errorMsg($message);
  200. $this->callBack($url, $message);
  201. }
  202. protected function checkUploadedFile() {
  203. $config = &$this->config;
  204. $file = &$this->file;
  205. if (!is_array($file) || !isset($file['name']))
  206. return $this->label("Unknown error");
  207. $extension = file::getExtension($file['name']);
  208. $typePatt = strtolower(text::clearWhitespaces($this->types[$this->type]));
  209. // CHECK FOR UPLOAD ERRORS
  210. if ($file['error'])
  211. return
  212. ($file['error'] == UPLOAD_ERR_INI_SIZE) ?
  213. $this->label("The uploaded file exceeds {size} bytes.",
  214. array('size' => ini_get('upload_max_filesize'))) : (
  215. ($file['error'] == UPLOAD_ERR_FORM_SIZE) ?
  216. $this->label("The uploaded file exceeds {size} bytes.",
  217. array('size' => $this->get['MAX_FILE_SIZE'])) : (
  218. ($file['error'] == UPLOAD_ERR_PARTIAL) ?
  219. $this->label("The uploaded file was only partially uploaded.") : (
  220. ($file['error'] == UPLOAD_ERR_NO_FILE) ?
  221. $this->label("No file was uploaded.") : (
  222. ($file['error'] == UPLOAD_ERR_NO_TMP_DIR) ?
  223. $this->label("Missing a temporary folder.") : (
  224. ($file['error'] == UPLOAD_ERR_CANT_WRITE) ?
  225. $this->label("Failed to write file.") :
  226. $this->label("Unknown error.")
  227. )))));
  228. // HIDDEN FILENAMES CHECK
  229. elseif (substr($file['name'], 0, 1) == ".")
  230. return $this->label("File name shouldn't begins with '.'");
  231. // EXTENSION CHECK
  232. elseif (!$this->validateExtension($extension, $this->type))
  233. return $this->label("Denied file extension.");
  234. // SPECIAL DIRECTORY TYPES CHECK (e.g. *img)
  235. elseif (preg_match('/^\*([^ ]+)(.*)?$/s', $typePatt, $patt)) {
  236. list($typePatt, $type, $params) = $patt;
  237. if (class_exists("type_$type")) {
  238. $class = "type_$type";
  239. $type = new $class();
  240. $cfg = $config;
  241. if (strlen($params))
  242. $cfg['params'] = trim($params);
  243. $response = $type->checkFile($file['tmp_name'], $cfg);
  244. if ($response !== true)
  245. return $this->label($response);
  246. } else
  247. return $this->label("Non-existing directory type.");
  248. }
  249. // IMAGE RESIZE
  250. $gd = new gd($file['tmp_name']);
  251. if (!$gd->init_error && !$this->imageResize($gd, $file['tmp_name']))
  252. return $this->label("The image is too big and/or cannot be resized.");
  253. return true;
  254. }
  255. protected function checkInputDir($dir, $inclType=true, $existing=true) {
  256. $dir = path::normalize($dir);
  257. if (substr($dir, 0, 1) == "/")
  258. $dir = substr($dir, 1);
  259. if ((substr($dir, 0, 1) == ".") || (substr(basename($dir), 0, 1) == "."))
  260. return false;
  261. if ($inclType) {
  262. $first = explode("/", $dir);
  263. $first = $first[0];
  264. if ($first != $this->type)
  265. return false;
  266. $return = $this->removeTypeFromPath($dir);
  267. } else {
  268. $return = $dir;
  269. $dir = "{$this->type}/$dir";
  270. }
  271. if (!$existing)
  272. return $return;
  273. $path = "{$this->config['uploadDir']}/$dir";
  274. return (is_dir($path) && is_readable($path)) ? $return : false;
  275. }
  276. protected function validateExtension($ext, $type) {
  277. $ext = trim(strtolower($ext));
  278. if (!isset($this->types[$type]))
  279. return false;
  280. $exts = strtolower(text::clearWhitespaces($this->config['deniedExts']));
  281. if (strlen($exts)) {
  282. $exts = explode(" ", $exts);
  283. if (in_array($ext, $exts))
  284. return false;
  285. }
  286. $exts = trim($this->types[$type]);
  287. if (!strlen($exts) || substr($exts, 0, 1) == "*")
  288. return true;
  289. if (substr($exts, 0, 1) == "!") {
  290. $exts = explode(" ", trim(strtolower(substr($exts, 1))));
  291. return !in_array($ext, $exts);
  292. }
  293. $exts = explode(" ", trim(strtolower($exts)));
  294. return in_array($ext, $exts);
  295. }
  296. protected function getTypeFromPath($path) {
  297. return preg_match('/^([^\/]*)\/.*$/', $path, $patt)
  298. ? $patt[1] : $path;
  299. }
  300. protected function removeTypeFromPath($path) {
  301. return preg_match('/^[^\/]*\/(.*)$/', $path, $patt)
  302. ? $patt[1] : "";
  303. }
  304. protected function imageResize($image, $file=null) {
  305. if (!($image instanceof gd)) {
  306. $gd = new gd($image);
  307. if ($gd->init_error) return false;
  308. $file = $image;
  309. } elseif ($file === null)
  310. return false;
  311. else
  312. $gd = $image;
  313. if ((!$this->config['maxImageWidth'] && !$this->config['maxImageHeight']) ||
  314. (
  315. ($gd->get_width() <= $this->config['maxImageWidth']) &&
  316. ($gd->get_height() <= $this->config['maxImageHeight'])
  317. )
  318. )
  319. return true;
  320. return (
  321. $gd->resize_fit($this->config['maxImageWidth'], $this->config['maxImageHeight']) &&
  322. $gd->imagejpeg($file, $this->config['jpegQuality'])
  323. );
  324. }
  325. protected function makeThumb($file, $overwrite=true) {
  326. $gd = new gd($file);
  327. // Drop files which are not GD handled images
  328. if ($gd->init_error)
  329. return true;
  330. $thumb = substr($file, strlen($this->config['uploadDir']));
  331. $thumb = $this->config['uploadDir'] . "/" . $this->config['thumbsDir'] . "/" . $thumb;
  332. $thumb = path::normalize($thumb);
  333. $thumbDir = dirname($thumb);
  334. if (!is_dir($thumbDir) && !dir::rmkdir($thumbDir, $this->config['dirPerms']))
  335. return false;
  336. if (!$overwrite && is_file($thumb))
  337. return true;
  338. // Images with smaller resolutions than thumbnails
  339. if (($gd->get_width() <= $this->config['thumbWidth']) &&
  340. ($gd->get_height() <= $this->config['thumbHeight'])
  341. ) {
  342. $browsable = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_JPEG2000, IMAGETYPE_PNG);
  343. // Drop only browsable types
  344. if (in_array($gd->type, $browsable))
  345. return true;
  346. // Resize image
  347. } elseif (!$gd->resize_fit($this->config['thumbWidth'], $this->config['thumbHeight']))
  348. return false;
  349. // Save thumbnail
  350. return $gd->imagejpeg($thumb, $this->config['jpegQuality']);
  351. }
  352. protected function localize($langCode) {
  353. require "lang/{$langCode}.php";
  354. setlocale(LC_ALL, $lang['_locale']);
  355. $this->charset = $lang['_charset'];
  356. $this->dateTimeFull = $lang['_dateTimeFull'];
  357. $this->dateTimeMid = $lang['_dateTimeMid'];
  358. $this->dateTimeSmall = $lang['_dateTimeSmall'];
  359. unset($lang['_locale']);
  360. unset($lang['_charset']);
  361. unset($lang['_dateTimeFull']);
  362. unset($lang['_dateTimeMid']);
  363. unset($lang['_dateTimeSmall']);
  364. $this->labels = $lang;
  365. }
  366. protected function label($string, array $data=null) {
  367. $return = isset($this->labels[$string]) ? $this->labels[$string] : $string;
  368. if (is_array($data))
  369. foreach ($data as $key => $val)
  370. $return = str_replace("{{$key}}", $val, $return);
  371. return $return;
  372. }
  373. protected function backMsg($message, array $data=null) {
  374. $message = $this->label($message, $data);
  375. if (isset($this->file['tmp_name']) && file_exists($this->file['tmp_name']))
  376. @unlink($this->file['tmp_name']);
  377. $this->callBack("", $message);
  378. die;
  379. }
  380. protected function callBack($url, $message="") {
  381. $message = text::jsValue($message);
  382. $CKfuncNum = isset($this->opener['CKEditor']['funcNum'])
  383. ? $this->opener['CKEditor']['funcNum'] : 0;
  384. if (!$CKfuncNum) $CKfuncNum = 0;
  385. header("Content-Type: text/html; charset={$this->charset}");
  386. ?><html>
  387. <body>
  388. <script type='text/javascript'>
  389. var kc_CKEditor = (window.parent && window.parent.CKEDITOR)
  390. ? window.parent.CKEDITOR.tools.callFunction
  391. : ((window.opener && window.opener.CKEDITOR)
  392. ? window.opener.CKEDITOR.tools.callFunction
  393. : false);
  394. var kc_FCKeditor = (window.opener && window.opener.OnUploadCompleted)
  395. ? window.opener.OnUploadCompleted
  396. : ((window.parent && window.parent.OnUploadCompleted)
  397. ? window.parent.OnUploadCompleted
  398. : false);
  399. var kc_Custom = (window.parent && window.parent.KCFinder)
  400. ? window.parent.KCFinder.callBack
  401. : ((window.opener && window.opener.KCFinder)
  402. ? window.opener.KCFinder.callBack
  403. : false);
  404. if (kc_CKEditor)
  405. kc_CKEditor(<?php echo $CKfuncNum ?>, '<?php echo $url ?>', '<?php echo $message ?>');
  406. if (kc_FCKeditor)
  407. kc_FCKeditor(<?php echo strlen($message) ? 1 : 0 ?>, '<?php echo $url ?>', '', '<?php echo $message ?>');
  408. if (kc_Custom) {
  409. if (<?php echo strlen($message) ?>) alert('<?php echo $message ?>');
  410. kc_Custom('<?php echo $url ?>');
  411. }
  412. if (!kc_CKEditor && !kc_FCKeditor && !kc_Custom)
  413. alert("<?php echo $message ?>");
  414. </script>
  415. </body>
  416. </html><?php
  417. }
  418. protected function get_htaccess() {
  419. return "<IfModule mod_php4.c>
  420. php_value engine off
  421. </IfModule>
  422. <IfModule mod_php5.c>
  423. php_value engine off
  424. </IfModule>
  425. ";
  426. }
  427. }
  428. ?>