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.

1610 lines
58 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Bjoern Schiessle, Michael Gapczynski
  6. * @copyright 2012 Michael Gapczynski <mtgap@owncloud.com>
  7. * 2014 Bjoern Schiessle <schiessle@owncloud.com>
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  11. * License as published by the Free Software Foundation; either
  12. * version 3 of the License, or any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public
  20. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  21. */
  22. namespace OC\Share;
  23. /**
  24. * This class provides the ability for apps to share their content between users.
  25. * Apps must create a backend class that implements OCP\Share_Backend and register it with this class.
  26. *
  27. * It provides the following hooks:
  28. * - post_shared
  29. */
  30. class Share extends \OC\Share\Constants {
  31. /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
  32. * Construct permissions for share() and setPermissions with Or (|) e.g.
  33. * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
  34. *
  35. * Check if permission is granted with And (&) e.g. Check if delete is
  36. * granted: if ($permissions & PERMISSION_DELETE)
  37. *
  38. * Remove permissions with And (&) and Not (~) e.g. Remove the update
  39. * permission: $permissions &= ~PERMISSION_UPDATE
  40. *
  41. * Apps are required to handle permissions on their own, this class only
  42. * stores and manages the permissions of shares
  43. * @see lib/public/constants.php
  44. */
  45. /**
  46. * Register a sharing backend class that implements OCP\Share_Backend for an item type
  47. * @param string Item type
  48. * @param string Backend class
  49. * @param string (optional) Depends on item type
  50. * @param array (optional) List of supported file extensions if this item type depends on files
  51. * @return Returns true if backend is registered or false if error
  52. */
  53. public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
  54. if (self::isEnabled()) {
  55. if (!isset(self::$backendTypes[$itemType])) {
  56. self::$backendTypes[$itemType] = array(
  57. 'class' => $class,
  58. 'collectionOf' => $collectionOf,
  59. 'supportedFileExtensions' => $supportedFileExtensions
  60. );
  61. if(count(self::$backendTypes) === 1) {
  62. \OC_Util::addScript('core', 'share');
  63. \OC_Util::addStyle('core', 'share');
  64. }
  65. return true;
  66. }
  67. \OC_Log::write('OCP\Share',
  68. 'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
  69. .' is already registered for '.$itemType,
  70. \OC_Log::WARN);
  71. }
  72. return false;
  73. }
  74. /**
  75. * Check if the Share API is enabled
  76. * @return Returns true if enabled or false
  77. *
  78. * The Share API is enabled by default if not configured
  79. */
  80. public static function isEnabled() {
  81. if (\OC_Appconfig::getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
  82. return true;
  83. }
  84. return false;
  85. }
  86. /**
  87. * Find which users can access a shared item
  88. * @param $path to the file
  89. * @param $user owner of the file
  90. * @param include owner to the list of users with access to the file
  91. * @return array
  92. * @note $path needs to be relative to user data dir, e.g. 'file.txt'
  93. * not '/admin/data/file.txt'
  94. */
  95. public static function getUsersSharingFile($path, $user, $includeOwner = false) {
  96. $shares = array();
  97. $publicShare = false;
  98. $source = -1;
  99. $cache = false;
  100. $view = new \OC\Files\View('/' . $user . '/files');
  101. if ($view->file_exists($path)) {
  102. $meta = $view->getFileInfo($path);
  103. } else {
  104. // if the file doesn't exists yet we start with the parent folder
  105. $meta = $view->getFileInfo(dirname($path));
  106. }
  107. if($meta !== false) {
  108. $source = $meta['fileid'];
  109. $cache = new \OC\Files\Cache\Cache($meta['storage']);
  110. }
  111. while ($source !== -1) {
  112. // Fetch all shares with another user
  113. $query = \OC_DB::prepare(
  114. 'SELECT `share_with`
  115. FROM
  116. `*PREFIX*share`
  117. WHERE
  118. `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
  119. );
  120. $result = $query->execute(array($source, self::SHARE_TYPE_USER));
  121. if (\OCP\DB::isError($result)) {
  122. \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR);
  123. } else {
  124. while ($row = $result->fetchRow()) {
  125. $shares[] = $row['share_with'];
  126. }
  127. }
  128. // We also need to take group shares into account
  129. $query = \OC_DB::prepare(
  130. 'SELECT `share_with`
  131. FROM
  132. `*PREFIX*share`
  133. WHERE
  134. `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
  135. );
  136. $result = $query->execute(array($source, self::SHARE_TYPE_GROUP));
  137. if (\OCP\DB::isError($result)) {
  138. \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR);
  139. } else {
  140. while ($row = $result->fetchRow()) {
  141. $usersInGroup = \OC_Group::usersInGroup($row['share_with']);
  142. $shares = array_merge($shares, $usersInGroup);
  143. }
  144. }
  145. //check for public link shares
  146. if (!$publicShare) {
  147. $query = \OC_DB::prepare(
  148. 'SELECT `share_with`
  149. FROM
  150. `*PREFIX*share`
  151. WHERE
  152. `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
  153. );
  154. $result = $query->execute(array($source, self::SHARE_TYPE_LINK));
  155. if (\OCP\DB::isError($result)) {
  156. \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR);
  157. } else {
  158. if ($result->fetchRow()) {
  159. $publicShare = true;
  160. }
  161. }
  162. }
  163. // let's get the parent for the next round
  164. $meta = $cache->get((int)$source);
  165. if($meta !== false) {
  166. $source = (int)$meta['parent'];
  167. } else {
  168. $source = -1;
  169. }
  170. }
  171. // Include owner in list of users, if requested
  172. if ($includeOwner) {
  173. $shares[] = $user;
  174. }
  175. return array("users" => array_unique($shares), "public" => $publicShare);
  176. }
  177. /**
  178. * Get the items of item type shared with the current user
  179. * @param string Item type
  180. * @param int Format (optional) Format type must be defined by the backend
  181. * @param mixed Parameters (optional)
  182. * @param int Number of items to return (optional) Returns all by default
  183. * @param bool include collections (optional)
  184. * @return Return depends on format
  185. */
  186. public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
  187. $parameters = null, $limit = -1, $includeCollections = false) {
  188. return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
  189. $parameters, $limit, $includeCollections);
  190. }
  191. /**
  192. * Get the item of item type shared with the current user
  193. * @param string $itemType
  194. * @param string $itemTarget
  195. * @param int $format (optional) Format type must be defined by the backend
  196. * @param mixed Parameters (optional)
  197. * @param bool include collections (optional)
  198. * @return Return depends on format
  199. */
  200. public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE,
  201. $parameters = null, $includeCollections = false) {
  202. return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
  203. $parameters, 1, $includeCollections);
  204. }
  205. /**
  206. * Get the item of item type shared with a given user by source
  207. * @param string $itemType
  208. * @param string $itemSource
  209. * @param string $user User user to whom the item was shared
  210. * @return array Return list of items with file_target, permissions and expiration
  211. */
  212. public static function getItemSharedWithUser($itemType, $itemSource, $user) {
  213. $shares = array();
  214. // first check if there is a db entry for the specific user
  215. $query = \OC_DB::prepare(
  216. 'SELECT `file_target`, `permissions`, `expiration`
  217. FROM
  218. `*PREFIX*share`
  219. WHERE
  220. `item_source` = ? AND `item_type` = ? AND `share_with` = ?'
  221. );
  222. $result = \OC_DB::executeAudited($query, array($itemSource, $itemType, $user));
  223. while ($row = $result->fetchRow()) {
  224. $shares[] = $row;
  225. }
  226. //if didn't found a result than let's look for a group share.
  227. if(empty($shares)) {
  228. $groups = \OC_Group::getUserGroups($user);
  229. $query = \OC_DB::prepare(
  230. 'SELECT `file_target`, `permissions`, `expiration`
  231. FROM
  232. `*PREFIX*share`
  233. WHERE
  234. `item_source` = ? AND `item_type` = ? AND `share_with` in (?)'
  235. );
  236. $result = \OC_DB::executeAudited($query, array($itemSource, $itemType, implode(',', $groups)));
  237. while ($row = $result->fetchRow()) {
  238. $shares[] = $row;
  239. }
  240. }
  241. return $shares;
  242. }
  243. /**
  244. * Get the item of item type shared with the current user by source
  245. * @param string Item type
  246. * @param string Item source
  247. * @param int Format (optional) Format type must be defined by the backend
  248. * @param mixed Parameters
  249. * @param bool include collections
  250. * @return Return depends on format
  251. */
  252. public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
  253. $parameters = null, $includeCollections = false) {
  254. return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
  255. $parameters, 1, $includeCollections, true);
  256. }
  257. /**
  258. * Get the item of item type shared by a link
  259. * @param string Item type
  260. * @param string Item source
  261. * @param string Owner of link
  262. * @return Item
  263. */
  264. public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
  265. return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE,
  266. null, 1);
  267. }
  268. /**
  269. * Based on the given token the share information will be returned - password protected shares will be verified
  270. * @param string $token
  271. * @return array | bool false will be returned in case the token is unknown or unauthorized
  272. */
  273. public static function getShareByToken($token, $checkPasswordProtection = true) {
  274. $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
  275. $result = $query->execute(array($token));
  276. if (\OC_DB::isError($result)) {
  277. \OC_Log::write('OCP\Share', \OC_DB::getErrorMessage($result) . ', token=' . $token, \OC_Log::ERROR);
  278. }
  279. $row = $result->fetchRow();
  280. if ($row === false) {
  281. return false;
  282. }
  283. if (is_array($row) and self::expireItem($row)) {
  284. return false;
  285. }
  286. // password protected shares need to be authenticated
  287. if ($checkPasswordProtection && !\OCP\Share::checkPasswordProtectedShare($row)) {
  288. return false;
  289. }
  290. return $row;
  291. }
  292. /**
  293. * resolves reshares down to the last real share
  294. * @param $linkItem
  295. * @return $fileOwner
  296. */
  297. public static function resolveReShare($linkItem)
  298. {
  299. if (isset($linkItem['parent'])) {
  300. $parent = $linkItem['parent'];
  301. while (isset($parent)) {
  302. $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
  303. $item = $query->execute(array($parent))->fetchRow();
  304. if (isset($item['parent'])) {
  305. $parent = $item['parent'];
  306. } else {
  307. return $item;
  308. }
  309. }
  310. }
  311. return $linkItem;
  312. }
  313. /**
  314. * Get the shared items of item type owned by the current user
  315. * @param string Item type
  316. * @param int Format (optional) Format type must be defined by the backend
  317. * @param mixed Parameters
  318. * @param int Number of items to return (optional) Returns all by default
  319. * @param bool include collections
  320. * @return Return depends on format
  321. */
  322. public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
  323. $limit = -1, $includeCollections = false) {
  324. return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
  325. $parameters, $limit, $includeCollections);
  326. }
  327. /**
  328. * Get the shared item of item type owned by the current user
  329. * @param string Item type
  330. * @param string Item source
  331. * @param int Format (optional) Format type must be defined by the backend
  332. * @param mixed Parameters
  333. * @param bool include collections
  334. * @return Return depends on format
  335. */
  336. public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
  337. $parameters = null, $includeCollections = false) {
  338. return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
  339. $parameters, -1, $includeCollections);
  340. }
  341. /**
  342. * Get all users an item is shared with
  343. * @param string Item type
  344. * @param string Item source
  345. * @param string Owner
  346. * @param bool Include collections
  347. * @praram bool check expire date
  348. * @return Return array of users
  349. */
  350. public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
  351. $users = array();
  352. $items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
  353. if ($items) {
  354. foreach ($items as $item) {
  355. if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
  356. $users[] = $item['share_with'];
  357. } else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
  358. $users = array_merge($users, \OC_Group::usersInGroup($item['share_with']));
  359. }
  360. }
  361. }
  362. return $users;
  363. }
  364. /**
  365. * Share an item with a user, group, or via private link
  366. * @param string $itemType
  367. * @param string $itemSource
  368. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  369. * @param string $shareWith User or group the item is being shared with
  370. * @param int $permissions CRUDS
  371. * @param null $itemSourceName
  372. * @throws \Exception
  373. * @internal param \OCP\Item $string type
  374. * @internal param \OCP\Item $string source
  375. * @internal param \OCP\SHARE_TYPE_USER $int , SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  376. * @internal param \OCP\User $string or group the item is being shared with
  377. * @internal param \OCP\CRUDS $int permissions
  378. * @return bool|string Returns true on success or false on failure, Returns token on success for links
  379. */
  380. public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null) {
  381. $uidOwner = \OC_User::getUser();
  382. $sharingPolicy = \OC_Appconfig::getValue('core', 'shareapi_share_policy', 'global');
  383. if (is_null($itemSourceName)) {
  384. $itemSourceName = $itemSource;
  385. }
  386. // Verify share type and sharing conditions are met
  387. if ($shareType === self::SHARE_TYPE_USER) {
  388. if ($shareWith == $uidOwner) {
  389. $message = 'Sharing '.$itemSourceName.' failed, because the user '.$shareWith.' is the item owner';
  390. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  391. throw new \Exception($message);
  392. }
  393. if (!\OC_User::userExists($shareWith)) {
  394. $message = 'Sharing '.$itemSourceName.' failed, because the user '.$shareWith.' does not exist';
  395. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  396. throw new \Exception($message);
  397. }
  398. if ($sharingPolicy == 'groups_only') {
  399. $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
  400. if (empty($inGroup)) {
  401. $message = 'Sharing '.$itemSourceName.' failed, because the user '
  402. .$shareWith.' is not a member of any groups that '.$uidOwner.' is a member of';
  403. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  404. throw new \Exception($message);
  405. }
  406. }
  407. // Check if the item source is already shared with the user, either from the same owner or a different user
  408. if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
  409. $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
  410. // Only allow the same share to occur again if it is the same
  411. // owner and is not a user share, this use case is for increasing
  412. // permissions for a specific user
  413. if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
  414. $message = 'Sharing '.$itemSourceName.' failed, because this item is already shared with '.$shareWith;
  415. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  416. throw new \Exception($message);
  417. }
  418. }
  419. } else if ($shareType === self::SHARE_TYPE_GROUP) {
  420. if (!\OC_Group::groupExists($shareWith)) {
  421. $message = 'Sharing '.$itemSourceName.' failed, because the group '.$shareWith.' does not exist';
  422. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  423. throw new \Exception($message);
  424. }
  425. if ($sharingPolicy == 'groups_only' && !\OC_Group::inGroup($uidOwner, $shareWith)) {
  426. $message = 'Sharing '.$itemSourceName.' failed, because '
  427. .$uidOwner.' is not a member of the group '.$shareWith;
  428. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  429. throw new \Exception($message);
  430. }
  431. // Check if the item source is already shared with the group, either from the same owner or a different user
  432. // The check for each user in the group is done inside the put() function
  433. if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
  434. null, self::FORMAT_NONE, null, 1, true, true)) {
  435. // Only allow the same share to occur again if it is the same
  436. // owner and is not a group share, this use case is for increasing
  437. // permissions for a specific user
  438. if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
  439. $message = 'Sharing '.$itemSourceName.' failed, because this item is already shared with '.$shareWith;
  440. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  441. throw new \Exception($message);
  442. }
  443. }
  444. // Convert share with into an array with the keys group and users
  445. $group = $shareWith;
  446. $shareWith = array();
  447. $shareWith['group'] = $group;
  448. $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
  449. } else if ($shareType === self::SHARE_TYPE_LINK) {
  450. if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
  451. // when updating a link share
  452. if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
  453. $uidOwner, self::FORMAT_NONE, null, 1)) {
  454. // remember old token
  455. $oldToken = $checkExists['token'];
  456. $oldPermissions = $checkExists['permissions'];
  457. //delete the old share
  458. Helper::delete($checkExists['id']);
  459. }
  460. // Generate hash of password - same method as user passwords
  461. if (isset($shareWith)) {
  462. $forcePortable = (CRYPT_BLOWFISH != 1);
  463. $hasher = new \PasswordHash(8, $forcePortable);
  464. $shareWith = $hasher->HashPassword($shareWith.\OC_Config::getValue('passwordsalt', ''));
  465. } else {
  466. // reuse the already set password, but only if we change permissions
  467. // otherwise the user disabled the password protection
  468. if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
  469. $shareWith = $checkExists['share_with'];
  470. }
  471. }
  472. // Generate token
  473. if (isset($oldToken)) {
  474. $token = $oldToken;
  475. } else {
  476. $token = \OC_Util::generateRandomBytes(self::TOKEN_LENGTH);
  477. }
  478. $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
  479. null, $token, $itemSourceName);
  480. if ($result) {
  481. return $token;
  482. } else {
  483. return false;
  484. }
  485. }
  486. $message = 'Sharing '.$itemSourceName.' failed, because sharing with links is not allowed';
  487. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  488. throw new \Exception($message);
  489. return false;
  490. } else {
  491. // Future share types need to include their own conditions
  492. $message = 'Share type '.$shareType.' is not valid for '.$itemSource;
  493. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  494. throw new \Exception($message);
  495. }
  496. // Put the item into the database
  497. return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName);
  498. }
  499. /**
  500. * Unshare an item from a user, group, or delete a private link
  501. * @param string Item type
  502. * @param string Item source
  503. * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  504. * @param string User or group the item is being shared with
  505. * @return Returns true on success or false on failure
  506. */
  507. public static function unshare($itemType, $itemSource, $shareType, $shareWith) {
  508. $item = self::getItems($itemType, $itemSource, $shareType, $shareWith, \OC_User::getUser(),self::FORMAT_NONE, null, 1);
  509. if (!empty($item)) {
  510. self::unshareItem($item);
  511. return true;
  512. }
  513. return false;
  514. }
  515. /**
  516. * Unshare an item from all users, groups, and remove all links
  517. * @param string Item type
  518. * @param string Item source
  519. * @return Returns true on success or false on failure
  520. */
  521. public static function unshareAll($itemType, $itemSource) {
  522. // Get all of the owners of shares of this item.
  523. $query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
  524. $result = $query->execute(array($itemType, $itemSource));
  525. $shares = array();
  526. // Add each owner's shares to the array of all shares for this item.
  527. while ($row = $result->fetchRow()) {
  528. $shares = array_merge($shares, self::getItems($itemType, $itemSource, null, null, $row['uid_owner']));
  529. }
  530. if (!empty($shares)) {
  531. // Pass all the vars we have for now, they may be useful
  532. $hookParams = array(
  533. 'itemType' => $itemType,
  534. 'itemSource' => $itemSource,
  535. 'shares' => $shares,
  536. );
  537. \OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams);
  538. foreach ($shares as $share) {
  539. self::unshareItem($share);
  540. }
  541. \OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams);
  542. return true;
  543. }
  544. return false;
  545. }
  546. /**
  547. * Unshare an item shared with the current user
  548. * @param string Item type
  549. * @param string Item target
  550. * @return Returns true on success or false on failure
  551. *
  552. * Unsharing from self is not allowed for items inside collections
  553. */
  554. public static function unshareFromSelf($itemType, $itemTarget) {
  555. $item = self::getItemSharedWith($itemType, $itemTarget);
  556. if (!empty($item)) {
  557. if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
  558. // Insert an extra row for the group share and set permission
  559. // to 0 to prevent it from showing up for the user
  560. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share`'
  561. .' (`item_type`, `item_source`, `item_target`, `parent`, `share_type`,'
  562. .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`)'
  563. .' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
  564. $query->execute(array($item['item_type'], $item['item_source'], $item['item_target'],
  565. $item['id'], self::$shareTypeGroupUserUnique,
  566. \OC_User::getUser(), $item['uid_owner'], 0, $item['stime'], $item['file_source'],
  567. $item['file_target']));
  568. \OC_DB::insertid('*PREFIX*share');
  569. // Delete all reshares by this user of the group share
  570. Helper::delete($item['id'], true, \OC_User::getUser());
  571. } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
  572. // Set permission to 0 to prevent it from showing up for the user
  573. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
  574. $query->execute(array(0, $item['id']));
  575. Helper::delete($item['id'], true);
  576. } else {
  577. Helper::delete($item['id']);
  578. }
  579. return true;
  580. }
  581. return false;
  582. }
  583. /**
  584. * sent status if users got informed by mail about share
  585. * @param string $itemType
  586. * @param string $itemSource
  587. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  588. * @param bool $status
  589. */
  590. public static function setSendMailStatus($itemType, $itemSource, $shareType, $status) {
  591. $status = $status ? 1 : 0;
  592. $query = \OC_DB::prepare(
  593. 'UPDATE `*PREFIX*share`
  594. SET `mail_send` = ?
  595. WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ?');
  596. $result = $query->execute(array($status, $itemType, $itemSource, $shareType));
  597. if($result === false) {
  598. \OC_Log::write('OCP\Share', 'Couldn\'t set send mail status', \OC_Log::ERROR);
  599. }
  600. }
  601. /**
  602. * Set the permissions of an item for a specific user or group
  603. * @param string Item type
  604. * @param string Item source
  605. * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  606. * @param string User or group the item is being shared with
  607. * @param int CRUDS permissions
  608. * @return Returns true on success or false on failure
  609. */
  610. public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
  611. if ($item = self::getItems($itemType, $itemSource, $shareType, $shareWith,
  612. \OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
  613. // Check if this item is a reshare and verify that the permissions
  614. // granted don't exceed the parent shared item
  615. if (isset($item['parent'])) {
  616. $query = \OC_DB::prepare('SELECT `permissions` FROM `*PREFIX*share` WHERE `id` = ?', 1);
  617. $result = $query->execute(array($item['parent']))->fetchRow();
  618. if (~(int)$result['permissions'] & $permissions) {
  619. $message = 'Setting permissions for '.$itemSource.' failed,'
  620. .' because the permissions exceed permissions granted to '.\OC_User::getUser();
  621. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  622. throw new \Exception($message);
  623. }
  624. }
  625. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
  626. $query->execute(array($permissions, $item['id']));
  627. if ($itemType === 'file' || $itemType === 'folder') {
  628. \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
  629. 'itemType' => $itemType,
  630. 'itemSource' => $itemSource,
  631. 'shareType' => $shareType,
  632. 'shareWith' => $shareWith,
  633. 'uidOwner' => \OC_User::getUser(),
  634. 'permissions' => $permissions,
  635. 'path' => $item['path'],
  636. ));
  637. }
  638. // Check if permissions were removed
  639. if ($item['permissions'] & ~$permissions) {
  640. // If share permission is removed all reshares must be deleted
  641. if (($item['permissions'] & \OCP\PERMISSION_SHARE) && (~$permissions & \OCP\PERMISSION_SHARE)) {
  642. Helper::delete($item['id'], true);
  643. } else {
  644. $ids = array();
  645. $parents = array($item['id']);
  646. while (!empty($parents)) {
  647. $parents = "'".implode("','", $parents)."'";
  648. $query = \OC_DB::prepare('SELECT `id`, `permissions` FROM `*PREFIX*share`'
  649. .' WHERE `parent` IN ('.$parents.')');
  650. $result = $query->execute();
  651. // Reset parents array, only go through loop again if
  652. // items are found that need permissions removed
  653. $parents = array();
  654. while ($item = $result->fetchRow()) {
  655. // Check if permissions need to be removed
  656. if ($item['permissions'] & ~$permissions) {
  657. // Add to list of items that need permissions removed
  658. $ids[] = $item['id'];
  659. $parents[] = $item['id'];
  660. }
  661. }
  662. }
  663. // Remove the permissions for all reshares of this item
  664. if (!empty($ids)) {
  665. $ids = "'".implode("','", $ids)."'";
  666. // TODO this should be done with Doctrine platform objects
  667. if (\OC_Config::getValue( "dbtype") === 'oci') {
  668. $andOp = 'BITAND(`permissions`, ?)';
  669. } else {
  670. $andOp = '`permissions` & ?';
  671. }
  672. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = '.$andOp
  673. .' WHERE `id` IN ('.$ids.')');
  674. $query->execute(array($permissions));
  675. }
  676. }
  677. }
  678. return true;
  679. }
  680. $message = 'Setting permissions for '.$itemSource.' failed, because the item was not found';
  681. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  682. throw new \Exception($message);
  683. }
  684. /**
  685. * Set expiration date for a share
  686. * @param string $itemType
  687. * @param string $itemSource
  688. * @param string $date expiration date
  689. * @return \OCP\Share_Backend
  690. */
  691. public static function setExpirationDate($itemType, $itemSource, $date) {
  692. $items = self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), self::FORMAT_NONE, null, -1, false);
  693. if (!empty($items)) {
  694. if ($date == '') {
  695. $date = null;
  696. } else {
  697. $date = new \DateTime($date);
  698. }
  699. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `id` = ?');
  700. $query->bindValue(1, $date, 'datetime');
  701. foreach ($items as $item) {
  702. $query->bindValue(2, (int) $item['id']);
  703. $query->execute();
  704. }
  705. return true;
  706. }
  707. return false;
  708. }
  709. /**
  710. * Checks whether a share has expired, calls unshareItem() if yes.
  711. * @param array $item Share data (usually database row)
  712. * @return bool True if item was expired, false otherwise.
  713. */
  714. protected static function expireItem(array $item) {
  715. if (!empty($item['expiration'])) {
  716. $now = new \DateTime();
  717. $expires = new \DateTime($item['expiration']);
  718. if ($now > $expires) {
  719. self::unshareItem($item);
  720. return true;
  721. }
  722. }
  723. return false;
  724. }
  725. /**
  726. * Unshares a share given a share data array
  727. * @param array $item Share data (usually database row)
  728. * @return null
  729. */
  730. protected static function unshareItem(array $item) {
  731. // Pass all the vars we have for now, they may be useful
  732. $hookParams = array(
  733. 'itemType' => $item['item_type'],
  734. 'itemSource' => $item['item_source'],
  735. 'shareType' => $item['share_type'],
  736. 'shareWith' => $item['share_with'],
  737. 'itemParent' => $item['parent'],
  738. 'uidOwner' => $item['uid_owner'],
  739. );
  740. \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams + array(
  741. 'fileSource' => $item['file_source'],
  742. ));
  743. Helper::delete($item['id']);
  744. \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
  745. }
  746. /**
  747. * Get the backend class for the specified item type
  748. * @param string $itemType
  749. * @return \OCP\Share_Backend
  750. */
  751. public static function getBackend($itemType) {
  752. if (isset(self::$backends[$itemType])) {
  753. return self::$backends[$itemType];
  754. } else if (isset(self::$backendTypes[$itemType]['class'])) {
  755. $class = self::$backendTypes[$itemType]['class'];
  756. if (class_exists($class)) {
  757. self::$backends[$itemType] = new $class;
  758. if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
  759. $message = 'Sharing backend '.$class.' must implement the interface OCP\Share_Backend';
  760. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  761. throw new \Exception($message);
  762. }
  763. return self::$backends[$itemType];
  764. } else {
  765. $message = 'Sharing backend '.$class.' not found';
  766. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  767. throw new \Exception($message);
  768. }
  769. }
  770. $message = 'Sharing backend for '.$itemType.' not found';
  771. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  772. throw new \Exception($message);
  773. }
  774. /**
  775. * Check if resharing is allowed
  776. * @return Returns true if allowed or false
  777. *
  778. * Resharing is allowed by default if not configured
  779. */
  780. private static function isResharingAllowed() {
  781. if (!isset(self::$isResharingAllowed)) {
  782. if (\OC_Appconfig::getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
  783. self::$isResharingAllowed = true;
  784. } else {
  785. self::$isResharingAllowed = false;
  786. }
  787. }
  788. return self::$isResharingAllowed;
  789. }
  790. /**
  791. * Get a list of collection item types for the specified item type
  792. * @param string Item type
  793. * @return array
  794. */
  795. private static function getCollectionItemTypes($itemType) {
  796. $collectionTypes = array($itemType);
  797. foreach (self::$backendTypes as $type => $backend) {
  798. if (in_array($backend['collectionOf'], $collectionTypes)) {
  799. $collectionTypes[] = $type;
  800. }
  801. }
  802. // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
  803. if (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder') {
  804. unset($collectionTypes[0]);
  805. }
  806. // Return array if collections were found or the item type is a
  807. // collection itself - collections can be inside collections
  808. if (count($collectionTypes) > 0) {
  809. return $collectionTypes;
  810. }
  811. return false;
  812. }
  813. /**
  814. * Get shared items from the database
  815. * @param string Item type
  816. * @param string Item source or target (optional)
  817. * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
  818. * @param string User or group the item is being shared with
  819. * @param string User that is the owner of shared items (optional)
  820. * @param int Format to convert items to with formatItems()
  821. * @param mixed Parameters to pass to formatItems()
  822. * @param int Number of items to return, -1 to return all matches (optional)
  823. * @param bool Include collection item types (optional)
  824. * @param bool TODO (optional)
  825. * @prams bool check expire date
  826. * @return array
  827. *
  828. * See public functions getItem(s)... for parameter usage
  829. *
  830. */
  831. public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
  832. $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
  833. $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) {
  834. if (!self::isEnabled()) {
  835. return array();
  836. }
  837. $backend = self::getBackend($itemType);
  838. $collectionTypes = false;
  839. // Get filesystem root to add it to the file target and remove from the
  840. // file source, match file_source with the file cache
  841. if ($itemType == 'file' || $itemType == 'folder') {
  842. if(!is_null($uidOwner)) {
  843. $root = \OC\Files\Filesystem::getRoot();
  844. } else {
  845. $root = '';
  846. }
  847. $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid`';
  848. if (!isset($item)) {
  849. $where .= ' WHERE `file_target` IS NOT NULL';
  850. }
  851. $fileDependent = true;
  852. $queryArgs = array();
  853. } else {
  854. $fileDependent = false;
  855. $root = '';
  856. $collectionTypes = self::getCollectionItemTypes($itemType);
  857. if ($includeCollections && !isset($item) && $collectionTypes) {
  858. // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
  859. if (!in_array($itemType, $collectionTypes)) {
  860. $itemTypes = array_merge(array($itemType), $collectionTypes);
  861. } else {
  862. $itemTypes = $collectionTypes;
  863. }
  864. $placeholders = join(',', array_fill(0, count($itemTypes), '?'));
  865. $where = ' WHERE `item_type` IN ('.$placeholders.'))';
  866. $queryArgs = $itemTypes;
  867. } else {
  868. $where = ' WHERE `item_type` = ?';
  869. $queryArgs = array($itemType);
  870. }
  871. }
  872. if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
  873. $where .= ' AND `share_type` != ?';
  874. $queryArgs[] = self::SHARE_TYPE_LINK;
  875. }
  876. if (isset($shareType)) {
  877. // Include all user and group items
  878. if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
  879. $where .= ' AND `share_type` IN (?,?,?)';
  880. $queryArgs[] = self::SHARE_TYPE_USER;
  881. $queryArgs[] = self::SHARE_TYPE_GROUP;
  882. $queryArgs[] = self::$shareTypeGroupUserUnique;
  883. $userAndGroups = array_merge(array($shareWith), \OC_Group::getUserGroups($shareWith));
  884. $placeholders = join(',', array_fill(0, count($userAndGroups), '?'));
  885. $where .= ' AND `share_with` IN ('.$placeholders.')';
  886. $queryArgs = array_merge($queryArgs, $userAndGroups);
  887. // Don't include own group shares
  888. $where .= ' AND `uid_owner` != ?';
  889. $queryArgs[] = $shareWith;
  890. } else {
  891. $where .= ' AND `share_type` = ?';
  892. $queryArgs[] = $shareType;
  893. if (isset($shareWith)) {
  894. $where .= ' AND `share_with` = ?';
  895. $queryArgs[] = $shareWith;
  896. }
  897. }
  898. }
  899. if (isset($uidOwner)) {
  900. $where .= ' AND `uid_owner` = ?';
  901. $queryArgs[] = $uidOwner;
  902. if (!isset($shareType)) {
  903. // Prevent unique user targets for group shares from being selected
  904. $where .= ' AND `share_type` != ?';
  905. $queryArgs[] = self::$shareTypeGroupUserUnique;
  906. }
  907. if ($fileDependent) {
  908. $column = 'file_source';
  909. } else {
  910. $column = 'item_source';
  911. }
  912. } else {
  913. if ($fileDependent) {
  914. $column = 'file_target';
  915. } else {
  916. $column = 'item_target';
  917. }
  918. }
  919. if (isset($item)) {
  920. $collectionTypes = self::getCollectionItemTypes($itemType);
  921. if ($includeCollections && $collectionTypes) {
  922. $where .= ' AND (';
  923. } else {
  924. $where .= ' AND';
  925. }
  926. // If looking for own shared items, check item_source else check item_target
  927. if (isset($uidOwner) || $itemShareWithBySource) {
  928. // If item type is a file, file source needs to be checked in case the item was converted
  929. if ($fileDependent) {
  930. $where .= ' `file_source` = ?';
  931. $column = 'file_source';
  932. } else {
  933. $where .= ' `item_source` = ?';
  934. $column = 'item_source';
  935. }
  936. } else {
  937. if ($fileDependent) {
  938. $where .= ' `file_target` = ?';
  939. $item = \OC\Files\Filesystem::normalizePath($item);
  940. } else {
  941. $where .= ' `item_target` = ?';
  942. }
  943. }
  944. $queryArgs[] = $item;
  945. if ($includeCollections && $collectionTypes) {
  946. $placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
  947. $where .= ' OR `item_type` IN ('.$placeholders.'))';
  948. $queryArgs = array_merge($queryArgs, $collectionTypes);
  949. }
  950. }
  951. if ($limit != -1 && !$includeCollections) {
  952. if ($shareType == self::$shareTypeUserAndGroups) {
  953. // Make sure the unique user target is returned if it exists,
  954. // unique targets should follow the group share in the database
  955. // If the limit is not 1, the filtering can be done later
  956. $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
  957. }
  958. // The limit must be at least 3, because filtering needs to be done
  959. if ($limit < 3) {
  960. $queryLimit = 3;
  961. } else {
  962. $queryLimit = $limit;
  963. }
  964. } else {
  965. $queryLimit = null;
  966. }
  967. $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
  968. $root = strlen($root);
  969. $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
  970. $result = $query->execute($queryArgs);
  971. if (\OC_DB::isError($result)) {
  972. \OC_Log::write('OCP\Share',
  973. \OC_DB::getErrorMessage($result) . ', select=' . $select . ' where=' . $where,
  974. \OC_Log::ERROR);
  975. }
  976. $items = array();
  977. $targets = array();
  978. $switchedItems = array();
  979. $mounts = array();
  980. while ($row = $result->fetchRow()) {
  981. self::transformDBResults($row);
  982. // Filter out duplicate group shares for users with unique targets
  983. if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
  984. $row['share_type'] = self::SHARE_TYPE_GROUP;
  985. $row['share_with'] = $items[$row['parent']]['share_with'];
  986. // Remove the parent group share
  987. unset($items[$row['parent']]);
  988. if ($row['permissions'] == 0) {
  989. continue;
  990. }
  991. } else if (!isset($uidOwner)) {
  992. // Check if the same target already exists
  993. if (isset($targets[$row[$column]])) {
  994. // Check if the same owner shared with the user twice
  995. // through a group and user share - this is allowed
  996. $id = $targets[$row[$column]];
  997. if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
  998. // Switch to group share type to ensure resharing conditions aren't bypassed
  999. if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
  1000. $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
  1001. $items[$id]['share_with'] = $row['share_with'];
  1002. }
  1003. // Switch ids if sharing permission is granted on only
  1004. // one share to ensure correct parent is used if resharing
  1005. if (~(int)$items[$id]['permissions'] & \OCP\PERMISSION_SHARE
  1006. && (int)$row['permissions'] & \OCP\PERMISSION_SHARE) {
  1007. $items[$row['id']] = $items[$id];
  1008. $switchedItems[$id] = $row['id'];
  1009. unset($items[$id]);
  1010. $id = $row['id'];
  1011. }
  1012. // Combine the permissions for the item
  1013. $items[$id]['permissions'] |= (int)$row['permissions'];
  1014. continue;
  1015. }
  1016. } else {
  1017. $targets[$row[$column]] = $row['id'];
  1018. }
  1019. }
  1020. // Remove root from file source paths if retrieving own shared items
  1021. if (isset($uidOwner) && isset($row['path'])) {
  1022. if (isset($row['parent'])) {
  1023. $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
  1024. $parentResult = $query->execute(array($row['parent']));
  1025. //$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
  1026. //$parentResult = $query->execute(array($row['id']));
  1027. if (\OC_DB::isError($result)) {
  1028. \OC_Log::write('OCP\Share', 'Can\'t select parent: ' .
  1029. \OC_DB::getErrorMessage($result) . ', select=' . $select . ' where=' . $where,
  1030. \OC_Log::ERROR);
  1031. } else {
  1032. $parentRow = $parentResult->fetchRow();
  1033. $tmpPath = '/Shared' . $parentRow['file_target'];
  1034. // find the right position where the row path continues from the target path
  1035. $pos = strrpos($row['path'], $parentRow['file_target']);
  1036. $subPath = substr($row['path'], $pos);
  1037. $splitPath = explode('/', $subPath);
  1038. foreach (array_slice($splitPath, 2) as $pathPart) {
  1039. $tmpPath = $tmpPath . '/' . $pathPart;
  1040. }
  1041. $row['path'] = $tmpPath;
  1042. }
  1043. } else {
  1044. if (!isset($mounts[$row['storage']])) {
  1045. $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
  1046. if (is_array($mountPoints)) {
  1047. $mounts[$row['storage']] = current($mountPoints);
  1048. }
  1049. }
  1050. if ($mounts[$row['storage']]) {
  1051. $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
  1052. $row['path'] = substr($path, $root);
  1053. }
  1054. }
  1055. }
  1056. if($checkExpireDate) {
  1057. if (self::expireItem($row)) {
  1058. continue;
  1059. }
  1060. }
  1061. // Check if resharing is allowed, if not remove share permission
  1062. if (isset($row['permissions']) && !self::isResharingAllowed()) {
  1063. $row['permissions'] &= ~\OCP\PERMISSION_SHARE;
  1064. }
  1065. // Add display names to result
  1066. if ( isset($row['share_with']) && $row['share_with'] != '') {
  1067. $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
  1068. }
  1069. if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
  1070. $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
  1071. }
  1072. $items[$row['id']] = $row;
  1073. }
  1074. if (!empty($items)) {
  1075. $collectionItems = array();
  1076. foreach ($items as &$row) {
  1077. // Return only the item instead of a 2-dimensional array
  1078. if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
  1079. if ($format == self::FORMAT_NONE) {
  1080. return $row;
  1081. } else {
  1082. break;
  1083. }
  1084. }
  1085. // Check if this is a collection of the requested item type
  1086. if ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
  1087. if (($collectionBackend = self::getBackend($row['item_type']))
  1088. && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
  1089. // Collections can be inside collections, check if the item is a collection
  1090. if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
  1091. $collectionItems[] = $row;
  1092. } else {
  1093. $collection = array();
  1094. $collection['item_type'] = $row['item_type'];
  1095. if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
  1096. $collection['path'] = basename($row['path']);
  1097. }
  1098. $row['collection'] = $collection;
  1099. // Fetch all of the children sources
  1100. $children = $collectionBackend->getChildren($row[$column]);
  1101. foreach ($children as $child) {
  1102. $childItem = $row;
  1103. $childItem['item_type'] = $itemType;
  1104. if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
  1105. $childItem['item_source'] = $child['source'];
  1106. $childItem['item_target'] = $child['target'];
  1107. }
  1108. if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
  1109. if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
  1110. $childItem['file_source'] = $child['source'];
  1111. } else { // TODO is this really needed if we already know that we use the file backend?
  1112. $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
  1113. $childItem['file_source'] = $meta['fileid'];
  1114. }
  1115. $childItem['file_target'] =
  1116. \OC\Files\Filesystem::normalizePath($child['file_path']);
  1117. }
  1118. if (isset($item)) {
  1119. if ($childItem[$column] == $item) {
  1120. // Return only the item instead of a 2-dimensional array
  1121. if ($limit == 1) {
  1122. if ($format == self::FORMAT_NONE) {
  1123. return $childItem;
  1124. } else {
  1125. // Unset the items array and break out of both loops
  1126. $items = array();
  1127. $items[] = $childItem;
  1128. break 2;
  1129. }
  1130. } else {
  1131. $collectionItems[] = $childItem;
  1132. }
  1133. }
  1134. } else {
  1135. $collectionItems[] = $childItem;
  1136. }
  1137. }
  1138. }
  1139. }
  1140. // Remove collection item
  1141. $toRemove = $row['id'];
  1142. if (array_key_exists($toRemove, $switchedItems)) {
  1143. $toRemove = $switchedItems[$toRemove];
  1144. }
  1145. unset($items[$toRemove]);
  1146. }
  1147. }
  1148. if (!empty($collectionItems)) {
  1149. $items = array_merge($items, $collectionItems);
  1150. }
  1151. return self::formatResult($items, $column, $backend, $format, $parameters);
  1152. }
  1153. return array();
  1154. }
  1155. /**
  1156. * Put shared item into the database
  1157. * @param string Item type
  1158. * @param string Item source
  1159. * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  1160. * @param string User or group the item is being shared with
  1161. * @param string User that is the owner of shared item
  1162. * @param int CRUDS permissions
  1163. * @param bool|array Parent folder target (optional)
  1164. * @param string token (optional)
  1165. * @param string name of the source item (optional)
  1166. * @return bool Returns true on success or false on failure
  1167. */
  1168. private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
  1169. $permissions, $parentFolder = null, $token = null, $itemSourceName = null) {
  1170. $backend = self::getBackend($itemType);
  1171. // Check if this is a reshare
  1172. if ($checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true)) {
  1173. // Check if attempting to share back to owner
  1174. if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
  1175. $message = 'Sharing '.$itemSourceName.' failed, because the user '.$shareWith.' is the original sharer';
  1176. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  1177. throw new \Exception($message);
  1178. }
  1179. // Check if share permissions is granted
  1180. if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\PERMISSION_SHARE) {
  1181. if (~(int)$checkReshare['permissions'] & $permissions) {
  1182. $message = 'Sharing '.$itemSourceName
  1183. .' failed, because the permissions exceed permissions granted to '.$uidOwner;
  1184. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  1185. throw new \Exception($message);
  1186. } else {
  1187. // TODO Don't check if inside folder
  1188. $parent = $checkReshare['id'];
  1189. $itemSource = $checkReshare['item_source'];
  1190. $fileSource = $checkReshare['file_source'];
  1191. $suggestedItemTarget = $checkReshare['item_target'];
  1192. $suggestedFileTarget = $checkReshare['file_target'];
  1193. $filePath = $checkReshare['file_target'];
  1194. }
  1195. } else {
  1196. $message = 'Sharing '.$itemSourceName.' failed, because resharing is not allowed';
  1197. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  1198. throw new \Exception($message);
  1199. }
  1200. } else {
  1201. $parent = null;
  1202. $suggestedItemTarget = null;
  1203. $suggestedFileTarget = null;
  1204. if (!$backend->isValidSource($itemSource, $uidOwner)) {
  1205. $message = 'Sharing '.$itemSource.' failed, because the sharing backend for '
  1206. .$itemType.' could not find its source';
  1207. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  1208. throw new \Exception($message);
  1209. }
  1210. if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
  1211. $filePath = $backend->getFilePath($itemSource, $uidOwner);
  1212. if ($itemType == 'file' || $itemType == 'folder') {
  1213. $fileSource = $itemSource;
  1214. } else {
  1215. $meta = \OC\Files\Filesystem::getFileInfo($filePath);
  1216. $fileSource = $meta['fileid'];
  1217. }
  1218. if ($fileSource == -1) {
  1219. $message = 'Sharing '.$itemSource.' failed, because the file could not be found in the file cache';
  1220. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  1221. throw new \Exception($message);
  1222. }
  1223. } else {
  1224. $filePath = null;
  1225. $fileSource = null;
  1226. }
  1227. }
  1228. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (`item_type`, `item_source`, `item_target`,'
  1229. .' `parent`, `share_type`, `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
  1230. .' `file_target`, `token`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
  1231. // Share with a group
  1232. if ($shareType == self::SHARE_TYPE_GROUP) {
  1233. $groupItemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith['group'],
  1234. $uidOwner, $suggestedItemTarget);
  1235. $run = true;
  1236. $error = '';
  1237. \OC_Hook::emit('OCP\Share', 'pre_shared', array(
  1238. 'itemType' => $itemType,
  1239. 'itemSource' => $itemSource,
  1240. 'itemTarget' => $groupItemTarget,
  1241. 'shareType' => $shareType,
  1242. 'shareWith' => $shareWith['group'],
  1243. 'uidOwner' => $uidOwner,
  1244. 'permissions' => $permissions,
  1245. 'fileSource' => $fileSource,
  1246. 'token' => $token,
  1247. 'run' => &$run,
  1248. 'error' => &$error
  1249. ));
  1250. if ($run === false) {
  1251. throw new \Exception($error);
  1252. }
  1253. if (isset($fileSource)) {
  1254. if ($parentFolder) {
  1255. if ($parentFolder === true) {
  1256. $groupFileTarget = Helper::generateTarget('file', $filePath, $shareType,
  1257. $shareWith['group'], $uidOwner, $suggestedFileTarget);
  1258. // Set group default file target for future use
  1259. $parentFolders[0]['folder'] = $groupFileTarget;
  1260. } else {
  1261. // Get group default file target
  1262. $groupFileTarget = $parentFolder[0]['folder'].$itemSource;
  1263. $parent = $parentFolder[0]['id'];
  1264. }
  1265. } else {
  1266. $groupFileTarget = Helper::generateTarget('file', $filePath, $shareType, $shareWith['group'],
  1267. $uidOwner, $suggestedFileTarget);
  1268. }
  1269. } else {
  1270. $groupFileTarget = null;
  1271. }
  1272. $query->execute(array($itemType, $itemSource, $groupItemTarget, $parent, $shareType,
  1273. $shareWith['group'], $uidOwner, $permissions, time(), $fileSource, $groupFileTarget, $token));
  1274. // Save this id, any extra rows for this group share will need to reference it
  1275. $parent = \OC_DB::insertid('*PREFIX*share');
  1276. // Loop through all users of this group in case we need to add an extra row
  1277. foreach ($shareWith['users'] as $uid) {
  1278. $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $uid,
  1279. $uidOwner, $suggestedItemTarget, $parent);
  1280. if (isset($fileSource)) {
  1281. if ($parentFolder) {
  1282. if ($parentFolder === true) {
  1283. $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $uid,
  1284. $uidOwner, $suggestedFileTarget, $parent);
  1285. if ($fileTarget != $groupFileTarget) {
  1286. $parentFolders[$uid]['folder'] = $fileTarget;
  1287. }
  1288. } else if (isset($parentFolder[$uid])) {
  1289. $fileTarget = $parentFolder[$uid]['folder'].$itemSource;
  1290. $parent = $parentFolder[$uid]['id'];
  1291. }
  1292. } else {
  1293. $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER,
  1294. $uid, $uidOwner, $suggestedFileTarget, $parent);
  1295. }
  1296. } else {
  1297. $fileTarget = null;
  1298. }
  1299. // Insert an extra row for the group share if the item or file target is unique for this user
  1300. if ($itemTarget != $groupItemTarget || (isset($fileSource) && $fileTarget != $groupFileTarget)) {
  1301. $query->execute(array($itemType, $itemSource, $itemTarget, $parent,
  1302. self::$shareTypeGroupUserUnique, $uid, $uidOwner, $permissions, time(),
  1303. $fileSource, $fileTarget, $token));
  1304. $id = \OC_DB::insertid('*PREFIX*share');
  1305. }
  1306. }
  1307. \OC_Hook::emit('OCP\Share', 'post_shared', array(
  1308. 'itemType' => $itemType,
  1309. 'itemSource' => $itemSource,
  1310. 'itemTarget' => $groupItemTarget,
  1311. 'parent' => $parent,
  1312. 'shareType' => $shareType,
  1313. 'shareWith' => $shareWith['group'],
  1314. 'uidOwner' => $uidOwner,
  1315. 'permissions' => $permissions,
  1316. 'fileSource' => $fileSource,
  1317. 'fileTarget' => $groupFileTarget,
  1318. 'id' => $parent,
  1319. 'token' => $token
  1320. ));
  1321. if ($parentFolder === true) {
  1322. // Return parent folders to preserve file target paths for potential children
  1323. return $parentFolders;
  1324. }
  1325. } else {
  1326. $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
  1327. $suggestedItemTarget);
  1328. $run = true;
  1329. $error = '';
  1330. \OC_Hook::emit('OCP\Share', 'pre_shared', array(
  1331. 'itemType' => $itemType,
  1332. 'itemSource' => $itemSource,
  1333. 'itemTarget' => $itemTarget,
  1334. 'shareType' => $shareType,
  1335. 'shareWith' => $shareWith,
  1336. 'uidOwner' => $uidOwner,
  1337. 'permissions' => $permissions,
  1338. 'fileSource' => $fileSource,
  1339. 'token' => $token,
  1340. 'run' => &$run,
  1341. 'error' => &$error
  1342. ));
  1343. if ($run === false) {
  1344. throw new \Exception($error);
  1345. }
  1346. if (isset($fileSource)) {
  1347. if ($parentFolder) {
  1348. if ($parentFolder === true) {
  1349. $fileTarget = Helper::generateTarget('file', $filePath, $shareType, $shareWith,
  1350. $uidOwner, $suggestedFileTarget);
  1351. $parentFolders['folder'] = $fileTarget;
  1352. } else {
  1353. $fileTarget = $parentFolder['folder'].$itemSource;
  1354. $parent = $parentFolder['id'];
  1355. }
  1356. } else {
  1357. $fileTarget = Helper::generateTarget('file', $filePath, $shareType, $shareWith, $uidOwner,
  1358. $suggestedFileTarget);
  1359. }
  1360. } else {
  1361. $fileTarget = null;
  1362. }
  1363. $query->execute(array($itemType, $itemSource, $itemTarget, $parent, $shareType, $shareWith, $uidOwner,
  1364. $permissions, time(), $fileSource, $fileTarget, $token));
  1365. $id = \OC_DB::insertid('*PREFIX*share');
  1366. \OC_Hook::emit('OCP\Share', 'post_shared', array(
  1367. 'itemType' => $itemType,
  1368. 'itemSource' => $itemSource,
  1369. 'itemTarget' => $itemTarget,
  1370. 'parent' => $parent,
  1371. 'shareType' => $shareType,
  1372. 'shareWith' => $shareWith,
  1373. 'uidOwner' => $uidOwner,
  1374. 'permissions' => $permissions,
  1375. 'fileSource' => $fileSource,
  1376. 'fileTarget' => $fileTarget,
  1377. 'id' => $id,
  1378. 'token' => $token
  1379. ));
  1380. if ($parentFolder === true) {
  1381. $parentFolders['id'] = $id;
  1382. // Return parent folder to preserve file target paths for potential children
  1383. return $parentFolders;
  1384. }
  1385. }
  1386. return true;
  1387. }
  1388. /**
  1389. * Delete all shares with type SHARE_TYPE_LINK
  1390. */
  1391. public static function removeAllLinkShares() {
  1392. // Delete any link shares
  1393. $query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ?');
  1394. $result = $query->execute(array(self::SHARE_TYPE_LINK));
  1395. while ($item = $result->fetchRow()) {
  1396. Helper::delete($item['id']);
  1397. }
  1398. }
  1399. /**
  1400. * In case a password protected link is not yet authenticated this function will return false
  1401. *
  1402. * @param array $linkItem
  1403. * @return bool
  1404. */
  1405. public static function checkPasswordProtectedShare(array $linkItem) {
  1406. if (!isset($linkItem['share_with'])) {
  1407. return true;
  1408. }
  1409. if (!isset($linkItem['share_type'])) {
  1410. return true;
  1411. }
  1412. if (!isset($linkItem['id'])) {
  1413. return true;
  1414. }
  1415. if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
  1416. return true;
  1417. }
  1418. if ( \OC::$session->exists('public_link_authenticated')
  1419. && \OC::$session->get('public_link_authenticated') === $linkItem['id'] ) {
  1420. return true;
  1421. }
  1422. return false;
  1423. }
  1424. /**
  1425. * @breif construct select statement
  1426. * @param int $format
  1427. * @param bool $fileDependent ist it a file/folder share or a generla share
  1428. * @param string $uidOwner
  1429. * @return string select statement
  1430. */
  1431. private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
  1432. $select = '*';
  1433. if ($format == self::FORMAT_STATUSES) {
  1434. if ($fileDependent) {
  1435. $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `share_with`, `uid_owner`';
  1436. } else {
  1437. $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`';
  1438. }
  1439. } else {
  1440. if (isset($uidOwner)) {
  1441. if ($fileDependent) {
  1442. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
  1443. . ' `share_type`, `share_with`, `file_source`, `path`, `permissions`, `stime`,'
  1444. . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`';
  1445. } else {
  1446. $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `permissions`,'
  1447. . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
  1448. }
  1449. } else {
  1450. if ($fileDependent) {
  1451. if ($format == \OC_Share_Backend_File::FORMAT_GET_FOLDER_CONTENTS || $format == \OC_Share_Backend_File::FORMAT_FILE_APP_ROOT) {
  1452. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
  1453. . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, '
  1454. . '`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
  1455. . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `unencrypted_size`, `encrypted`, `etag`, `mail_send`';
  1456. } else {
  1457. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,
  1458. `*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,
  1459. `file_source`, `path`, `file_target`, `permissions`, `stime`, `expiration`, `token`, `storage`, `mail_send`';
  1460. }
  1461. }
  1462. }
  1463. }
  1464. return $select;
  1465. }
  1466. /**
  1467. * @brief transform db results
  1468. * @param array $row result
  1469. */
  1470. private static function transformDBResults(&$row) {
  1471. if (isset($row['id'])) {
  1472. $row['id'] = (int) $row['id'];
  1473. }
  1474. if (isset($row['share_type'])) {
  1475. $row['share_type'] = (int) $row['share_type'];
  1476. }
  1477. if (isset($row['parent'])) {
  1478. $row['parent'] = (int) $row['parent'];
  1479. }
  1480. if (isset($row['file_parent'])) {
  1481. $row['file_parent'] = (int) $row['file_parent'];
  1482. }
  1483. if (isset($row['file_source'])) {
  1484. $row['file_source'] = (int) $row['file_source'];
  1485. }
  1486. if (isset($row['permissions'])) {
  1487. $row['permissions'] = (int) $row['permissions'];
  1488. }
  1489. if (isset($row['storage'])) {
  1490. $row['storage'] = (int) $row['storage'];
  1491. }
  1492. if (isset($row['stime'])) {
  1493. $row['stime'] = (int) $row['stime'];
  1494. }
  1495. }
  1496. /**
  1497. * @brief format result
  1498. * @param array $items result
  1499. * @prams string $column is it a file share or a general share ('file_target' or 'item_target')
  1500. * @params \OCP\Share_Backend $backend sharing backend
  1501. * @param int $format
  1502. * @param array additional format parameters
  1503. * @return array formate result
  1504. */
  1505. private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
  1506. if ($format === self::FORMAT_NONE) {
  1507. return $items;
  1508. } else if ($format === self::FORMAT_STATUSES) {
  1509. $statuses = array();
  1510. foreach ($items as $item) {
  1511. if ($item['share_type'] === self::SHARE_TYPE_LINK) {
  1512. $statuses[$item[$column]]['link'] = true;
  1513. } else if (!isset($statuses[$item[$column]])) {
  1514. $statuses[$item[$column]]['link'] = false;
  1515. }
  1516. if ('file_target') {
  1517. $statuses[$item[$column]]['path'] = $item['path'];
  1518. }
  1519. }
  1520. return $statuses;
  1521. } else {
  1522. return $backend->formatItems($items, $format, $parameters);
  1523. }
  1524. }
  1525. }