You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ViewController.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author fnuesse <felix.nuesse@t-online.de>
  8. * @author fnuesse <fnuesse@techfak.uni-bielefeld.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Max Kovalenko <mxss1998@yandex.ru>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Nina Pypchenko <22447785+nina-py@users.noreply.github.com>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Roeland Jago Douma <roeland@famdouma.nl>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Vincent Petry <vincent@nextcloud.com>
  20. *
  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. namespace OCA\Files\Controller;
  37. use OCA\Files\Activity\Helper;
  38. use OCA\Files\AppInfo\Application;
  39. use OCA\Files\Event\LoadAdditionalScriptsEvent;
  40. use OCA\Files\Event\LoadSidebar;
  41. use OCA\Files\Service\UserConfig;
  42. use OCA\Files\Service\ViewConfig;
  43. use OCA\Viewer\Event\LoadViewer;
  44. use OCP\App\IAppManager;
  45. use OCP\AppFramework\Controller;
  46. use OCP\AppFramework\Http\Attribute\OpenAPI;
  47. use OCP\AppFramework\Http\ContentSecurityPolicy;
  48. use OCP\AppFramework\Http\RedirectResponse;
  49. use OCP\AppFramework\Http\Response;
  50. use OCP\AppFramework\Http\TemplateResponse;
  51. use OCP\AppFramework\Services\IInitialState;
  52. use OCP\Collaboration\Resources\LoadAdditionalScriptsEvent as ResourcesLoadAdditionalScriptsEvent;
  53. use OCP\Constants;
  54. use OCP\EventDispatcher\IEventDispatcher;
  55. use OCP\Files\Folder;
  56. use OCP\Files\IRootFolder;
  57. use OCP\Files\NotFoundException;
  58. use OCP\Files\Template\ITemplateManager;
  59. use OCP\IConfig;
  60. use OCP\IL10N;
  61. use OCP\IRequest;
  62. use OCP\IURLGenerator;
  63. use OCP\IUserSession;
  64. use OCP\Share\IManager;
  65. /**
  66. * @package OCA\Files\Controller
  67. */
  68. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  69. class ViewController extends Controller {
  70. private IURLGenerator $urlGenerator;
  71. private IL10N $l10n;
  72. private IConfig $config;
  73. private IEventDispatcher $eventDispatcher;
  74. private IUserSession $userSession;
  75. private IAppManager $appManager;
  76. private IRootFolder $rootFolder;
  77. private Helper $activityHelper;
  78. private IInitialState $initialState;
  79. private ITemplateManager $templateManager;
  80. private IManager $shareManager;
  81. private UserConfig $userConfig;
  82. private ViewConfig $viewConfig;
  83. public function __construct(string $appName,
  84. IRequest $request,
  85. IURLGenerator $urlGenerator,
  86. IL10N $l10n,
  87. IConfig $config,
  88. IEventDispatcher $eventDispatcher,
  89. IUserSession $userSession,
  90. IAppManager $appManager,
  91. IRootFolder $rootFolder,
  92. Helper $activityHelper,
  93. IInitialState $initialState,
  94. ITemplateManager $templateManager,
  95. IManager $shareManager,
  96. UserConfig $userConfig,
  97. ViewConfig $viewConfig
  98. ) {
  99. parent::__construct($appName, $request);
  100. $this->urlGenerator = $urlGenerator;
  101. $this->l10n = $l10n;
  102. $this->config = $config;
  103. $this->eventDispatcher = $eventDispatcher;
  104. $this->userSession = $userSession;
  105. $this->appManager = $appManager;
  106. $this->rootFolder = $rootFolder;
  107. $this->activityHelper = $activityHelper;
  108. $this->initialState = $initialState;
  109. $this->templateManager = $templateManager;
  110. $this->shareManager = $shareManager;
  111. $this->userConfig = $userConfig;
  112. $this->viewConfig = $viewConfig;
  113. }
  114. /**
  115. * FIXME: Replace with non static code
  116. *
  117. * @return array
  118. * @throws \OCP\Files\NotFoundException
  119. */
  120. protected function getStorageInfo(string $dir = '/') {
  121. $rootInfo = \OC\Files\Filesystem::getFileInfo('/', false);
  122. return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
  123. }
  124. /**
  125. * @NoCSRFRequired
  126. * @NoAdminRequired
  127. *
  128. * @param string $fileid
  129. * @return TemplateResponse|RedirectResponse
  130. */
  131. public function showFile(string $fileid = null): Response {
  132. if (!$fileid) {
  133. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  134. }
  135. // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
  136. try {
  137. return $this->redirectToFile((int) $fileid);
  138. } catch (NotFoundException $e) {
  139. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
  140. }
  141. }
  142. /**
  143. * @NoCSRFRequired
  144. * @NoAdminRequired
  145. * @UseSession
  146. *
  147. * @param string $dir
  148. * @param string $view
  149. * @param string $fileid
  150. * @param bool $fileNotFound
  151. * @return TemplateResponse|RedirectResponse
  152. */
  153. public function indexView($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  154. return $this->index($dir, $view, $fileid, $fileNotFound);
  155. }
  156. /**
  157. * @NoCSRFRequired
  158. * @NoAdminRequired
  159. * @UseSession
  160. *
  161. * @param string $dir
  162. * @param string $view
  163. * @param string $fileid
  164. * @param bool $fileNotFound
  165. * @return TemplateResponse|RedirectResponse
  166. */
  167. public function indexViewFileid($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  168. return $this->index($dir, $view, $fileid, $fileNotFound);
  169. }
  170. /**
  171. * @NoCSRFRequired
  172. * @NoAdminRequired
  173. * @UseSession
  174. *
  175. * @param string $dir
  176. * @param string $view
  177. * @param string $fileid
  178. * @param bool $fileNotFound
  179. * @return TemplateResponse|RedirectResponse
  180. */
  181. public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  182. if ($fileid !== null && $view !== 'trashbin') {
  183. try {
  184. return $this->redirectToFileIfInTrashbin((int) $fileid);
  185. } catch (NotFoundException $e) {
  186. }
  187. }
  188. // Load the files we need
  189. \OCP\Util::addInitScript('files', 'init');
  190. \OCP\Util::addStyle('files', 'merged');
  191. \OCP\Util::addScript('files', 'main');
  192. $userId = $this->userSession->getUser()->getUID();
  193. // Get all the user favorites to create a submenu
  194. try {
  195. $userFolder = $this->rootFolder->getUserFolder($userId);
  196. $favElements = $this->activityHelper->getFavoriteNodes($userId, true);
  197. $favElements = array_map(fn (Folder $node) => [
  198. 'fileid' => $node->getId(),
  199. 'path' => $userFolder->getRelativePath($node->getPath()),
  200. ], $favElements);
  201. } catch (\RuntimeException $e) {
  202. $favElements = [];
  203. }
  204. // If the file doesn't exists in the folder and
  205. // exists in only one occurrence, redirect to that file
  206. // in the correct folder
  207. if ($fileid && $dir !== '') {
  208. $baseFolder = $this->rootFolder->getUserFolder($userId);
  209. $nodes = $baseFolder->getById((int) $fileid);
  210. if (!empty($nodes)) {
  211. $nodePath = $baseFolder->getRelativePath($nodes[0]->getPath());
  212. $relativePath = $nodePath ? dirname($nodePath) : '';
  213. // If the requested path does not contain the file id
  214. // or if the requested path is not the file id itself
  215. if (count($nodes) === 1 && $relativePath !== $dir && $nodePath !== $dir) {
  216. return $this->redirectToFile((int) $fileid);
  217. }
  218. } else { // fileid does not exist anywhere
  219. $fileNotFound = true;
  220. }
  221. }
  222. try {
  223. // If view is files, we use the directory, otherwise we use the root storage
  224. $storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
  225. } catch(\Exception $e) {
  226. $storageInfo = $this->getStorageInfo();
  227. }
  228. $this->initialState->provideInitialState('storageStats', $storageInfo);
  229. $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
  230. $this->initialState->provideInitialState('viewConfigs', $this->viewConfig->getConfigs());
  231. $this->initialState->provideInitialState('favoriteFolders', $favElements);
  232. // File sorting user config
  233. $filesSortingConfig = json_decode($this->config->getUserValue($userId, 'files', 'files_sorting_configs', '{}'), true);
  234. $this->initialState->provideInitialState('filesSortingConfig', $filesSortingConfig);
  235. // Forbidden file characters
  236. /** @var string[] */
  237. $forbiddenCharacters = $this->config->getSystemValue('forbidden_chars', []);
  238. $this->initialState->provideInitialState('forbiddenCharacters', Constants::FILENAME_INVALID_CHARS . implode('', $forbiddenCharacters));
  239. $event = new LoadAdditionalScriptsEvent();
  240. $this->eventDispatcher->dispatchTyped($event);
  241. $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
  242. $this->eventDispatcher->dispatchTyped(new LoadSidebar());
  243. // Load Viewer scripts
  244. if (class_exists(LoadViewer::class)) {
  245. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  246. }
  247. $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
  248. $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
  249. $response = new TemplateResponse(
  250. Application::APP_ID,
  251. 'index',
  252. );
  253. $policy = new ContentSecurityPolicy();
  254. $policy->addAllowedFrameDomain('\'self\'');
  255. // Allow preview service worker
  256. $policy->addAllowedWorkerSrcDomain('\'self\'');
  257. $response->setContentSecurityPolicy($policy);
  258. $this->provideInitialState($dir, $fileid);
  259. return $response;
  260. }
  261. /**
  262. * Add openFileInfo in initialState.
  263. * @param string $dir - the ?dir= URL param
  264. * @param string $fileid - the fileid URL param
  265. * @return void
  266. */
  267. private function provideInitialState(string $dir, ?string $fileid): void {
  268. if ($fileid === null) {
  269. return;
  270. }
  271. $user = $this->userSession->getUser();
  272. if ($user === null) {
  273. return;
  274. }
  275. $uid = $user->getUID();
  276. $userFolder = $this->rootFolder->getUserFolder($uid);
  277. $node = $userFolder->getFirstNodeById((int) $fileid);
  278. if ($node === null) {
  279. return;
  280. }
  281. // properly format full path and make sure
  282. // we're relative to the user home folder
  283. $isRoot = $node === $userFolder;
  284. $path = $userFolder->getRelativePath($node->getPath());
  285. $directory = $userFolder->getRelativePath($node->getParent()->getPath());
  286. // Prevent opening a file from another folder.
  287. if ($dir !== $directory) {
  288. return;
  289. }
  290. $this->initialState->provideInitialState(
  291. 'openFileInfo', [
  292. 'id' => $node->getId(),
  293. 'name' => $isRoot ? '' : $node->getName(),
  294. 'path' => $path,
  295. 'directory' => $directory,
  296. 'mime' => $node->getMimetype(),
  297. 'type' => $node->getType(),
  298. 'permissions' => $node->getPermissions(),
  299. ]
  300. );
  301. }
  302. /**
  303. * Redirects to the trashbin file list and highlight the given file id
  304. *
  305. * @param int $fileId file id to show
  306. * @return RedirectResponse redirect response or not found response
  307. * @throws NotFoundException
  308. */
  309. private function redirectToFileIfInTrashbin($fileId): RedirectResponse {
  310. $uid = $this->userSession->getUser()->getUID();
  311. $baseFolder = $this->rootFolder->getUserFolder($uid);
  312. $node = $baseFolder->getFirstNodeById($fileId);
  313. $params = [];
  314. if (!$node && $this->appManager->isEnabledForUser('files_trashbin')) {
  315. /** @var Folder */
  316. $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
  317. $node = $baseFolder->getFirstNodeById($fileId);
  318. $params['view'] = 'trashbin';
  319. if ($node) {
  320. $params['fileid'] = $fileId;
  321. if ($node instanceof Folder) {
  322. // set the full path to enter the folder
  323. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  324. } else {
  325. // set parent path as dir
  326. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  327. }
  328. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  329. }
  330. }
  331. throw new NotFoundException();
  332. }
  333. /**
  334. * Redirects to the file list and highlight the given file id
  335. *
  336. * @param int $fileId file id to show
  337. * @return RedirectResponse redirect response or not found response
  338. * @throws NotFoundException
  339. */
  340. private function redirectToFile(int $fileId) {
  341. $uid = $this->userSession->getUser()->getUID();
  342. $baseFolder = $this->rootFolder->getUserFolder($uid);
  343. $node = $baseFolder->getFirstNodeById($fileId);
  344. $params = ['view' => 'files'];
  345. try {
  346. $this->redirectToFileIfInTrashbin($fileId);
  347. } catch (NotFoundException $e) {
  348. }
  349. if ($node) {
  350. $params['fileid'] = $fileId;
  351. if ($node instanceof Folder) {
  352. // set the full path to enter the folder
  353. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  354. } else {
  355. // set parent path as dir
  356. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  357. }
  358. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  359. }
  360. throw new NotFoundException();
  361. }
  362. }