helper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. <?php
  2. /**
  3. * @author Bart Visscher <bartv@thisnet.nl>
  4. * @author Björn Schießle <schiessle@owncloud.com>
  5. * @author Joas Schilling <nickvergessen@owncloud.com>
  6. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  7. * @author Lukas Reschke <lukas@owncloud.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <icewind@owncloud.com>
  10. * @author Vincent Petry <pvince81@owncloud.com>
  11. *
  12. * @copyright Copyright (c) 2015, ownCloud, Inc.
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\Files_Sharing;
  29. class Helper {
  30. public static function registerHooks() {
  31. \OCP\Util::connectHook('OC_Filesystem', 'setup', '\OC\Files\Storage\Shared', 'setup');
  32. \OCP\Util::connectHook('OC_Filesystem', 'setup', '\OCA\Files_Sharing\External\Manager', 'setup');
  33. \OCP\Util::connectHook('OC_Filesystem', 'post_write', '\OC\Files\Cache\Shared_Updater', 'writeHook');
  34. \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OC\Files\Cache\Shared_Updater', 'postDeleteHook');
  35. \OCP\Util::connectHook('OC_Filesystem', 'delete', '\OC\Files\Cache\Shared_Updater', 'deleteHook');
  36. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OC\Files\Cache\Shared_Updater', 'renameHook');
  37. \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
  38. \OCP\Util::connectHook('OC_Appconfig', 'post_set_value', '\OCA\Files\Share\Maintainer', 'configChangeHook');
  39. \OCP\Util::connectHook('OCP\Share', 'post_shared', '\OC\Files\Cache\Shared_Updater', 'postShareHook');
  40. \OCP\Util::connectHook('OCP\Share', 'post_unshare', '\OC\Files\Cache\Shared_Updater', 'postUnshareHook');
  41. \OCP\Util::connectHook('OCP\Share', 'post_unshareFromSelf', '\OC\Files\Cache\Shared_Updater', 'postUnshareFromSelfHook');
  42. \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
  43. }
  44. /**
  45. * Sets up the filesystem and user for public sharing
  46. * @param string $token string share token
  47. * @param string $relativePath optional path relative to the share
  48. * @param string $password optional password
  49. */
  50. public static function setupFromToken($token, $relativePath = null, $password = null) {
  51. \OC_User::setIncognitoMode(true);
  52. $linkItem = \OCP\Share::getShareByToken($token, !$password);
  53. if($linkItem === false || ($linkItem['item_type'] !== 'file' && $linkItem['item_type'] !== 'folder')) {
  54. \OC_Response::setStatus(404);
  55. \OC_Log::write('core-preview', 'Passed token parameter is not valid', \OC_Log::DEBUG);
  56. exit;
  57. }
  58. if(!isset($linkItem['uid_owner']) || !isset($linkItem['file_source'])) {
  59. \OC_Response::setStatus(500);
  60. \OC_Log::write('core-preview', 'Passed token seems to be valid, but it does not contain all necessary information . ("' . $token . '")', \OC_Log::WARN);
  61. exit;
  62. }
  63. $rootLinkItem = \OCP\Share::resolveReShare($linkItem);
  64. $path = null;
  65. if (isset($rootLinkItem['uid_owner'])) {
  66. \OCP\JSON::checkUserExists($rootLinkItem['uid_owner']);
  67. \OC_Util::tearDownFS();
  68. \OC_Util::setupFS($rootLinkItem['uid_owner']);
  69. $path = \OC\Files\Filesystem::getPath($linkItem['file_source']);
  70. }
  71. if ($path === null) {
  72. \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
  73. \OC_Response::setStatus(404);
  74. \OCP\JSON::error(array('success' => false));
  75. exit();
  76. }
  77. if (!isset($linkItem['item_type'])) {
  78. \OCP\Util::writeLog('share', 'No item type set for share id: ' . $linkItem['id'], \OCP\Util::ERROR);
  79. \OC_Response::setStatus(404);
  80. \OCP\JSON::error(array('success' => false));
  81. exit();
  82. }
  83. if (isset($linkItem['share_with']) && (int)$linkItem['share_type'] === \OCP\Share::SHARE_TYPE_LINK) {
  84. if (!self::authenticate($linkItem, $password)) {
  85. \OC_Response::setStatus(403);
  86. \OCP\JSON::error(array('success' => false));
  87. exit();
  88. }
  89. }
  90. $basePath = $path;
  91. if ($relativePath !== null && \OC\Files\Filesystem::isReadable($basePath . $relativePath)) {
  92. $path .= \OC\Files\Filesystem::normalizePath($relativePath);
  93. }
  94. return array(
  95. 'linkItem' => $linkItem,
  96. 'basePath' => $basePath,
  97. 'realPath' => $path
  98. );
  99. }
  100. /**
  101. * Authenticate link item with the given password
  102. * or with the session if no password was given.
  103. * @param array $linkItem link item array
  104. * @param string $password optional password
  105. *
  106. * @return boolean true if authorized, false otherwise
  107. */
  108. public static function authenticate($linkItem, $password = null) {
  109. if ($password !== null) {
  110. if ($linkItem['share_type'] == \OCP\Share::SHARE_TYPE_LINK) {
  111. // Check Password
  112. $newHash = '';
  113. if(\OC::$server->getHasher()->verify($password, $linkItem['share_with'], $newHash)) {
  114. // Save item id in session for future requests
  115. \OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']);
  116. /**
  117. * FIXME: Migrate old hashes to new hash format
  118. * Due to the fact that there is no reasonable functionality to update the password
  119. * of an existing share no migration is yet performed there.
  120. * The only possibility is to update the existing share which will result in a new
  121. * share ID and is a major hack.
  122. *
  123. * In the future the migration should be performed once there is a proper method
  124. * to update the share's password. (for example `$share->updatePassword($password)`
  125. *
  126. * @link https://github.com/owncloud/core/issues/10671
  127. */
  128. if(!empty($newHash)) {
  129. }
  130. } else {
  131. return false;
  132. }
  133. } else {
  134. \OCP\Util::writeLog('share', 'Unknown share type '.$linkItem['share_type']
  135. .' for share id '.$linkItem['id'], \OCP\Util::ERROR);
  136. return false;
  137. }
  138. }
  139. else {
  140. // not authenticated ?
  141. if ( ! \OC::$server->getSession()->exists('public_link_authenticated')
  142. || \OC::$server->getSession()->get('public_link_authenticated') !== $linkItem['id']) {
  143. return false;
  144. }
  145. }
  146. return true;
  147. }
  148. public static function getSharesFromItem($target) {
  149. $result = array();
  150. $owner = \OC\Files\Filesystem::getOwner($target);
  151. \OC\Files\Filesystem::initMountPoints($owner);
  152. $info = \OC\Files\Filesystem::getFileInfo($target);
  153. $ownerView = new \OC\Files\View('/'.$owner.'/files');
  154. if ( $owner != \OCP\User::getUser() ) {
  155. $path = $ownerView->getPath($info['fileid']);
  156. } else {
  157. $path = $target;
  158. }
  159. $ids = array();
  160. while ($path !== dirname($path)) {
  161. $info = $ownerView->getFileInfo($path);
  162. if ($info instanceof \OC\Files\FileInfo) {
  163. $ids[] = $info['fileid'];
  164. } else {
  165. \OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
  166. }
  167. $path = dirname($path);
  168. }
  169. if (!empty($ids)) {
  170. $idList = array_chunk($ids, 99, true);
  171. foreach ($idList as $subList) {
  172. $statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
  173. $query = \OCP\DB::prepare($statement);
  174. $r = $query->execute();
  175. $result = array_merge($result, $r->fetchAll());
  176. }
  177. }
  178. return $result;
  179. }
  180. public static function getUidAndFilename($filename) {
  181. $uid = \OC\Files\Filesystem::getOwner($filename);
  182. \OC\Files\Filesystem::initMountPoints($uid);
  183. if ( $uid != \OCP\User::getUser() ) {
  184. $info = \OC\Files\Filesystem::getFileInfo($filename);
  185. $ownerView = new \OC\Files\View('/'.$uid.'/files');
  186. $filename = $ownerView->getPath($info['fileid']);
  187. }
  188. return array($uid, $filename);
  189. }
  190. /**
  191. * Format a path to be relative to the /user/files/ directory
  192. * @param string $path the absolute path
  193. * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
  194. */
  195. public static function stripUserFilesPath($path) {
  196. $trimmed = ltrim($path, '/');
  197. $split = explode('/', $trimmed);
  198. // it is not a file relative to data/user/files
  199. if (count($split) < 3 || $split[1] !== 'files') {
  200. return false;
  201. }
  202. $sliced = array_slice($split, 2);
  203. $relPath = implode('/', $sliced);
  204. return $relPath;
  205. }
  206. /**
  207. * check if file name already exists and generate unique target
  208. *
  209. * @param string $path
  210. * @param array $excludeList
  211. * @param \OC\Files\View $view
  212. * @return string $path
  213. */
  214. public static function generateUniqueTarget($path, $excludeList, $view) {
  215. $pathinfo = pathinfo($path);
  216. $ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
  217. $name = $pathinfo['filename'];
  218. $dir = $pathinfo['dirname'];
  219. $i = 2;
  220. while ($view->file_exists($path) || in_array($path, $excludeList)) {
  221. $path = \OC\Files\Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
  222. $i++;
  223. }
  224. return $path;
  225. }
  226. /**
  227. * allow users from other ownCloud instances to mount public links share by this instance
  228. * @return bool
  229. */
  230. public static function isOutgoingServer2serverShareEnabled() {
  231. $appConfig = \OC::$server->getAppConfig();
  232. $result = $appConfig->getValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
  233. return ($result === 'yes') ? true : false;
  234. }
  235. /**
  236. * allow user to mount public links from onther ownClouds
  237. * @return bool
  238. */
  239. public static function isIncomingServer2serverShareEnabled() {
  240. $appConfig = \OC::$server->getAppConfig();
  241. $result = $appConfig->getValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
  242. return ($result === 'yes') ? true : false;
  243. }
  244. /**
  245. * get default share folder
  246. *
  247. * @return string
  248. */
  249. public static function getShareFolder() {
  250. $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
  251. $shareFolder = \OC\Files\Filesystem::normalizePath($shareFolder);
  252. if (!\OC\Files\Filesystem::file_exists($shareFolder)) {
  253. $dir = '';
  254. $subdirs = explode('/', $shareFolder);
  255. foreach ($subdirs as $subdir) {
  256. $dir = $dir . '/' . $subdir;
  257. if (!\OC\Files\Filesystem::is_dir($dir)) {
  258. \OC\Files\Filesystem::mkdir($dir);
  259. }
  260. }
  261. }
  262. return $shareFolder;
  263. }
  264. /**
  265. * set default share folder
  266. *
  267. * @param string $shareFolder
  268. */
  269. public static function setShareFolder($shareFolder) {
  270. \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
  271. }
  272. }