ViewController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. * @param string $appName
  116. * @param string $scriptName
  117. * @return string
  118. */
  119. protected function renderScript($appName, $scriptName) {
  120. $content = '';
  121. $appPath = \OC_App::getAppPath($appName);
  122. $scriptPath = $appPath . '/' . $scriptName;
  123. if (file_exists($scriptPath)) {
  124. // TODO: sanitize path / script name ?
  125. ob_start();
  126. include $scriptPath;
  127. $content = ob_get_contents();
  128. @ob_end_clean();
  129. }
  130. return $content;
  131. }
  132. /**
  133. * FIXME: Replace with non static code
  134. *
  135. * @return array
  136. * @throws \OCP\Files\NotFoundException
  137. */
  138. protected function getStorageInfo(string $dir = '/') {
  139. $rootInfo = \OC\Files\Filesystem::getFileInfo('/', false);
  140. return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
  141. }
  142. /**
  143. * @NoCSRFRequired
  144. * @NoAdminRequired
  145. *
  146. * @param string $fileid
  147. * @return TemplateResponse|RedirectResponse
  148. */
  149. public function showFile(string $fileid = null): Response {
  150. if (!$fileid) {
  151. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  152. }
  153. // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
  154. try {
  155. return $this->redirectToFile((int) $fileid);
  156. } catch (NotFoundException $e) {
  157. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
  158. }
  159. }
  160. /**
  161. * @NoCSRFRequired
  162. * @NoAdminRequired
  163. * @UseSession
  164. *
  165. * @param string $dir
  166. * @param string $view
  167. * @param string $fileid
  168. * @param bool $fileNotFound
  169. * @return TemplateResponse|RedirectResponse
  170. */
  171. public function indexView($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  172. return $this->index($dir, $view, $fileid, $fileNotFound);
  173. }
  174. /**
  175. * @NoCSRFRequired
  176. * @NoAdminRequired
  177. * @UseSession
  178. *
  179. * @param string $dir
  180. * @param string $view
  181. * @param string $fileid
  182. * @param bool $fileNotFound
  183. * @return TemplateResponse|RedirectResponse
  184. */
  185. public function indexViewFileid($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  186. return $this->index($dir, $view, $fileid, $fileNotFound);
  187. }
  188. /**
  189. * @NoCSRFRequired
  190. * @NoAdminRequired
  191. * @UseSession
  192. *
  193. * @param string $dir
  194. * @param string $view
  195. * @param string $fileid
  196. * @param bool $fileNotFound
  197. * @return TemplateResponse|RedirectResponse
  198. */
  199. public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  200. if ($fileid !== null && $view !== 'trashbin') {
  201. try {
  202. return $this->redirectToFileIfInTrashbin((int) $fileid);
  203. } catch (NotFoundException $e) {
  204. }
  205. }
  206. // Load the files we need
  207. \OCP\Util::addInitScript('files', 'init');
  208. \OCP\Util::addStyle('files', 'merged');
  209. \OCP\Util::addScript('files', 'main');
  210. $userId = $this->userSession->getUser()->getUID();
  211. // Get all the user favorites to create a submenu
  212. try {
  213. $userFolder = $this->rootFolder->getUserFolder($userId);
  214. $favElements = $this->activityHelper->getFavoriteNodes($userId, true);
  215. $favElements = array_map(fn (Folder $node) => [
  216. 'fileid' => $node->getId(),
  217. 'path' => $userFolder->getRelativePath($node->getPath()),
  218. ], $favElements);
  219. } catch (\RuntimeException $e) {
  220. $favElements = [];
  221. }
  222. // If the file doesn't exists in the folder and
  223. // exists in only one occurrence, redirect to that file
  224. // in the correct folder
  225. if ($fileid && $dir !== '') {
  226. $baseFolder = $this->rootFolder->getUserFolder($userId);
  227. $nodes = $baseFolder->getById((int) $fileid);
  228. if (!empty($nodes)) {
  229. $nodePath = $baseFolder->getRelativePath($nodes[0]->getPath());
  230. $relativePath = $nodePath ? dirname($nodePath) : '';
  231. // If the requested path does not contain the file id
  232. // or if the requested path is not the file id itself
  233. if (count($nodes) === 1 && $relativePath !== $dir && $nodePath !== $dir) {
  234. return $this->redirectToFile((int) $fileid);
  235. }
  236. } else { // fileid does not exist anywhere
  237. $fileNotFound = true;
  238. }
  239. }
  240. try {
  241. // If view is files, we use the directory, otherwise we use the root storage
  242. $storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
  243. } catch(\Exception $e) {
  244. $storageInfo = $this->getStorageInfo();
  245. }
  246. $this->initialState->provideInitialState('storageStats', $storageInfo);
  247. $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
  248. $this->initialState->provideInitialState('viewConfigs', $this->viewConfig->getConfigs());
  249. $this->initialState->provideInitialState('favoriteFolders', $favElements);
  250. // File sorting user config
  251. $filesSortingConfig = json_decode($this->config->getUserValue($userId, 'files', 'files_sorting_configs', '{}'), true);
  252. $this->initialState->provideInitialState('filesSortingConfig', $filesSortingConfig);
  253. // Forbidden file characters
  254. /** @var string[] */
  255. $forbiddenCharacters = $this->config->getSystemValue('forbidden_chars', []);
  256. $this->initialState->provideInitialState('forbiddenCharacters', Constants::FILENAME_INVALID_CHARS . implode('', $forbiddenCharacters));
  257. $event = new LoadAdditionalScriptsEvent();
  258. $this->eventDispatcher->dispatchTyped($event);
  259. $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
  260. $this->eventDispatcher->dispatchTyped(new LoadSidebar());
  261. // Load Viewer scripts
  262. if (class_exists(LoadViewer::class)) {
  263. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  264. }
  265. $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
  266. $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
  267. $response = new TemplateResponse(
  268. Application::APP_ID,
  269. 'index',
  270. );
  271. $policy = new ContentSecurityPolicy();
  272. $policy->addAllowedFrameDomain('\'self\'');
  273. // Allow preview service worker
  274. $policy->addAllowedWorkerSrcDomain('\'self\'');
  275. $response->setContentSecurityPolicy($policy);
  276. $this->provideInitialState($dir, $fileid);
  277. return $response;
  278. }
  279. /**
  280. * Add openFileInfo in initialState.
  281. * @param string $dir - the ?dir= URL param
  282. * @param string $fileid - the fileid URL param
  283. * @return void
  284. */
  285. private function provideInitialState(string $dir, ?string $fileid): void {
  286. if ($fileid === null) {
  287. return;
  288. }
  289. $user = $this->userSession->getUser();
  290. if ($user === null) {
  291. return;
  292. }
  293. $uid = $user->getUID();
  294. $userFolder = $this->rootFolder->getUserFolder($uid);
  295. $nodes = $userFolder->getById((int) $fileid);
  296. $node = array_shift($nodes);
  297. if ($node === null) {
  298. return;
  299. }
  300. // properly format full path and make sure
  301. // we're relative to the user home folder
  302. $isRoot = $node === $userFolder;
  303. $path = $userFolder->getRelativePath($node->getPath());
  304. $directory = $userFolder->getRelativePath($node->getParent()->getPath());
  305. // Prevent opening a file from another folder.
  306. if ($dir !== $directory) {
  307. return;
  308. }
  309. $this->initialState->provideInitialState(
  310. 'openFileInfo', [
  311. 'id' => $node->getId(),
  312. 'name' => $isRoot ? '' : $node->getName(),
  313. 'path' => $path,
  314. 'directory' => $directory,
  315. 'mime' => $node->getMimetype(),
  316. 'type' => $node->getType(),
  317. 'permissions' => $node->getPermissions(),
  318. ]
  319. );
  320. }
  321. /**
  322. * Redirects to the trashbin file list and highlight the given file id
  323. *
  324. * @param int $fileId file id to show
  325. * @return RedirectResponse redirect response or not found response
  326. * @throws NotFoundException
  327. */
  328. private function redirectToFileIfInTrashbin($fileId): RedirectResponse {
  329. $uid = $this->userSession->getUser()->getUID();
  330. $baseFolder = $this->rootFolder->getUserFolder($uid);
  331. $nodes = $baseFolder->getById($fileId);
  332. $params = [];
  333. if (empty($nodes) && $this->appManager->isEnabledForUser('files_trashbin')) {
  334. /** @var Folder */
  335. $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
  336. $nodes = $baseFolder->getById($fileId);
  337. $params['view'] = 'trashbin';
  338. if (!empty($nodes)) {
  339. $node = current($nodes);
  340. $params['fileid'] = $fileId;
  341. if ($node instanceof Folder) {
  342. // set the full path to enter the folder
  343. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  344. } else {
  345. // set parent path as dir
  346. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  347. }
  348. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  349. }
  350. }
  351. throw new NotFoundException();
  352. }
  353. /**
  354. * Redirects to the file list and highlight the given file id
  355. *
  356. * @param int $fileId file id to show
  357. * @return RedirectResponse redirect response or not found response
  358. * @throws NotFoundException
  359. */
  360. private function redirectToFile(int $fileId) {
  361. $uid = $this->userSession->getUser()->getUID();
  362. $baseFolder = $this->rootFolder->getUserFolder($uid);
  363. $nodes = $baseFolder->getById($fileId);
  364. $params = ['view' => 'files'];
  365. try {
  366. $this->redirectToFileIfInTrashbin($fileId);
  367. } catch (NotFoundException $e) {
  368. }
  369. if (!empty($nodes)) {
  370. $node = current($nodes);
  371. $params['fileid'] = $fileId;
  372. if ($node instanceof Folder) {
  373. // set the full path to enter the folder
  374. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  375. } else {
  376. // set parent path as dir
  377. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  378. }
  379. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  380. }
  381. throw new NotFoundException();
  382. }
  383. }