share.php 64 KB

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