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 14KB

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