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

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