PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/assets/core/plugin/filemanager-berita/uploader/jupload.php

https://github.com/aldiferdiyan/Codeigniter-SMS-Gateway-Gammu
PHP | 767 lines | 556 code | 44 blank | 167 comment | 178 complexity | 635088898fca99e730c7cfa59b9134a7 MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /**
  3. * This class manage upload, with use of the JUpload applet. It's both a sample to show how to use the applet, and
  4. * a class you can use directly into your own application.
  5. *
  6. * Recommandation: Don't update its code !
  7. *
  8. * By doing this, you'll be able to reuse directly any update coming from the JUpload project, instead of reporting your
  9. * modifications into any new version of this class. This guarantees you that your project can use the last version of
  10. * JUpload, without any code modification. We work so that the applet behavior remains unchanged, but from time to time,
  11. * a change can appear.
  12. *
  13. * Sample:
  14. * - See the index.php samples, in the same folder.
  15. *
  16. * Notes:
  17. * - maxChunkSize: this class use a default maxChunkSize of 500K (or less, depending on the script max size). This allows
  18. * upload of FILES OF ANY SIZE on quite all ISP hosting. If it's too big for you (the max upload size of your ISP is less
  19. * than 500K), or if you want no chunk at all, you can, of course, override this default value.
  20. *
  21. *
  22. *
  23. * Parameters:
  24. * - $appletparams contains a map for applet parameters: key is the applet parameter name. The value is the value to transmit
  25. * to the applet. See the applet documentation for information on all applet parameters.
  26. * - $classparams contains the parameter specific for the JUpload class below. Here are the main class parameters:
  27. * - demo_mode. Files are uploaded to the server, but not stored on its hard drive. That is: you can simulate the global
  28. * behavior, but won't consume hard drive space. This mode is used on sourceforge web site.
  29. *
  30. *
  31. * Output generated for uploaded files:
  32. * - $files is an array of array. This can be managed by (a) the function given in the callbackAfterUploadManagement class
  33. * parameter, or (b) within the page whose URL is given in the afterUploadURL applet parameter, or (c) you can Extend the
  34. * class and redeclare defaultAfterUploadManagement() to your needs.
  35. * See the defaultAfterUploadManagement() for a sample on howto manage this array.
  36. *
  37. * This array contains:
  38. * - One entry per file. Each entry is an array, that contains all files properties, stored as $key=>$value.
  39. * The available keys are:
  40. * - name: the filename, as it is now stored on the system.
  41. * - size: the file size
  42. * - path: the absolute path, where the file has been stored.
  43. * - fullName: the canonical file name (i.e. including the absolute path)
  44. * - md5sum: the md5sum of the file, if further control is needed.
  45. * - mimetype: the calculated mime type of the file
  46. * - If the formData applet parameter is used: all attributes (key and value) uploaded by the applet, are put here,
  47. * repeated for each file.
  48. *
  49. * Note: if you are using a callback function (i.e. callbackAfterUploadManagement) and you do not see a global 'object' you
  50. * are expecting then it might have been destroyed by PHP - c.f. http://bugs.php.net/bug.php?id=39693
  51. *
  52. */
  53. class JUpload {
  54. var $appletparams;
  55. var $classparams;
  56. var $files;
  57. public function JUpload($appletparams = array(), $classparams = array()) {
  58. if (gettype($classparams) != 'array')
  59. $this->abort('Invalid type of parameter classparams: Expecting an array');
  60. if (gettype($appletparams) != 'array')
  61. $this->abort('Invalid type of parameter appletparams: Expecting an array');
  62. // set some defaults for the applet params
  63. if (!isset($appletparams['afterUploadURL']))
  64. $appletparams['afterUploadURL'] = $_SERVER['PHP_SELF'] . '?afterupload=1';
  65. if (!isset($appletparams['name']))
  66. $appletparams['name'] = 'JUpload';
  67. if (!isset($appletparams['archive']))
  68. $appletparams['archive'] = 'wjhk.jupload.jar';
  69. if (!isset($appletparams['code']))
  70. $appletparams['code'] = 'wjhk.jupload2.JUploadApplet';
  71. if (!isset($appletparams['debugLevel']))
  72. $appletparams['debugLevel'] = 0;
  73. if (!isset($appletparams['httpUploadParameterType']))
  74. $appletparams['httpUploadParameterType'] = 'array';
  75. if (!isset($appletparams['showLogWindow']))
  76. $appletparams['showLogWindow'] = ($appletparams['debugLevel'] > 0) ? 'true' : 'false';
  77. if (!isset($appletparams['width']))
  78. $appletparams['width'] = 640;
  79. if (!isset($appletparams['height']))
  80. $appletparams['height'] = ($appletparams['showLogWindow'] == 'true') ? 500 : 300;
  81. if (!isset($appletparams['mayscript']))
  82. $appletparams['mayscript'] = 'true';
  83. if (!isset($appletparams['scriptable']))
  84. $appletparams['scriptable'] = 'false';
  85. //if (!isset($appletparams['stringUploadSuccess']))
  86. $appletparams['stringUploadSuccess'] = 'SUCCESS';
  87. //if (!isset($appletparams['stringUploadError']))
  88. $appletparams['stringUploadError'] = 'ERROR: (.*)';
  89. $maxpost = $this->tobytes(ini_get('post_max_size'));
  90. $maxmem = $this->tobytes(ini_get('memory_limit'));
  91. $maxfs = $this->tobytes(ini_get('upload_max_filesize'));
  92. $obd = ini_get('open_basedir');
  93. if (!isset($appletparams['maxChunkSize'])) {
  94. $maxchunk = ($maxpost < $maxmem) ? $maxpost : $maxmem;
  95. $maxchunk = ($maxchunk < $maxfs) ? $maxchunk : $maxfs;
  96. $maxchunk /= 4;
  97. $optchunk = (500000 > $maxchunk) ? $maxchunk : 500000;
  98. $appletparams['maxChunkSize'] = $optchunk;
  99. }
  100. $appletparams['maxChunkSize'] = $this->tobytes($appletparams['maxChunkSize']);
  101. if (!isset($appletparams['maxFileSize']))
  102. $appletparams['maxFileSize'] = $maxfs;
  103. $appletparams['maxFileSize'] = $this->tobytes($appletparams['maxFileSize']);
  104. if (isset($classparams['errormail'])) {
  105. $appletparams['urlToSendErrorTo'] = $_SERVER["PHP_SELF"] . '?errormail';
  106. }
  107. // Same for class parameters
  108. if (!isset($classparams['demo_mode']))
  109. $classparams['demo_mode'] = false;
  110. if ($classparams['demo_mode']) {
  111. $classparams['create_destdir'] = false;
  112. $classparams['allow_subdirs'] = true;
  113. $classparams['allow_zerosized'] = true;
  114. $classparams['duplicate'] = 'overwrite';
  115. }
  116. if (!isset($classparams['debug_php'])) // set true to log some messages in PHP log
  117. $classparams['debug_php'] = false;
  118. if (!isset($this->classparams['allowed_mime_types'])) // array of allowed MIME type
  119. $classparams['allowed_mime_types'] = 'all';
  120. if (!isset($this->classparams['allowed_file_extensions'])) // array of allowed file extensions
  121. $classparams['allowed_file_extensions'] = 'all';
  122. if (!isset($classparams['verbose_errors'])) // shouldn't display server info on a production site!
  123. $classparams['verbose_errors'] = true;
  124. if (!isset($classparams['session_regenerate']))
  125. $classparams['session_regenerate'] = false;
  126. if (!isset($classparams['create_destdir']))
  127. $classparams['create_destdir'] = true;
  128. if (!isset($classparams['allow_subdirs']))
  129. $classparams['allow_subdirs'] = false;
  130. if (!isset($classparams['spaces_in_subdirs']))
  131. $classparams['spaces_in_subdirs'] = false;
  132. if (!isset($classparams['allow_zerosized']))
  133. $classparams['allow_zerosized'] = false;
  134. if (!isset($classparams['duplicate']))
  135. $classparams['duplicate'] = 'rename';
  136. if (!isset($classparams['dirperm']))
  137. $classparams['dirperm'] = 0755;
  138. if (!isset($classparams['fileperm']))
  139. $classparams['fileperm'] = 0644;
  140. if (!isset($classparams['destdir'])) {
  141. if ($obd != '')
  142. $classparams['destdir'] = $obd;
  143. else
  144. $classparams['destdir'] = '/var/tmp/jupload_test';
  145. }else{
  146. $classparams['destdir']=str_replace('~',' ',$classparams['destdir']);
  147. }
  148. if ($classparams['create_destdir']) {
  149. $_umask = umask(0); // override the system mask
  150. @mkdir($classparams['destdir'], $classparams['dirperm']);
  151. umask($_umask);
  152. }
  153. if (!is_dir($classparams['destdir']) && is_writable($classparams['destdir']))
  154. $this->abort('Destination dir not accessible');
  155. if (!isset($classparams['tmp_prefix']))
  156. $classparams['tmp_prefix'] = 'jutmp.';
  157. if (!isset($classparams['var_prefix']))
  158. $classparams['var_prefix'] = 'juvar.';
  159. if (!isset($classparams['jscript_wrapper']))
  160. $classparams['jscript_wrapper'] = 'JUploadSetProperty';
  161. if (!isset($classparams['tag_jscript']))
  162. $classparams['tag_jscript'] = '<!--JUPLOAD_JSCRIPT-->';
  163. if (!isset($classparams['tag_applet']))
  164. $classparams['tag_applet'] = '<!--JUPLOAD_APPLET-->';
  165. if (!isset($classparams['tag_flist']))
  166. $classparams['tag_flist'] = '<!--JUPLOAD_FILES-->';
  167. if (!isset($classparams['http_flist_start']))
  168. $classparams['http_flist_start'] =
  169. "<table border='1'><TR><TH>Filename</TH><TH>file size</TH><TH>Relative path</TH><TH>Full name</TH><TH>md5sum</TH><TH>Specific parameters</TH></TR>";
  170. if (!isset($classparams['http_flist_end']))
  171. $classparams['http_flist_end'] = "</table>\n";
  172. if (!isset($classparams['http_flist_file_before']))
  173. $classparams['http_flist_file_before'] = "<tr><td>";
  174. if (!isset($classparams['http_flist_file_between']))
  175. $classparams['http_flist_file_between'] = "</td><td>";
  176. if (!isset($classparams['http_flist_file_after']))
  177. $classparams['http_flist_file_after'] = "</td></tr>\n";
  178. $this->appletparams = $appletparams;
  179. $this->classparams = $classparams;
  180. $this->page_start();
  181. }
  182. /**
  183. * Return an array of uploaded files * The array contains: name, size, tmp_name, error,
  184. * relativePath, md5sum, mimetype, fullName, path
  185. */
  186. public function uploadedfiles() {
  187. return $this->files;
  188. }
  189. /**
  190. * Log a message on the current output, as a HTML comment.
  191. */
  192. protected function logDebug($function, $msg, $htmlComment=true) {
  193. $output = "[DEBUG] [$function] $msg";
  194. if ($htmlComment) {
  195. echo("<!-- $output -->\r\n");
  196. } else {
  197. echo("$output\r\n");
  198. }
  199. }
  200. /**
  201. * Log a message to the PHP log.
  202. * Declared "protected" so it may be Extended if you require customised logging (e.g. particular log file location).
  203. */
  204. protected function logPHPDebug($function, $msg) {
  205. if ($this->classparams['debug_php'] === true) {
  206. $output = "[DEBUG] [$function] ".$this->arrayexpand($msg);
  207. error_log($output);
  208. }
  209. }
  210. private function arrayexpand($array) {
  211. $output = '';
  212. if (is_array($array)) {
  213. foreach ($array as $key => $value) {
  214. $output .= "\n ".$key.' => '.$this->arrayexpand($value);
  215. }
  216. } else {
  217. $output .= $array;
  218. }
  219. return $output;
  220. }
  221. /**
  222. * Convert a value ending in 'G','M' or 'K' to bytes
  223. *
  224. */
  225. private function tobytes($val) {
  226. $val = trim($val);
  227. $last = mb_strtolower($val{strlen($val)-1});
  228. switch($last) {
  229. case 'g':
  230. $val *= 1024;
  231. case 'm':
  232. $val *= 1024;
  233. case 'k':
  234. $val *= 1024;
  235. }
  236. return $val;
  237. }
  238. /**
  239. * Build a string, containing a javascript wrapper function
  240. * for setting applet properties via JavaScript. This is necessary,
  241. * because we use the "modern" method of including the applet (using
  242. * <object> resp. <embed> tags) in order to trigger automatic JRE downloading.
  243. * Therefore, in Netscape-like browsers, the applet is accessible via
  244. * the document.embeds[] array while in others, it is accessible via the
  245. * document.applets[] array.
  246. *
  247. * @return A string, containing the necessary wrapper function (named JUploadSetProperty)
  248. */
  249. private function str_jsinit() {
  250. $N = "\n";
  251. $name = $this->appletparams['name'];
  252. $ret = '<script type="text/javascript">'.$N;
  253. $ret .= '<!--'.$N;
  254. $ret .= 'function '.$this->classparams['jscript_wrapper'].'(name, value) {'.$N;
  255. $ret .= ' document.applets["'.$name.'"] == null || document.applets["'.$name.'"].setProperty(name,value);'.$N;
  256. $ret .= ' document.embeds["'.$name.'"] == null || document.embeds["'.$name.'"].setProperty(name,value);'.$N;
  257. $ret .= '}'.$N;
  258. $ret .= '//-->'.$N;
  259. $ret .= '</script>';
  260. return $ret;
  261. }
  262. /**
  263. * Build a string, containing the applet tag with all parameters.
  264. *
  265. * @return A string, containing the applet tag
  266. */
  267. private function str_applet() {
  268. $N = "\n";
  269. $params = $this->appletparams;
  270. // return the actual applet tag
  271. $ret = '<object classid = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"'.$N;
  272. $ret .= ' codebase = "http://java.sun.com/update/1.5.0/jinstall-1_5-windows-i586.cab#Version=5,0,0,3"'.$N;
  273. $ret .= ' width = "'.$params['width'].'"'.$N;
  274. $ret .= ' height = "'.$params['height'].'"'.$N;
  275. $ret .= ' name = "'.$params['name'].'">'.$N;
  276. foreach ($params as $key => $val) {
  277. if ($key != 'width' && $key != 'height')
  278. $ret .= ' <param name = "'.$key.'" value = "'.$val.'" />'.$N;
  279. }
  280. $ret .= ' <comment>'.$N;
  281. $ret .= ' <embed'.$N;
  282. $ret .= ' type = "application/x-java-applet;version=1.5"'.$N;
  283. foreach ($params as $key => $val)
  284. $ret .= ' '.$key.' = "'.$val.'"'.$N;
  285. $ret .= ' pluginspage = "http://java.sun.com/products/plugin/index.html#download">'.$N;
  286. $ret .= ' <noembed>'.$N;
  287. $ret .= ' Java 1.5 or higher plugin required.'.$N;
  288. $ret .= ' </noembed>'.$N;
  289. $ret .= ' </embed>'.$N;
  290. $ret .= ' </comment>'.$N;
  291. $ret .= '</object>';
  292. return $ret;
  293. }
  294. private function abort($msg = '') {
  295. $this->cleanup();
  296. if ($msg != '')
  297. die(str_replace('(.*)',$msg,$this->appletparams['stringUploadError'])."\n");
  298. exit;
  299. }
  300. private function warning($msg = '') {
  301. $this->cleanup();
  302. if ($msg != '')
  303. echo('WARNING: '.$msg."\n");
  304. echo $this->appletparams['stringUploadSuccess']."\n";
  305. exit;
  306. }
  307. private function cleanup() {
  308. // remove all uploaded files of *this* request
  309. if (isset($_FILES)) {
  310. foreach ($_FILES as $key => $val)
  311. @unlink($val['tmp_name']);
  312. }
  313. // remove accumulated file, if any.
  314. @unlink($this->classparams['destdir'].'/'.$this->classparams['tmp_prefix'].session_id());
  315. @unlink($this->classparams['destdir'].'/'.$this->classparams['tmp_prefix'].'tmp'.session_id());
  316. // reset session var
  317. $_SESSION[$this->classparams['var_prefix'].'size'] = 0;
  318. return;
  319. }
  320. private function mkdirp($path) {
  321. // create subdir (hierary) below destdir;
  322. $dirs = explode('/', $path);
  323. $path = $this->classparams['destdir'];
  324. foreach ($dirs as $dir) {
  325. $path .= '/'.$dir;
  326. if (!file_exists($path)) { // @ does NOT always supress the error!
  327. $_umask = umask(0); // override the system mask
  328. @mkdir($path, $this->classparams['dirperm']);
  329. umask($_umask);
  330. }
  331. }
  332. if (!is_dir($path) && is_writable($path))
  333. $this->abort('Destination dir not accessible');
  334. }
  335. /**
  336. * This method:
  337. * - Replaces some potentially dangerous characters by '_' (in the given name an relative path)
  338. * - Checks if a files of the same name already exists.
  339. * - If no: no problem.
  340. * - If yes, and the duplicate class param is set to rename, the file is renamed.
  341. * - If yes, and the duplicate class param is set to overwrite, the file is not renamed. The existing one will be erased.
  342. * - If yes, and the duplicate class param is set to reject, an error is thrown.
  343. */
  344. private function dstfinal(&$name, &$subdir) {
  345. $name = preg_replace('![`$\\\\/|]!', '_', $name);
  346. if ($this->classparams['allow_subdirs'] && ($subdir != '')) {
  347. $subdir = trim(preg_replace('!\\\\!','/',$subdir),'/');
  348. $subdir = preg_replace('![`$|]!', '_', $subdir);
  349. if (!$this->classparams['spaces_in_subdirs']) {
  350. $subdir = str_replace(' ','_',$subdir);
  351. }
  352. // recursively create subdir
  353. if (!$this->classparams['demo_mode'])
  354. $this->mkdirp($subdir);
  355. // append a slash
  356. $subdir .= '/';
  357. } else {
  358. $subdir = '';
  359. }
  360. $ret = $this->classparams['destdir'].'/'.$subdir.$name;
  361. if (file_exists($ret)) {
  362. if ($this->classparams['duplicate'] == 'overwrite') {
  363. return $ret;
  364. }
  365. if ($this->classparams['duplicate'] == 'reject') {
  366. $this->abort('A file with the same name already exists');
  367. }
  368. if ($this->classparams['duplicate'] == 'warning') {
  369. $this->warning("File $name already exists - rejected");
  370. }
  371. if ($this->classparams['duplicate'] == 'rename') {
  372. $cnt = 1;
  373. $dir = $this->classparams['destdir'].'/'.$subdir;
  374. $ext = strrchr($name, '.');
  375. if ($ext) {
  376. $nameWithoutExtension = substr($name, 0, strlen($name) - strlen($ext));
  377. } else {
  378. $ext = '';
  379. $nameWithoutExtension = $name;
  380. }
  381. $rtry = $dir.$nameWithoutExtension.'.['.$cnt.']'.$ext;
  382. while (file_exists($rtry)) {
  383. $cnt++;
  384. $rtry = $dir.$nameWithoutExtension.'.['.$cnt.']'.$ext;
  385. }
  386. //We store the result name in the byReference name parameter.
  387. $name = $nameWithoutExtension.'.['.$cnt.']'.$ext;
  388. $ret = $rtry;
  389. }
  390. }
  391. return $ret;
  392. }
  393. /**
  394. * Example function to process the files uploaded. This one simply displays the files' data.
  395. *
  396. */
  397. public function defaultAfterUploadManagement() {
  398. $flist = '[defaultAfterUploadManagement] Nb uploaded files is: ' . sizeof($this->files);
  399. $flist = $this->classparams['http_flist_start'];
  400. foreach ($this->files as $f) {
  401. //$f is an array, that contains all info about the uploaded file.
  402. $this->logDebug('defaultAfterUploadManagement', " Reading file ${f['name']}");
  403. $flist .= $this->classparams['http_flist_file_before'];
  404. $flist .= $f['name'];
  405. $flist .= $this->classparams['http_flist_file_between'];
  406. $flist .= $f['size'];
  407. $flist .= $this->classparams['http_flist_file_between'];
  408. $flist .= $f['relativePath'];
  409. $flist .= $this->classparams['http_flist_file_between'];
  410. $flist .= $f['fullName'];
  411. $flist .= $this->classparams['http_flist_file_between'];
  412. $flist .= $f['md5sum'];
  413. $addBR = false;
  414. foreach ($f as $key=>$value) {
  415. //If it's a specific key, let's display it:
  416. if ($key != 'name' && $key != 'size' && $key != 'relativePath' && $key != 'fullName' && $key != 'md5sum') {
  417. if ($addBR) {
  418. $flist .= "<br>";
  419. } else {
  420. // First line. We must add a new 'official' list separator.
  421. $flist .= $this->classparams['http_flist_file_between'];
  422. $addBR = true;
  423. }
  424. $flist .= "$key => $value";
  425. }
  426. }
  427. $flist .= $this->classparams['http_flist_file_after'];
  428. }
  429. $flist .= $this->classparams['http_flist_end'];
  430. return $flist;
  431. }
  432. /**
  433. * Generation of the applet tag, and necessary things around (js content). Insertion of this into the content of the
  434. * page.
  435. * See the tag_jscript and tag_applet class parameters.
  436. */
  437. private function generateAppletTag($str) {
  438. $this->logDebug('generateAppletTag', 'Entering function');
  439. $str = preg_replace('/'.$this->classparams['tag_jscript'].'/', $this->str_jsinit(), $str);
  440. return preg_replace('/'.$this->classparams['tag_applet'].'/', $this->str_applet(), $str);
  441. }
  442. /**
  443. * This function is called when constructing the page, when we're not reveiving uploaded files. It 'just' construct
  444. * the applet tag, by calling the relevant function.
  445. *
  446. * This *must* be public, because it is called from PHP's output buffering
  447. */
  448. public function interceptBeforeUpload($str) {
  449. $this->logDebug('interceptBeforeUpload', 'Entering function');
  450. return $this->generateAppletTag($str);
  451. }
  452. /**
  453. * This function displays the uploaded files description in the current page (see tag_flist class parameter)
  454. *
  455. * This *must* be public, because it is called from PHP's output buffering.
  456. */
  457. public function interceptAfterUpload($str) {
  458. $this->logDebug('interceptAfterUpload', 'Entering function');
  459. $this->logPHPDebug('interceptAfterUpload', $this->files);
  460. if (count($this->files) > 0) {
  461. if (isset($this->classparams['callbackAfterUploadManagement'])) {
  462. $this->logDebug('interceptAfterUpload', 'Before call of ' .$this->classparams['callbackAfterUploadManagement']);
  463. $strForFListContent = call_user_func($this->classparams['callbackAfterUploadManagement'], $this, $this->files);
  464. } else {
  465. $strForFListContent = $this->defaultAfterUploadManagement();
  466. }
  467. $str = preg_replace('/'.$this->classparams['tag_flist'].'/', $strForFListContent, $str);
  468. }
  469. return $this->generateAppletTag($str);
  470. }
  471. /**
  472. * This method manages the receiving of the debug log, when an error occurs.
  473. */
  474. private function receive_debug_log() {
  475. // handle error report
  476. if (isset($_POST['description']) && isset($_POST['log'])) {
  477. $msg = $_POST['log'];
  478. mail($this->classparams['errormail'], $_POST['description'], $msg);
  479. } else {
  480. if (isset($_SERVER['SERVER_ADMIN']))
  481. mail($_SERVER['SERVER_ADMIN'], 'Empty jupload error log',
  482. 'An empty log has just been posted.');
  483. $this->logPHPDebug('receive_debug_log', 'Empty error log received');
  484. }
  485. exit;
  486. }
  487. /**
  488. * This method is the heart of the system. It manage the files sent by the applet, check the incoming parameters (md5sum) and
  489. * reconstruct the files sent in chunk mode.
  490. *
  491. * The result is stored in the $files array, and can then be managed by the function given in the callbackAfterUploadManagement
  492. * class parameter, or within the page whose URL is given in the afterUploadURL applet parameter.
  493. * Or you can Extend the class and redeclare defaultAfterUploadManagement() to your needs.
  494. */
  495. private function receive_uploaded_files() {
  496. $this->logDebug('receive_uploaded_files', 'Entering POST management');
  497. if (session_id() == '') {
  498. session_start();
  499. }
  500. // we check for the session *after* handling possible error log
  501. // because an error could have happened because the session-id is missing.
  502. if (!isset($_SESSION[$this->classparams['var_prefix'].'size'])) {
  503. $this->abort('Invalid session (in afterupload, POST, check of size)');
  504. }
  505. if (!isset($_SESSION[$this->classparams['var_prefix'].'files'])) {
  506. $this->abort('Invalid session (in afterupload, POST, check of files)');
  507. }
  508. $this->files = $_SESSION[$this->classparams['var_prefix'].'files'];
  509. if (!is_array($this->files)) {
  510. $this->abort('Invalid session (in afterupload, POST, is_array(files))');
  511. }
  512. if ($this->appletparams['sendMD5Sum'] == 'true' && !isset($_POST['md5sum'])) {
  513. $this->abort('Required POST variable md5sum is missing');
  514. }
  515. $cnt = 0;
  516. foreach ($_FILES as $key => $value) {
  517. //Let's read the $_FILES data
  518. if (isset($files_data)) {
  519. unset($files_data);
  520. }
  521. $jupart = (isset($_POST['jupart'])) ? (int)$_POST['jupart'] : 0;
  522. $jufinal = (isset($_POST['jufinal'])) ? (int)$_POST['jufinal'] : 1;
  523. $relpaths = (isset($_POST['relpathinfo'])) ? $_POST['relpathinfo'] : null;
  524. $md5sums = (isset($_POST['md5sum'])) ? $_POST['md5sum'] : null;
  525. $mimetypes = (isset($_POST['mimetype'])) ? $_POST['mimetype'] : null;
  526. //$relpaths = (isset($_POST["relpathinfo$cnt"])) ? $_POST["relpathinfo$cnt"] : null;
  527. //$md5sums = (isset($_POST["md5sum$cnt"])) ? $_POST["md5sum$cnt"] : null;
  528. if (gettype($relpaths) == 'string') {
  529. $relpaths = array($relpaths);
  530. }
  531. if (gettype($md5sums) == 'string') {
  532. $md5sums = array($md5sums);
  533. }
  534. if ($this->appletparams['sendMD5Sum'] == 'true' && !is_array($md5sums)) {
  535. $this->abort('Expecting an array of MD5 checksums');
  536. }
  537. if (!is_array($relpaths)) {
  538. $this->abort('Expecting an array of relative paths');
  539. }
  540. if (!is_array($mimetypes)) {
  541. $this->abort('Expecting an array of MIME types');
  542. }
  543. // Check the MIME type (note: this is easily forged!)
  544. if (isset($this->classparams['allowed_mime_types']) && is_array($this->classparams['allowed_mime_types'])) {
  545. if (!in_array($mimetypes[$cnt], $this->classparams['allowed_mime_types'])) {
  546. $this->abort('MIME type '.$mimetypes[$cnt].' not allowed');
  547. }
  548. }
  549. if (isset($this->classparams['allowed_file_extensions']) && is_array($this->classparams['allowed_file_extensions'])) {
  550. $fileExtension = substr(strrchr($value['name'][$cnt], "."), 1);
  551. if (!in_array($fileExtension, $this->classparams['allowed_file_extensions'])) {
  552. $this->abort('File extension '.$fileExtension.' not allowed');
  553. }
  554. }
  555. $dstdir = $this->classparams['destdir'];
  556. $dstname = $dstdir.'/'.$this->classparams['tmp_prefix'].session_id();
  557. $tmpname = $dstdir.'/'.$this->classparams['tmp_prefix'].'tmp'.session_id();
  558. // Controls are now done. Let's store the current uploaded files properties in an array, for future use.
  559. $files_data['name'] = $value['name'][$cnt];
  560. $files_data['size'] = 'not calculated yet';
  561. $files_data['tmp_name'] = $value['tmp_name'][$cnt];
  562. $files_data['error'] = $value['error'][$cnt];
  563. $files_data['relativePath'] = $relpaths[$cnt];
  564. $files_data['md5sum'] = $md5sums[$cnt];
  565. $files_data['mimetype'] = $mimetypes[$cnt];
  566. if (!move_uploaded_file($files_data['tmp_name'], $tmpname)) {
  567. if ($classparams['verbose_errors']) {
  568. $this->abort("Unable to move uploaded file (from ${files_data['tmp_name']} to $tmpname)");
  569. } else {
  570. trigger_error("Unable to move uploaded file (from ${files_data['tmp_name']} to $tmpname)",E_USER_WARNING);
  571. $this->abort("Unable to move uploaded file");
  572. }
  573. }
  574. // In demo mode, no file storing is done. We just delete the newly uploaded file.
  575. if ($this->classparams['demo_mode']) {
  576. if ($jufinal || (!$jupart)) {
  577. if ($jupart) {
  578. $files_data['size'] = ($jupart-1) * $this->appletparams['maxChunkSize'] + filesize($tmpname);
  579. } else {
  580. $files_data['size'] = filesize($tmpname);
  581. }
  582. $files_data['fullName'] = 'Demo mode<BR>No file storing';
  583. array_push($this->files, $files_data);
  584. }
  585. unlink($tmpname);
  586. $cnt++;
  587. continue;
  588. }
  589. //If we get here, the upload is a real one (no demo)
  590. if ($jupart) {
  591. // got a chunk of a multi-part upload
  592. $len = filesize($tmpname);
  593. $_SESSION[$this->classparams['var_prefix'].'size'] += $len;
  594. if ($len > 0) {
  595. $src = fopen($tmpname, 'rb');
  596. $dst = fopen($dstname, ($jupart == 1) ? 'wb' : 'ab');
  597. while ($len > 0) {
  598. $rlen = ($len > 8192) ? 8192 : $len;
  599. $buf = fread($src, $rlen);
  600. if (!$buf) {
  601. fclose($src);
  602. fclose($dst);
  603. unlink($dstname);
  604. $this->abort('read IO error');
  605. }
  606. if (!fwrite($dst, $buf, $rlen)) {
  607. fclose($src);
  608. fclose($dst);
  609. unlink($dstname);
  610. $this->abort('write IO error');
  611. }
  612. $len -= $rlen;
  613. }
  614. fclose($src);
  615. fclose($dst);
  616. unlink($tmpname);
  617. }
  618. if ($jufinal) {
  619. // This is the last chunk. Check total lenght and
  620. // rename it to it's final name.
  621. $dlen = filesize($dstname);
  622. if ($dlen != $_SESSION[$this->classparams['var_prefix'].'size'])
  623. $this->abort('file size mismatch');
  624. if ($this->appletparams['sendMD5Sum'] == 'true' ) {
  625. if ($md5sums[$cnt] != md5_file($dstname))
  626. $this->abort('MD5 checksum mismatch');
  627. }
  628. // remove zero sized files
  629. if (($dlen > 0) || $this->classparams['allow_zerosized']) {
  630. $dstfinal = $this->dstfinal($files_data['name'],$files_data['relativePath']);
  631. if (!rename($dstname, $dstfinal))
  632. $this->abort('rename IO error');
  633. $_umask = umask(0); // override the system mask
  634. if (!chmod($dstfinal, $this->classparams['fileperm']))
  635. $this->abort('chmod IO error');
  636. umask($_umask);
  637. $files_data['size'] = filesize($dstfinal);
  638. $files_data['fullName'] = $dstfinal;
  639. $files_data['path'] = fix_dirname($dstfinal);
  640. array_push($this->files, $files_data);
  641. } else {
  642. unlink($dstname);
  643. }
  644. // reset session var
  645. $_SESSION[$this->classparams['var_prefix'].'size'] = 0;
  646. }
  647. } else {
  648. // Got a single file upload. Trivial.
  649. if ($this->appletparams['sendMD5Sum'] == 'true' ) {
  650. if ($md5sums[$cnt] != md5_file($tmpname))
  651. $this->abort('MD5 checksum mismatch');
  652. }
  653. $dstfinal = $this->dstfinal($files_data['name'],$files_data['relativePath']);
  654. if (!rename($tmpname, $dstfinal))
  655. $this->abort('rename IO error');
  656. $_umask = umask(0); // override the system mask
  657. if (!chmod($dstfinal, $this->classparams['fileperm']))
  658. $this->abort('chmod IO error');
  659. umask($_umask);
  660. $files_data['size'] = filesize($dstfinal);
  661. $files_data['fullName'] = $dstfinal;
  662. $files_data['path'] = fix_dirname($dstfinal);
  663. array_push($this->files, $files_data);
  664. }
  665. $cnt++;
  666. }
  667. echo $this->appletparams['stringUploadSuccess']."\n";
  668. $_SESSION[$this->classparams['var_prefix'].'files'] = $this->files;
  669. session_write_close();
  670. exit;
  671. }
  672. /**
  673. *
  674. *
  675. */
  676. private function page_start() {
  677. $this->logDebug('page_start', 'Entering function');
  678. // If the applet checks for the serverProtocol, it issues a HEAD request
  679. // -> Simply return an empty doc.
  680. if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
  681. // Nothing to do
  682. } else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  683. // A GET request means: return upload page
  684. $this->logDebug('page_start', 'Entering GET management');
  685. if (session_id() == '') {
  686. session_start();
  687. }
  688. if (isset($_GET['afterupload'])) {
  689. $this->logDebug('page_start', 'afterupload is set');
  690. if (!isset($_SESSION[$this->classparams['var_prefix'].'files'])) {
  691. $this->abort('Invalid session (in afterupload, GET, check of $_SESSION): files array is not set');
  692. }
  693. $this->files = $_SESSION[$this->classparams['var_prefix'].'files'];
  694. if (!is_array($this->files)) {
  695. $this->abort('Invalid session (in afterupload, GET, check of is_array(files)): files is not an array');
  696. }
  697. // clear session data ready for new upload
  698. $_SESSION[$this->classparams['var_prefix'].'files'] = array();
  699. // start intercepting the content of the calling page, to display the upload result.
  700. ob_start(array(& $this, 'interceptAfterUpload'));
  701. } else {
  702. $this->logDebug('page_start', 'afterupload is not set');
  703. if ($this->classparams['session_regenerate']) {
  704. session_regenerate_id(true);
  705. }
  706. $this->files = array();
  707. $_SESSION[$this->classparams['var_prefix'].'size'] = 0;
  708. $_SESSION[$this->classparams['var_prefix'].'files'] = $this->files;
  709. // start intercepting the content of the calling page, to display the applet tag.
  710. ob_start(array(& $this, 'interceptBeforeUpload'));
  711. }
  712. } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  713. // If we got a POST request, this is the real work.
  714. if (isset($_GET['errormail'])) {
  715. //Hum, an error occurs on server side. Let's manage the debug log, that we just received.
  716. $this->receive_debug_log();
  717. } else {
  718. $this->receive_uploaded_files();
  719. }
  720. }
  721. }
  722. }
  723. // PHP end tag omitted intentionally!!