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.

share.php 68KB

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