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

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