upload.php 8.4 KB

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