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.

1143 lines
42 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Reiter <ockham@raz.or.at>
  8. * @author Bjoern Schiessle <bjoern@schiessle.org>
  9. * @author Björn Schießle <bjoern@schiessle.org>
  10. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Robin McCorkell <robin@mccorkell.me.uk>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Sebastian Döll <sebastian.doell@libasys.de>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Vincent Petry <pvince81@owncloud.com>
  20. * @author Volkan Gezer <volkangezer@gmail.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\Share;
  38. use OCP\DB\QueryBuilder\IQueryBuilder;
  39. use OCP\ILogger;
  40. use OCP\Share\IShare;
  41. /**
  42. * This class provides the ability for apps to share their content between users.
  43. * Apps must create a backend class that implements OCP\Share_Backend and register it with this class.
  44. *
  45. * It provides the following hooks:
  46. * - post_shared
  47. */
  48. class Share extends Constants {
  49. /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
  50. * Construct permissions for share() and setPermissions with Or (|) e.g.
  51. * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
  52. *
  53. * Check if permission is granted with And (&) e.g. Check if delete is
  54. * granted: if ($permissions & PERMISSION_DELETE)
  55. *
  56. * Remove permissions with And (&) and Not (~) e.g. Remove the update
  57. * permission: $permissions &= ~PERMISSION_UPDATE
  58. *
  59. * Apps are required to handle permissions on their own, this class only
  60. * stores and manages the permissions of shares
  61. * @see lib/public/constants.php
  62. */
  63. /**
  64. * Register a sharing backend class that implements OCP\Share_Backend for an item type
  65. * @param string $itemType Item type
  66. * @param string $class Backend class
  67. * @param string $collectionOf (optional) Depends on item type
  68. * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
  69. * @return boolean true if backend is registered or false if error
  70. */
  71. public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
  72. if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
  73. if (!isset(self::$backendTypes[$itemType])) {
  74. self::$backendTypes[$itemType] = [
  75. 'class' => $class,
  76. 'collectionOf' => $collectionOf,
  77. 'supportedFileExtensions' => $supportedFileExtensions
  78. ];
  79. return true;
  80. }
  81. \OCP\Util::writeLog('OCP\Share',
  82. 'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
  83. .' is already registered for '.$itemType,
  84. ILogger::WARN);
  85. }
  86. return false;
  87. }
  88. /**
  89. * Get the items of item type shared with the current user
  90. * @param string $itemType
  91. * @param int $format (optional) Format type must be defined by the backend
  92. * @param mixed $parameters (optional)
  93. * @param int $limit Number of items to return (optional) Returns all by default
  94. * @param boolean $includeCollections (optional)
  95. * @return mixed Return depends on format
  96. * @deprecated TESTS ONLY - this methods is only used by tests
  97. * called like this:
  98. * \OC\Share\Share::getItemsSharedWith('folder'); (apps/files_sharing/tests/UpdaterTest.php)
  99. */
  100. public static function getItemsSharedWith() {
  101. return self::getItems('folder', null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, self::FORMAT_NONE,
  102. null, -1, false);
  103. }
  104. /**
  105. * Get the items of item type shared with a user
  106. * @param string $itemType
  107. * @param string $user id for which user we want the shares
  108. * @param int $format (optional) Format type must be defined by the backend
  109. * @param mixed $parameters (optional)
  110. * @param int $limit Number of items to return (optional) Returns all by default
  111. * @param boolean $includeCollections (optional)
  112. * @return mixed Return depends on format
  113. */
  114. public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
  115. $parameters = null, $limit = -1, $includeCollections = false) {
  116. return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
  117. $parameters, $limit, $includeCollections);
  118. }
  119. /**
  120. * Get the item of item type shared with a given user by source
  121. * @param string $itemType
  122. * @param string $itemSource
  123. * @param string $user User to whom the item was shared
  124. * @param string $owner Owner of the share
  125. * @param int $shareType only look for a specific share type
  126. * @return array Return list of items with file_target, permissions and expiration
  127. */
  128. public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
  129. $shares = [];
  130. $fileDependent = false;
  131. $where = 'WHERE';
  132. $fileDependentWhere = '';
  133. if ($itemType === 'file' || $itemType === 'folder') {
  134. $fileDependent = true;
  135. $column = 'file_source';
  136. $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
  137. $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
  138. } else {
  139. $column = 'item_source';
  140. }
  141. $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
  142. $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
  143. $arguments = [$itemSource, $itemType];
  144. // for link shares $user === null
  145. if ($user !== null) {
  146. $where .= ' AND `share_with` = ? ';
  147. $arguments[] = $user;
  148. }
  149. if ($shareType !== null) {
  150. $where .= ' AND `share_type` = ? ';
  151. $arguments[] = $shareType;
  152. }
  153. if ($owner !== null) {
  154. $where .= ' AND `uid_owner` = ? ';
  155. $arguments[] = $owner;
  156. }
  157. $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
  158. $result = \OC_DB::executeAudited($query, $arguments);
  159. while ($row = $result->fetchRow()) {
  160. if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
  161. continue;
  162. }
  163. if ($fileDependent && (int)$row['file_parent'] === -1) {
  164. // if it is a mount point we need to get the path from the mount manager
  165. $mountManager = \OC\Files\Filesystem::getMountManager();
  166. $mountPoint = $mountManager->findByStorageId($row['storage_id']);
  167. if (!empty($mountPoint)) {
  168. $path = $mountPoint[0]->getMountPoint();
  169. $path = trim($path, '/');
  170. $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
  171. $row['path'] = $path;
  172. } else {
  173. \OC::$server->getLogger()->warning(
  174. 'Could not resolve mount point for ' . $row['storage_id'],
  175. ['app' => 'OCP\Share']
  176. );
  177. }
  178. }
  179. $shares[] = $row;
  180. }
  181. //if didn't found a result than let's look for a group share.
  182. if (empty($shares) && $user !== null) {
  183. $userObject = \OC::$server->getUserManager()->get($user);
  184. $groups = [];
  185. if ($userObject) {
  186. $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
  187. }
  188. if (!empty($groups)) {
  189. $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
  190. $arguments = [$itemSource, $itemType, $groups];
  191. $types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
  192. if ($owner !== null) {
  193. $where .= ' AND `uid_owner` = ?';
  194. $arguments[] = $owner;
  195. $types[] = null;
  196. }
  197. // TODO: inject connection, hopefully one day in the future when this
  198. // class isn't static anymore...
  199. $conn = \OC::$server->getDatabaseConnection();
  200. $result = $conn->executeQuery(
  201. 'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
  202. $arguments,
  203. $types
  204. );
  205. while ($row = $result->fetch()) {
  206. $shares[] = $row;
  207. }
  208. }
  209. }
  210. return $shares;
  211. }
  212. /**
  213. * Get the item of item type shared with the current user by source
  214. * @param string $itemType
  215. * @param string $itemSource
  216. * @param int $format (optional) Format type must be defined by the backend
  217. * @param mixed $parameters
  218. * @param boolean $includeCollections
  219. * @param string $shareWith (optional) define against which user should be checked, default: current user
  220. * @return array
  221. */
  222. public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
  223. $parameters = null, $includeCollections = false, $shareWith = null) {
  224. $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
  225. return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
  226. $parameters, 1, $includeCollections, true);
  227. }
  228. /**
  229. * Get the shared item of item type owned by the current user
  230. * @param string $itemType
  231. * @param string $itemSource
  232. * @param int $format (optional) Format type must be defined by the backend
  233. * @param mixed $parameters
  234. * @param boolean $includeCollections
  235. * @return mixed Return depends on format
  236. */
  237. public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
  238. $parameters = null, $includeCollections = false) {
  239. return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
  240. $parameters, -1, $includeCollections);
  241. }
  242. /**
  243. * Unshare an item from a user, group, or delete a private link
  244. * @param string $itemType
  245. * @param string $itemSource
  246. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  247. * @param string $shareWith User or group the item is being shared with
  248. * @param string $owner owner of the share, if null the current user is used
  249. * @return boolean true on success or false on failure
  250. */
  251. public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
  252. // check if it is a valid itemType
  253. self::getBackend($itemType);
  254. $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
  255. $toDelete = [];
  256. $newParent = null;
  257. $currentUser = $owner ? $owner : \OC_User::getUser();
  258. foreach ($items as $item) {
  259. // delete the item with the expected share_type and owner
  260. if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
  261. $toDelete = $item;
  262. // if there is more then one result we don't have to delete the children
  263. // but update their parent. For group shares the new parent should always be
  264. // the original group share and not the db entry with the unique name
  265. } elseif ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
  266. $newParent = $item['parent'];
  267. } else {
  268. $newParent = $item['id'];
  269. }
  270. }
  271. if (!empty($toDelete)) {
  272. self::unshareItem($toDelete, $newParent);
  273. return true;
  274. }
  275. return false;
  276. }
  277. /**
  278. * Checks whether a share has expired, calls unshareItem() if yes.
  279. * @param array $item Share data (usually database row)
  280. * @return boolean True if item was expired, false otherwise.
  281. */
  282. protected static function expireItem(array $item) {
  283. $result = false;
  284. // only use default expiration date for link shares
  285. if ((int) $item['share_type'] === IShare::TYPE_LINK) {
  286. // calculate expiration date
  287. if (!empty($item['expiration'])) {
  288. $userDefinedExpire = new \DateTime($item['expiration']);
  289. $expires = $userDefinedExpire->getTimestamp();
  290. } else {
  291. $expires = null;
  292. }
  293. // get default expiration settings
  294. $defaultSettings = Helper::getDefaultExpireSetting();
  295. $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
  296. if (is_int($expires)) {
  297. $now = time();
  298. if ($now > $expires) {
  299. self::unshareItem($item);
  300. $result = true;
  301. }
  302. }
  303. }
  304. return $result;
  305. }
  306. /**
  307. * Unshares a share given a share data array
  308. * @param array $item Share data (usually database row)
  309. * @param int $newParent parent ID
  310. * @return null
  311. */
  312. protected static function unshareItem(array $item, $newParent = null) {
  313. $shareType = (int)$item['share_type'];
  314. $shareWith = null;
  315. if ($shareType !== IShare::TYPE_LINK) {
  316. $shareWith = $item['share_with'];
  317. }
  318. // Pass all the vars we have for now, they may be useful
  319. $hookParams = [
  320. 'id' => $item['id'],
  321. 'itemType' => $item['item_type'],
  322. 'itemSource' => $item['item_source'],
  323. 'shareType' => $shareType,
  324. 'shareWith' => $shareWith,
  325. 'itemParent' => $item['parent'],
  326. 'uidOwner' => $item['uid_owner'],
  327. ];
  328. if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
  329. $hookParams['fileSource'] = $item['file_source'];
  330. $hookParams['fileTarget'] = $item['file_target'];
  331. }
  332. \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
  333. $deletedShares = Helper::delete($item['id'], false, null, $newParent);
  334. $deletedShares[] = $hookParams;
  335. $hookParams['deletedShares'] = $deletedShares;
  336. \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
  337. if ((int)$item['share_type'] === IShare::TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
  338. list(, $remote) = Helper::splitUserRemote($item['share_with']);
  339. self::sendRemoteUnshare($remote, $item['id'], $item['token']);
  340. }
  341. }
  342. /**
  343. * Get the backend class for the specified item type
  344. * @param string $itemType
  345. * @throws \Exception
  346. * @return \OCP\Share_Backend
  347. */
  348. public static function getBackend($itemType) {
  349. $l = \OC::$server->getL10N('lib');
  350. if (isset(self::$backends[$itemType])) {
  351. return self::$backends[$itemType];
  352. } elseif (isset(self::$backendTypes[$itemType]['class'])) {
  353. $class = self::$backendTypes[$itemType]['class'];
  354. if (class_exists($class)) {
  355. self::$backends[$itemType] = new $class;
  356. if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
  357. $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
  358. $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]);
  359. \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
  360. throw new \Exception($message_t);
  361. }
  362. return self::$backends[$itemType];
  363. } else {
  364. $message = 'Sharing backend %s not found';
  365. $message_t = $l->t('Sharing backend %s not found', [$class]);
  366. \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
  367. throw new \Exception($message_t);
  368. }
  369. }
  370. $message = 'Sharing backend for %s not found';
  371. $message_t = $l->t('Sharing backend for %s not found', [$itemType]);
  372. \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
  373. throw new \Exception($message_t);
  374. }
  375. /**
  376. * Check if resharing is allowed
  377. * @return boolean true if allowed or false
  378. *
  379. * Resharing is allowed by default if not configured
  380. */
  381. public static function isResharingAllowed() {
  382. if (!isset(self::$isResharingAllowed)) {
  383. if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
  384. self::$isResharingAllowed = true;
  385. } else {
  386. self::$isResharingAllowed = false;
  387. }
  388. }
  389. return self::$isResharingAllowed;
  390. }
  391. /**
  392. * Get a list of collection item types for the specified item type
  393. * @param string $itemType
  394. * @return array
  395. */
  396. private static function getCollectionItemTypes($itemType) {
  397. $collectionTypes = [$itemType];
  398. foreach (self::$backendTypes as $type => $backend) {
  399. if (in_array($backend['collectionOf'], $collectionTypes)) {
  400. $collectionTypes[] = $type;
  401. }
  402. }
  403. // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
  404. if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
  405. unset($collectionTypes[0]);
  406. }
  407. // Return array if collections were found or the item type is a
  408. // collection itself - collections can be inside collections
  409. if (count($collectionTypes) > 0) {
  410. return $collectionTypes;
  411. }
  412. return false;
  413. }
  414. /**
  415. * Get shared items from the database
  416. * @param string $itemType
  417. * @param string $item Item source or target (optional)
  418. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
  419. * @param string $shareWith User or group the item is being shared with
  420. * @param string $uidOwner User that is the owner of shared items (optional)
  421. * @param int $format Format to convert items to with formatItems() (optional)
  422. * @param mixed $parameters to pass to formatItems() (optional)
  423. * @param int $limit Number of items to return, -1 to return all matches (optional)
  424. * @param boolean $includeCollections Include collection item types (optional)
  425. * @param boolean $itemShareWithBySource (optional)
  426. * @param boolean $checkExpireDate
  427. * @return array
  428. *
  429. * See public functions getItem(s)... for parameter usage
  430. *
  431. */
  432. public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
  433. $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
  434. $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) {
  435. if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
  436. return [];
  437. }
  438. $backend = self::getBackend($itemType);
  439. $collectionTypes = false;
  440. // Get filesystem root to add it to the file target and remove from the
  441. // file source, match file_source with the file cache
  442. if ($itemType == 'file' || $itemType == 'folder') {
  443. if (!is_null($uidOwner)) {
  444. $root = \OC\Files\Filesystem::getRoot();
  445. } else {
  446. $root = '';
  447. }
  448. $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
  449. if (!isset($item)) {
  450. $where .= ' AND `file_target` IS NOT NULL ';
  451. }
  452. $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
  453. $fileDependent = true;
  454. $queryArgs = [];
  455. } else {
  456. $fileDependent = false;
  457. $root = '';
  458. $collectionTypes = self::getCollectionItemTypes($itemType);
  459. if ($includeCollections && !isset($item) && $collectionTypes) {
  460. // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
  461. if (!in_array($itemType, $collectionTypes)) {
  462. $itemTypes = array_merge([$itemType], $collectionTypes);
  463. } else {
  464. $itemTypes = $collectionTypes;
  465. }
  466. $placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
  467. $where = ' WHERE `item_type` IN ('.$placeholders.'))';
  468. $queryArgs = $itemTypes;
  469. } else {
  470. $where = ' WHERE `item_type` = ?';
  471. $queryArgs = [$itemType];
  472. }
  473. }
  474. if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
  475. $where .= ' AND `share_type` != ?';
  476. $queryArgs[] = IShare::TYPE_LINK;
  477. }
  478. if (isset($shareType)) {
  479. // Include all user and group items
  480. if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
  481. $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
  482. $queryArgs[] = IShare::TYPE_USER;
  483. $queryArgs[] = self::$shareTypeGroupUserUnique;
  484. $queryArgs[] = $shareWith;
  485. $user = \OC::$server->getUserManager()->get($shareWith);
  486. $groups = [];
  487. if ($user) {
  488. $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
  489. }
  490. if (!empty($groups)) {
  491. $placeholders = implode(',', array_fill(0, count($groups), '?'));
  492. $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
  493. $queryArgs[] = IShare::TYPE_GROUP;
  494. $queryArgs = array_merge($queryArgs, $groups);
  495. }
  496. $where .= ')';
  497. // Don't include own group shares
  498. $where .= ' AND `uid_owner` != ?';
  499. $queryArgs[] = $shareWith;
  500. } else {
  501. $where .= ' AND `share_type` = ?';
  502. $queryArgs[] = $shareType;
  503. if (isset($shareWith)) {
  504. $where .= ' AND `share_with` = ?';
  505. $queryArgs[] = $shareWith;
  506. }
  507. }
  508. }
  509. if (isset($uidOwner)) {
  510. $where .= ' AND `uid_owner` = ?';
  511. $queryArgs[] = $uidOwner;
  512. if (!isset($shareType)) {
  513. // Prevent unique user targets for group shares from being selected
  514. $where .= ' AND `share_type` != ?';
  515. $queryArgs[] = self::$shareTypeGroupUserUnique;
  516. }
  517. if ($fileDependent) {
  518. $column = 'file_source';
  519. } else {
  520. $column = 'item_source';
  521. }
  522. } else {
  523. if ($fileDependent) {
  524. $column = 'file_target';
  525. } else {
  526. $column = 'item_target';
  527. }
  528. }
  529. if (isset($item)) {
  530. $collectionTypes = self::getCollectionItemTypes($itemType);
  531. if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
  532. $where .= ' AND (';
  533. } else {
  534. $where .= ' AND';
  535. }
  536. // If looking for own shared items, check item_source else check item_target
  537. if (isset($uidOwner) || $itemShareWithBySource) {
  538. // If item type is a file, file source needs to be checked in case the item was converted
  539. if ($fileDependent) {
  540. $where .= ' `file_source` = ?';
  541. $column = 'file_source';
  542. } else {
  543. $where .= ' `item_source` = ?';
  544. $column = 'item_source';
  545. }
  546. } else {
  547. if ($fileDependent) {
  548. $where .= ' `file_target` = ?';
  549. $item = \OC\Files\Filesystem::normalizePath($item);
  550. } else {
  551. $where .= ' `item_target` = ?';
  552. }
  553. }
  554. $queryArgs[] = $item;
  555. if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
  556. $placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
  557. $where .= ' OR `item_type` IN ('.$placeholders.'))';
  558. $queryArgs = array_merge($queryArgs, $collectionTypes);
  559. }
  560. }
  561. if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
  562. // Make sure the unique user target is returned if it exists,
  563. // unique targets should follow the group share in the database
  564. // If the limit is not 1, the filtering can be done later
  565. $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
  566. } else {
  567. $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
  568. }
  569. if ($limit != -1 && !$includeCollections) {
  570. // The limit must be at least 3, because filtering needs to be done
  571. if ($limit < 3) {
  572. $queryLimit = 3;
  573. } else {
  574. $queryLimit = $limit;
  575. }
  576. } else {
  577. $queryLimit = null;
  578. }
  579. $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
  580. $root = strlen($root);
  581. $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
  582. $result = $query->execute($queryArgs);
  583. if ($result === false) {
  584. \OCP\Util::writeLog('OCP\Share',
  585. \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
  586. ILogger::ERROR);
  587. }
  588. $items = [];
  589. $targets = [];
  590. $switchedItems = [];
  591. $mounts = [];
  592. while ($row = $result->fetchRow()) {
  593. self::transformDBResults($row);
  594. // Filter out duplicate group shares for users with unique targets
  595. if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
  596. continue;
  597. }
  598. if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
  599. $row['share_type'] = IShare::TYPE_GROUP;
  600. $row['unique_name'] = true; // remember that we use a unique name for this user
  601. $row['share_with'] = $items[$row['parent']]['share_with'];
  602. // if the group share was unshared from the user we keep the permission, otherwise
  603. // we take the permission from the parent because this is always the up-to-date
  604. // permission for the group share
  605. if ($row['permissions'] > 0) {
  606. $row['permissions'] = $items[$row['parent']]['permissions'];
  607. }
  608. // Remove the parent group share
  609. unset($items[$row['parent']]);
  610. if ($row['permissions'] == 0) {
  611. continue;
  612. }
  613. } elseif (!isset($uidOwner)) {
  614. // Check if the same target already exists
  615. if (isset($targets[$row['id']])) {
  616. // Check if the same owner shared with the user twice
  617. // through a group and user share - this is allowed
  618. $id = $targets[$row['id']];
  619. if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
  620. // Switch to group share type to ensure resharing conditions aren't bypassed
  621. if ($items[$id]['share_type'] != IShare::TYPE_GROUP) {
  622. $items[$id]['share_type'] = IShare::TYPE_GROUP;
  623. $items[$id]['share_with'] = $row['share_with'];
  624. }
  625. // Switch ids if sharing permission is granted on only
  626. // one share to ensure correct parent is used if resharing
  627. if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
  628. && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
  629. $items[$row['id']] = $items[$id];
  630. $switchedItems[$id] = $row['id'];
  631. unset($items[$id]);
  632. $id = $row['id'];
  633. }
  634. $items[$id]['permissions'] |= (int)$row['permissions'];
  635. }
  636. continue;
  637. } elseif (!empty($row['parent'])) {
  638. $targets[$row['parent']] = $row['id'];
  639. }
  640. }
  641. // Remove root from file source paths if retrieving own shared items
  642. if (isset($uidOwner) && isset($row['path'])) {
  643. if (isset($row['parent'])) {
  644. $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
  645. $parentResult = $query->execute([$row['parent']]);
  646. if ($result === false) {
  647. \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
  648. \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
  649. ILogger::ERROR);
  650. } else {
  651. $parentRow = $parentResult->fetchRow();
  652. $tmpPath = $parentRow['file_target'];
  653. // find the right position where the row path continues from the target path
  654. $pos = strrpos($row['path'], $parentRow['file_target']);
  655. $subPath = substr($row['path'], $pos);
  656. $splitPath = explode('/', $subPath);
  657. foreach (array_slice($splitPath, 2) as $pathPart) {
  658. $tmpPath = $tmpPath . '/' . $pathPart;
  659. }
  660. $row['path'] = $tmpPath;
  661. }
  662. } else {
  663. if (!isset($mounts[$row['storage']])) {
  664. $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
  665. if (is_array($mountPoints) && !empty($mountPoints)) {
  666. $mounts[$row['storage']] = current($mountPoints);
  667. }
  668. }
  669. if (!empty($mounts[$row['storage']])) {
  670. $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
  671. $relPath = substr($path, $root); // path relative to data/user
  672. $row['path'] = rtrim($relPath, '/');
  673. }
  674. }
  675. }
  676. if ($checkExpireDate) {
  677. if (self::expireItem($row)) {
  678. continue;
  679. }
  680. }
  681. // Check if resharing is allowed, if not remove share permission
  682. if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
  683. $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
  684. }
  685. // Add display names to result
  686. $row['share_with_displayname'] = $row['share_with'];
  687. if (isset($row['share_with']) && $row['share_with'] != '' &&
  688. $row['share_type'] === IShare::TYPE_USER) {
  689. $shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
  690. $row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
  691. } elseif (isset($row['share_with']) && $row['share_with'] != '' &&
  692. $row['share_type'] === IShare::TYPE_REMOTE) {
  693. $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
  694. foreach ($addressBookEntries as $entry) {
  695. foreach ($entry['CLOUD'] as $cloudID) {
  696. if ($cloudID === $row['share_with']) {
  697. $row['share_with_displayname'] = $entry['FN'];
  698. }
  699. }
  700. }
  701. }
  702. if (isset($row['uid_owner']) && $row['uid_owner'] != '') {
  703. $ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
  704. $row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
  705. }
  706. if ($row['permissions'] > 0) {
  707. $items[$row['id']] = $row;
  708. }
  709. }
  710. // group items if we are looking for items shared with the current user
  711. if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
  712. $items = self::groupItems($items, $itemType);
  713. }
  714. if (!empty($items)) {
  715. $collectionItems = [];
  716. foreach ($items as &$row) {
  717. // Return only the item instead of a 2-dimensional array
  718. if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
  719. if ($format == self::FORMAT_NONE) {
  720. return $row;
  721. } else {
  722. break;
  723. }
  724. }
  725. // Check if this is a collection of the requested item type
  726. if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
  727. if (($collectionBackend = self::getBackend($row['item_type']))
  728. && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
  729. // Collections can be inside collections, check if the item is a collection
  730. if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
  731. $collectionItems[] = $row;
  732. } else {
  733. $collection = [];
  734. $collection['item_type'] = $row['item_type'];
  735. if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
  736. $collection['path'] = basename($row['path']);
  737. }
  738. $row['collection'] = $collection;
  739. // Fetch all of the children sources
  740. $children = $collectionBackend->getChildren($row[$column]);
  741. foreach ($children as $child) {
  742. $childItem = $row;
  743. $childItem['item_type'] = $itemType;
  744. if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
  745. $childItem['item_source'] = $child['source'];
  746. $childItem['item_target'] = $child['target'];
  747. }
  748. if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
  749. if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
  750. $childItem['file_source'] = $child['source'];
  751. } else { // TODO is this really needed if we already know that we use the file backend?
  752. $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
  753. $childItem['file_source'] = $meta['fileid'];
  754. }
  755. $childItem['file_target'] =
  756. \OC\Files\Filesystem::normalizePath($child['file_path']);
  757. }
  758. if (isset($item)) {
  759. if ($childItem[$column] == $item) {
  760. // Return only the item instead of a 2-dimensional array
  761. if ($limit == 1) {
  762. if ($format == self::FORMAT_NONE) {
  763. return $childItem;
  764. } else {
  765. // Unset the items array and break out of both loops
  766. $items = [];
  767. $items[] = $childItem;
  768. break 2;
  769. }
  770. } else {
  771. $collectionItems[] = $childItem;
  772. }
  773. }
  774. } else {
  775. $collectionItems[] = $childItem;
  776. }
  777. }
  778. }
  779. }
  780. // Remove collection item
  781. $toRemove = $row['id'];
  782. if (array_key_exists($toRemove, $switchedItems)) {
  783. $toRemove = $switchedItems[$toRemove];
  784. }
  785. unset($items[$toRemove]);
  786. } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
  787. // FIXME: Thats a dirty hack to improve file sharing performance,
  788. // see github issue #10588 for more details
  789. // Need to find a solution which works for all back-ends
  790. $collectionBackend = self::getBackend($row['item_type']);
  791. $sharedParents = $collectionBackend->getParents($row['item_source']);
  792. foreach ($sharedParents as $parent) {
  793. $collectionItems[] = $parent;
  794. }
  795. }
  796. }
  797. if (!empty($collectionItems)) {
  798. $collectionItems = array_unique($collectionItems, SORT_REGULAR);
  799. $items = array_merge($items, $collectionItems);
  800. }
  801. // filter out invalid items, these can appear when subshare entries exist
  802. // for a group in which the requested user isn't a member any more
  803. $items = array_filter($items, function ($item) {
  804. return $item['share_type'] !== self::$shareTypeGroupUserUnique;
  805. });
  806. return self::formatResult($items, $column, $backend, $format, $parameters);
  807. } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
  808. // FIXME: Thats a dirty hack to improve file sharing performance,
  809. // see github issue #10588 for more details
  810. // Need to find a solution which works for all back-ends
  811. $collectionItems = [];
  812. $collectionBackend = self::getBackend('folder');
  813. $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
  814. foreach ($sharedParents as $parent) {
  815. $collectionItems[] = $parent;
  816. }
  817. if ($limit === 1) {
  818. return reset($collectionItems);
  819. }
  820. return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
  821. }
  822. return [];
  823. }
  824. /**
  825. * group items with link to the same source
  826. *
  827. * @param array $items
  828. * @param string $itemType
  829. * @return array of grouped items
  830. */
  831. protected static function groupItems($items, $itemType) {
  832. $fileSharing = $itemType === 'file' || $itemType === 'folder';
  833. $result = [];
  834. foreach ($items as $item) {
  835. $grouped = false;
  836. foreach ($result as $key => $r) {
  837. // for file/folder shares we need to compare file_source, otherwise we compare item_source
  838. // only group shares if they already point to the same target, otherwise the file where shared
  839. // before grouping of shares was added. In this case we don't group them toi avoid confusions
  840. if (($fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
  841. (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
  842. // add the first item to the list of grouped shares
  843. if (!isset($result[$key]['grouped'])) {
  844. $result[$key]['grouped'][] = $result[$key];
  845. }
  846. $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
  847. $result[$key]['grouped'][] = $item;
  848. $grouped = true;
  849. break;
  850. }
  851. }
  852. if (!$grouped) {
  853. $result[] = $item;
  854. }
  855. }
  856. return $result;
  857. }
  858. /**
  859. * construct select statement
  860. * @param int $format
  861. * @param boolean $fileDependent ist it a file/folder share or a generla share
  862. * @param string $uidOwner
  863. * @return string select statement
  864. */
  865. private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
  866. $select = '*';
  867. if ($format == self::FORMAT_STATUSES) {
  868. if ($fileDependent) {
  869. $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
  870. . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
  871. . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
  872. . '`uid_initiator`';
  873. } else {
  874. $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
  875. }
  876. } else {
  877. if (isset($uidOwner)) {
  878. if ($fileDependent) {
  879. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
  880. . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
  881. . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
  882. . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
  883. } else {
  884. $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
  885. . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
  886. }
  887. } else {
  888. if ($fileDependent) {
  889. if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
  890. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
  891. . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
  892. . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
  893. . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
  894. } else {
  895. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
  896. . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
  897. . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
  898. . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
  899. . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
  900. }
  901. }
  902. }
  903. }
  904. return $select;
  905. }
  906. /**
  907. * transform db results
  908. * @param array $row result
  909. */
  910. private static function transformDBResults(&$row) {
  911. if (isset($row['id'])) {
  912. $row['id'] = (int) $row['id'];
  913. }
  914. if (isset($row['share_type'])) {
  915. $row['share_type'] = (int) $row['share_type'];
  916. }
  917. if (isset($row['parent'])) {
  918. $row['parent'] = (int) $row['parent'];
  919. }
  920. if (isset($row['file_parent'])) {
  921. $row['file_parent'] = (int) $row['file_parent'];
  922. }
  923. if (isset($row['file_source'])) {
  924. $row['file_source'] = (int) $row['file_source'];
  925. }
  926. if (isset($row['permissions'])) {
  927. $row['permissions'] = (int) $row['permissions'];
  928. }
  929. if (isset($row['storage'])) {
  930. $row['storage'] = (int) $row['storage'];
  931. }
  932. if (isset($row['stime'])) {
  933. $row['stime'] = (int) $row['stime'];
  934. }
  935. if (isset($row['expiration']) && $row['share_type'] !== IShare::TYPE_LINK) {
  936. // discard expiration date for non-link shares, which might have been
  937. // set by ancient bugs
  938. $row['expiration'] = null;
  939. }
  940. }
  941. /**
  942. * format result
  943. * @param array $items result
  944. * @param string $column is it a file share or a general share ('file_target' or 'item_target')
  945. * @param \OCP\Share_Backend $backend sharing backend
  946. * @param int $format
  947. * @param array $parameters additional format parameters
  948. * @return array format result
  949. */
  950. private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
  951. if ($format === self::FORMAT_NONE) {
  952. return $items;
  953. } elseif ($format === self::FORMAT_STATUSES) {
  954. $statuses = [];
  955. foreach ($items as $item) {
  956. if ($item['share_type'] === IShare::TYPE_LINK) {
  957. if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
  958. continue;
  959. }
  960. $statuses[$item[$column]]['link'] = true;
  961. } elseif (!isset($statuses[$item[$column]])) {
  962. $statuses[$item[$column]]['link'] = false;
  963. }
  964. if (!empty($item['file_target'])) {
  965. $statuses[$item[$column]]['path'] = $item['path'];
  966. }
  967. }
  968. return $statuses;
  969. } else {
  970. return $backend->formatItems($items, $format, $parameters);
  971. }
  972. }
  973. /**
  974. * remove protocol from URL
  975. *
  976. * @param string $url
  977. * @return string
  978. */
  979. public static function removeProtocolFromUrl($url) {
  980. if (strpos($url, 'https://') === 0) {
  981. return substr($url, strlen('https://'));
  982. } elseif (strpos($url, 'http://') === 0) {
  983. return substr($url, strlen('http://'));
  984. }
  985. return $url;
  986. }
  987. /**
  988. * try http post first with https and then with http as a fallback
  989. *
  990. * @param string $remoteDomain
  991. * @param string $urlSuffix
  992. * @param array $fields post parameters
  993. * @return array
  994. */
  995. private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
  996. $protocol = 'https://';
  997. $result = [
  998. 'success' => false,
  999. 'result' => '',
  1000. ];
  1001. $try = 0;
  1002. $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
  1003. while ($result['success'] === false && $try < 2) {
  1004. $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
  1005. $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
  1006. $client = \OC::$server->getHTTPClientService()->newClient();
  1007. try {
  1008. $response = $client->post(
  1009. $protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
  1010. [
  1011. 'body' => $fields,
  1012. 'connect_timeout' => 10,
  1013. ]
  1014. );
  1015. $result = ['success' => true, 'result' => $response->getBody()];
  1016. } catch (\Exception $e) {
  1017. $result = ['success' => false, 'result' => $e->getMessage()];
  1018. }
  1019. $try++;
  1020. $protocol = 'http://';
  1021. }
  1022. return $result;
  1023. }
  1024. /**
  1025. * send server-to-server unshare to remote server
  1026. *
  1027. * @param string $remote url
  1028. * @param int $id share id
  1029. * @param string $token
  1030. * @return bool
  1031. */
  1032. private static function sendRemoteUnshare($remote, $id, $token) {
  1033. $url = rtrim($remote, '/');
  1034. $fields = ['token' => $token, 'format' => 'json'];
  1035. $url = self::removeProtocolFromUrl($url);
  1036. $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
  1037. $status = json_decode($result['result'], true);
  1038. return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
  1039. }
  1040. /**
  1041. * @return int
  1042. */
  1043. public static function getExpireInterval() {
  1044. return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
  1045. }
  1046. /**
  1047. * Checks whether the given path is reachable for the given owner
  1048. *
  1049. * @param string $path path relative to files
  1050. * @param string $ownerStorageId storage id of the owner
  1051. *
  1052. * @return boolean true if file is reachable, false otherwise
  1053. */
  1054. private static function isFileReachable($path, $ownerStorageId) {
  1055. // if outside the home storage, file is always considered reachable
  1056. if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
  1057. substr($ownerStorageId, 0, 13) === 'object::user:'
  1058. )) {
  1059. return true;
  1060. }
  1061. // if inside the home storage, the file has to be under "/files/"
  1062. $path = ltrim($path, '/');
  1063. if (substr($path, 0, 6) === 'files/') {
  1064. return true;
  1065. }
  1066. return false;
  1067. }
  1068. }