ViewController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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\Viewer\Event\LoadViewer;
  43. use OCP\App\IAppManager;
  44. use OCP\AppFramework\Controller;
  45. use OCP\AppFramework\Http\ContentSecurityPolicy;
  46. use OCP\AppFramework\Http\RedirectResponse;
  47. use OCP\AppFramework\Http\Response;
  48. use OCP\AppFramework\Http\TemplateResponse;
  49. use OCP\AppFramework\Services\IInitialState;
  50. use OCP\Collaboration\Resources\LoadAdditionalScriptsEvent as ResourcesLoadAdditionalScriptsEvent;
  51. use OCP\EventDispatcher\IEventDispatcher;
  52. use OCP\Files\Folder;
  53. use OCP\Files\IRootFolder;
  54. use OCP\Files\NotFoundException;
  55. use OCP\Files\Template\ITemplateManager;
  56. use OCP\IConfig;
  57. use OCP\IL10N;
  58. use OCP\IRequest;
  59. use OCP\IURLGenerator;
  60. use OCP\IUserSession;
  61. use OCP\Share\IManager;
  62. /**
  63. * Class ViewController
  64. *
  65. * @package OCA\Files\Controller
  66. */
  67. class ViewController extends Controller {
  68. private IURLGenerator $urlGenerator;
  69. private IL10N $l10n;
  70. private IConfig $config;
  71. private IEventDispatcher $eventDispatcher;
  72. private IUserSession $userSession;
  73. private IAppManager $appManager;
  74. private IRootFolder $rootFolder;
  75. private Helper $activityHelper;
  76. private IInitialState $initialState;
  77. private ITemplateManager $templateManager;
  78. private IManager $shareManager;
  79. private UserConfig $userConfig;
  80. public function __construct(string $appName,
  81. IRequest $request,
  82. IURLGenerator $urlGenerator,
  83. IL10N $l10n,
  84. IConfig $config,
  85. IEventDispatcher $eventDispatcher,
  86. IUserSession $userSession,
  87. IAppManager $appManager,
  88. IRootFolder $rootFolder,
  89. Helper $activityHelper,
  90. IInitialState $initialState,
  91. ITemplateManager $templateManager,
  92. IManager $shareManager,
  93. UserConfig $userConfig
  94. ) {
  95. parent::__construct($appName, $request);
  96. $this->urlGenerator = $urlGenerator;
  97. $this->l10n = $l10n;
  98. $this->config = $config;
  99. $this->eventDispatcher = $eventDispatcher;
  100. $this->userSession = $userSession;
  101. $this->appManager = $appManager;
  102. $this->rootFolder = $rootFolder;
  103. $this->activityHelper = $activityHelper;
  104. $this->initialState = $initialState;
  105. $this->templateManager = $templateManager;
  106. $this->shareManager = $shareManager;
  107. $this->userConfig = $userConfig;
  108. }
  109. /**
  110. * @param string $appName
  111. * @param string $scriptName
  112. * @return string
  113. */
  114. protected function renderScript($appName, $scriptName) {
  115. $content = '';
  116. $appPath = \OC_App::getAppPath($appName);
  117. $scriptPath = $appPath . '/' . $scriptName;
  118. if (file_exists($scriptPath)) {
  119. // TODO: sanitize path / script name ?
  120. ob_start();
  121. include $scriptPath;
  122. $content = ob_get_contents();
  123. @ob_end_clean();
  124. }
  125. return $content;
  126. }
  127. /**
  128. * FIXME: Replace with non static code
  129. *
  130. * @return array
  131. * @throws \OCP\Files\NotFoundException
  132. */
  133. protected function getStorageInfo(string $dir = '/') {
  134. \OC_Util::setupFS();
  135. $rootInfo = \OC\Files\Filesystem::getFileInfo('/', false);
  136. return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
  137. }
  138. /**
  139. * @NoCSRFRequired
  140. * @NoAdminRequired
  141. *
  142. * @param string $fileid
  143. * @return TemplateResponse|RedirectResponse
  144. * @throws NotFoundException
  145. */
  146. public function showFile(string $fileid = null, int $openfile = 1): Response {
  147. // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
  148. try {
  149. return $this->redirectToFile($fileid, $openfile !== 0);
  150. } catch (NotFoundException $e) {
  151. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
  152. }
  153. }
  154. /**
  155. * @NoCSRFRequired
  156. * @NoAdminRequired
  157. * @UseSession
  158. *
  159. * @param string $dir
  160. * @param string $view
  161. * @param string $fileid
  162. * @param bool $fileNotFound
  163. * @param string $openfile - the openfile URL parameter if it was present in the initial request
  164. * @return TemplateResponse|RedirectResponse
  165. * @throws NotFoundException
  166. */
  167. public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false, $openfile = null) {
  168. if ($fileid !== null && $dir === '') {
  169. try {
  170. return $this->redirectToFile($fileid);
  171. } catch (NotFoundException $e) {
  172. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
  173. }
  174. }
  175. $nav = new \OCP\Template('files', 'appnavigation', '');
  176. // Load the files we need
  177. \OCP\Util::addStyle('files', 'merged');
  178. \OCP\Util::addScript('files', 'merged-index', 'files');
  179. \OCP\Util::addScript('files', 'main');
  180. // mostly for the home storage's free space
  181. // FIXME: Make non static
  182. $storageInfo = $this->getStorageInfo();
  183. $userId = $this->userSession->getUser()->getUID();
  184. // Get all the user favorites to create a submenu
  185. try {
  186. $favElements = $this->activityHelper->getFavoriteFilePaths($userId);
  187. } catch (\RuntimeException $e) {
  188. $favElements['folders'] = [];
  189. }
  190. $collapseClasses = '';
  191. if (count($favElements['folders']) > 0) {
  192. $collapseClasses = 'collapsible';
  193. }
  194. $favoritesSublistArray = [];
  195. $navBarPositionPosition = 6;
  196. foreach ($favElements['folders'] as $favElement) {
  197. $element = [
  198. 'id' => str_replace('/', '-', $favElement),
  199. 'dir' => $favElement,
  200. 'order' => $navBarPositionPosition,
  201. 'name' => basename($favElement),
  202. 'icon' => 'folder',
  203. 'params' => [
  204. 'view' => 'files',
  205. 'dir' => $favElement,
  206. ],
  207. ];
  208. array_push($favoritesSublistArray, $element);
  209. $navBarPositionPosition++;
  210. }
  211. $navItems = \OCA\Files\App::getNavigationManager()->getAll();
  212. // add the favorites entry in menu
  213. $navItems['favorites']['sublist'] = $favoritesSublistArray;
  214. $navItems['favorites']['classes'] = $collapseClasses;
  215. // parse every menu and add the expanded user value
  216. foreach ($navItems as $key => $item) {
  217. $navItems[$key]['expanded'] = $this->config->getUserValue($userId, 'files', 'show_' . $item['id'], '0') === '1';
  218. }
  219. $nav->assign('navigationItems', $navItems);
  220. $contentItems = [];
  221. try {
  222. // If view is files, we use the directory, otherwise we use the root storage
  223. $storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
  224. } catch(\Exception $e) {
  225. $storageInfo = $this->getStorageInfo();
  226. }
  227. $this->initialState->provideInitialState('storageStats', $storageInfo);
  228. $this->initialState->provideInitialState('navigation', $navItems);
  229. $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
  230. // render the container content for every navigation item
  231. foreach ($navItems as $item) {
  232. $content = '';
  233. if (isset($item['script'])) {
  234. $content = $this->renderScript($item['appname'], $item['script']);
  235. }
  236. // parse submenus
  237. if (isset($item['sublist'])) {
  238. foreach ($item['sublist'] as $subitem) {
  239. $subcontent = '';
  240. if (isset($subitem['script'])) {
  241. $subcontent = $this->renderScript($subitem['appname'], $subitem['script']);
  242. }
  243. $contentItems[$subitem['id']] = [
  244. 'id' => $subitem['id'],
  245. 'content' => $subcontent
  246. ];
  247. }
  248. }
  249. $contentItems[$item['id']] = [
  250. 'id' => $item['id'],
  251. 'content' => $content
  252. ];
  253. }
  254. $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
  255. $event = new LoadAdditionalScriptsEvent();
  256. $this->eventDispatcher->dispatchTyped($event);
  257. $this->eventDispatcher->dispatchTyped(new LoadSidebar());
  258. // Load Viewer scripts
  259. if (class_exists(LoadViewer::class)) {
  260. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  261. }
  262. $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
  263. $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
  264. $params = [];
  265. $params['usedSpacePercent'] = (int) $storageInfo['relative'];
  266. $params['owner'] = $storageInfo['owner'] ?? '';
  267. $params['ownerDisplayName'] = $storageInfo['ownerDisplayName'] ?? '';
  268. $params['isPublic'] = false;
  269. $params['allowShareWithLink'] = $this->shareManager->shareApiAllowLinks() ? 'yes' : 'no';
  270. $params['defaultFileSorting'] = $this->config->getUserValue($userId, 'files', 'file_sorting', 'name');
  271. $params['defaultFileSortingDirection'] = $this->config->getUserValue($userId, 'files', 'file_sorting_direction', 'asc');
  272. $params['showgridview'] = $this->config->getUserValue($userId, 'files', 'show_grid', false);
  273. $showHidden = (bool) $this->config->getUserValue($userId, 'files', 'show_hidden', false);
  274. $params['showHiddenFiles'] = $showHidden ? 1 : 0;
  275. $cropImagePreviews = (bool) $this->config->getUserValue($userId, 'files', 'crop_image_previews', true);
  276. $params['cropImagePreviews'] = $cropImagePreviews ? 1 : 0;
  277. $params['fileNotFound'] = $fileNotFound ? 1 : 0;
  278. $params['appNavigation'] = $nav;
  279. $params['appContents'] = $contentItems;
  280. $params['hiddenFields'] = $event->getHiddenFields();
  281. $response = new TemplateResponse(
  282. Application::APP_ID,
  283. 'index',
  284. $params
  285. );
  286. $policy = new ContentSecurityPolicy();
  287. $policy->addAllowedFrameDomain('\'self\'');
  288. $response->setContentSecurityPolicy($policy);
  289. $this->provideInitialState($dir, $openfile);
  290. return $response;
  291. }
  292. /**
  293. * Add openFileInfo in initialState if $openfile is set.
  294. * @param string $dir - the ?dir= URL param
  295. * @param string $openfile - the ?openfile= URL param
  296. * @return void
  297. */
  298. private function provideInitialState(string $dir, ?string $openfile): void {
  299. if ($openfile === null) {
  300. return;
  301. }
  302. $user = $this->userSession->getUser();
  303. if ($user === null) {
  304. return;
  305. }
  306. $uid = $user->getUID();
  307. $userFolder = $this->rootFolder->getUserFolder($uid);
  308. $nodes = $userFolder->getById((int) $openfile);
  309. $node = array_shift($nodes);
  310. if ($node === null) {
  311. return;
  312. }
  313. // properly format full path and make sure
  314. // we're relative to the user home folder
  315. $isRoot = $node === $userFolder;
  316. $path = $userFolder->getRelativePath($node->getPath());
  317. $directory = $userFolder->getRelativePath($node->getParent()->getPath());
  318. // Prevent opening a file from another folder.
  319. if ($dir !== $directory) {
  320. return;
  321. }
  322. $this->initialState->provideInitialState(
  323. 'openFileInfo', [
  324. 'id' => $node->getId(),
  325. 'name' => $isRoot ? '' : $node->getName(),
  326. 'path' => $path,
  327. 'directory' => $directory,
  328. 'mime' => $node->getMimetype(),
  329. 'type' => $node->getType(),
  330. 'permissions' => $node->getPermissions(),
  331. ]
  332. );
  333. }
  334. /**
  335. * Redirects to the file list and highlight the given file id
  336. *
  337. * @param string $fileId file id to show
  338. * @param bool $setOpenfile - whether or not to set the openfile URL parameter
  339. * @return RedirectResponse redirect response or not found response
  340. * @throws \OCP\Files\NotFoundException
  341. */
  342. private function redirectToFile($fileId, bool $setOpenfile = false) {
  343. $uid = $this->userSession->getUser()->getUID();
  344. $baseFolder = $this->rootFolder->getUserFolder($uid);
  345. $files = $baseFolder->getById($fileId);
  346. $params = [];
  347. if (empty($files) && $this->appManager->isEnabledForUser('files_trashbin')) {
  348. $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
  349. $files = $baseFolder->getById($fileId);
  350. $params['view'] = 'trashbin';
  351. }
  352. if (!empty($files)) {
  353. $file = current($files);
  354. if ($file instanceof Folder) {
  355. // set the full path to enter the folder
  356. $params['dir'] = $baseFolder->getRelativePath($file->getPath());
  357. } else {
  358. // set parent path as dir
  359. $params['dir'] = $baseFolder->getRelativePath($file->getParent()->getPath());
  360. // and scroll to the entry
  361. $params['scrollto'] = $file->getName();
  362. if ($setOpenfile) {
  363. // forward the openfile URL parameter.
  364. $params['openfile'] = $fileId;
  365. }
  366. }
  367. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', $params));
  368. }
  369. throw new \OCP\Files\NotFoundException();
  370. }
  371. }