ViewController.php 13 KB

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