plupload.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. // @todo 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. // Need more investigation into what else is needed for it to be okay to
  210. // call file_validate(). For example, file_validate_size() will not have
  211. // access to a meaningful $file->filesize unless we set that here. For
  212. // now, we can at least rely on file_validate_extensions() running
  213. // successfully.
  214. $destination = variable_get('file_default_scheme', 'public') . '://' . $file_info['name'];
  215. $file = plupload_file_uri_to_object($destination);
  216. foreach (file_validate($file, $element['#upload_validators']) as $error_message) {
  217. $message = t('The specified file %name could not be uploaded.', array('%name' => $file->filename));
  218. form_error($element, $message . ' ' . $error_message);
  219. }
  220. }
  221. }
  222. /**
  223. * Pre render (#pre_render) callback to attach JS settings for the element.
  224. */
  225. function plupload_element_pre_render($element) {
  226. $settings = isset($element['#plupload_settings']) ? $element['#plupload_settings'] : array();
  227. // The Plupload library supports client-side validation of file extension, so
  228. // pass along the information for it to do that. However, as with all client-
  229. // side validation, this is a UI enhancement only, and not a replacement for
  230. // server-side validation.
  231. if (empty($settings['filters']) && isset($element['#upload_validators']['file_validate_extensions'][0])) {
  232. $settings['filters'][] = array(
  233. // @todo Some runtimes (e.g., flash) require a non-empty title for each
  234. // filter, but I don't know what this title is used for. Seems a shame
  235. // to hard-code it, but what's a good way to avoid that?
  236. 'title' => t('Allowed files'),
  237. 'extensions' => str_replace(' ', ',', $element['#upload_validators']['file_validate_extensions'][0]),
  238. );
  239. }
  240. if (empty($element['#description'])) {
  241. $element['#description'] = '';
  242. }
  243. $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
  244. $element['#attached']['js'][] = array(
  245. 'type' => 'setting',
  246. 'data' => array('plupload' => array($element['#id'] => $settings)),
  247. );
  248. return $element;
  249. }
  250. /**
  251. * Returns the path to the plupload library.
  252. */
  253. function _plupload_library_path() {
  254. return variable_get('plupload_library_path', module_exists('libraries') ? libraries_get_path('plupload') : 'sites/all/libraries/plupload');
  255. }
  256. /**
  257. * Implements hook_library().
  258. */
  259. function plupload_library() {
  260. $library_path = _plupload_library_path();
  261. $libraries['plupload'] = array(
  262. 'title' => 'Plupload',
  263. 'website' => 'http://www.plupload.com',
  264. 'version' => '1.5.1.1',
  265. 'js' => array(
  266. // @todo - only add gears JS if gears is an enabled runtime.
  267. // $library_path . '/js/gears_init.js' => array(),
  268. $library_path . '/js/jquery.plupload.queue/jquery.plupload.queue.js' => array(),
  269. $library_path . '/js/plupload.full.js' => array(),
  270. 0 => array(
  271. 'type' => 'setting',
  272. 'data' => array(
  273. 'plupload' => array(
  274. // Element-specific settings get keyed by the element id (see
  275. // plupload_element_pre_render()), so put default settings in
  276. // '_default' (Drupal element ids do not have underscores, because
  277. // they have hyphens instead).
  278. '_default' => array(
  279. // @todo Provide a settings page for configuring these.
  280. 'runtimes' => 'html5,flash,html4',
  281. 'url' => url('plupload-handle-uploads', array('query' => array('plupload_token' => drupal_get_token('plupload-handle-uploads')))),
  282. 'max_file_size' => file_upload_max_size() . 'b',
  283. 'chunk_size' => parse_size(ini_get('post_max_size')) . 'b',
  284. 'unique_names' => TRUE,
  285. 'flash_swf_url' => file_create_url($library_path . '/js/plupload.flash.swf'),
  286. 'silverlight_xap_url' => file_create_url($library_path . '/js/plupload.silverlight.xap'),
  287. ),
  288. // The plupload.js integration file in the module folder can do
  289. // additional browser checking to remove unsupported runtimes.
  290. // This is in addition to what is done by the Plupload library.
  291. '_requirements' => array(
  292. 'html5' => array(
  293. // The Plupload library recognizes Firefox 3.5 as supporting
  294. // HTML 5, but Firefox 3.5 does not support the HTML 5
  295. // "multiple" attribute for file input controls. This makes the
  296. // html5 runtime much less appealing, so we treat all Firefox
  297. // versions less than 3.6 as ineligible for the html5 runtime.
  298. 'mozilla' => '1.9.2',
  299. ),
  300. ),
  301. ),
  302. ),
  303. ),
  304. ),
  305. );
  306. if (module_exists('locale')) {
  307. $module_path = drupal_get_path('module', 'plupload');
  308. $libraries['plupload']['js'][$module_path . '/js/i18n.js'] = array('scope' => 'footer');
  309. }
  310. return $libraries;
  311. }
  312. /**
  313. * Callback that handles and saves uploaded files.
  314. *
  315. * This will respond to the URL on which plupoad library will upload files.
  316. */
  317. function plupload_handle_uploads() {
  318. // @todo: Implement file_validate_size();
  319. // Added a variable for this because in HA environments, temporary may need
  320. // to be a shared location for this to work.
  321. $temp_directory = variable_get('plupload_temporary_uri', 'temporary://');
  322. $writable = file_prepare_directory($temp_directory, FILE_CREATE_DIRECTORY);
  323. if (!$writable) {
  324. die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "Failed to open temporary directory."}, "id" : "id"}');
  325. }
  326. // Try to make sure this is private via htaccess.
  327. file_create_htaccess($temp_directory, TRUE);
  328. // Chunk it?
  329. $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
  330. // Get and clean the filename.
  331. $file_name = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
  332. $file_name = _plupload_fix_temporary_filename($file_name);
  333. // Check the file name for security reasons; it must contain letters, numbers
  334. // and underscores followed by a (single) ".tmp" extension. Since this check
  335. // is more stringent than the one performed in plupload_element_value(), we
  336. // do not need to run the checks performed in that function here. This is
  337. // fortunate, because it would be difficult for us to get the correct list of
  338. // allowed extensions to pass in to file_munge_filename() from this point in
  339. // the code (outside the form API).
  340. if (empty($file_name) || !preg_match('/^\w+\.tmp$/', $file_name)) {
  341. die('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "Invalid temporary file name."}, "id" : "id"}');
  342. }
  343. // Look for the content type header.
  344. if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
  345. $content_type = $_SERVER["HTTP_CONTENT_TYPE"];
  346. }
  347. if (isset($_SERVER["CONTENT_TYPE"])) {
  348. $content_type = $_SERVER["CONTENT_TYPE"];
  349. }
  350. // Is this a multipart upload?.
  351. if (strpos($content_type, "multipart") !== FALSE) {
  352. if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
  353. // Open temp file.
  354. $out = fopen($temp_directory . $file_name, $chunk == 0 ? "wb" : "ab");
  355. if ($out) {
  356. // Read binary input stream and append it to temp file.
  357. $in = fopen($_FILES['file']['tmp_name'], "rb");
  358. if ($in) {
  359. while ($buff = fread($in, 4096)) {
  360. fwrite($out, $buff);
  361. }
  362. fclose($in);
  363. }
  364. else {
  365. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  366. }
  367. fclose($out);
  368. drupal_unlink($_FILES['file']['tmp_name']);
  369. }
  370. else {
  371. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  372. }
  373. }
  374. else {
  375. die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
  376. }
  377. }
  378. else {
  379. // Open temp file.
  380. $out = fopen($temp_directory . $file_name, $chunk == 0 ? "wb" : "ab");
  381. if ($out) {
  382. // Read binary input stream and append it to temp file.
  383. $in = fopen("php://input", "rb");
  384. if ($in) {
  385. while ($buff = fread($in, 4096)) {
  386. fwrite($out, $buff);
  387. }
  388. fclose($in);
  389. }
  390. else {
  391. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  392. }
  393. fclose($out);
  394. }
  395. else {
  396. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  397. }
  398. }
  399. // Return JSON-RPC response.
  400. die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
  401. }
  402. /**
  403. * Returns a file object which can be passed to file_save().
  404. *
  405. * @param string $uri
  406. * A string containing the URI, path, or filename.
  407. *
  408. * @return boolean
  409. * A file object, or FALSE on error.
  410. *
  411. * @todo Replace with calls to this function with file_uri_to_object() when
  412. * http://drupal.org/node/685818 is fixed in core.
  413. */
  414. function plupload_file_uri_to_object($uri) {
  415. global $user;
  416. $uri = file_stream_wrapper_uri_normalize($uri);
  417. $wrapper = file_stream_wrapper_get_instance_by_uri($uri);
  418. $file = new StdClass();
  419. $file->uid = $user->uid;
  420. $file->filename = basename($uri);
  421. $file->uri = $uri;
  422. $file->filemime = file_get_mimetype($uri);
  423. // This is gagged because some uris will not support it.
  424. $file->filesize = @filesize($uri);
  425. $file->timestamp = REQUEST_TIME;
  426. $file->status = FILE_STATUS_PERMANENT;
  427. return $file;
  428. }
  429. /**
  430. * Fix the temporary filename provided by the plupload library.
  431. *
  432. * Newer versions of the plupload JavaScript library upload temporary files
  433. * with names that contain the intended final prefix of the uploaded file
  434. * (e.g., ".jpg" or ".png"). Older versions of the plupload library always use
  435. * ".tmp" as the temporary file extension.
  436. *
  437. * We prefer the latter behavior, since although the plupload temporary
  438. * directory where these files live is always expected to be private (and we
  439. * protect it via .htaccess; see plupload_handle_uploads()), in case it ever
  440. * isn't we don't want people to be able to upload files with an arbitrary
  441. * extension into that directory.
  442. *
  443. * This function therefore fixes the plupload temporary filenames so that they
  444. * will always use a ".tmp" extension.
  445. *
  446. * @param string $filename
  447. * The original temporary filename provided by the plupload library.
  448. *
  449. * @return string
  450. * The corrected temporary filename, with a ".tmp" extension replacing the
  451. * original one.
  452. */
  453. function _plupload_fix_temporary_filename($filename) {
  454. $pos = strpos($filename, '.');
  455. if ($pos !== FALSE) {
  456. $filename = substr_replace($filename, '.tmp', $pos);
  457. }
  458. return $filename;
  459. }
  460. /**
  461. * Helper function to add defaults to $element['#upload_validators'].
  462. */
  463. function _plupload_default_upload_validators() {
  464. return array(
  465. // See file_save_upload() for details.
  466. 'file_validate_extensions' => array('jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'),
  467. );
  468. }