share.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  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. * @param int $shareType only look for a specific share type
  263. * @return array Return list of items with file_target, permissions and expiration
  264. */
  265. public static function getItemSharedWithUser($itemType, $itemSource, $user, $shareType = null) {
  266. $shares = array();
  267. $fileDependend = false;
  268. if ($itemType === 'file' || $itemType === 'folder') {
  269. $fileDependend = true;
  270. $column = 'file_source';
  271. $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` WHERE';
  272. } else {
  273. $column = 'item_source';
  274. $where = 'WHERE';
  275. }
  276. $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependend);
  277. $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
  278. $arguments = array($itemSource, $itemType);
  279. // for link shares $user === null
  280. if ($user !== null) {
  281. $where .= ' AND `share_with` = ? ';
  282. $arguments[] = $user;
  283. }
  284. if ($shareType !== null) {
  285. $where .= ' AND `share_type` = ? ';
  286. $arguments[] = $shareType;
  287. }
  288. $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $where);
  289. $result = \OC_DB::executeAudited($query, $arguments);
  290. while ($row = $result->fetchRow()) {
  291. $shares[] = $row;
  292. }
  293. //if didn't found a result than let's look for a group share.
  294. if(empty($shares) && $user !== null) {
  295. $groups = \OC_Group::getUserGroups($user);
  296. $query = \OC_DB::prepare(
  297. 'SELECT *
  298. FROM
  299. `*PREFIX*share`
  300. WHERE
  301. `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)'
  302. );
  303. $result = \OC_DB::executeAudited($query, array($itemSource, $itemType, implode(',', $groups)));
  304. while ($row = $result->fetchRow()) {
  305. $shares[] = $row;
  306. }
  307. }
  308. return $shares;
  309. }
  310. /**
  311. * Get the item of item type shared with the current user by source
  312. * @param string $itemType
  313. * @param string $itemSource
  314. * @param int $format (optional) Format type must be defined by the backend
  315. * @param mixed $parameters
  316. * @param boolean $includeCollections
  317. * @param string $shareWith (optional) define against which user should be checked, default: current user
  318. * @return array
  319. */
  320. public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
  321. $parameters = null, $includeCollections = false, $shareWith = null) {
  322. $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
  323. return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
  324. $parameters, 1, $includeCollections, true);
  325. }
  326. /**
  327. * Get the item of item type shared by a link
  328. * @param string $itemType
  329. * @param string $itemSource
  330. * @param string $uidOwner Owner of link
  331. * @return array
  332. */
  333. public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
  334. return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE,
  335. null, 1);
  336. }
  337. /**
  338. * Based on the given token the share information will be returned - password protected shares will be verified
  339. * @param string $token
  340. * @return array|boolean false will be returned in case the token is unknown or unauthorized
  341. */
  342. public static function getShareByToken($token, $checkPasswordProtection = true) {
  343. $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
  344. $result = $query->execute(array($token));
  345. if (\OC_DB::isError($result)) {
  346. \OC_Log::write('OCP\Share', \OC_DB::getErrorMessage($result) . ', token=' . $token, \OC_Log::ERROR);
  347. }
  348. $row = $result->fetchRow();
  349. if ($row === false) {
  350. return false;
  351. }
  352. if (is_array($row) and self::expireItem($row)) {
  353. return false;
  354. }
  355. // password protected shares need to be authenticated
  356. if ($checkPasswordProtection && !\OCP\Share::checkPasswordProtectedShare($row)) {
  357. return false;
  358. }
  359. return $row;
  360. }
  361. /**
  362. * resolves reshares down to the last real share
  363. * @param array $linkItem
  364. * @return array file owner
  365. */
  366. public static function resolveReShare($linkItem)
  367. {
  368. if (isset($linkItem['parent'])) {
  369. $parent = $linkItem['parent'];
  370. while (isset($parent)) {
  371. $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
  372. $item = $query->execute(array($parent))->fetchRow();
  373. if (isset($item['parent'])) {
  374. $parent = $item['parent'];
  375. } else {
  376. return $item;
  377. }
  378. }
  379. }
  380. return $linkItem;
  381. }
  382. /**
  383. * Get the shared items of item type owned by the current user
  384. * @param string $itemType
  385. * @param int $format (optional) Format type must be defined by the backend
  386. * @param mixed $parameters
  387. * @param int $limit Number of items to return (optional) Returns all by default
  388. * @param boolean $includeCollections
  389. * @return mixed Return depends on format
  390. */
  391. public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
  392. $limit = -1, $includeCollections = false) {
  393. return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
  394. $parameters, $limit, $includeCollections);
  395. }
  396. /**
  397. * Get the shared item of item type owned by the current user
  398. * @param string $itemType
  399. * @param string $itemSource
  400. * @param int $format (optional) Format type must be defined by the backend
  401. * @param mixed $parameters
  402. * @param boolean $includeCollections
  403. * @return mixed Return depends on format
  404. */
  405. public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
  406. $parameters = null, $includeCollections = false) {
  407. return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
  408. $parameters, -1, $includeCollections);
  409. }
  410. /**
  411. * Get all users an item is shared with
  412. * @param string $itemType
  413. * @param string $itemSource
  414. * @param string $uidOwner
  415. * @param boolean $includeCollections
  416. * @param boolean $checkExpireDate
  417. * @return array Return array of users
  418. */
  419. public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
  420. $users = array();
  421. $items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
  422. if ($items) {
  423. foreach ($items as $item) {
  424. if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
  425. $users[] = $item['share_with'];
  426. } else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
  427. $users = array_merge($users, \OC_Group::usersInGroup($item['share_with']));
  428. }
  429. }
  430. }
  431. return $users;
  432. }
  433. /**
  434. * Share an item with a user, group, or via private link
  435. * @param string $itemType
  436. * @param string $itemSource
  437. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  438. * @param string $shareWith User or group the item is being shared with
  439. * @param int $permissions CRUDS
  440. * @param string $itemSourceName
  441. * @param \DateTime $expirationDate
  442. * @return boolean|string Returns true on success or false on failure, Returns token on success for links
  443. * @throws \Exception
  444. */
  445. public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null) {
  446. $uidOwner = \OC_User::getUser();
  447. $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
  448. $l = \OC::$server->getL10N('lib');
  449. if (is_null($itemSourceName)) {
  450. $itemSourceName = $itemSource;
  451. }
  452. // check if file can be shared
  453. if ($itemType === 'file' or $itemType === 'folder') {
  454. $path = \OC\Files\Filesystem::getPath($itemSource);
  455. // verify that the file exists before we try to share it
  456. if (!$path) {
  457. $message = 'Sharing %s failed, because the file does not exist';
  458. $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
  459. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
  460. throw new \Exception($message_t);
  461. }
  462. // verify that the user has share permission
  463. if (!\OC\Files\Filesystem::isSharable($path)) {
  464. $message = 'You are not allowed to share %s';
  465. $message_t = $l->t('You are not allowed to share %s', array($itemSourceName));
  466. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
  467. throw new \Exception($message_t);
  468. }
  469. }
  470. //verify that we don't share a folder which already contains a share mount point
  471. if ($itemType === 'folder') {
  472. $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
  473. $mountManager = \OC\Files\Filesystem::getMountManager();
  474. $mounts = $mountManager->findIn($path);
  475. foreach ($mounts as $mount) {
  476. if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  477. $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
  478. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  479. throw new \Exception($message);
  480. }
  481. }
  482. }
  483. // single file shares should never have delete permissions
  484. if ($itemType === 'file') {
  485. $permissions = (int)$permissions & ~\OCP\PERMISSION_DELETE;
  486. }
  487. // Verify share type and sharing conditions are met
  488. if ($shareType === self::SHARE_TYPE_USER) {
  489. if ($shareWith == $uidOwner) {
  490. $message = 'Sharing %s failed, because the user %s is the item owner';
  491. $message_t = $l->t('Sharing %s failed, because the user %s is the item owner', array($itemSourceName, $shareWith));
  492. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  493. throw new \Exception($message_t);
  494. }
  495. if (!\OC_User::userExists($shareWith)) {
  496. $message = 'Sharing %s failed, because the user %s does not exist';
  497. $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
  498. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  499. throw new \Exception($message_t);
  500. }
  501. if ($shareWithinGroupOnly) {
  502. $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
  503. if (empty($inGroup)) {
  504. $message = 'Sharing %s failed, because the user '
  505. .'%s is not a member of any groups that %s is a member of';
  506. $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));
  507. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith, $uidOwner), \OC_Log::ERROR);
  508. throw new \Exception($message_t);
  509. }
  510. }
  511. // Check if the item source is already shared with the user, either from the same owner or a different user
  512. if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
  513. $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
  514. // Only allow the same share to occur again if it is the same
  515. // owner and is not a user share, this use case is for increasing
  516. // permissions for a specific user
  517. if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
  518. $message = 'Sharing %s failed, because this item is already shared with %s';
  519. $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
  520. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  521. throw new \Exception($message_t);
  522. }
  523. }
  524. } else if ($shareType === self::SHARE_TYPE_GROUP) {
  525. if (!\OC_Group::groupExists($shareWith)) {
  526. $message = 'Sharing %s failed, because the group %s does not exist';
  527. $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
  528. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  529. throw new \Exception($message_t);
  530. }
  531. if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
  532. $message = 'Sharing %s failed, because '
  533. .'%s is not a member of the group %s';
  534. $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
  535. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OC_Log::ERROR);
  536. throw new \Exception($message_t);
  537. }
  538. // Check if the item source is already shared with the group, either from the same owner or a different user
  539. // The check for each user in the group is done inside the put() function
  540. if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
  541. null, self::FORMAT_NONE, null, 1, true, true)) {
  542. // Only allow the same share to occur again if it is the same
  543. // owner and is not a group share, this use case is for increasing
  544. // permissions for a specific user
  545. if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
  546. $message = 'Sharing %s failed, because this item is already shared with %s';
  547. $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
  548. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  549. throw new \Exception($message_t);
  550. }
  551. }
  552. // Convert share with into an array with the keys group and users
  553. $group = $shareWith;
  554. $shareWith = array();
  555. $shareWith['group'] = $group;
  556. $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
  557. } else if ($shareType === self::SHARE_TYPE_LINK) {
  558. $updateExistingShare = false;
  559. if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
  560. // when updating a link share
  561. // FIXME Don't delete link if we update it
  562. if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
  563. $uidOwner, self::FORMAT_NONE, null, 1)) {
  564. // remember old token
  565. $oldToken = $checkExists['token'];
  566. $oldPermissions = $checkExists['permissions'];
  567. //delete the old share
  568. Helper::delete($checkExists['id']);
  569. $updateExistingShare = true;
  570. }
  571. // Generate hash of password - same method as user passwords
  572. if (!empty($shareWith)) {
  573. $shareWith = \OC::$server->getHasher()->hash($shareWith);
  574. } else {
  575. // reuse the already set password, but only if we change permissions
  576. // otherwise the user disabled the password protection
  577. if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
  578. $shareWith = $checkExists['share_with'];
  579. }
  580. }
  581. if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
  582. $message = 'You need to provide a password to create a public link, only protected links are allowed';
  583. $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
  584. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  585. throw new \Exception($message_t);
  586. }
  587. if ($updateExistingShare === false &&
  588. self::isDefaultExpireDateEnabled() &&
  589. empty($expirationDate)) {
  590. $expirationDate = Helper::calcExpireDate();
  591. }
  592. // Generate token
  593. if (isset($oldToken)) {
  594. $token = $oldToken;
  595. } else {
  596. $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(self::TOKEN_LENGTH,
  597. \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_UPPER.
  598. \OCP\Security\ISecureRandom::CHAR_DIGITS
  599. );
  600. }
  601. $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
  602. null, $token, $itemSourceName, $expirationDate);
  603. if ($result) {
  604. return $token;
  605. } else {
  606. return false;
  607. }
  608. }
  609. $message = 'Sharing %s failed, because sharing with links is not allowed';
  610. $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
  611. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
  612. throw new \Exception($message_t);
  613. } else {
  614. // Future share types need to include their own conditions
  615. $message = 'Share type %s is not valid for %s';
  616. $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
  617. \OC_Log::write('OCP\Share', sprintf($message, $shareType, $itemSource), \OC_Log::ERROR);
  618. throw new \Exception($message_t);
  619. }
  620. // Put the item into the database
  621. return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
  622. }
  623. /**
  624. * Unshare an item from a user, group, or delete a private link
  625. * @param string $itemType
  626. * @param string $itemSource
  627. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  628. * @param string $shareWith User or group the item is being shared with
  629. * @return boolean true on success or false on failure
  630. */
  631. public static function unshare($itemType, $itemSource, $shareType, $shareWith) {
  632. // check if it is a valid itemType
  633. self::getBackend($itemType);
  634. $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $shareType);
  635. $toDelete = array();
  636. $newParent = null;
  637. $currentUser = \OC_User::getUser();
  638. foreach ($items as $item) {
  639. // delete the item with the expected share_type and owner
  640. if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
  641. $toDelete = $item;
  642. // if there is more then one result we don't have to delete the children
  643. // but update their parent. For group shares the new parent should always be
  644. // the original group share and not the db entry with the unique name
  645. } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
  646. $newParent = $item['parent'];
  647. } else {
  648. $newParent = $item['id'];
  649. }
  650. }
  651. if (!empty($toDelete)) {
  652. self::unshareItem($toDelete, $newParent);
  653. return true;
  654. }
  655. return false;
  656. }
  657. /**
  658. * Unshare an item from all users, groups, and remove all links
  659. * @param string $itemType
  660. * @param string $itemSource
  661. * @return boolean true on success or false on failure
  662. */
  663. public static function unshareAll($itemType, $itemSource) {
  664. // Get all of the owners of shares of this item.
  665. $query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
  666. $result = $query->execute(array($itemType, $itemSource));
  667. $shares = array();
  668. // Add each owner's shares to the array of all shares for this item.
  669. while ($row = $result->fetchRow()) {
  670. $shares = array_merge($shares, self::getItems($itemType, $itemSource, null, null, $row['uid_owner']));
  671. }
  672. if (!empty($shares)) {
  673. // Pass all the vars we have for now, they may be useful
  674. $hookParams = array(
  675. 'itemType' => $itemType,
  676. 'itemSource' => $itemSource,
  677. 'shares' => $shares,
  678. );
  679. \OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams);
  680. foreach ($shares as $share) {
  681. self::unshareItem($share);
  682. }
  683. \OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams);
  684. return true;
  685. }
  686. return false;
  687. }
  688. /**
  689. * Unshare an item shared with the current user
  690. * @param string $itemType
  691. * @param string $itemOrigin Item target or source
  692. * @param boolean $originIsSource true if $itemOrigin is the source, false if $itemOrigin is the target (optional)
  693. * @return boolean true on success or false on failure
  694. *
  695. * Unsharing from self is not allowed for items inside collections
  696. */
  697. public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = false) {
  698. $originType = ($originIsSource) ? 'source' : 'target';
  699. $uid = \OCP\User::getUser();
  700. if ($itemType === 'file' || $itemType === 'folder') {
  701. $statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_' . $originType . '` = ?';
  702. } else {
  703. $statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_' . $originType . '` = ?';
  704. }
  705. $query = \OCP\DB::prepare($statement);
  706. $result = $query->execute(array($itemType, $itemOrigin));
  707. $shares = $result->fetchAll();
  708. $listOfUnsharedItems = array();
  709. $itemUnshared = false;
  710. foreach ($shares as $share) {
  711. if ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
  712. $share['share_with'] === $uid) {
  713. $deletedShares = Helper::delete($share['id']);
  714. $shareTmp = array(
  715. 'id' => $share['id'],
  716. 'shareWith' => $share['share_with'],
  717. 'itemTarget' => $share['item_target'],
  718. 'itemType' => $share['item_type'],
  719. 'shareType' => (int)$share['share_type'],
  720. );
  721. if (isset($share['file_target'])) {
  722. $shareTmp['fileTarget'] = $share['file_target'];
  723. }
  724. $listOfUnsharedItems = array_merge($listOfUnsharedItems, $deletedShares, array($shareTmp));
  725. $itemUnshared = true;
  726. break;
  727. } elseif ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
  728. if (\OC_Group::inGroup($uid, $share['share_with'])) {
  729. $groupShare = $share;
  730. }
  731. } elseif ((int)$share['share_type'] === self::$shareTypeGroupUserUnique &&
  732. $share['share_with'] === $uid) {
  733. $uniqueGroupShare = $share;
  734. }
  735. }
  736. if (!$itemUnshared && isset($groupShare) && !isset($uniqueGroupShare)) {
  737. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share`'
  738. .' (`item_type`, `item_source`, `item_target`, `parent`, `share_type`,'
  739. .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`)'
  740. .' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
  741. $query->execute(array($groupShare['item_type'], $groupShare['item_source'], $groupShare['item_target'],
  742. $groupShare['id'], self::$shareTypeGroupUserUnique,
  743. \OC_User::getUser(), $groupShare['uid_owner'], 0, $groupShare['stime'], $groupShare['file_source'],
  744. $groupShare['file_target']));
  745. $shareTmp = array(
  746. 'id' => $groupShare['id'],
  747. 'shareWith' => $groupShare['share_with'],
  748. 'itemTarget' => $groupShare['item_target'],
  749. 'itemType' => $groupShare['item_type'],
  750. 'shareType' => (int)$groupShare['share_type'],
  751. );
  752. if (isset($groupShare['file_target'])) {
  753. $shareTmp['fileTarget'] = $groupShare['file_target'];
  754. }
  755. $listOfUnsharedItems = array_merge($listOfUnsharedItems, array($groupShare));
  756. $itemUnshared = true;
  757. } elseif (!$itemUnshared && isset($uniqueGroupShare)) {
  758. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
  759. $query->execute(array(0, $uniqueGroupShare['id']));
  760. $shareTmp = array(
  761. 'id' => $uniqueGroupShare['id'],
  762. 'shareWith' => $uniqueGroupShare['share_with'],
  763. 'itemTarget' => $uniqueGroupShare['item_target'],
  764. 'itemType' => $uniqueGroupShare['item_type'],
  765. 'shareType' => (int)$uniqueGroupShare['share_type'],
  766. );
  767. if (isset($uniqueGroupShare['file_target'])) {
  768. $shareTmp['fileTarget'] = $uniqueGroupShare['file_target'];
  769. }
  770. $listOfUnsharedItems = array_merge($listOfUnsharedItems, array($uniqueGroupShare));
  771. $itemUnshared = true;
  772. }
  773. if ($itemUnshared) {
  774. \OC_Hook::emit('OCP\Share', 'post_unshareFromSelf',
  775. array('unsharedItems' => $listOfUnsharedItems, 'itemType' => $itemType));
  776. }
  777. return $itemUnshared;
  778. }
  779. /**
  780. * sent status if users got informed by mail about share
  781. * @param string $itemType
  782. * @param string $itemSource
  783. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  784. * @param string $recipient with whom was the file shared
  785. * @param boolean $status
  786. */
  787. public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
  788. $status = $status ? 1 : 0;
  789. $query = \OC_DB::prepare(
  790. 'UPDATE `*PREFIX*share`
  791. SET `mail_send` = ?
  792. WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
  793. $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
  794. if($result === false) {
  795. \OC_Log::write('OCP\Share', 'Couldn\'t set send mail status', \OC_Log::ERROR);
  796. }
  797. }
  798. /**
  799. * Set the permissions of an item for a specific user or group
  800. * @param string $itemType
  801. * @param string $itemSource
  802. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  803. * @param string $shareWith User or group the item is being shared with
  804. * @param int $permissions CRUDS permissions
  805. * @return boolean true on success or false on failure
  806. */
  807. public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
  808. $l = \OC::$server->getL10N('lib');
  809. if ($item = self::getItems($itemType, $itemSource, $shareType, $shareWith,
  810. \OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
  811. // Check if this item is a reshare and verify that the permissions
  812. // granted don't exceed the parent shared item
  813. if (isset($item['parent'])) {
  814. $query = \OC_DB::prepare('SELECT `permissions` FROM `*PREFIX*share` WHERE `id` = ?', 1);
  815. $result = $query->execute(array($item['parent']))->fetchRow();
  816. if (~(int)$result['permissions'] & $permissions) {
  817. $message = 'Setting permissions for %s failed,'
  818. .' because the permissions exceed permissions granted to %s';
  819. $message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', array($itemSource, \OC_User::getUser()));
  820. \OC_Log::write('OCP\Share', sprintf($message, $itemSource, \OC_User::getUser()), \OC_Log::ERROR);
  821. throw new \Exception($message_t);
  822. }
  823. }
  824. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
  825. $query->execute(array($permissions, $item['id']));
  826. if ($itemType === 'file' || $itemType === 'folder') {
  827. \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
  828. 'itemType' => $itemType,
  829. 'itemSource' => $itemSource,
  830. 'shareType' => $shareType,
  831. 'shareWith' => $shareWith,
  832. 'uidOwner' => \OC_User::getUser(),
  833. 'permissions' => $permissions,
  834. 'path' => $item['path'],
  835. ));
  836. }
  837. // Check if permissions were removed
  838. if ($item['permissions'] & ~$permissions) {
  839. // If share permission is removed all reshares must be deleted
  840. if (($item['permissions'] & \OCP\PERMISSION_SHARE) && (~$permissions & \OCP\PERMISSION_SHARE)) {
  841. Helper::delete($item['id'], true);
  842. } else {
  843. $ids = array();
  844. $parents = array($item['id']);
  845. while (!empty($parents)) {
  846. $parents = "'".implode("','", $parents)."'";
  847. $query = \OC_DB::prepare('SELECT `id`, `permissions` FROM `*PREFIX*share`'
  848. .' WHERE `parent` IN ('.$parents.')');
  849. $result = $query->execute();
  850. // Reset parents array, only go through loop again if
  851. // items are found that need permissions removed
  852. $parents = array();
  853. while ($item = $result->fetchRow()) {
  854. // Check if permissions need to be removed
  855. if ($item['permissions'] & ~$permissions) {
  856. // Add to list of items that need permissions removed
  857. $ids[] = $item['id'];
  858. $parents[] = $item['id'];
  859. }
  860. }
  861. }
  862. // Remove the permissions for all reshares of this item
  863. if (!empty($ids)) {
  864. $ids = "'".implode("','", $ids)."'";
  865. // TODO this should be done with Doctrine platform objects
  866. if (\OC_Config::getValue( "dbtype") === 'oci') {
  867. $andOp = 'BITAND(`permissions`, ?)';
  868. } else {
  869. $andOp = '`permissions` & ?';
  870. }
  871. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = '.$andOp
  872. .' WHERE `id` IN ('.$ids.')');
  873. $query->execute(array($permissions));
  874. }
  875. }
  876. }
  877. return true;
  878. }
  879. $message = 'Setting permissions for %s failed, because the item was not found';
  880. $message_t = $l->t('Setting permissions for %s failed, because the item was not found', array($itemSource));
  881. \OC_Log::write('OCP\Share', sprintf($message, $itemSource), \OC_Log::ERROR);
  882. throw new \Exception($message_t);
  883. }
  884. /**
  885. * validate expiration date if it meets all constraints
  886. *
  887. * @param string $expireDate well formate date string, e.g. "DD-MM-YYYY"
  888. * @param string $shareTime timestamp when the file was shared
  889. * @param string $itemType
  890. * @param string $itemSource
  891. * @return DateTime validated date
  892. * @throws \Exception
  893. */
  894. private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
  895. $l = \OC::$server->getL10N('lib');
  896. $date = new \DateTime($expireDate);
  897. $today = new \DateTime('now');
  898. // if the user doesn't provide a share time we need to get it from the database
  899. // fall-back mode to keep API stable, because the $shareTime parameter was added later
  900. $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
  901. if ($defaultExpireDateEnforced && $shareTime === null) {
  902. $items = self::getItemShared($itemType, $itemSource);
  903. $firstItem = reset($items);
  904. $shareTime = (int)$firstItem['stime'];
  905. }
  906. if ($defaultExpireDateEnforced) {
  907. // initialize max date with share time
  908. $maxDate = new \DateTime();
  909. $maxDate->setTimestamp($shareTime);
  910. $maxDays = \OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
  911. $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
  912. if ($date > $maxDate) {
  913. $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
  914. $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
  915. \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
  916. throw new \Exception($warning_t);
  917. }
  918. }
  919. if ($date < $today) {
  920. $message = 'Cannot set expiration date. Expiration date is in the past';
  921. $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
  922. \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
  923. throw new \Exception($message_t);
  924. }
  925. return $date;
  926. }
  927. /**
  928. * Set expiration date for a share
  929. * @param string $itemType
  930. * @param string $itemSource
  931. * @param string $date expiration date
  932. * @param int $shareTime timestamp from when the file was shared
  933. * @throws \Exception
  934. * @return boolean
  935. */
  936. public static function setExpirationDate($itemType, $itemSource, $date, $shareTime = null) {
  937. $user = \OC_User::getUser();
  938. if ($date == '') {
  939. $date = null;
  940. } else {
  941. $date = self::validateExpireDate($date, $shareTime, $itemType, $itemSource);
  942. }
  943. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ? AND `uid_owner` = ? AND `share_type` = ?');
  944. $query->bindValue(1, $date, 'datetime');
  945. $query->bindValue(2, $itemType);
  946. $query->bindValue(3, $itemSource);
  947. $query->bindValue(4, $user);
  948. $query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
  949. $query->execute();
  950. \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', array(
  951. 'itemType' => $itemType,
  952. 'itemSource' => $itemSource,
  953. 'date' => $date,
  954. 'uidOwner' => $user
  955. ));
  956. return true;
  957. }
  958. /**
  959. * Checks whether a share has expired, calls unshareItem() if yes.
  960. * @param array $item Share data (usually database row)
  961. * @return boolean True if item was expired, false otherwise.
  962. */
  963. protected static function expireItem(array $item) {
  964. $result = false;
  965. // only use default expiration date for link shares
  966. if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
  967. // calculate expiration date
  968. if (!empty($item['expiration'])) {
  969. $userDefinedExpire = new \DateTime($item['expiration']);
  970. $expires = $userDefinedExpire->getTimestamp();
  971. } else {
  972. $expires = null;
  973. }
  974. // get default expiration settings
  975. $defaultSettings = Helper::getDefaultExpireSetting();
  976. $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
  977. if (is_int($expires)) {
  978. $now = time();
  979. if ($now > $expires) {
  980. self::unshareItem($item);
  981. $result = true;
  982. }
  983. }
  984. }
  985. return $result;
  986. }
  987. /**
  988. * Unshares a share given a share data array
  989. * @param array $item Share data (usually database row)
  990. * @param int new parent ID
  991. * @return null
  992. */
  993. protected static function unshareItem(array $item, $newParent = null) {
  994. // Pass all the vars we have for now, they may be useful
  995. $hookParams = array(
  996. 'id' => $item['id'],
  997. 'itemType' => $item['item_type'],
  998. 'itemSource' => $item['item_source'],
  999. 'shareType' => (int)$item['share_type'],
  1000. 'shareWith' => $item['share_with'],
  1001. 'itemParent' => $item['parent'],
  1002. 'uidOwner' => $item['uid_owner'],
  1003. );
  1004. if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
  1005. $hookParams['fileSource'] = $item['file_source'];
  1006. $hookParams['fileTarget'] = $item['file_target'];
  1007. }
  1008. \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
  1009. $deletedShares = Helper::delete($item['id'], false, null, $newParent);
  1010. $deletedShares[] = $hookParams;
  1011. $hookParams['deletedShares'] = $deletedShares;
  1012. \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
  1013. }
  1014. /**
  1015. * Get the backend class for the specified item type
  1016. * @param string $itemType
  1017. * @throws \Exception
  1018. * @return \OCP\Share_Backend
  1019. */
  1020. public static function getBackend($itemType) {
  1021. $l = \OC::$server->getL10N('lib');
  1022. if (isset(self::$backends[$itemType])) {
  1023. return self::$backends[$itemType];
  1024. } else if (isset(self::$backendTypes[$itemType]['class'])) {
  1025. $class = self::$backendTypes[$itemType]['class'];
  1026. if (class_exists($class)) {
  1027. self::$backends[$itemType] = new $class;
  1028. if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
  1029. $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
  1030. $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
  1031. \OC_Log::write('OCP\Share', sprintf($message, $class), \OC_Log::ERROR);
  1032. throw new \Exception($message_t);
  1033. }
  1034. return self::$backends[$itemType];
  1035. } else {
  1036. $message = 'Sharing backend %s not found';
  1037. $message_t = $l->t('Sharing backend %s not found', array($class));
  1038. \OC_Log::write('OCP\Share', sprintf($message, $class), \OC_Log::ERROR);
  1039. throw new \Exception($message_t);
  1040. }
  1041. }
  1042. $message = 'Sharing backend for %s not found';
  1043. $message_t = $l->t('Sharing backend for %s not found', array($itemType));
  1044. \OC_Log::write('OCP\Share', sprintf($message, $itemType), \OC_Log::ERROR);
  1045. throw new \Exception($message_t);
  1046. }
  1047. /**
  1048. * Check if resharing is allowed
  1049. * @return boolean true if allowed or false
  1050. *
  1051. * Resharing is allowed by default if not configured
  1052. */
  1053. public static function isResharingAllowed() {
  1054. if (!isset(self::$isResharingAllowed)) {
  1055. if (\OC_Appconfig::getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
  1056. self::$isResharingAllowed = true;
  1057. } else {
  1058. self::$isResharingAllowed = false;
  1059. }
  1060. }
  1061. return self::$isResharingAllowed;
  1062. }
  1063. /**
  1064. * Get a list of collection item types for the specified item type
  1065. * @param string $itemType
  1066. * @return array
  1067. */
  1068. private static function getCollectionItemTypes($itemType) {
  1069. $collectionTypes = array($itemType);
  1070. foreach (self::$backendTypes as $type => $backend) {
  1071. if (in_array($backend['collectionOf'], $collectionTypes)) {
  1072. $collectionTypes[] = $type;
  1073. }
  1074. }
  1075. // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
  1076. if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
  1077. unset($collectionTypes[0]);
  1078. }
  1079. // Return array if collections were found or the item type is a
  1080. // collection itself - collections can be inside collections
  1081. if (count($collectionTypes) > 0) {
  1082. return $collectionTypes;
  1083. }
  1084. return false;
  1085. }
  1086. /**
  1087. * Get the owners of items shared with a user.
  1088. *
  1089. * @param string $user The user the items are shared with.
  1090. * @param string $type The type of the items shared with the user.
  1091. * @param boolean $includeCollections Include collection item types (optional)
  1092. * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
  1093. * @return array
  1094. */
  1095. public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
  1096. // First, we find out if $type is part of a collection (and if that collection is part of
  1097. // another one and so on).
  1098. $collectionTypes = array();
  1099. if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
  1100. $collectionTypes[] = $type;
  1101. }
  1102. // Of these collection types, along with our original $type, we make a
  1103. // list of the ones for which a sharing backend has been registered.
  1104. // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
  1105. // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
  1106. $allMaybeSharedItems = array();
  1107. foreach ($collectionTypes as $collectionType) {
  1108. if (isset(self::$backends[$collectionType])) {
  1109. $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
  1110. $collectionType,
  1111. $user,
  1112. self::FORMAT_NONE
  1113. );
  1114. }
  1115. }
  1116. $owners = array();
  1117. if ($includeOwner) {
  1118. $owners[] = $user;
  1119. }
  1120. // We take a look at all shared items of the given $type (or of the collections it is part of)
  1121. // and find out their owners. Then, we gather the tags for the original $type from all owners,
  1122. // and return them as elements of a list that look like "Tag (owner)".
  1123. foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
  1124. foreach ($maybeSharedItems as $sharedItem) {
  1125. if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
  1126. $owners[] = $sharedItem['uid_owner'];
  1127. }
  1128. }
  1129. }
  1130. return $owners;
  1131. }
  1132. /**
  1133. * Get shared items from the database
  1134. * @param string $itemType
  1135. * @param string $item Item source or target (optional)
  1136. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
  1137. * @param string $shareWith User or group the item is being shared with
  1138. * @param string $uidOwner User that is the owner of shared items (optional)
  1139. * @param int $format Format to convert items to with formatItems() (optional)
  1140. * @param mixed $parameters to pass to formatItems() (optional)
  1141. * @param int $limit Number of items to return, -1 to return all matches (optional)
  1142. * @param boolean $includeCollections Include collection item types (optional)
  1143. * @param boolean $itemShareWithBySource (optional)
  1144. * @param boolean $checkExpireDate
  1145. * @return array
  1146. *
  1147. * See public functions getItem(s)... for parameter usage
  1148. *
  1149. */
  1150. public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
  1151. $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
  1152. $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) {
  1153. if (!self::isEnabled()) {
  1154. return array();
  1155. }
  1156. $backend = self::getBackend($itemType);
  1157. $collectionTypes = false;
  1158. // Get filesystem root to add it to the file target and remove from the
  1159. // file source, match file_source with the file cache
  1160. if ($itemType == 'file' || $itemType == 'folder') {
  1161. if(!is_null($uidOwner)) {
  1162. $root = \OC\Files\Filesystem::getRoot();
  1163. } else {
  1164. $root = '';
  1165. }
  1166. $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid`';
  1167. if (!isset($item)) {
  1168. $where .= ' WHERE `file_target` IS NOT NULL';
  1169. }
  1170. $fileDependent = true;
  1171. $queryArgs = array();
  1172. } else {
  1173. $fileDependent = false;
  1174. $root = '';
  1175. $collectionTypes = self::getCollectionItemTypes($itemType);
  1176. if ($includeCollections && !isset($item) && $collectionTypes) {
  1177. // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
  1178. if (!in_array($itemType, $collectionTypes)) {
  1179. $itemTypes = array_merge(array($itemType), $collectionTypes);
  1180. } else {
  1181. $itemTypes = $collectionTypes;
  1182. }
  1183. $placeholders = join(',', array_fill(0, count($itemTypes), '?'));
  1184. $where = ' WHERE `item_type` IN ('.$placeholders.'))';
  1185. $queryArgs = $itemTypes;
  1186. } else {
  1187. $where = ' WHERE `item_type` = ?';
  1188. $queryArgs = array($itemType);
  1189. }
  1190. }
  1191. if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
  1192. $where .= ' AND `share_type` != ?';
  1193. $queryArgs[] = self::SHARE_TYPE_LINK;
  1194. }
  1195. if (isset($shareType)) {
  1196. // Include all user and group items
  1197. if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
  1198. $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
  1199. $queryArgs[] = self::SHARE_TYPE_USER;
  1200. $queryArgs[] = self::$shareTypeGroupUserUnique;
  1201. $queryArgs[] = $shareWith;
  1202. $groups = \OC_Group::getUserGroups($shareWith);
  1203. if (!empty($groups)) {
  1204. $placeholders = join(',', array_fill(0, count($groups), '?'));
  1205. $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
  1206. $queryArgs[] = self::SHARE_TYPE_GROUP;
  1207. $queryArgs = array_merge($queryArgs, $groups);
  1208. }
  1209. $where .= ')';
  1210. // Don't include own group shares
  1211. $where .= ' AND `uid_owner` != ?';
  1212. $queryArgs[] = $shareWith;
  1213. } else {
  1214. $where .= ' AND `share_type` = ?';
  1215. $queryArgs[] = $shareType;
  1216. if (isset($shareWith)) {
  1217. $where .= ' AND `share_with` = ?';
  1218. $queryArgs[] = $shareWith;
  1219. }
  1220. }
  1221. }
  1222. if (isset($uidOwner)) {
  1223. $where .= ' AND `uid_owner` = ?';
  1224. $queryArgs[] = $uidOwner;
  1225. if (!isset($shareType)) {
  1226. // Prevent unique user targets for group shares from being selected
  1227. $where .= ' AND `share_type` != ?';
  1228. $queryArgs[] = self::$shareTypeGroupUserUnique;
  1229. }
  1230. if ($fileDependent) {
  1231. $column = 'file_source';
  1232. } else {
  1233. $column = 'item_source';
  1234. }
  1235. } else {
  1236. if ($fileDependent) {
  1237. $column = 'file_target';
  1238. } else {
  1239. $column = 'item_target';
  1240. }
  1241. }
  1242. if (isset($item)) {
  1243. $collectionTypes = self::getCollectionItemTypes($itemType);
  1244. if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
  1245. $where .= ' AND (';
  1246. } else {
  1247. $where .= ' AND';
  1248. }
  1249. // If looking for own shared items, check item_source else check item_target
  1250. if (isset($uidOwner) || $itemShareWithBySource) {
  1251. // If item type is a file, file source needs to be checked in case the item was converted
  1252. if ($fileDependent) {
  1253. $where .= ' `file_source` = ?';
  1254. $column = 'file_source';
  1255. } else {
  1256. $where .= ' `item_source` = ?';
  1257. $column = 'item_source';
  1258. }
  1259. } else {
  1260. if ($fileDependent) {
  1261. $where .= ' `file_target` = ?';
  1262. $item = \OC\Files\Filesystem::normalizePath($item);
  1263. } else {
  1264. $where .= ' `item_target` = ?';
  1265. }
  1266. }
  1267. $queryArgs[] = $item;
  1268. if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
  1269. $placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
  1270. $where .= ' OR `item_type` IN ('.$placeholders.'))';
  1271. $queryArgs = array_merge($queryArgs, $collectionTypes);
  1272. }
  1273. }
  1274. if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
  1275. // Make sure the unique user target is returned if it exists,
  1276. // unique targets should follow the group share in the database
  1277. // If the limit is not 1, the filtering can be done later
  1278. $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
  1279. } else {
  1280. $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
  1281. }
  1282. if ($limit != -1 && !$includeCollections) {
  1283. // The limit must be at least 3, because filtering needs to be done
  1284. if ($limit < 3) {
  1285. $queryLimit = 3;
  1286. } else {
  1287. $queryLimit = $limit;
  1288. }
  1289. } else {
  1290. $queryLimit = null;
  1291. }
  1292. $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
  1293. $root = strlen($root);
  1294. $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
  1295. $result = $query->execute($queryArgs);
  1296. if (\OC_DB::isError($result)) {
  1297. \OC_Log::write('OCP\Share',
  1298. \OC_DB::getErrorMessage($result) . ', select=' . $select . ' where=',
  1299. \OC_Log::ERROR);
  1300. }
  1301. $items = array();
  1302. $targets = array();
  1303. $switchedItems = array();
  1304. $mounts = array();
  1305. while ($row = $result->fetchRow()) {
  1306. self::transformDBResults($row);
  1307. // Filter out duplicate group shares for users with unique targets
  1308. if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
  1309. $row['share_type'] = self::SHARE_TYPE_GROUP;
  1310. $row['unique_name'] = true; // remember that we use a unique name for this user
  1311. $row['share_with'] = $items[$row['parent']]['share_with'];
  1312. // if the group share was unshared from the user we keep the permission, otherwise
  1313. // we take the permission from the parent because this is always the up-to-date
  1314. // permission for the group share
  1315. if ($row['permissions'] > 0) {
  1316. $row['permissions'] = $items[$row['parent']]['permissions'];
  1317. }
  1318. // Remove the parent group share
  1319. unset($items[$row['parent']]);
  1320. if ($row['permissions'] == 0) {
  1321. continue;
  1322. }
  1323. } else if (!isset($uidOwner)) {
  1324. // Check if the same target already exists
  1325. if (isset($targets[$row['id']])) {
  1326. // Check if the same owner shared with the user twice
  1327. // through a group and user share - this is allowed
  1328. $id = $targets[$row['id']];
  1329. if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
  1330. // Switch to group share type to ensure resharing conditions aren't bypassed
  1331. if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
  1332. $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
  1333. $items[$id]['share_with'] = $row['share_with'];
  1334. }
  1335. // Switch ids if sharing permission is granted on only
  1336. // one share to ensure correct parent is used if resharing
  1337. if (~(int)$items[$id]['permissions'] & \OCP\PERMISSION_SHARE
  1338. && (int)$row['permissions'] & \OCP\PERMISSION_SHARE) {
  1339. $items[$row['id']] = $items[$id];
  1340. $switchedItems[$id] = $row['id'];
  1341. unset($items[$id]);
  1342. $id = $row['id'];
  1343. }
  1344. $items[$id]['permissions'] |= (int)$row['permissions'];
  1345. }
  1346. continue;
  1347. } elseif (!empty($row['parent'])) {
  1348. $targets[$row['parent']] = $row['id'];
  1349. }
  1350. }
  1351. // Remove root from file source paths if retrieving own shared items
  1352. if (isset($uidOwner) && isset($row['path'])) {
  1353. if (isset($row['parent'])) {
  1354. $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
  1355. $parentResult = $query->execute(array($row['parent']));
  1356. if (\OC_DB::isError($result)) {
  1357. \OC_Log::write('OCP\Share', 'Can\'t select parent: ' .
  1358. \OC_DB::getErrorMessage($result) . ', select=' . $select . ' where=' . $where,
  1359. \OC_Log::ERROR);
  1360. } else {
  1361. $parentRow = $parentResult->fetchRow();
  1362. $tmpPath = $parentRow['file_target'];
  1363. // find the right position where the row path continues from the target path
  1364. $pos = strrpos($row['path'], $parentRow['file_target']);
  1365. $subPath = substr($row['path'], $pos);
  1366. $splitPath = explode('/', $subPath);
  1367. foreach (array_slice($splitPath, 2) as $pathPart) {
  1368. $tmpPath = $tmpPath . '/' . $pathPart;
  1369. }
  1370. $row['path'] = $tmpPath;
  1371. }
  1372. } else {
  1373. if (!isset($mounts[$row['storage']])) {
  1374. $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
  1375. if (is_array($mountPoints) && !empty($mountPoints)) {
  1376. $mounts[$row['storage']] = current($mountPoints);
  1377. }
  1378. }
  1379. if (!empty($mounts[$row['storage']])) {
  1380. $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
  1381. $relPath = substr($path, $root); // path relative to data/user
  1382. $row['path'] = rtrim($relPath, '/');
  1383. }
  1384. }
  1385. }
  1386. if($checkExpireDate) {
  1387. if (self::expireItem($row)) {
  1388. continue;
  1389. }
  1390. }
  1391. // Check if resharing is allowed, if not remove share permission
  1392. if (isset($row['permissions']) && (!self::isResharingAllowed() | \OC_Util::isSharingDisabledForUser())) {
  1393. $row['permissions'] &= ~\OCP\PERMISSION_SHARE;
  1394. }
  1395. // Add display names to result
  1396. if ( isset($row['share_with']) && $row['share_with'] != '' &&
  1397. isset($row['share_with']) && $row['share_type'] === self::SHARE_TYPE_USER) {
  1398. $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
  1399. } else {
  1400. $row['share_with_displayname'] = $row['share_with'];
  1401. }
  1402. if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
  1403. $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
  1404. }
  1405. if ($row['permissions'] > 0) {
  1406. $items[$row['id']] = $row;
  1407. }
  1408. }
  1409. // group items if we are looking for items shared with the current user
  1410. if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
  1411. $items = self::groupItems($items, $itemType);
  1412. }
  1413. if (!empty($items)) {
  1414. $collectionItems = array();
  1415. foreach ($items as &$row) {
  1416. // Return only the item instead of a 2-dimensional array
  1417. if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
  1418. if ($format == self::FORMAT_NONE) {
  1419. return $row;
  1420. } else {
  1421. break;
  1422. }
  1423. }
  1424. // Check if this is a collection of the requested item type
  1425. if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
  1426. if (($collectionBackend = self::getBackend($row['item_type']))
  1427. && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
  1428. // Collections can be inside collections, check if the item is a collection
  1429. if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
  1430. $collectionItems[] = $row;
  1431. } else {
  1432. $collection = array();
  1433. $collection['item_type'] = $row['item_type'];
  1434. if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
  1435. $collection['path'] = basename($row['path']);
  1436. }
  1437. $row['collection'] = $collection;
  1438. // Fetch all of the children sources
  1439. $children = $collectionBackend->getChildren($row[$column]);
  1440. foreach ($children as $child) {
  1441. $childItem = $row;
  1442. $childItem['item_type'] = $itemType;
  1443. if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
  1444. $childItem['item_source'] = $child['source'];
  1445. $childItem['item_target'] = $child['target'];
  1446. }
  1447. if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
  1448. if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
  1449. $childItem['file_source'] = $child['source'];
  1450. } else { // TODO is this really needed if we already know that we use the file backend?
  1451. $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
  1452. $childItem['file_source'] = $meta['fileid'];
  1453. }
  1454. $childItem['file_target'] =
  1455. \OC\Files\Filesystem::normalizePath($child['file_path']);
  1456. }
  1457. if (isset($item)) {
  1458. if ($childItem[$column] == $item) {
  1459. // Return only the item instead of a 2-dimensional array
  1460. if ($limit == 1) {
  1461. if ($format == self::FORMAT_NONE) {
  1462. return $childItem;
  1463. } else {
  1464. // Unset the items array and break out of both loops
  1465. $items = array();
  1466. $items[] = $childItem;
  1467. break 2;
  1468. }
  1469. } else {
  1470. $collectionItems[] = $childItem;
  1471. }
  1472. }
  1473. } else {
  1474. $collectionItems[] = $childItem;
  1475. }
  1476. }
  1477. }
  1478. }
  1479. // Remove collection item
  1480. $toRemove = $row['id'];
  1481. if (array_key_exists($toRemove, $switchedItems)) {
  1482. $toRemove = $switchedItems[$toRemove];
  1483. }
  1484. unset($items[$toRemove]);
  1485. } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
  1486. // FIXME: Thats a dirty hack to improve file sharing performance,
  1487. // see github issue #10588 for more details
  1488. // Need to find a solution which works for all back-ends
  1489. $collectionBackend = self::getBackend($row['item_type']);
  1490. $sharedParents = $collectionBackend->getParents($row['item_source']);
  1491. foreach ($sharedParents as $parent) {
  1492. $collectionItems[] = $parent;
  1493. }
  1494. }
  1495. }
  1496. if (!empty($collectionItems)) {
  1497. $items = array_merge($items, $collectionItems);
  1498. }
  1499. return self::formatResult($items, $column, $backend, $format, $parameters);
  1500. } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
  1501. // FIXME: Thats a dirty hack to improve file sharing performance,
  1502. // see github issue #10588 for more details
  1503. // Need to find a solution which works for all back-ends
  1504. $collectionItems = array();
  1505. $collectionBackend = self::getBackend('folder');
  1506. $sharedParents = $collectionBackend->getParents($item, $shareWith);
  1507. foreach ($sharedParents as $parent) {
  1508. $collectionItems[] = $parent;
  1509. }
  1510. if ($limit === 1) {
  1511. return reset($collectionItems);
  1512. }
  1513. return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
  1514. }
  1515. return array();
  1516. }
  1517. /**
  1518. * group items with link to the same source
  1519. *
  1520. * @param array $items
  1521. * @param string $itemType
  1522. * @return array of grouped items
  1523. */
  1524. protected static function groupItems($items, $itemType) {
  1525. $fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
  1526. $result = array();
  1527. foreach ($items as $item) {
  1528. $grouped = false;
  1529. foreach ($result as $key => $r) {
  1530. // for file/folder shares we need to compare file_source, otherwise we compare item_source
  1531. // only group shares if they already point to the same target, otherwise the file where shared
  1532. // before grouping of shares was added. In this case we don't group them toi avoid confusions
  1533. if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
  1534. (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
  1535. // add the first item to the list of grouped shares
  1536. if (!isset($result[$key]['grouped'])) {
  1537. $result[$key]['grouped'][] = $result[$key];
  1538. }
  1539. $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
  1540. $result[$key]['grouped'][] = $item;
  1541. $grouped = true;
  1542. break;
  1543. }
  1544. }
  1545. if (!$grouped) {
  1546. $result[] = $item;
  1547. }
  1548. }
  1549. return $result;
  1550. }
  1551. /**
  1552. * Put shared item into the database
  1553. * @param string $itemType Item type
  1554. * @param string $itemSource Item source
  1555. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  1556. * @param string $shareWith User or group the item is being shared with
  1557. * @param string $uidOwner User that is the owner of shared item
  1558. * @param int $permissions CRUDS permissions
  1559. * @param boolean|array $parentFolder Parent folder target (optional)
  1560. * @param string $token (optional)
  1561. * @param string $itemSourceName name of the source item (optional)
  1562. * @param \DateTime $expirationDate (optional)
  1563. * @throws \Exception
  1564. * @return boolean Returns true on success or false on failure
  1565. */
  1566. private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
  1567. $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
  1568. $queriesToExecute = array();
  1569. $suggestedItemTarget = null;
  1570. $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
  1571. if(!empty($result)) {
  1572. $parent = $result['parent'];
  1573. $itemSource = $result['itemSource'];
  1574. $fileSource = $result['fileSource'];
  1575. $suggestedItemTarget = $result['suggestedItemTarget'];
  1576. $suggestedFileTarget = $result['suggestedFileTarget'];
  1577. $filePath = $result['filePath'];
  1578. $expirationDate = $result['expirationDate'];
  1579. }
  1580. $isGroupShare = false;
  1581. if ($shareType == self::SHARE_TYPE_GROUP) {
  1582. $isGroupShare = true;
  1583. $users = \OC_Group::usersInGroup($shareWith['group']);
  1584. // remove current user from list
  1585. if (in_array(\OCP\User::getUser(), $users)) {
  1586. unset($users[array_search(\OCP\User::getUser(), $users)]);
  1587. }
  1588. $groupItemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith['group'],
  1589. $uidOwner, $suggestedItemTarget);
  1590. $groupFileTarget = $filePath;
  1591. // add group share to table and remember the id as parent
  1592. $queriesToExecute['groupShare'] = array(
  1593. 'itemType' => $itemType,
  1594. 'itemSource' => $itemSource,
  1595. 'itemTarget' => $groupItemTarget,
  1596. 'shareType' => $shareType,
  1597. 'shareWith' => $shareWith['group'],
  1598. 'uidOwner' => $uidOwner,
  1599. 'permissions' => $permissions,
  1600. 'shareTime' => time(),
  1601. 'fileSource' => $fileSource,
  1602. 'fileTarget' => $filePath,
  1603. 'token' => $token,
  1604. 'parent' => $parent,
  1605. 'expiration' => $expirationDate,
  1606. );
  1607. } else {
  1608. $users = array($shareWith);
  1609. $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
  1610. $suggestedItemTarget);
  1611. }
  1612. $run = true;
  1613. $error = '';
  1614. $preHookData = array(
  1615. 'itemType' => $itemType,
  1616. 'itemSource' => $itemSource,
  1617. 'shareType' => $shareType,
  1618. 'uidOwner' => $uidOwner,
  1619. 'permissions' => $permissions,
  1620. 'fileSource' => $fileSource,
  1621. 'expiration' => $expirationDate,
  1622. 'token' => $token,
  1623. 'run' => &$run,
  1624. 'error' => &$error
  1625. );
  1626. $preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
  1627. $preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
  1628. \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
  1629. if ($run === false) {
  1630. throw new \Exception($error);
  1631. }
  1632. foreach ($users as $user) {
  1633. $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
  1634. $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
  1635. $shareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
  1636. if ($sourceExists) {
  1637. $fileTarget = $sourceExists['file_target'];
  1638. $itemTarget = $sourceExists['item_target'];
  1639. // for group shares we don't need a additional entry if the target is the same
  1640. if($isGroupShare && $groupItemTarget === $itemTarget) {
  1641. continue;
  1642. }
  1643. } elseif(!$sourceExists && !$isGroupShare) {
  1644. $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $user,
  1645. $uidOwner, $suggestedItemTarget, $parent);
  1646. if (isset($fileSource)) {
  1647. if ($parentFolder) {
  1648. if ($parentFolder === true) {
  1649. $fileTarget = Helper::generateTarget('file', $filePath, $shareType, $user,
  1650. $uidOwner, $suggestedFileTarget, $parent);
  1651. if ($fileTarget != $groupFileTarget) {
  1652. $parentFolders[$user]['folder'] = $fileTarget;
  1653. }
  1654. } else if (isset($parentFolder[$user])) {
  1655. $fileTarget = $parentFolder[$user]['folder'].$itemSource;
  1656. $parent = $parentFolder[$user]['id'];
  1657. }
  1658. } else {
  1659. $fileTarget = Helper::generateTarget('file', $filePath, $shareType,
  1660. $user, $uidOwner, $suggestedFileTarget, $parent);
  1661. }
  1662. } else {
  1663. $fileTarget = null;
  1664. }
  1665. } else {
  1666. // group share which doesn't exists until now, check if we need a unique target for this user
  1667. $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
  1668. $uidOwner, $suggestedItemTarget, $parent);
  1669. // do we also need a file target
  1670. if (isset($fileSource)) {
  1671. $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
  1672. $uidOwner, $suggestedFileTarget, $parent);
  1673. } else {
  1674. $fileTarget = null;
  1675. }
  1676. if ($itemTarget === $groupItemTarget && (isset($fileSource) && $fileTarget === $groupItemTarget)) {
  1677. continue;
  1678. }
  1679. }
  1680. $queriesToExecute[] = array(
  1681. 'itemType' => $itemType,
  1682. 'itemSource' => $itemSource,
  1683. 'itemTarget' => $itemTarget,
  1684. 'shareType' => $shareType,
  1685. 'shareWith' => $user,
  1686. 'uidOwner' => $uidOwner,
  1687. 'permissions' => $permissions,
  1688. 'shareTime' => time(),
  1689. 'fileSource' => $fileSource,
  1690. 'fileTarget' => $fileTarget,
  1691. 'token' => $token,
  1692. 'parent' => $parent,
  1693. 'expiration' => $expirationDate,
  1694. );
  1695. }
  1696. if ($isGroupShare) {
  1697. self::insertShare($queriesToExecute['groupShare']);
  1698. // Save this id, any extra rows for this group share will need to reference it
  1699. $parent = \OC_DB::insertid('*PREFIX*share');
  1700. unset($queriesToExecute['groupShare']);
  1701. }
  1702. foreach ($queriesToExecute as $shareQuery) {
  1703. $shareQuery['parent'] = $parent;
  1704. self::insertShare($shareQuery);
  1705. }
  1706. $postHookData = array(
  1707. 'itemType' => $itemType,
  1708. 'itemSource' => $itemSource,
  1709. 'parent' => $parent,
  1710. 'shareType' => $shareType,
  1711. 'uidOwner' => $uidOwner,
  1712. 'permissions' => $permissions,
  1713. 'fileSource' => $fileSource,
  1714. 'id' => $parent,
  1715. 'token' => $token,
  1716. 'expirationDate' => $expirationDate,
  1717. );
  1718. $postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
  1719. $postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
  1720. $postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
  1721. \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
  1722. return true;
  1723. }
  1724. private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
  1725. $backend = self::getBackend($itemType);
  1726. $l = \OC::$server->getL10N('lib');
  1727. $result = array();
  1728. $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
  1729. $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
  1730. if ($checkReshare) {
  1731. // Check if attempting to share back to owner
  1732. if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
  1733. $message = 'Sharing %s failed, because the user %s is the original sharer';
  1734. $message_t = $l->t('Sharing %s failed, because the user %s is the original sharer', array($itemSourceName, $shareWith));
  1735. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  1736. throw new \Exception($message_t);
  1737. }
  1738. // Check if share permissions is granted
  1739. if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\PERMISSION_SHARE) {
  1740. if (~(int)$checkReshare['permissions'] & $permissions) {
  1741. $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
  1742. $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
  1743. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OC_Log::ERROR);
  1744. throw new \Exception($message_t);
  1745. } else {
  1746. // TODO Don't check if inside folder
  1747. $result['parent'] = $checkReshare['id'];
  1748. $result['expirationDate'] = min($expirationDate, $checkReshare['expiration']);
  1749. // only suggest the same name as new target if it is a reshare of the
  1750. // same file/folder and not the reshare of a child
  1751. if ($checkReshare[$column] === $itemSource) {
  1752. $result['filePath'] = $checkReshare['file_target'];
  1753. $result['itemSource'] = $checkReshare['item_source'];
  1754. $result['fileSource'] = $checkReshare['file_source'];
  1755. $result['suggestedItemTarget'] = $checkReshare['item_target'];
  1756. $result['suggestedFileTarget'] = $checkReshare['file_target'];
  1757. } else {
  1758. $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
  1759. $result['suggestedItemTarget'] = null;
  1760. $result['suggestedFileTarget'] = null;
  1761. $result['itemSource'] = $itemSource;
  1762. $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
  1763. }
  1764. }
  1765. } else {
  1766. $message = 'Sharing %s failed, because resharing is not allowed';
  1767. $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
  1768. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
  1769. throw new \Exception($message_t);
  1770. }
  1771. } else {
  1772. $result['parent'] = null;
  1773. $result['suggestedItemTarget'] = null;
  1774. $result['suggestedFileTarget'] = null;
  1775. $result['itemSource'] = $itemSource;
  1776. $result['expirationDate'] = $expirationDate;
  1777. if (!$backend->isValidSource($itemSource, $uidOwner)) {
  1778. $message = 'Sharing %s failed, because the sharing backend for '
  1779. .'%s could not find its source';
  1780. $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
  1781. \OC_Log::write('OCP\Share', sprintf($message, $itemSource, $itemType), \OC_Log::ERROR);
  1782. throw new \Exception($message_t);
  1783. }
  1784. if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
  1785. $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
  1786. if ($itemType == 'file' || $itemType == 'folder') {
  1787. $result['fileSource'] = $itemSource;
  1788. } else {
  1789. $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
  1790. $result['fileSource'] = $meta['fileid'];
  1791. }
  1792. if ($result['fileSource'] == -1) {
  1793. $message = 'Sharing %s failed, because the file could not be found in the file cache';
  1794. $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
  1795. \OC_Log::write('OCP\Share', sprintf($message, $itemSource), \OC_Log::ERROR);
  1796. throw new \Exception($message_t);
  1797. }
  1798. } else {
  1799. $result['filePath'] = null;
  1800. $result['fileSource'] = null;
  1801. }
  1802. }
  1803. return $result;
  1804. }
  1805. private static function insertShare(array $shareData)
  1806. {
  1807. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
  1808. .' `item_type`, `item_source`, `item_target`, `share_type`,'
  1809. .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
  1810. .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
  1811. $query->bindValue(1, $shareData['itemType']);
  1812. $query->bindValue(2, $shareData['itemSource']);
  1813. $query->bindValue(3, $shareData['itemTarget']);
  1814. $query->bindValue(4, $shareData['shareType']);
  1815. $query->bindValue(5, $shareData['shareWith']);
  1816. $query->bindValue(6, $shareData['uidOwner']);
  1817. $query->bindValue(7, $shareData['permissions']);
  1818. $query->bindValue(8, $shareData['shareTime']);
  1819. $query->bindValue(9, $shareData['fileSource']);
  1820. $query->bindValue(10, $shareData['fileTarget']);
  1821. $query->bindValue(11, $shareData['token']);
  1822. $query->bindValue(12, $shareData['parent']);
  1823. $query->bindValue(13, $shareData['expiration'], 'datetime');
  1824. $query->execute();
  1825. }
  1826. /**
  1827. * Delete all shares with type SHARE_TYPE_LINK
  1828. */
  1829. public static function removeAllLinkShares() {
  1830. // Delete any link shares
  1831. $query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ?');
  1832. $result = $query->execute(array(self::SHARE_TYPE_LINK));
  1833. while ($item = $result->fetchRow()) {
  1834. Helper::delete($item['id']);
  1835. }
  1836. }
  1837. /**
  1838. * In case a password protected link is not yet authenticated this function will return false
  1839. *
  1840. * @param array $linkItem
  1841. * @return boolean
  1842. */
  1843. public static function checkPasswordProtectedShare(array $linkItem) {
  1844. if (!isset($linkItem['share_with'])) {
  1845. return true;
  1846. }
  1847. if (!isset($linkItem['share_type'])) {
  1848. return true;
  1849. }
  1850. if (!isset($linkItem['id'])) {
  1851. return true;
  1852. }
  1853. if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
  1854. return true;
  1855. }
  1856. if ( \OC::$server->getSession()->exists('public_link_authenticated')
  1857. && \OC::$server->getSession()->get('public_link_authenticated') === $linkItem['id'] ) {
  1858. return true;
  1859. }
  1860. return false;
  1861. }
  1862. /**
  1863. * construct select statement
  1864. * @param int $format
  1865. * @param boolean $fileDependent ist it a file/folder share or a generla share
  1866. * @param string $uidOwner
  1867. * @return string select statement
  1868. */
  1869. private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
  1870. $select = '*';
  1871. if ($format == self::FORMAT_STATUSES) {
  1872. if ($fileDependent) {
  1873. $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, `share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`';
  1874. } else {
  1875. $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
  1876. }
  1877. } else {
  1878. if (isset($uidOwner)) {
  1879. if ($fileDependent) {
  1880. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
  1881. . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
  1882. . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`';
  1883. } else {
  1884. $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
  1885. . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
  1886. }
  1887. } else {
  1888. if ($fileDependent) {
  1889. if ($format == \OC_Share_Backend_File::FORMAT_GET_FOLDER_CONTENTS || $format == \OC_Share_Backend_File::FORMAT_FILE_APP_ROOT) {
  1890. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
  1891. . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
  1892. . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
  1893. . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `unencrypted_size`, `encrypted`, `etag`, `mail_send`';
  1894. } else {
  1895. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,
  1896. `*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,
  1897. `file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`, `stime`, `expiration`, `token`, `storage`, `mail_send`';
  1898. }
  1899. }
  1900. }
  1901. }
  1902. return $select;
  1903. }
  1904. /**
  1905. * transform db results
  1906. * @param array $row result
  1907. */
  1908. private static function transformDBResults(&$row) {
  1909. if (isset($row['id'])) {
  1910. $row['id'] = (int) $row['id'];
  1911. }
  1912. if (isset($row['share_type'])) {
  1913. $row['share_type'] = (int) $row['share_type'];
  1914. }
  1915. if (isset($row['parent'])) {
  1916. $row['parent'] = (int) $row['parent'];
  1917. }
  1918. if (isset($row['file_parent'])) {
  1919. $row['file_parent'] = (int) $row['file_parent'];
  1920. }
  1921. if (isset($row['file_source'])) {
  1922. $row['file_source'] = (int) $row['file_source'];
  1923. }
  1924. if (isset($row['permissions'])) {
  1925. $row['permissions'] = (int) $row['permissions'];
  1926. }
  1927. if (isset($row['storage'])) {
  1928. $row['storage'] = (int) $row['storage'];
  1929. }
  1930. if (isset($row['stime'])) {
  1931. $row['stime'] = (int) $row['stime'];
  1932. }
  1933. }
  1934. /**
  1935. * format result
  1936. * @param array $items result
  1937. * @param string $column is it a file share or a general share ('file_target' or 'item_target')
  1938. * @param \OCP\Share_Backend $backend sharing backend
  1939. * @param int $format
  1940. * @param array $parameters additional format parameters
  1941. * @return array format result
  1942. */
  1943. private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
  1944. if ($format === self::FORMAT_NONE) {
  1945. return $items;
  1946. } else if ($format === self::FORMAT_STATUSES) {
  1947. $statuses = array();
  1948. foreach ($items as $item) {
  1949. if ($item['share_type'] === self::SHARE_TYPE_LINK) {
  1950. $statuses[$item[$column]]['link'] = true;
  1951. } else if (!isset($statuses[$item[$column]])) {
  1952. $statuses[$item[$column]]['link'] = false;
  1953. }
  1954. if (!empty($item['file_target'])) {
  1955. $statuses[$item[$column]]['path'] = $item['path'];
  1956. }
  1957. }
  1958. return $statuses;
  1959. } else {
  1960. return $backend->formatItems($items, $format, $parameters);
  1961. }
  1962. }
  1963. /**
  1964. * check if user can only share with group members
  1965. * @return bool
  1966. */
  1967. public static function shareWithGroupMembersOnly() {
  1968. $value = \OC_Appconfig::getValue('core', 'shareapi_only_share_with_group_members', 'no');
  1969. return ($value === 'yes') ? true : false;
  1970. }
  1971. public static function isDefaultExpireDateEnabled() {
  1972. $defaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
  1973. return ($defaultExpireDateEnabled === "yes") ? true : false;
  1974. }
  1975. public static function enforceDefaultExpireDate() {
  1976. $enforceDefaultExpireDate = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
  1977. return ($enforceDefaultExpireDate === "yes") ? true : false;
  1978. }
  1979. public static function getExpireInterval() {
  1980. return (int)\OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
  1981. }
  1982. }