plupload.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. <?php
  2. /**
  3. * @file
  4. * Implementation of plupload.module.
  5. */
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function plupload_menu() {
  10. $items['plupload-handle-uploads'] = array(
  11. 'title' => 'Handles uploads',
  12. 'page callback' => 'plupload_handle_uploads',
  13. 'type' => MENU_CALLBACK,
  14. 'access callback' => 'plupload_upload_access',
  15. 'access arguments' => array('access content'),
  16. );
  17. $items['plupload-test'] = array(
  18. 'title' => 'Test Plupload',
  19. 'page callback' => 'drupal_get_form',
  20. 'page arguments' => array('plupload_test'),
  21. // @todo: change this to something appropriate, not sure what.
  22. 'access arguments' => array('Administer site configuration'),
  23. 'type' => MENU_CALLBACK,
  24. );
  25. return $items;
  26. }
  27. /**
  28. * Verifies the token for this request.
  29. */
  30. function plupload_upload_access() {
  31. foreach (func_get_args() as $permission) {
  32. if (!user_access($permission)) {
  33. return FALSE;
  34. }
  35. }
  36. return !empty($_REQUEST['plupload_token']) && drupal_valid_token($_REQUEST['plupload_token'], 'plupload-handle-uploads');
  37. }
  38. /**
  39. * Form callback function for test page visible at URL "plupload-test".
  40. */
  41. function plupload_test($form, &$form_state) {
  42. $form['pud'] = array(
  43. '#type' => 'plupload',
  44. '#title' => 'Plupload',
  45. // '#validators' => array(...);
  46. );
  47. $form['submit'] = array(
  48. '#type' => 'submit',
  49. '#value' => 'Submit',
  50. );
  51. return $form;
  52. }
  53. /**
  54. * Submit callback for plupload_test form.
  55. */
  56. function plupload_test_submit($form, &$form_state) {
  57. $saved_files = array();
  58. $scheme = variable_get('file_default_scheme', 'public') . '://';
  59. // We can't use file_save_upload() because of
  60. // http://www.jacobsingh.name/content/tight-coupling-no-not
  61. // file_uri_to_object();
  62. foreach ($form_state['values']['pud'] as $uploaded_file) {
  63. if ($uploaded_file['status'] == 'done') {
  64. $source = $uploaded_file['tmppath'];
  65. $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
  66. // Rename it to its original name, and put it in its final home.
  67. // Note - not using file_move here because if we call file_get_mime
  68. // (in file_uri_to_object) while it has a .tmp extension, it horks.
  69. $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
  70. $file = plupload_file_uri_to_object($destination);
  71. file_save($file);
  72. $saved_files[] = $file;
  73. }
  74. else {
  75. // @todo: move this to element validate or something and clean up t().
  76. form_set_error('pud', "Upload of {$uploaded_file['name']} failed");
  77. }
  78. }
  79. }
  80. /**
  81. * Implements hook_element_info().
  82. */
  83. function plupload_element_info() {
  84. $types = array();
  85. $module_path = drupal_get_path('module', 'plupload');
  86. $types['plupload'] = array(
  87. '#input' => TRUE,
  88. '#attributes' => array('class' => array('plupload-element')),
  89. // @todo
  90. // '#element_validate' => array('file_managed_file_validate'),
  91. '#theme_wrappers' => array('form_element'),
  92. '#theme' => 'container',
  93. '#value_callback' => 'plupload_element_value',
  94. '#attached' => array(
  95. 'library' => array(array('plupload', 'plupload')),
  96. 'js' => array($module_path . '/plupload.js'),
  97. 'css' => array($module_path . '/plupload.css'),
  98. ),
  99. '#process' => array('plupload_element_process'),
  100. '#element_validate' => array('plupload_element_validate'),
  101. '#pre_render' => array('plupload_element_pre_render'),
  102. );
  103. return $types;
  104. }
  105. /**
  106. * Validate callback for plupload form element.
  107. */
  108. function plupload_element_value(&$element, $input = FALSE, $form_state = NULL) {
  109. $id = $element['#id'];
  110. $files = array();
  111. foreach ($form_state['input'] as $key => $value) {
  112. if (preg_match('/' . $id . '_([0-9]+)_(.*)/', $key, $reg)) {
  113. $i = $reg[1];
  114. $key = $reg[2];
  115. // Only add the keys we expect.
  116. if (!in_array($key, array('tmpname', 'name', 'status'))) {
  117. continue;
  118. }
  119. // Munge the submitted file names for security.
  120. //
  121. // Similar munging is normally done by file_save_upload(), but submit
  122. // handlers for forms containing plupload elements can't use
  123. // file_save_upload(), for reasons discussed in plupload_test_submit().
  124. // So we have to do this for them.
  125. //
  126. // Note that we do the munging here in the value callback function
  127. // (rather than during form validation or elsewhere) because we want to
  128. // actually modify the submitted values rather than reject them outright;
  129. // file names that require munging can be innocent and do not necessarily
  130. // indicate an attempted exploit. Actual validation of the file names is
  131. // performed later, in plupload_element_validate().
  132. if (in_array($key, array('tmpname', 'name'))) {
  133. // Find the whitelist of extensions to use when munging. If there are
  134. // none, we'll be adding default ones in plupload_element_process(), so
  135. // use those here.
  136. if (isset($element['#upload_validators']['file_validate_extensions'][0])) {
  137. $extensions = $element['#upload_validators']['file_validate_extensions'][0];
  138. }
  139. else {
  140. $validators = _plupload_default_upload_validators();
  141. $extensions = $validators['file_validate_extensions'][0];
  142. }
  143. $value = file_munge_filename($value, $extensions, FALSE);
  144. // To prevent directory traversal issues, make sure the file name does
  145. // not contain any directory components in it. (This more properly
  146. // belongs in the form validation step, but it's simpler to do here so
  147. // that we don't have to deal with the temporary file names during form
  148. // validation and can just focus on the final file name.)
  149. //
  150. // This step is necessary since this module allows a large amount of
  151. // flexibility in where its files are placed (for example, they could
  152. // be intended for public://subdirectory rather than public://, and we
  153. // don't want an attacker to be able to get them back into the top
  154. // level of public:// in that case).
  155. $value = rtrim(basename($value), '.');
  156. // Based on the same feture from file_save_upload().
  157. if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js)(\.|$)/i', $value) && (substr($value, -4) != '.txt')) {
  158. $value .= '.txt';
  159. // The .txt extension may not be in the allowed list of extensions.
  160. // We have to add it here or else the file upload will fail.
  161. if (!empty($extensions)) {
  162. $element['#upload_validators']['file_validate_extensions'][0] .= ' txt';
  163. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $value)));
  164. }
  165. }
  166. }
  167. // The temporary file name has to be processed further so it matches what
  168. // was used when the file was written; see plupload_handle_uploads().
  169. if ($key == 'tmpname') {
  170. $value = _plupload_fix_temporary_filename($value);
  171. // We also define an extra key 'tmppath' which is useful so that submit
  172. // handlers do not need to know which directory plupload stored the
  173. // temporary files in before trying to copy them.
  174. $files[$i]['tmppath'] = variable_get('plupload_temporary_uri', 'temporary://') . $value;
  175. }
  176. elseif ($key == 'name') {
  177. if (module_exists('transliteration')) {
  178. $value = transliteration_clean_filename($value);
  179. }
  180. }
  181. // Store the final value in the array we will return.
  182. $files[$i][$key] = $value;
  183. }
  184. }
  185. return $files;
  186. }
  187. /**
  188. * Process callback (#process) for plupload form element.
  189. */
  190. function plupload_element_process($element) {
  191. // Start session if not there yet. We need session if we want security
  192. // tokens to work properly.
  193. if (!drupal_session_started()) {
  194. drupal_session_start();
  195. }
  196. if (!isset($element['#upload_validators'])) {
  197. $element['#upload_validators'] = array();
  198. }
  199. $element['#upload_validators'] += _plupload_default_upload_validators();
  200. return $element;
  201. }
  202. /**
  203. * Element validation handler for a Plupload element.
  204. */
  205. function plupload_element_validate($element, &$form_state) {
  206. foreach ($element['#value'] as $file_info) {
  207. // Here we create a $file object for a file that doesn't exist yet,
  208. // because saving the file to its destination is done in a submit handler.
  209. // Using tmp path will give validators access to the actual file on disk and
  210. // filesize information. We manually modify filename and mime to allow
  211. // extension checks.
  212. $file = plupload_file_uri_to_object($file_info['tmppath']);
  213. $destination = variable_get('file_default_scheme', 'public') . '://' . $file_info['name'];
  214. $destination = file_stream_wrapper_uri_normalize($destination);
  215. $file->filename = basename($destination);
  216. $file->filemime = file_get_mimetype($destination);
  217. foreach (file_validate($file, $element['#upload_validators']) as $error_message) {
  218. $message = t('The specified file %name could not be uploaded.', array('%name' => $file->filename));
  219. form_error($element, $message . ' ' . $error_message);
  220. }
  221. }
  222. }
  223. /**
  224. * Pre render (#pre_render) callback to attach JS settings for the element.
  225. */
  226. function plupload_element_pre_render($element) {
  227. $settings = isset($element['#plupload_settings']) ? $element['#plupload_settings'] : array();
  228. // The Plupload library supports client-side validation of file extension, so
  229. // pass along the information for it to do that. However, as with all client-
  230. // side validation, this is a UI enhancement only, and not a replacement for
  231. // server-side validation.
  232. if (empty($settings['filters']) && isset($element['#upload_validators']['file_validate_extensions'][0])) {
  233. $settings['filters'][] = array(
  234. // @todo Some runtimes (e.g., flash) require a non-empty title for each
  235. // filter, but I don't know what this title is used for. Seems a shame
  236. // to hard-code it, but what's a good way to avoid that?
  237. 'title' => t('Allowed files'),
  238. 'extensions' => str_replace(' ', ',', $element['#upload_validators']['file_validate_extensions'][0]),
  239. );
  240. }
  241. // Add a specific submit element that we want to click if one is specified.
  242. if (!empty($element['#submit_element'])) {
  243. $settings['submit_element'] = $element['#submit_element'];
  244. }
  245. if (empty($element['#description'])) {
  246. $element['#description'] = '';
  247. }
  248. $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
  249. $element['#attached']['js'][] = array(
  250. 'type' => 'setting',
  251. 'data' => array('plupload' => array($element['#id'] => $settings)),
  252. );
  253. return $element;
  254. }
  255. /**
  256. * Returns the path to the plupload library.
  257. */
  258. function _plupload_library_path() {
  259. return variable_get('plupload_library_path', module_exists('libraries') ? libraries_get_path('plupload') : 'sites/all/libraries/plupload');
  260. }
  261. /**
  262. * Implements hook_library().
  263. */
  264. function plupload_library() {
  265. $library_path = _plupload_library_path();
  266. $libraries['plupload'] = array(
  267. 'title' => 'Plupload',
  268. 'website' => 'http://www.plupload.com',
  269. 'version' => '1.5.1.1',
  270. 'js' => array(
  271. // @todo - only add gears JS if gears is an enabled runtime.
  272. // $library_path . '/js/gears_init.js' => array(),
  273. $library_path . '/js/jquery.plupload.queue/jquery.plupload.queue.js' => array(),
  274. $library_path . '/js/plupload.full.js' => array(),
  275. 0 => array(
  276. 'type' => 'setting',
  277. 'data' => array(
  278. 'plupload' => array(
  279. // Element-specific settings get keyed by the element id (see
  280. // plupload_element_pre_render()), so put default settings in
  281. // '_default' (Drupal element ids do not have underscores, because
  282. // they have hyphens instead).
  283. '_default' => array(
  284. // @todo Provide a settings page for configuring these.
  285. 'runtimes' => 'html5,flash,html4',
  286. 'url' => url('plupload-handle-uploads', array('query' => array('plupload_token' => drupal_get_token('plupload-handle-uploads')))),
  287. 'max_file_size' => file_upload_max_size() . 'b',
  288. 'chunk_size' => parse_size(ini_get('post_max_size')) . 'b',
  289. 'unique_names' => TRUE,
  290. 'flash_swf_url' => file_create_url($library_path . '/js/plupload.flash.swf'),
  291. 'silverlight_xap_url' => file_create_url($library_path . '/js/plupload.silverlight.xap'),
  292. ),
  293. // The plupload.js integration file in the module folder can do
  294. // additional browser checking to remove unsupported runtimes.
  295. // This is in addition to what is done by the Plupload library.
  296. '_requirements' => array(
  297. 'html5' => array(
  298. // The Plupload library recognizes Firefox 3.5 as supporting
  299. // HTML 5, but Firefox 3.5 does not support the HTML 5
  300. // "multiple" attribute for file input controls. This makes the
  301. // html5 runtime much less appealing, so we treat all Firefox
  302. // versions less than 3.6 as ineligible for the html5 runtime.
  303. 'mozilla' => '1.9.2',
  304. ),
  305. ),
  306. ),
  307. ),
  308. ),
  309. ),
  310. );
  311. if (module_exists('locale')) {
  312. $module_path = drupal_get_path('module', 'plupload');
  313. $libraries['plupload']['js'][$module_path . '/js/i18n.js'] = array('scope' => 'footer');
  314. }
  315. return $libraries;
  316. }
  317. /**
  318. * Callback that handles and saves uploaded files.
  319. *
  320. * This will respond to the URL on which plupoad library will upload files.
  321. */
  322. function plupload_handle_uploads() {
  323. // @todo: Implement file_validate_size();
  324. // Added a variable for this because in HA environments, temporary may need
  325. // to be a shared location for this to work.
  326. $temp_directory = variable_get('plupload_temporary_uri', 'temporary://');
  327. $writable = file_prepare_directory($temp_directory, FILE_CREATE_DIRECTORY);
  328. if (!$writable) {
  329. die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "Failed to open temporary directory."}, "id" : "id"}');
  330. }
  331. // Try to make sure this is private via htaccess.
  332. file_create_htaccess($temp_directory, TRUE);
  333. // Chunk it?
  334. $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
  335. // Get and clean the filename.
  336. $file_name = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
  337. $file_name = _plupload_fix_temporary_filename($file_name);
  338. // Check the file name for security reasons; it must contain letters, numbers
  339. // and underscores followed by a (single) ".tmp" extension. Since this check
  340. // is more stringent than the one performed in plupload_element_value(), we
  341. // do not need to run the checks performed in that function here. This is
  342. // fortunate, because it would be difficult for us to get the correct list of
  343. // allowed extensions to pass in to file_munge_filename() from this point in
  344. // the code (outside the form API).
  345. if (empty($file_name) || !preg_match('/^\w+\.tmp$/', $file_name)) {
  346. die('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "Invalid temporary file name."}, "id" : "id"}');
  347. }
  348. // Look for the content type header.
  349. if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
  350. $content_type = $_SERVER["HTTP_CONTENT_TYPE"];
  351. }
  352. if (isset($_SERVER["CONTENT_TYPE"])) {
  353. $content_type = $_SERVER["CONTENT_TYPE"];
  354. }
  355. // Is this a multipart upload?.
  356. if (strpos($content_type, "multipart") !== FALSE) {
  357. if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
  358. // Open temp file.
  359. $out = fopen($temp_directory . $file_name, $chunk == 0 ? "wb" : "ab");
  360. if ($out) {
  361. // Read binary input stream and append it to temp file.
  362. $in = fopen($_FILES['file']['tmp_name'], "rb");
  363. if ($in) {
  364. while ($buff = fread($in, 4096)) {
  365. fwrite($out, $buff);
  366. }
  367. fclose($in);
  368. }
  369. else {
  370. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  371. }
  372. fclose($out);
  373. drupal_unlink($_FILES['file']['tmp_name']);
  374. }
  375. else {
  376. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  377. }
  378. }
  379. else {
  380. die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
  381. }
  382. }
  383. else {
  384. // Open temp file.
  385. $out = fopen($temp_directory . $file_name, $chunk == 0 ? "wb" : "ab");
  386. if ($out) {
  387. // Read binary input stream and append it to temp file.
  388. $in = fopen("php://input", "rb");
  389. if ($in) {
  390. while ($buff = fread($in, 4096)) {
  391. fwrite($out, $buff);
  392. }
  393. fclose($in);
  394. }
  395. else {
  396. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  397. }
  398. fclose($out);
  399. }
  400. else {
  401. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  402. }
  403. }
  404. // Return JSON-RPC response.
  405. die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
  406. }
  407. /**
  408. * Returns a file object which can be passed to file_save().
  409. *
  410. * @param string $uri
  411. * A string containing the URI, path, or filename.
  412. *
  413. * @return boolean
  414. * A file object, or FALSE on error.
  415. *
  416. * @todo Replace with calls to this function with file_uri_to_object() when
  417. * http://drupal.org/node/685818 is fixed in core.
  418. */
  419. function plupload_file_uri_to_object($uri) {
  420. global $user;
  421. $uri = file_stream_wrapper_uri_normalize($uri);
  422. $wrapper = file_stream_wrapper_get_instance_by_uri($uri);
  423. $file = new StdClass();
  424. $file->uid = $user->uid;
  425. $file->filename = basename($uri);
  426. $file->uri = $uri;
  427. $file->filemime = file_get_mimetype($uri);
  428. // This is gagged because some uris will not support it.
  429. $file->filesize = @filesize($uri);
  430. $file->timestamp = REQUEST_TIME;
  431. $file->status = FILE_STATUS_PERMANENT;
  432. return $file;
  433. }
  434. /**
  435. * Fix the temporary filename provided by the plupload library.
  436. *
  437. * Newer versions of the plupload JavaScript library upload temporary files
  438. * with names that contain the intended final prefix of the uploaded file
  439. * (e.g., ".jpg" or ".png"). Older versions of the plupload library always use
  440. * ".tmp" as the temporary file extension.
  441. *
  442. * We prefer the latter behavior, since although the plupload temporary
  443. * directory where these files live is always expected to be private (and we
  444. * protect it via .htaccess; see plupload_handle_uploads()), in case it ever
  445. * isn't we don't want people to be able to upload files with an arbitrary
  446. * extension into that directory.
  447. *
  448. * This function therefore fixes the plupload temporary filenames so that they
  449. * will always use a ".tmp" extension.
  450. *
  451. * @param string $filename
  452. * The original temporary filename provided by the plupload library.
  453. *
  454. * @return string
  455. * The corrected temporary filename, with a ".tmp" extension replacing the
  456. * original one.
  457. */
  458. function _plupload_fix_temporary_filename($filename) {
  459. $pos = strpos($filename, '.');
  460. if ($pos !== FALSE) {
  461. $filename = substr_replace($filename, '.tmp', $pos);
  462. }
  463. return $filename;
  464. }
  465. /**
  466. * Helper function to add defaults to $element['#upload_validators'].
  467. */
  468. function _plupload_default_upload_validators() {
  469. return array(
  470. // See file_save_upload() for details.
  471. 'file_validate_extensions' => array('jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'),
  472. );
  473. }