upload.php 9.7 KB

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