PageRenderTime 40ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/pivotx_2.2.5-sqlite/pivotx/fileupload.php

http://pivotx-sqlite.googlecode.com/
PHP | 223 lines | 148 code | 31 blank | 44 comment | 49 complexity | 62a58b61d037ff84512e7f0ac8d52ba6 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /**
  3. * upload.php
  4. *
  5. * Copyright 2009, Moxiecode Systems AB
  6. * Released under GPL License.
  7. *
  8. * License: http://www.plupload.com/license
  9. * Contributing: http://www.plupload.com/contributing
  10. *
  11. * ----
  12. *
  13. * Modified by the PivotX team.
  14. *
  15. * $Id: fileupload.php 3384 2011-01-06 14:18:51Z marcelfw $
  16. */
  17. // HTTP headers for no cache etc
  18. header('Content-type: text/plain; charset=UTF-8');
  19. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  20. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  21. header("Cache-Control: no-store, no-cache, must-revalidate");
  22. header("Cache-Control: post-check=0, pre-check=0", false);
  23. header("Pragma: no-cache");
  24. if (($_COOKIE['PHPSESSID'] == '') && ($_GET['sess'] != '')) {
  25. session_id($_GET['sess']);
  26. }
  27. // Make sure we're logged in..
  28. require_once(dirname(__FILE__).'/lib.php');
  29. initializePivotX(false);
  30. $PIVOTX['session']->minLevel(PIVOTX_UL_NORMAL);
  31. // Settings
  32. $targetDir = $PIVOTX['paths']['cache_path'].'plupload';
  33. $cleanupTargetDir = true; // Remove old files
  34. $maxFileAge = 60 * 60; // Temp file age in seconds
  35. switch ($_GET['type']) {
  36. case 'image':
  37. case 'images':
  38. case 'file':
  39. case 'files':
  40. $targetDir = makeUploadFolder();
  41. $cleanupTargetDir = false;
  42. break;
  43. }
  44. if (isset($_GET['path']) && ($_GET['path'] != '')) {
  45. /* Using same user level as in fileOperations (in lib.php) */
  46. $PIVOTX['session']->minLevel(PIVOTX_UL_ADVANCED);
  47. $path = $_GET['path'];
  48. // Remove some idiotic and unsafe parts of the path
  49. $path = str_replace('../','',$path);
  50. $path = str_replace('..\\','',$path);
  51. $path = str_replace('..'.DIRECTORY_SEPARATOR,'',$path);
  52. // Don't ever allow uploading outside the images, templates and db folders.
  53. $allowedpaths = array($PIVOTX['paths']['templates_path'], $PIVOTX['paths']['upload_base_path'], $PIVOTX['paths']['db_path']);
  54. $allowed = false;
  55. foreach ($allowedpaths as $allowedpath) {
  56. if (strpos($path, $allowedpath) === 0) {
  57. $allowed = true;
  58. break;
  59. }
  60. }
  61. if (!$allowed) {
  62. die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "Uploading to illegal directory."}, "id" : "id"}');
  63. }
  64. $targetDir = stripTrailingSlash($path);
  65. $cleanupTargetDir = false;
  66. }
  67. // 5 minutes execution time
  68. @set_time_limit(5 * 60);
  69. // usleep(5000);
  70. // Get parameters
  71. $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
  72. $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
  73. $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
  74. if (($fileName == '') && isset($_FILES['file']['name'])) {
  75. $fileName = $_FILES['file']['name'];
  76. }
  77. // Clean the fileName for security reasons
  78. // This *has* to be the same as the javascript one!
  79. //$fileName = preg_replace('/[^a-zA-Z0-9_. -]+/', ' ', $fileName);
  80. $fileName = safeString($fileName,true,'.');
  81. // Make sure the fileName is unique
  82. $previous_fileName = $fileName;
  83. if (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
  84. $ext = strrpos($fileName, '.');
  85. $fileName_a = substr($fileName, 0, $ext);
  86. $fileName_b = substr($fileName, $ext);
  87. $count = 1;
  88. while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
  89. $count++;
  90. $fileName = $fileName_a . '_' . $count . $fileName_b;
  91. if ($count > 1) {
  92. $previous_fileName = $fileName_a . '_' . ($count-1) . $fileName_b;
  93. }
  94. }
  95. // special hook to allow the javascript to
  96. if ($_GET['act'] == 'filename') {
  97. echo $previous_fileName;
  98. exit();
  99. }
  100. if (false) {
  101. $dbg = '';
  102. $dbg .= 'date: ' . date('Y-m-d H:i:s') . "\n";
  103. $dbg .= 'targetdir: ' . $targetDir . "\n";
  104. $dbg .= 'fileName: ' . $fileName . "\n";
  105. file_put_contents('/tmp/sess.txt',$dbg);
  106. }
  107. // Create target dir
  108. if (!file_exists($targetDir))
  109. @mkdir($targetDir);
  110. // Remove old temp files
  111. if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
  112. if ($cleanupTargetDir) {
  113. while (($file = readdir($dir)) !== false) {
  114. $filePath = $targetDir . DIRECTORY_SEPARATOR . $file;
  115. // Remove temp files if they are older than the max age
  116. if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
  117. @unlink($filePath);
  118. }
  119. }
  120. closedir($dir);
  121. } else {
  122. die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
  123. }
  124. // Look for the content type header
  125. if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
  126. $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
  127. }
  128. if (isset($_SERVER["CONTENT_TYPE"])) {
  129. $contentType = $_SERVER["CONTENT_TYPE"];
  130. }
  131. if (strpos($contentType, "multipart") !== false) {
  132. /* NB! Plupload currently changes the file type for all uploaded files
  133. to 'application/octet-stream' - ref http://www.plupload.com/punbb/viewtopic.php?id=58
  134. Using the PHP Fileinfo extension as a work-around.
  135. */
  136. if ($_FILES['file']['type'] == 'application/octet-stream') {
  137. // Pluplod has probably messed with the file type
  138. if (function_exists('finfo_open')) {
  139. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  140. if (!$finfo) {
  141. debug("Opening fileinfo database failed");
  142. } else {
  143. $_FILES['file']['type'] = finfo_file($finfo, $_FILES['file']['tmp_name']);
  144. finfo_close($finfo);
  145. }
  146. }
  147. }
  148. // Only allowing user approved file types.
  149. $allowedtypes = array_map('trim', explode(',', $PIVOTX['config']->get('upload_accept')));
  150. if (!in_array($_FILES['file']['type'], $allowedtypes)) {
  151. $msg = sprintf(__("Illegal file type %s uploaded. Check your %s setting."), $_FILES['file']['type'], __('Allow filetypes'));
  152. die('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "'.$msg.'"}, "id" : "id"}');
  153. // Argh! This die statement is *not* reflected in the upload dialog at all.
  154. }
  155. if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
  156. // Open temp file
  157. $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
  158. if ($out) {
  159. // Read binary input stream and append it to temp file
  160. $in = fopen($_FILES['file']['tmp_name'], "rb");
  161. if ($in) {
  162. while ($buff = fread($in, 4096))
  163. fwrite($out, $buff);
  164. } else
  165. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  166. fclose($out);
  167. unlink($_FILES['file']['tmp_name']);
  168. } else {
  169. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  170. }
  171. } else {
  172. die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
  173. }
  174. } else {
  175. // Open temp file
  176. $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
  177. if ($out) {
  178. // Read binary input stream and append it to temp file
  179. $in = fopen("php://input", "rb");
  180. if ($in) {
  181. while ($buff = fread($in, 4096))
  182. fwrite($out, $buff);
  183. } else
  184. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  185. fclose($out);
  186. } else
  187. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  188. }
  189. // Return JSON-RPC response
  190. die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
  191. ?>