upload.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. /**
  3. * @author Arthur Schiwon <blizzz@owncloud.com>
  4. * @author Bart Visscher <bartv@thisnet.nl>
  5. * @author Björn Schießle <schiessle@owncloud.com>
  6. * @author Clark Tomlinson <fallen013@gmail.com>
  7. * @author Florian Pritz <bluewind@xinu.at>
  8. * @author Frank Karlitschek <frank@owncloud.org>
  9. * @author Individual IT Services <info@individual-it.net>
  10. * @author Joas Schilling <nickvergessen@owncloud.com>
  11. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  12. * @author Lukas Reschke <lukas@owncloud.com>
  13. * @author Luke Policinski <lpolicinski@gmail.com>
  14. * @author Robin Appelman <icewind@owncloud.com>
  15. * @author Roman Geber <rgeber@owncloudapps.com>
  16. * @author TheSFReader <TheSFReader@gmail.com>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Vincent Petry <pvince81@owncloud.com>
  19. *
  20. * @copyright Copyright (c) 2016, ownCloud, Inc.
  21. * @license AGPL-3.0
  22. *
  23. * This code is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU Affero General Public License, version 3,
  25. * as published by the Free Software Foundation.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU Affero General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU Affero General Public License, version 3,
  33. * along with this program. If not, see <http://www.gnu.org/licenses/>
  34. *
  35. */
  36. \OC::$server->getSession()->close();
  37. // Firefox and Konqueror tries to download application/json for me. --Arthur
  38. OCP\JSON::setContentTypeHeader('text/plain');
  39. // If a directory token is sent along check if public upload is permitted.
  40. // If not, check the login.
  41. // If no token is sent along, rely on login only
  42. $errorCode = null;
  43. $l = \OC::$server->getL10N('files');
  44. if (empty($_POST['dirToken'])) {
  45. // The standard case, files are uploaded through logged in users :)
  46. OCP\JSON::checkLoggedIn();
  47. $dir = isset($_POST['dir']) ? (string)$_POST['dir'] : '';
  48. if (!$dir || empty($dir) || $dir === false) {
  49. OCP\JSON::error(array('data' => array_merge(array('message' => $l->t('Unable to set upload directory.')))));
  50. die();
  51. }
  52. } else {
  53. // TODO: ideally this code should be in files_sharing/ajax/upload.php
  54. // and the upload/file transfer code needs to be refactored into a utility method
  55. // that could be used there
  56. \OC_User::setIncognitoMode(true);
  57. $publicDirectory = !empty($_POST['subdir']) ? (string)$_POST['subdir'] : '/';
  58. $linkItem = OCP\Share::getShareByToken((string)$_POST['dirToken']);
  59. if ($linkItem === false) {
  60. OCP\JSON::error(array('data' => array_merge(array('message' => $l->t('Invalid Token')))));
  61. die();
  62. }
  63. if (!($linkItem['permissions'] & \OCP\Constants::PERMISSION_CREATE)) {
  64. OCP\JSON::checkLoggedIn();
  65. } else {
  66. // resolve reshares
  67. $rootLinkItem = OCP\Share::resolveReShare($linkItem);
  68. OCP\JSON::checkUserExists($rootLinkItem['uid_owner']);
  69. // Setup FS with owner
  70. OC_Util::tearDownFS();
  71. OC_Util::setupFS($rootLinkItem['uid_owner']);
  72. // The token defines the target directory (security reasons)
  73. $path = \OC\Files\Filesystem::getPath($linkItem['file_source']);
  74. if($path === null) {
  75. OCP\JSON::error(array('data' => array_merge(array('message' => $l->t('Unable to set upload directory.')))));
  76. die();
  77. }
  78. $dir = sprintf(
  79. "/%s/%s",
  80. $path,
  81. $publicDirectory
  82. );
  83. if (!$dir || empty($dir) || $dir === false) {
  84. OCP\JSON::error(array('data' => array_merge(array('message' => $l->t('Unable to set upload directory.')))));
  85. die();
  86. }
  87. $dir = rtrim($dir, '/');
  88. }
  89. }
  90. OCP\JSON::callCheck();
  91. // get array with current storage stats (e.g. max file size)
  92. $storageStats = \OCA\Files\Helper::buildFileStorageStatistics($dir);
  93. if (!isset($_FILES['files'])) {
  94. OCP\JSON::error(array('data' => array_merge(array('message' => $l->t('No file was uploaded. Unknown error')), $storageStats)));
  95. exit();
  96. }
  97. foreach ($_FILES['files']['error'] as $error) {
  98. if ($error != 0) {
  99. $errors = array(
  100. UPLOAD_ERR_OK => $l->t('There is no error, the file uploaded with success'),
  101. UPLOAD_ERR_INI_SIZE => $l->t('The uploaded file exceeds the upload_max_filesize directive in php.ini: ')
  102. . OC::$server->getIniWrapper()->getNumeric('upload_max_filesize'),
  103. UPLOAD_ERR_FORM_SIZE => $l->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  104. UPLOAD_ERR_PARTIAL => $l->t('The uploaded file was only partially uploaded'),
  105. UPLOAD_ERR_NO_FILE => $l->t('No file was uploaded'),
  106. UPLOAD_ERR_NO_TMP_DIR => $l->t('Missing a temporary folder'),
  107. UPLOAD_ERR_CANT_WRITE => $l->t('Failed to write to disk'),
  108. );
  109. $errorMessage = $errors[$error];
  110. \OC::$server->getLogger()->alert("Upload error: $error - $errorMessage", array('app' => 'files'));
  111. OCP\JSON::error(array('data' => array_merge(array('message' => $errorMessage), $storageStats)));
  112. exit();
  113. }
  114. }
  115. $files = $_FILES['files'];
  116. $error = false;
  117. $maxUploadFileSize = $storageStats['uploadMaxFilesize'];
  118. $maxHumanFileSize = OCP\Util::humanFileSize($maxUploadFileSize);
  119. $totalSize = 0;
  120. foreach ($files['size'] as $size) {
  121. $totalSize += $size;
  122. }
  123. if ($maxUploadFileSize >= 0 and $totalSize > $maxUploadFileSize) {
  124. OCP\JSON::error(array('data' => array('message' => $l->t('Not enough storage available'),
  125. 'uploadMaxFilesize' => $maxUploadFileSize,
  126. 'maxHumanFilesize' => $maxHumanFileSize)));
  127. exit();
  128. }
  129. $result = array();
  130. if (\OC\Files\Filesystem::isValidPath($dir) === true) {
  131. $fileCount = count($files['name']);
  132. for ($i = 0; $i < $fileCount; $i++) {
  133. if (isset($_POST['resolution'])) {
  134. $resolution = $_POST['resolution'];
  135. } else {
  136. $resolution = null;
  137. }
  138. // target directory for when uploading folders
  139. $relativePath = '';
  140. if(!empty($_POST['file_directory'])) {
  141. $relativePath = '/'.$_POST['file_directory'];
  142. }
  143. // $path needs to be normalized - this failed within drag'n'drop upload to a sub-folder
  144. if ($resolution === 'autorename') {
  145. // append a number in brackets like 'filename (2).ext'
  146. $target = OCP\Files::buildNotExistingFileName($dir . $relativePath, $files['name'][$i]);
  147. } else {
  148. $target = \OC\Files\Filesystem::normalizePath($dir . $relativePath.'/'.$files['name'][$i]);
  149. }
  150. // relative dir to return to the client
  151. if (isset($publicDirectory)) {
  152. // path relative to the public root
  153. $returnedDir = $publicDirectory . $relativePath;
  154. } else {
  155. // full path
  156. $returnedDir = $dir . $relativePath;
  157. }
  158. $returnedDir = \OC\Files\Filesystem::normalizePath($returnedDir);
  159. $exists = \OC\Files\Filesystem::file_exists($target);
  160. if ($exists) {
  161. $updatable = \OC\Files\Filesystem::isUpdatable($target);
  162. }
  163. if ( ! $exists || ($updatable && $resolution === 'replace' ) ) {
  164. // upload and overwrite file
  165. try
  166. {
  167. if (is_uploaded_file($files['tmp_name'][$i]) and \OC\Files\Filesystem::fromTmpFile($files['tmp_name'][$i], $target)) {
  168. // updated max file size after upload
  169. $storageStats = \OCA\Files\Helper::buildFileStorageStatistics($dir);
  170. $meta = \OC\Files\Filesystem::getFileInfo($target);
  171. if ($meta === false) {
  172. $error = $l->t('The target folder has been moved or deleted.');
  173. $errorCode = 'targetnotfound';
  174. } else {
  175. $data = \OCA\Files\Helper::formatFileInfo($meta);
  176. $data['status'] = 'success';
  177. $data['originalname'] = $files['name'][$i];
  178. $data['uploadMaxFilesize'] = $maxUploadFileSize;
  179. $data['maxHumanFilesize'] = $maxHumanFileSize;
  180. $data['permissions'] = $meta['permissions'];
  181. $data['directory'] = $returnedDir;
  182. $result[] = $data;
  183. }
  184. } else {
  185. $error = $l->t('Upload failed. Could not find uploaded file');
  186. }
  187. } catch(Exception $ex) {
  188. $error = $ex->getMessage();
  189. }
  190. } else {
  191. // file already exists
  192. $meta = \OC\Files\Filesystem::getFileInfo($target);
  193. if ($meta === false) {
  194. $error = $l->t('Upload failed. Could not get file info.');
  195. } else {
  196. $data = \OCA\Files\Helper::formatFileInfo($meta);
  197. if ($updatable) {
  198. $data['status'] = 'existserror';
  199. } else {
  200. $data['status'] = 'readonly';
  201. }
  202. $data['originalname'] = $files['name'][$i];
  203. $data['uploadMaxFilesize'] = $maxUploadFileSize;
  204. $data['maxHumanFilesize'] = $maxHumanFileSize;
  205. $data['permissions'] = $meta['permissions'];
  206. $data['directory'] = $returnedDir;
  207. $result[] = $data;
  208. }
  209. }
  210. }
  211. } else {
  212. $error = $l->t('Invalid directory.');
  213. }
  214. if ($error === false) {
  215. OCP\JSON::encodedPrint($result);
  216. } else {
  217. OCP\JSON::error(array(array('data' => array_merge(array('message' => $error, 'code' => $errorCode), $storageStats))));
  218. }