1
0

ViewController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. *
  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. *
  160. * @param string $dir
  161. * @param string $view
  162. * @param string $fileid
  163. * @param bool $fileNotFound
  164. * @return TemplateResponse|RedirectResponse
  165. */
  166. public function indexViewFileid($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  167. return $this->index($dir, $view, $fileid, $fileNotFound);
  168. }
  169. /**
  170. * @NoCSRFRequired
  171. * @NoAdminRequired
  172. *
  173. * @param string $dir
  174. * @param string $view
  175. * @param string $fileid
  176. * @param bool $fileNotFound
  177. * @return TemplateResponse|RedirectResponse
  178. */
  179. public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  180. if ($fileid !== null && $view !== 'trashbin') {
  181. try {
  182. return $this->redirectToFileIfInTrashbin((int) $fileid);
  183. } catch (NotFoundException $e) {
  184. }
  185. }
  186. // Load the files we need
  187. \OCP\Util::addInitScript('files', 'init');
  188. \OCP\Util::addStyle('files', 'merged');
  189. \OCP\Util::addScript('files', 'main');
  190. $userId = $this->userSession->getUser()->getUID();
  191. // Get all the user favorites to create a submenu
  192. try {
  193. $userFolder = $this->rootFolder->getUserFolder($userId);
  194. $favElements = $this->activityHelper->getFavoriteNodes($userId, true);
  195. $favElements = array_map(fn (Folder $node) => [
  196. 'fileid' => $node->getId(),
  197. 'path' => $userFolder->getRelativePath($node->getPath()),
  198. ], $favElements);
  199. } catch (\RuntimeException $e) {
  200. $favElements = [];
  201. }
  202. // If the file doesn't exists in the folder and
  203. // exists in only one occurrence, redirect to that file
  204. // in the correct folder
  205. if ($fileid && $dir !== '') {
  206. $baseFolder = $this->rootFolder->getUserFolder($userId);
  207. $nodes = $baseFolder->getById((int) $fileid);
  208. if (!empty($nodes)) {
  209. $nodePath = $baseFolder->getRelativePath($nodes[0]->getPath());
  210. $relativePath = $nodePath ? dirname($nodePath) : '';
  211. // If the requested path does not contain the file id
  212. // or if the requested path is not the file id itself
  213. if (count($nodes) === 1 && $relativePath !== $dir && $nodePath !== $dir) {
  214. return $this->redirectToFile((int) $fileid);
  215. }
  216. } else { // fileid does not exist anywhere
  217. $fileNotFound = true;
  218. }
  219. }
  220. try {
  221. // If view is files, we use the directory, otherwise we use the root storage
  222. $storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
  223. } catch(\Exception $e) {
  224. $storageInfo = $this->getStorageInfo();
  225. }
  226. $this->initialState->provideInitialState('storageStats', $storageInfo);
  227. $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
  228. $this->initialState->provideInitialState('viewConfigs', $this->viewConfig->getConfigs());
  229. $this->initialState->provideInitialState('favoriteFolders', $favElements);
  230. // File sorting user config
  231. $filesSortingConfig = json_decode($this->config->getUserValue($userId, 'files', 'files_sorting_configs', '{}'), true);
  232. $this->initialState->provideInitialState('filesSortingConfig', $filesSortingConfig);
  233. // Forbidden file characters
  234. /** @var string[] */
  235. $forbiddenCharacters = $this->config->getSystemValue('forbidden_chars', []);
  236. $this->initialState->provideInitialState('forbiddenCharacters', Constants::FILENAME_INVALID_CHARS . implode('', $forbiddenCharacters));
  237. $event = new LoadAdditionalScriptsEvent();
  238. $this->eventDispatcher->dispatchTyped($event);
  239. $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
  240. $this->eventDispatcher->dispatchTyped(new LoadSidebar());
  241. $this->eventDispatcher->dispatchTyped(new LoadSearchPlugins());
  242. // Load Viewer scripts
  243. if (class_exists(LoadViewer::class)) {
  244. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  245. }
  246. $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
  247. $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
  248. $response = new TemplateResponse(
  249. Application::APP_ID,
  250. 'index',
  251. );
  252. $policy = new ContentSecurityPolicy();
  253. $policy->addAllowedFrameDomain('\'self\'');
  254. // Allow preview service worker
  255. $policy->addAllowedWorkerSrcDomain('\'self\'');
  256. $response->setContentSecurityPolicy($policy);
  257. return $response;
  258. }
  259. /**
  260. * Redirects to the trashbin file list and highlight the given file id
  261. *
  262. * @param int $fileId file id to show
  263. * @return RedirectResponse redirect response or not found response
  264. * @throws NotFoundException
  265. */
  266. private function redirectToFileIfInTrashbin($fileId): RedirectResponse {
  267. $uid = $this->userSession->getUser()->getUID();
  268. $baseFolder = $this->rootFolder->getUserFolder($uid);
  269. $node = $baseFolder->getFirstNodeById($fileId);
  270. $params = [];
  271. if (!$node && $this->appManager->isEnabledForUser('files_trashbin')) {
  272. /** @var Folder */
  273. $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
  274. $node = $baseFolder->getFirstNodeById($fileId);
  275. $params['view'] = 'trashbin';
  276. if ($node) {
  277. $params['fileid'] = $fileId;
  278. if ($node instanceof Folder) {
  279. // set the full path to enter the folder
  280. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  281. } else {
  282. // set parent path as dir
  283. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  284. }
  285. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  286. }
  287. }
  288. throw new NotFoundException();
  289. }
  290. /**
  291. * Redirects to the file list and highlight the given file id
  292. *
  293. * @param int $fileId file id to show
  294. * @return RedirectResponse redirect response or not found response
  295. * @throws NotFoundException
  296. */
  297. private function redirectToFile(int $fileId) {
  298. $uid = $this->userSession->getUser()->getUID();
  299. $baseFolder = $this->rootFolder->getUserFolder($uid);
  300. $node = $baseFolder->getFirstNodeById($fileId);
  301. $params = ['view' => 'files'];
  302. try {
  303. $this->redirectToFileIfInTrashbin($fileId);
  304. } catch (NotFoundException $e) {
  305. }
  306. if ($node) {
  307. $params['fileid'] = $fileId;
  308. if ($node instanceof Folder) {
  309. // set the full path to enter the folder
  310. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  311. } else {
  312. // set parent path as dir
  313. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  314. // open the file by default (opening the viewer)
  315. $params['openfile'] = 'true';
  316. }
  317. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  318. }
  319. throw new NotFoundException();
  320. }
  321. }