helper.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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', '\OCA\Files_Sharing\External\Manager', 'setup');
  32. \OCP\Util::connectHook('OC_Filesystem', 'delete', '\OC\Files\Cache\Shared_Updater', 'deleteHook');
  33. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OC\Files\Cache\Shared_Updater', 'renameHook');
  34. \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
  35. \OCP\Util::connectHook('OC_Appconfig', 'post_set_value', '\OCA\Files\Share\Maintainer', 'configChangeHook');
  36. \OCP\Util::connectHook('OCP\Share', 'post_shared', '\OC\Files\Cache\Shared_Updater', 'postShareHook');
  37. \OCP\Util::connectHook('OCP\Share', 'post_unshare', '\OC\Files\Cache\Shared_Updater', 'postUnshareHook');
  38. \OCP\Util::connectHook('OCP\Share', 'post_unshareFromSelf', '\OC\Files\Cache\Shared_Updater', 'postUnshareFromSelfHook');
  39. \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
  40. }
  41. /**
  42. * Sets up the filesystem and user for public sharing
  43. * @param string $token string share token
  44. * @param string $relativePath optional path relative to the share
  45. * @param string $password optional password
  46. */
  47. public static function setupFromToken($token, $relativePath = null, $password = null) {
  48. \OC_User::setIncognitoMode(true);
  49. $linkItem = \OCP\Share::getShareByToken($token, !$password);
  50. if($linkItem === false || ($linkItem['item_type'] !== 'file' && $linkItem['item_type'] !== 'folder')) {
  51. \OC_Response::setStatus(404);
  52. \OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
  53. exit;
  54. }
  55. if(!isset($linkItem['uid_owner']) || !isset($linkItem['file_source'])) {
  56. \OC_Response::setStatus(500);
  57. \OCP\Util::writeLog('core-preview', 'Passed token seems to be valid, but it does not contain all necessary information . ("' . $token . '")', \OCP\Util::WARN);
  58. exit;
  59. }
  60. $rootLinkItem = \OCP\Share::resolveReShare($linkItem);
  61. $path = null;
  62. if (isset($rootLinkItem['uid_owner'])) {
  63. \OCP\JSON::checkUserExists($rootLinkItem['uid_owner']);
  64. \OC_Util::tearDownFS();
  65. \OC_Util::setupFS($rootLinkItem['uid_owner']);
  66. $path = \OC\Files\Filesystem::getPath($linkItem['file_source']);
  67. }
  68. if ($path === null) {
  69. \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
  70. \OC_Response::setStatus(404);
  71. \OCP\JSON::error(array('success' => false));
  72. exit();
  73. }
  74. if (!isset($linkItem['item_type'])) {
  75. \OCP\Util::writeLog('share', 'No item type set for share id: ' . $linkItem['id'], \OCP\Util::ERROR);
  76. \OC_Response::setStatus(404);
  77. \OCP\JSON::error(array('success' => false));
  78. exit();
  79. }
  80. if (isset($linkItem['share_with']) && (int)$linkItem['share_type'] === \OCP\Share::SHARE_TYPE_LINK) {
  81. if (!self::authenticate($linkItem, $password)) {
  82. \OC_Response::setStatus(403);
  83. \OCP\JSON::error(array('success' => false));
  84. exit();
  85. }
  86. }
  87. $basePath = $path;
  88. if ($relativePath !== null && \OC\Files\Filesystem::isReadable($basePath . $relativePath)) {
  89. $path .= \OC\Files\Filesystem::normalizePath($relativePath);
  90. }
  91. return array(
  92. 'linkItem' => $linkItem,
  93. 'basePath' => $basePath,
  94. 'realPath' => $path
  95. );
  96. }
  97. /**
  98. * Authenticate link item with the given password
  99. * or with the session if no password was given.
  100. * @param array $linkItem link item array
  101. * @param string $password optional password
  102. *
  103. * @return boolean true if authorized, false otherwise
  104. */
  105. public static function authenticate($linkItem, $password = null) {
  106. if ($password !== null) {
  107. if ($linkItem['share_type'] == \OCP\Share::SHARE_TYPE_LINK) {
  108. // Check Password
  109. $newHash = '';
  110. if(\OC::$server->getHasher()->verify($password, $linkItem['share_with'], $newHash)) {
  111. // Save item id in session for future requests
  112. \OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']);
  113. /**
  114. * FIXME: Migrate old hashes to new hash format
  115. * Due to the fact that there is no reasonable functionality to update the password
  116. * of an existing share no migration is yet performed there.
  117. * The only possibility is to update the existing share which will result in a new
  118. * share ID and is a major hack.
  119. *
  120. * In the future the migration should be performed once there is a proper method
  121. * to update the share's password. (for example `$share->updatePassword($password)`
  122. *
  123. * @link https://github.com/owncloud/core/issues/10671
  124. */
  125. if(!empty($newHash)) {
  126. }
  127. } else {
  128. return false;
  129. }
  130. } else {
  131. \OCP\Util::writeLog('share', 'Unknown share type '.$linkItem['share_type']
  132. .' for share id '.$linkItem['id'], \OCP\Util::ERROR);
  133. return false;
  134. }
  135. }
  136. else {
  137. // not authenticated ?
  138. if ( ! \OC::$server->getSession()->exists('public_link_authenticated')
  139. || \OC::$server->getSession()->get('public_link_authenticated') !== $linkItem['id']) {
  140. return false;
  141. }
  142. }
  143. return true;
  144. }
  145. public static function getSharesFromItem($target) {
  146. $result = array();
  147. $owner = \OC\Files\Filesystem::getOwner($target);
  148. \OC\Files\Filesystem::initMountPoints($owner);
  149. $info = \OC\Files\Filesystem::getFileInfo($target);
  150. $ownerView = new \OC\Files\View('/'.$owner.'/files');
  151. if ( $owner != \OCP\User::getUser() ) {
  152. $path = $ownerView->getPath($info['fileid']);
  153. } else {
  154. $path = $target;
  155. }
  156. $ids = array();
  157. while ($path !== dirname($path)) {
  158. $info = $ownerView->getFileInfo($path);
  159. if ($info instanceof \OC\Files\FileInfo) {
  160. $ids[] = $info['fileid'];
  161. } else {
  162. \OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
  163. }
  164. $path = dirname($path);
  165. }
  166. if (!empty($ids)) {
  167. $idList = array_chunk($ids, 99, true);
  168. foreach ($idList as $subList) {
  169. $statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
  170. $query = \OCP\DB::prepare($statement);
  171. $r = $query->execute();
  172. $result = array_merge($result, $r->fetchAll());
  173. }
  174. }
  175. return $result;
  176. }
  177. public static function getUidAndFilename($filename) {
  178. $uid = \OC\Files\Filesystem::getOwner($filename);
  179. \OC\Files\Filesystem::initMountPoints($uid);
  180. if ( $uid != \OCP\User::getUser() ) {
  181. $info = \OC\Files\Filesystem::getFileInfo($filename);
  182. $ownerView = new \OC\Files\View('/'.$uid.'/files');
  183. $filename = $ownerView->getPath($info['fileid']);
  184. }
  185. return array($uid, $filename);
  186. }
  187. /**
  188. * Format a path to be relative to the /user/files/ directory
  189. * @param string $path the absolute path
  190. * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
  191. */
  192. public static function stripUserFilesPath($path) {
  193. $trimmed = ltrim($path, '/');
  194. $split = explode('/', $trimmed);
  195. // it is not a file relative to data/user/files
  196. if (count($split) < 3 || $split[1] !== 'files') {
  197. return false;
  198. }
  199. $sliced = array_slice($split, 2);
  200. $relPath = implode('/', $sliced);
  201. return $relPath;
  202. }
  203. /**
  204. * check if file name already exists and generate unique target
  205. *
  206. * @param string $path
  207. * @param array $excludeList
  208. * @param \OC\Files\View $view
  209. * @return string $path
  210. */
  211. public static function generateUniqueTarget($path, $excludeList, $view) {
  212. $pathinfo = pathinfo($path);
  213. $ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
  214. $name = $pathinfo['filename'];
  215. $dir = $pathinfo['dirname'];
  216. $i = 2;
  217. while ($view->file_exists($path) || in_array($path, $excludeList)) {
  218. $path = \OC\Files\Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
  219. $i++;
  220. }
  221. return $path;
  222. }
  223. /**
  224. * allow users from other ownCloud instances to mount public links share by this instance
  225. * @return bool
  226. */
  227. public static function isOutgoingServer2serverShareEnabled() {
  228. $appConfig = \OC::$server->getAppConfig();
  229. $result = $appConfig->getValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
  230. return ($result === 'yes') ? true : false;
  231. }
  232. /**
  233. * allow user to mount public links from onther ownClouds
  234. * @return bool
  235. */
  236. public static function isIncomingServer2serverShareEnabled() {
  237. $appConfig = \OC::$server->getAppConfig();
  238. $result = $appConfig->getValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
  239. return ($result === 'yes') ? true : false;
  240. }
  241. /**
  242. * get default share folder
  243. *
  244. * @return string
  245. */
  246. public static function getShareFolder() {
  247. $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
  248. $shareFolder = \OC\Files\Filesystem::normalizePath($shareFolder);
  249. if (!\OC\Files\Filesystem::file_exists($shareFolder)) {
  250. $dir = '';
  251. $subdirs = explode('/', $shareFolder);
  252. foreach ($subdirs as $subdir) {
  253. $dir = $dir . '/' . $subdir;
  254. if (!\OC\Files\Filesystem::is_dir($dir)) {
  255. \OC\Files\Filesystem::mkdir($dir);
  256. }
  257. }
  258. }
  259. return $shareFolder;
  260. }
  261. /**
  262. * set default share folder
  263. *
  264. * @param string $shareFolder
  265. */
  266. public static function setShareFolder($shareFolder) {
  267. \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
  268. }
  269. /**
  270. * remove protocol from URL
  271. *
  272. * @param string $url
  273. * @return string
  274. */
  275. public static function removeProtocolFromUrl($url) {
  276. if (strpos($url, 'https://') === 0) {
  277. return substr($url, strlen('https://'));
  278. } else if (strpos($url, 'http://') === 0) {
  279. return substr($url, strlen('http://'));
  280. }
  281. return $url;
  282. }
  283. }